1 | # -*- coding: utf-8 -*- |
---|
2 | |
---|
3 | # Copyright Puzzlebox Productions, LLC (2010) |
---|
4 | # |
---|
5 | # This code is released under the GNU Pulic License (GPL) version 2 |
---|
6 | # For more information please refer to http://www.gnu.org/copyleft/gpl.html |
---|
7 | |
---|
8 | # Old Class Names: |
---|
9 | # puzzlebox_synapse_interface = QtUI |
---|
10 | |
---|
11 | __changelog__ = """\ |
---|
12 | Last Update: 2010.11.04 |
---|
13 | |
---|
14 | """ |
---|
15 | |
---|
16 | __todo__ = """ |
---|
17 | - update configuration.ini file with settings entered into interface |
---|
18 | |
---|
19 | """ |
---|
20 | |
---|
21 | ### IMPORTS ### |
---|
22 | import os, sys, time |
---|
23 | import simplejson as json |
---|
24 | |
---|
25 | try: |
---|
26 | from Interface_Plot import * |
---|
27 | MATPLOTLIB_AVAILABLE = True |
---|
28 | except: |
---|
29 | MATPLOTLIB_AVAILABLE = False |
---|
30 | |
---|
31 | if (sys.platform != 'win32'): |
---|
32 | import bluetooth |
---|
33 | DEFAULT_IMAGE_PATH = '/usr/share/puzzlebox_synapse/images' |
---|
34 | else: |
---|
35 | import _winreg as winreg |
---|
36 | import itertools |
---|
37 | import re |
---|
38 | import serial |
---|
39 | DEFAULT_IMAGE_PATH = 'images' |
---|
40 | |
---|
41 | try: |
---|
42 | import PySide as PyQt4 |
---|
43 | from PySide import QtCore, QtGui |
---|
44 | except: |
---|
45 | print "Using PyQt4 module" |
---|
46 | from PyQt4 import QtCore, QtGui |
---|
47 | else: |
---|
48 | print "Using PySide module" |
---|
49 | |
---|
50 | try: |
---|
51 | import cPickle as pickle |
---|
52 | except: |
---|
53 | import pickle |
---|
54 | |
---|
55 | # from puzzlebox_synapse_interface_design import Ui_Form |
---|
56 | from Interface_Design import Ui_Form as Design |
---|
57 | |
---|
58 | import Configuration as configuration |
---|
59 | import Server as synapse_server |
---|
60 | import Client as thinkgear_client |
---|
61 | #import puzzlebox_logger |
---|
62 | |
---|
63 | ### GLOBALS ### |
---|
64 | |
---|
65 | DEBUG = 1 |
---|
66 | |
---|
67 | THINKGEAR_SERVER_HOST = configuration.THINKGEAR_SERVER_HOST |
---|
68 | THINKGEAR_SERVER_PORT = configuration.THINKGEAR_SERVER_PORT |
---|
69 | |
---|
70 | THINKGEAR_EEG_POWER_BAND_ORDER = configuration.THINKGEAR_EEG_POWER_BAND_ORDER |
---|
71 | |
---|
72 | THINKGEAR_EMULATION_MAX_ESENSE_VALUE = \ |
---|
73 | configuration.THINKGEAR_EMULATION_MAX_ESENSE_VALUE |
---|
74 | THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE = \ |
---|
75 | configuration.THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE |
---|
76 | |
---|
77 | PATH_TO_HCITOOL = '/usr/bin/hcitool' |
---|
78 | |
---|
79 | #UPDATE_INTERFACE_VIA_TIMER = True # Alternative is to establish a |
---|
80 | ## ThinkGear Connect client which |
---|
81 | ## updates the interface on demand |
---|
82 | ## as packets are received |
---|
83 | |
---|
84 | UPDATE_INTERFACE_VIA_TIMER = False |
---|
85 | |
---|
86 | #INTERFACE_UPDATE_FREQUENCY = (1 / 512) * 1000 # ms (512 Hz) |
---|
87 | INTERFACE_UPDATE_FREQUENCY = 1000 # ms |
---|
88 | |
---|
89 | INTERFACE_RAW_EEG_UPDATE_FREQUENCY = 512 |
---|
90 | |
---|
91 | ### CLASSES ### |
---|
92 | |
---|
93 | class QtUI(QtGui.QWidget, Design): |
---|
94 | |
---|
95 | def __init__(self, log, server=None, DEBUG=DEBUG, parent = None): |
---|
96 | |
---|
97 | self.log = log |
---|
98 | self.DEBUG = DEBUG |
---|
99 | |
---|
100 | QtGui.QWidget.__init__(self, parent) |
---|
101 | self.setupUi(self) |
---|
102 | |
---|
103 | self.configureSettings() |
---|
104 | self.connectWidgets() |
---|
105 | |
---|
106 | self.name = "Synapse Interface" |
---|
107 | |
---|
108 | self.thinkGearConnectServer = None |
---|
109 | self.thinkgearConnectClient = None |
---|
110 | |
---|
111 | self.maxEEGPower = THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE |
---|
112 | |
---|
113 | self.debug_console_buffer = '' |
---|
114 | |
---|
115 | self.packets = {} |
---|
116 | self.packets['rawEeg'] = [] |
---|
117 | self.packets['signals'] = [] |
---|
118 | |
---|
119 | if UPDATE_INTERFACE_VIA_TIMER: |
---|
120 | self.updateInterfaceTimer = QtCore.QTimer() |
---|
121 | QtCore.QObject.connect(self.updateInterfaceTimer, \ |
---|
122 | QtCore.SIGNAL("timeout()"), \ |
---|
123 | self.updateInterface) |
---|
124 | |
---|
125 | |
---|
126 | ################################################################## |
---|
127 | |
---|
128 | def configureSettings(self): |
---|
129 | |
---|
130 | # Synapse Interface |
---|
131 | image_path = "puzzlebox.ico" |
---|
132 | if not os.path.exists(image_path): |
---|
133 | image_path = os.path.join(DEFAULT_IMAGE_PATH, image_path) |
---|
134 | |
---|
135 | if os.path.exists(image_path): |
---|
136 | icon = QtGui.QIcon() |
---|
137 | icon.addPixmap(QtGui.QPixmap(image_path), \ |
---|
138 | QtGui.QIcon.Normal, \ |
---|
139 | QtGui.QIcon.Off) |
---|
140 | self.setWindowIcon(icon) |
---|
141 | |
---|
142 | image_path = "puzzlebox_logo.png" |
---|
143 | if not os.path.exists(image_path): |
---|
144 | image_path = os.path.join(DEFAULT_IMAGE_PATH, image_path) |
---|
145 | if os.path.exists(image_path): |
---|
146 | self.labelPuzzleboxIcon.setPixmap(QtGui.QPixmap(image_path)) |
---|
147 | |
---|
148 | |
---|
149 | # ThinkGear Device |
---|
150 | self.searchForThinkGearDevices() |
---|
151 | |
---|
152 | |
---|
153 | # ThinkGear Connect Server |
---|
154 | self.textLabelBluetoothStatus.setText("Status: Disconnected") |
---|
155 | |
---|
156 | # Display Host for ThinkGear Connect Socket Server |
---|
157 | self.lineEditThinkGearHost.setText(THINKGEAR_SERVER_HOST) |
---|
158 | |
---|
159 | # Display Port for ThinkGear Connect Socket Server |
---|
160 | self.lineEditThinkGearPort.setText('%i' % THINKGEAR_SERVER_PORT) |
---|
161 | |
---|
162 | |
---|
163 | # ThinkgGear Progress Bars |
---|
164 | self.progressBarEEGDelta.setMaximum(THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE) |
---|
165 | self.progressBarEEGTheta.setMaximum(THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE) |
---|
166 | self.progressBarEEGLowAlpha.setMaximum(THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE) |
---|
167 | self.progressBarEEGHighAlpha.setMaximum(THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE) |
---|
168 | self.progressBarEEGLowBeta.setMaximum(THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE) |
---|
169 | self.progressBarEEGHighBeta.setMaximum(THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE) |
---|
170 | self.progressBarEEGLowGamma.setMaximum(THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE) |
---|
171 | self.progressBarEEGMidGamma.setMaximum(THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE) |
---|
172 | |
---|
173 | self.progressBarAttention.setMaximum(THINKGEAR_EMULATION_MAX_ESENSE_VALUE) |
---|
174 | self.progressBarMeditation.setMaximum(THINKGEAR_EMULATION_MAX_ESENSE_VALUE) |
---|
175 | |
---|
176 | self.progressBarSignalContactQuality.setMaximum(200) |
---|
177 | |
---|
178 | |
---|
179 | if MATPLOTLIB_AVAILABLE: |
---|
180 | self.rawEEGMatplot = rawEEGMatplotlibCanvas( \ |
---|
181 | self.tabEEGSignals, \ |
---|
182 | width=8, \ |
---|
183 | height=4, \ |
---|
184 | dpi=100, \ |
---|
185 | title='Raw EEG Waves') |
---|
186 | self.chartEEGMatplot = chartEEGMatplotlibCanvas( \ |
---|
187 | self.tabCharts, \ |
---|
188 | width=8, \ |
---|
189 | height=4, \ |
---|
190 | dpi=100, \ |
---|
191 | title='EEG Brain Signals') |
---|
192 | |
---|
193 | else: |
---|
194 | self.tabWidget.removeTab(self.tabWidget.indexOf(self.tabEEGSignals)) |
---|
195 | self.tabWidget.removeTab(self.tabWidget.indexOf(self.tabCharts)) |
---|
196 | |
---|
197 | |
---|
198 | ################################################################## |
---|
199 | |
---|
200 | def connectWidgets(self): |
---|
201 | |
---|
202 | self.connect(self.pushButtonBluetoothSearch, \ |
---|
203 | QtCore.SIGNAL("clicked()"), \ |
---|
204 | self.searchForThinkGearDevices) |
---|
205 | |
---|
206 | self.connect(self.pushButtonBluetoothConnect, \ |
---|
207 | QtCore.SIGNAL("clicked()"), \ |
---|
208 | self.connectToThinkGearDevice) |
---|
209 | |
---|
210 | self.connect(self.pushButtonThinkGearConnect, \ |
---|
211 | QtCore.SIGNAL("clicked()"), \ |
---|
212 | self.startThinkGearConnectServer) |
---|
213 | |
---|
214 | self.connect(self.pushButtonSave, \ |
---|
215 | QtCore.SIGNAL("clicked()"), \ |
---|
216 | self.saveData) |
---|
217 | |
---|
218 | self.connect(self.pushButtonExport, \ |
---|
219 | QtCore.SIGNAL("clicked()"), \ |
---|
220 | self.exportData) |
---|
221 | |
---|
222 | self.connect(self.pushButtonReset, \ |
---|
223 | QtCore.SIGNAL("clicked()"), \ |
---|
224 | self.resetData) |
---|
225 | |
---|
226 | |
---|
227 | ################################################################## |
---|
228 | |
---|
229 | def connectToThinkGearDevice(self): |
---|
230 | |
---|
231 | device_selection = self.comboBoxDeviceSelect.currentText() |
---|
232 | |
---|
233 | self.disconnect(self.pushButtonBluetoothConnect, \ |
---|
234 | QtCore.SIGNAL("clicked()"), \ |
---|
235 | self.connectToThinkGearDevice) |
---|
236 | |
---|
237 | self.connect(self.pushButtonBluetoothConnect, \ |
---|
238 | QtCore.SIGNAL("clicked()"), \ |
---|
239 | self.disconnectFromThinkGearDevice) |
---|
240 | |
---|
241 | self.textLabelBluetoothStatus.setText("Status: Connected") |
---|
242 | |
---|
243 | self.pushButtonBluetoothSearch.setEnabled(False) |
---|
244 | |
---|
245 | self.pushButtonBluetoothConnect.setText('Disconnect') |
---|
246 | self.pushButtonBluetoothConnect.setChecked(True) |
---|
247 | |
---|
248 | self.comboBoxDeviceSelect.setEnabled(False) |
---|
249 | |
---|
250 | |
---|
251 | ################################################################## |
---|
252 | |
---|
253 | def disconnectFromThinkGearDevice(self): |
---|
254 | |
---|
255 | self.disconnect(self.pushButtonBluetoothConnect, \ |
---|
256 | QtCore.SIGNAL("clicked()"), \ |
---|
257 | self.disconnectFromThinkGearDevice) |
---|
258 | |
---|
259 | self.connect(self.pushButtonBluetoothConnect, \ |
---|
260 | QtCore.SIGNAL("clicked()"), \ |
---|
261 | self.connectToThinkGearDevice) |
---|
262 | |
---|
263 | self.textLabelBluetoothStatus.setText("Status: Disconnected") |
---|
264 | |
---|
265 | self.pushButtonBluetoothSearch.setEnabled(True) |
---|
266 | |
---|
267 | self.pushButtonBluetoothConnect.setText('Connect') |
---|
268 | self.pushButtonBluetoothConnect.setChecked(False) |
---|
269 | |
---|
270 | self.comboBoxDeviceSelect.setEnabled(True) |
---|
271 | |
---|
272 | |
---|
273 | self.progressBarEEGDelta.setValue(0) |
---|
274 | self.progressBarEEGTheta.setValue(0) |
---|
275 | self.progressBarEEGLowAlpha.setValue(0) |
---|
276 | self.progressBarEEGHighAlpha.setValue(0) |
---|
277 | self.progressBarEEGLowBeta.setValue(0) |
---|
278 | self.progressBarEEGHighBeta.setValue(0) |
---|
279 | self.progressBarEEGLowGamma.setValue(0) |
---|
280 | self.progressBarEEGMidGamma.setValue(0) |
---|
281 | |
---|
282 | self.progressBarAttention.setValue(0) |
---|
283 | self.progressBarMeditation.setValue(0) |
---|
284 | |
---|
285 | self.progressBarSignalContactQuality.setValue(0) |
---|
286 | |
---|
287 | self.maxEEGPower = THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE |
---|
288 | |
---|
289 | # In case the user connects to a MindSet, then disconnects |
---|
290 | # and re-connects to a MindSet Emulator, |
---|
291 | # we need to reset the max power values |
---|
292 | self.progressBarEEGDelta.setMaximum(self.maxEEGPower) |
---|
293 | self.progressBarEEGTheta.setMaximum(self.maxEEGPower) |
---|
294 | self.progressBarEEGLowAlpha.setMaximum(self.maxEEGPower) |
---|
295 | self.progressBarEEGHighAlpha.setMaximum(self.maxEEGPower) |
---|
296 | self.progressBarEEGLowBeta.setMaximum(self.maxEEGPower) |
---|
297 | self.progressBarEEGHighBeta.setMaximum(self.maxEEGPower) |
---|
298 | self.progressBarEEGLowGamma.setMaximum(self.maxEEGPower) |
---|
299 | self.progressBarEEGMidGamma.setMaximum(self.maxEEGPower) |
---|
300 | |
---|
301 | |
---|
302 | ################################################################## |
---|
303 | |
---|
304 | def startThinkGearConnectServer(self): |
---|
305 | |
---|
306 | # Ensure EEG device is connected first |
---|
307 | |
---|
308 | if not self.pushButtonBluetoothConnect.isChecked(): |
---|
309 | self.connectToThinkGearDevice() |
---|
310 | |
---|
311 | |
---|
312 | self.pushButtonBluetoothSearch.setEnabled(False) |
---|
313 | self.pushButtonBluetoothConnect.setEnabled(False) |
---|
314 | |
---|
315 | server_interface = str(self.lineEditThinkGearHost.text()) |
---|
316 | server_port = int(self.lineEditThinkGearPort.text()) |
---|
317 | device_address = str(self.comboBoxDeviceSelect.currentText()) |
---|
318 | emulate_headset_data = (device_address == 'MindSet Emulator') |
---|
319 | |
---|
320 | |
---|
321 | self.thinkGearConnectServer = \ |
---|
322 | synapse_server.ThinkgearServer( \ |
---|
323 | self.log, \ |
---|
324 | server_interface=server_interface, \ |
---|
325 | server_port=server_port, \ |
---|
326 | device_address=device_address, \ |
---|
327 | emulate_headset_data=emulate_headset_data, \ |
---|
328 | DEBUG=DEBUG, \ |
---|
329 | parent=self) |
---|
330 | |
---|
331 | self.thinkGearConnectServer.start() |
---|
332 | |
---|
333 | |
---|
334 | if UPDATE_INTERFACE_VIA_TIMER: |
---|
335 | self.updateInterfaceTimer.start(INTERFACE_UPDATE_FREQUENCY) |
---|
336 | |
---|
337 | else: |
---|
338 | self.thinkgearConnectClient = \ |
---|
339 | thinkgear_client.QtClient( \ |
---|
340 | self.log, \ |
---|
341 | server_host=server_interface, \ |
---|
342 | server_port=server_port, \ |
---|
343 | DEBUG=0, \ |
---|
344 | parent=self) |
---|
345 | |
---|
346 | self.thinkgearConnectClient.start() |
---|
347 | |
---|
348 | |
---|
349 | self.disconnect(self.pushButtonThinkGearConnect, \ |
---|
350 | QtCore.SIGNAL("clicked()"), \ |
---|
351 | self.startThinkGearConnectServer) |
---|
352 | |
---|
353 | self.connect(self.pushButtonThinkGearConnect, \ |
---|
354 | QtCore.SIGNAL("clicked()"), \ |
---|
355 | self.stopThinkGearConnectServer) |
---|
356 | |
---|
357 | self.lineEditThinkGearHost.setEnabled(False) |
---|
358 | self.lineEditThinkGearPort.setEnabled(False) |
---|
359 | |
---|
360 | self.pushButtonThinkGearConnect.setText('Stop') |
---|
361 | |
---|
362 | |
---|
363 | ################################################################## |
---|
364 | |
---|
365 | def stopThinkGearConnectServer(self): |
---|
366 | |
---|
367 | if UPDATE_INTERFACE_VIA_TIMER: |
---|
368 | self.updateInterfaceTimer.stop() |
---|
369 | else: |
---|
370 | try: |
---|
371 | self.thinkgearConnectClient.disconnectFromHost() |
---|
372 | except Exception, e: |
---|
373 | if self.DEBUG: |
---|
374 | print "Call failed to self.thinkgearConnectClient.disconnectFromHost():", |
---|
375 | print e |
---|
376 | |
---|
377 | try: |
---|
378 | self.thinkGearConnectServer.exitThread() |
---|
379 | except Exception, e: |
---|
380 | if self.DEBUG: |
---|
381 | print "Call failed to self.thinkGearConnectServer.exitThread():", |
---|
382 | print e |
---|
383 | |
---|
384 | self.disconnect(self.pushButtonThinkGearConnect, \ |
---|
385 | QtCore.SIGNAL("clicked()"), \ |
---|
386 | self.stopThinkGearConnectServer) |
---|
387 | |
---|
388 | self.connect(self.pushButtonThinkGearConnect, \ |
---|
389 | QtCore.SIGNAL("clicked()"), \ |
---|
390 | self.startThinkGearConnectServer) |
---|
391 | |
---|
392 | self.lineEditThinkGearHost.setEnabled(True) |
---|
393 | self.lineEditThinkGearPort.setEnabled(True) |
---|
394 | |
---|
395 | self.pushButtonThinkGearConnect.setText('Start') |
---|
396 | |
---|
397 | #self.pushButtonBluetoothSearch.setEnabled(True) |
---|
398 | self.pushButtonBluetoothConnect.setEnabled(True) |
---|
399 | |
---|
400 | self.pushButtonThinkGearConnect.setChecked(False) |
---|
401 | |
---|
402 | |
---|
403 | ################################################################## |
---|
404 | |
---|
405 | def updateInterface(self): |
---|
406 | |
---|
407 | if not self.thinkGearConnectServer.emulate_headset_data: |
---|
408 | self.processPacketThinkGear( \ |
---|
409 | self.thinkGearConnectServer.protocol.data_packet) |
---|
410 | |
---|
411 | |
---|
412 | ################################################################## |
---|
413 | |
---|
414 | def parseTimeStamp(self, timestamp, local_version=False): |
---|
415 | |
---|
416 | print timestamp |
---|
417 | |
---|
418 | try: |
---|
419 | decimal = '%f' % timestamp |
---|
420 | decimal = decimal.split('.')[1] |
---|
421 | except: |
---|
422 | decimal = '0' |
---|
423 | |
---|
424 | localtime = time.localtime(timestamp) |
---|
425 | |
---|
426 | if local_version: |
---|
427 | date = time.strftime('%x', localtime) |
---|
428 | localtime = time.strftime('%X', localtime) |
---|
429 | |
---|
430 | else: |
---|
431 | date = time.strftime('%Y-%m-%d', localtime) |
---|
432 | localtime = time.strftime('%H:%M:%S', localtime) |
---|
433 | localtime = '%s.%s %s' % (localtime, decimal, \ |
---|
434 | time.strftime('%Z', time.localtime(timestamp))) |
---|
435 | |
---|
436 | |
---|
437 | return(date, localtime) |
---|
438 | |
---|
439 | |
---|
440 | ################################################################## |
---|
441 | |
---|
442 | def processPacketThinkGear(self, packet): |
---|
443 | |
---|
444 | if self.DEBUG > 2: |
---|
445 | print packet |
---|
446 | |
---|
447 | |
---|
448 | if ('rawEeg' in packet.keys()): |
---|
449 | self.packets['rawEeg'].append(packet['rawEeg']) |
---|
450 | value = packet['rawEeg'] |
---|
451 | if MATPLOTLIB_AVAILABLE and \ |
---|
452 | (self.tabWidget.currentIndex() == \ |
---|
453 | self.tabWidget.indexOf(self.tabEEGSignals)): |
---|
454 | self.rawEEGMatplot.update_figure(value) |
---|
455 | else: |
---|
456 | self.packets['signals'].append(packet) |
---|
457 | |
---|
458 | |
---|
459 | if ('poorSignalLevel' in packet.keys()): |
---|
460 | value = 200 - packet['poorSignalLevel'] |
---|
461 | self.progressBarSignalContactQuality.setValue(value) |
---|
462 | self.textEditDebugConsole.append("") |
---|
463 | (date, localtime) = self.parseTimeStamp(packet['timestamp']) |
---|
464 | self.textEditDebugConsole.append("Timestamp: %s %s" % (date, localtime)) |
---|
465 | self.textEditDebugConsole.append("poorSignalLevel: %i" % \ |
---|
466 | packet['poorSignalLevel']) |
---|
467 | |
---|
468 | |
---|
469 | if ('eSense' in packet.keys()): |
---|
470 | |
---|
471 | if ('attention' in packet['eSense'].keys()): |
---|
472 | value = packet['eSense']['attention'] |
---|
473 | self.progressBarAttention.setValue(value) |
---|
474 | self.textEditDebugConsole.append("eSense attention: %i" % value) |
---|
475 | |
---|
476 | if ('meditation' in packet['eSense'].keys()): |
---|
477 | value = packet['eSense']['meditation'] |
---|
478 | self.progressBarMeditation.setValue(value) |
---|
479 | self.textEditDebugConsole.append("eSense meditation: %i" % value) |
---|
480 | |
---|
481 | |
---|
482 | if MATPLOTLIB_AVAILABLE: |
---|
483 | self.chartEEGMatplot.update_values('eSense', packet['eSense']) |
---|
484 | if (self.tabWidget.currentIndex() == \ |
---|
485 | self.tabWidget.indexOf(self.tabCharts)): |
---|
486 | self.chartEEGMatplot.update_figure('eSense', packet['eSense']) |
---|
487 | |
---|
488 | |
---|
489 | if ('eegPower' in packet.keys()): |
---|
490 | |
---|
491 | # If we are not emulating packets we'll set the maximum EEG Power value |
---|
492 | # threshold to the default (or maximum value found within this packet) |
---|
493 | if not self.thinkGearConnectServer.emulate_headset_data: |
---|
494 | self.maxEEGPower = THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE |
---|
495 | |
---|
496 | for value in packet['eegPower'].keys(): |
---|
497 | if packet['eegPower'][value] > self.maxEEGPower: |
---|
498 | self.maxEEGPower = packet['eegPower'][value] |
---|
499 | |
---|
500 | |
---|
501 | if ('delta' in packet['eegPower'].keys()): |
---|
502 | value = packet['eegPower']['delta'] |
---|
503 | self.progressBarEEGDelta.setMaximum(self.maxEEGPower) |
---|
504 | self.progressBarEEGDelta.setValue(value) |
---|
505 | self.textEditDebugConsole.append("delta: %i" % value) |
---|
506 | |
---|
507 | if ('theta' in packet['eegPower'].keys()): |
---|
508 | value = packet['eegPower']['theta'] |
---|
509 | self.progressBarEEGTheta.setMaximum(self.maxEEGPower) |
---|
510 | self.progressBarEEGTheta.setValue(value) |
---|
511 | self.textEditDebugConsole.append("theta: %i" % value) |
---|
512 | |
---|
513 | if ('lowAlpha' in packet['eegPower'].keys()): |
---|
514 | value = packet['eegPower']['lowAlpha'] |
---|
515 | self.progressBarEEGLowAlpha.setMaximum(self.maxEEGPower) |
---|
516 | self.progressBarEEGLowAlpha.setValue(value) |
---|
517 | self.textEditDebugConsole.append("lowAlpha: %i" % value) |
---|
518 | |
---|
519 | if ('highAlpha' in packet['eegPower'].keys()): |
---|
520 | value = packet['eegPower']['highAlpha'] |
---|
521 | self.progressBarEEGHighAlpha.setMaximum(self.maxEEGPower) |
---|
522 | self.progressBarEEGHighAlpha.setValue(value) |
---|
523 | self.textEditDebugConsole.append("highAlpha: %i" % value) |
---|
524 | |
---|
525 | if ('lowBeta' in packet['eegPower'].keys()): |
---|
526 | value = packet['eegPower']['lowBeta'] |
---|
527 | self.progressBarEEGLowBeta.setMaximum(self.maxEEGPower) |
---|
528 | self.progressBarEEGLowBeta.setValue(value) |
---|
529 | self.textEditDebugConsole.append("lowBeta: %i" % value) |
---|
530 | |
---|
531 | if ('highBeta' in packet['eegPower'].keys()): |
---|
532 | value = packet['eegPower']['highBeta'] |
---|
533 | self.progressBarEEGHighBeta.setMaximum(self.maxEEGPower) |
---|
534 | self.progressBarEEGHighBeta.setValue(value) |
---|
535 | self.textEditDebugConsole.append("highBeta: %i" % value) |
---|
536 | |
---|
537 | if ('lowGamma' in packet['eegPower'].keys()): |
---|
538 | value = packet['eegPower']['lowGamma'] |
---|
539 | self.progressBarEEGLowGamma.setMaximum(self.maxEEGPower) |
---|
540 | self.progressBarEEGLowGamma.setValue(value) |
---|
541 | self.textEditDebugConsole.append("lowGamma: %i" % value) |
---|
542 | |
---|
543 | if ('highGamma' in packet['eegPower'].keys()): |
---|
544 | value = packet['eegPower']['highGamma'] |
---|
545 | self.progressBarEEGMidGamma.setMaximum(self.maxEEGPower) |
---|
546 | self.progressBarEEGMidGamma.setValue(value) |
---|
547 | self.textEditDebugConsole.append("highGamma: %i" % value) |
---|
548 | |
---|
549 | |
---|
550 | if MATPLOTLIB_AVAILABLE: |
---|
551 | self.chartEEGMatplot.update_values('eegPower', packet['eegPower']) |
---|
552 | if (self.tabWidget.currentIndex() == \ |
---|
553 | self.tabWidget.indexOf(self.tabCharts)): |
---|
554 | self.chartEEGMatplot.update_figure('eegPower', packet['eegPower']) |
---|
555 | |
---|
556 | |
---|
557 | if ((self.thinkGearConnectServer.protocol != None) and |
---|
558 | (self.tabWidget.currentIndex() == \ |
---|
559 | self.tabWidget.indexOf(self.tabControlPanel))): |
---|
560 | |
---|
561 | self.updateProfileSessionStatus() |
---|
562 | |
---|
563 | |
---|
564 | ################################################################## |
---|
565 | |
---|
566 | def updateProfileSessionStatus(self): |
---|
567 | |
---|
568 | session_time = self.calculateSessionTime() |
---|
569 | |
---|
570 | self.textLabelSessionTime.setText(session_time) |
---|
571 | |
---|
572 | self.textLabelPacketsReceived.setText( "%i" % \ |
---|
573 | self.thinkGearConnectServer.protocol.packet_count) |
---|
574 | self.textLabelPacketsDropped.setText( "%i" % \ |
---|
575 | self.thinkGearConnectServer.protocol.bad_packets) |
---|
576 | |
---|
577 | |
---|
578 | ################################################################## |
---|
579 | |
---|
580 | def calculateSessionTime(self): |
---|
581 | |
---|
582 | session_time = time.time() - \ |
---|
583 | self.thinkGearConnectServer.protocol.session_start_timestamp |
---|
584 | |
---|
585 | session_time = int(session_time) |
---|
586 | |
---|
587 | session_time = self.convert_seconds_to_datetime(session_time) |
---|
588 | |
---|
589 | return(session_time) |
---|
590 | |
---|
591 | |
---|
592 | ################################################################## |
---|
593 | |
---|
594 | def enumerateSerialPorts(self): |
---|
595 | |
---|
596 | """ Uses the Win32 registry to return an |
---|
597 | iterator of serial (COM) ports |
---|
598 | existing on this computer. |
---|
599 | |
---|
600 | from http://eli.thegreenplace.net/2009/07/31/listing-all-serial-ports-on-windows-with-python/ |
---|
601 | """ |
---|
602 | |
---|
603 | path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' |
---|
604 | try: |
---|
605 | key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) |
---|
606 | except WindowsError: |
---|
607 | #raise IterationError |
---|
608 | return |
---|
609 | |
---|
610 | for i in itertools.count(): |
---|
611 | try: |
---|
612 | val = winreg.EnumValue(key, i) |
---|
613 | yield str(val[1]) |
---|
614 | except EnvironmentError: |
---|
615 | break |
---|
616 | |
---|
617 | |
---|
618 | ################################################################## |
---|
619 | |
---|
620 | def fullPortName(self, portname): |
---|
621 | |
---|
622 | """ Given a port-name (of the form COM7, |
---|
623 | COM12, CNCA0, etc.) returns a full |
---|
624 | name suitable for opening with the |
---|
625 | Serial class. |
---|
626 | """ |
---|
627 | |
---|
628 | m = re.match('^COM(\d+)$', portname) |
---|
629 | if m and int(m.group(1)) < 10: |
---|
630 | return portname |
---|
631 | |
---|
632 | return '\\\\.\\' + portname |
---|
633 | |
---|
634 | |
---|
635 | ################################################################## |
---|
636 | |
---|
637 | def searchForThinkGearDevices(self): |
---|
638 | |
---|
639 | #self.pushButtonBluetoothSearch.setText('Searching') |
---|
640 | |
---|
641 | mindset_devices = [] |
---|
642 | |
---|
643 | if (sys.platform == 'win32'): |
---|
644 | |
---|
645 | for portname in self.enumerateSerialPorts(): |
---|
646 | |
---|
647 | if portname not in mindset_devices: |
---|
648 | #portname = self.fullPortName(portname) |
---|
649 | mindset_devices.append(portname) |
---|
650 | |
---|
651 | |
---|
652 | else: |
---|
653 | |
---|
654 | # Bluetooth module doesn't compile properly under Windows |
---|
655 | |
---|
656 | bluetooth_devices = [] |
---|
657 | |
---|
658 | #bluetooth_devices = bluetooth.discover_devices( \ |
---|
659 | #duration=5, \ |
---|
660 | #flush_cache=True, \ |
---|
661 | #lookup_names=True) |
---|
662 | |
---|
663 | command = '%s con' % PATH_TO_HCITOOL |
---|
664 | |
---|
665 | output = os.popen(command, 'r') |
---|
666 | |
---|
667 | for line in output.readlines(): |
---|
668 | try: |
---|
669 | address = line.split(' ')[2] |
---|
670 | except: |
---|
671 | pass |
---|
672 | else: |
---|
673 | bluetooth_devices.append(address) |
---|
674 | |
---|
675 | for address in bluetooth_devices: |
---|
676 | device_name = bluetooth.lookup_name(address) |
---|
677 | if ((device_name == 'MindSet') and \ |
---|
678 | (address not in mindset_devices)): |
---|
679 | mindset_devices.append(address) |
---|
680 | |
---|
681 | |
---|
682 | if self.DEBUG: |
---|
683 | print "Bluetooth MindSet devices found:", |
---|
684 | print mindset_devices |
---|
685 | |
---|
686 | |
---|
687 | self.comboBoxDeviceSelect.clear() |
---|
688 | |
---|
689 | self.comboBoxDeviceSelect.addItem('MindSet Emulator') |
---|
690 | |
---|
691 | |
---|
692 | for mindset_device in mindset_devices: |
---|
693 | self.comboBoxDeviceSelect.addItem(mindset_device) |
---|
694 | |
---|
695 | |
---|
696 | #self.pushButtonBluetoothSearch.setText('Search') |
---|
697 | |
---|
698 | |
---|
699 | ################################################################## |
---|
700 | |
---|
701 | def collectData(self): |
---|
702 | |
---|
703 | data = {} |
---|
704 | |
---|
705 | data['rawEeg'] = self.packets['rawEeg'] |
---|
706 | data['signals'] = self.packets['signals'] |
---|
707 | |
---|
708 | data['sessionTime'] = self.calculateSessionTime() |
---|
709 | |
---|
710 | data['profileName'] = str(self.lineEditSessionProfile.text()) |
---|
711 | |
---|
712 | return(data) |
---|
713 | |
---|
714 | |
---|
715 | ################################################################## |
---|
716 | |
---|
717 | def saveData(self): |
---|
718 | |
---|
719 | data = self.collectData() |
---|
720 | |
---|
721 | #output_file = 'data.synapse' |
---|
722 | |
---|
723 | output_file = QtGui.QFileDialog.getSaveFileName(self, \ |
---|
724 | "Save Synapse Data File", \ |
---|
725 | "", \ |
---|
726 | "Synapse Data File (*.synapse)") |
---|
727 | |
---|
728 | |
---|
729 | file = open(output_file, 'w') |
---|
730 | pickle.dump(data, file) |
---|
731 | file.close() |
---|
732 | |
---|
733 | |
---|
734 | ################################################################## |
---|
735 | |
---|
736 | def exportData(self): |
---|
737 | |
---|
738 | #output_file = 'text.synapse' |
---|
739 | |
---|
740 | (date, localtime) = self.parseTimeStamp(time.time()) |
---|
741 | |
---|
742 | default_filename = '%s %s.csv' % (date, \ |
---|
743 | self.lineEditSessionProfile.text()) |
---|
744 | |
---|
745 | output_file = QtGui.QFileDialog.getSaveFileName(self, \ |
---|
746 | "Export Synapse Data to File", \ |
---|
747 | default_filename, \ |
---|
748 | "CSV File (*.csv);;Text File (*.txt)") |
---|
749 | |
---|
750 | print output_file |
---|
751 | |
---|
752 | if str(output_file).endswith('.csv'): |
---|
753 | |
---|
754 | outputData = self.exportDataToCSV() |
---|
755 | |
---|
756 | |
---|
757 | else: |
---|
758 | |
---|
759 | outputData = self.textEditDebugConsole.toPlainText() |
---|
760 | |
---|
761 | |
---|
762 | file = open(output_file, 'w') |
---|
763 | file.write(outputData) |
---|
764 | file.close() |
---|
765 | |
---|
766 | |
---|
767 | ################################################################## |
---|
768 | |
---|
769 | def exportDataToCSV(self): |
---|
770 | |
---|
771 | header = 'Date,Time,Delta,Theta,Low Alpha,High Alpha,Low Beta,High Beta,Low Gamma,Mid Gamma,Attention,Meditation,Signal Level\n' |
---|
772 | |
---|
773 | csv = {} |
---|
774 | |
---|
775 | for packet in self.packets['signals']: |
---|
776 | |
---|
777 | if 'rawEeg' in packet.keys(): |
---|
778 | continue |
---|
779 | |
---|
780 | if packet['timestamp'] not in csv.keys(): |
---|
781 | |
---|
782 | print packet |
---|
783 | timestamp = packet['timestamp'] |
---|
784 | (date, localtime) = self.parseTimeStamp(timestamp) |
---|
785 | |
---|
786 | csv[timestamp] = {} |
---|
787 | csv[timestamp]['Date'] = date |
---|
788 | csv[timestamp]['Time'] = localtime |
---|
789 | csv[timestamp]['Delta'] = '' |
---|
790 | csv[timestamp]['Theta'] = '' |
---|
791 | csv[timestamp]['Low Alpha'] = '' |
---|
792 | csv[timestamp]['High Alpha'] = '' |
---|
793 | csv[timestamp]['Low Beta'] = '' |
---|
794 | csv[timestamp]['High Beta'] = '' |
---|
795 | csv[timestamp]['Low Gamma'] = '' |
---|
796 | csv[timestamp]['Mid Gamma'] = '' |
---|
797 | csv[timestamp]['Attention'] = '' |
---|
798 | csv[timestamp]['Meditation'] = '' |
---|
799 | csv[timestamp]['Signal Level'] = '' |
---|
800 | |
---|
801 | |
---|
802 | if 'eSense' in packet.keys(): |
---|
803 | if 'attention' in packet['eSense'].keys(): |
---|
804 | csv[timestamp]['Attention'] = packet['eSense']['attention'] |
---|
805 | if 'meditation' in packet['eSense'].keys(): |
---|
806 | csv[timestamp]['Meditation'] = packet['eSense']['meditation'] |
---|
807 | |
---|
808 | if 'eegPower' in packet.keys(): |
---|
809 | if 'delta' in packet['eegPower'].keys(): |
---|
810 | csv[timestamp]['Delta'] = packet['eegPower']['delta'] |
---|
811 | if 'theta' in packet['eegPower'].keys(): |
---|
812 | csv[timestamp]['Theta'] = packet['eegPower']['theta'] |
---|
813 | if 'lowAlpha' in packet['eegPower'].keys(): |
---|
814 | csv[timestamp]['Low Alpha'] = packet['eegPower']['lowAlpha'] |
---|
815 | if 'highAlpha' in packet['eegPower'].keys(): |
---|
816 | csv[timestamp]['High Alpha'] = packet['eegPower']['highAlpha'] |
---|
817 | if 'lowBeta' in packet['eegPower'].keys(): |
---|
818 | csv[timestamp]['Low Beta'] = packet['eegPower']['lowBeta'] |
---|
819 | if 'highBeta' in packet['eegPower'].keys(): |
---|
820 | csv[timestamp]['High Beta'] = packet['eegPower']['highBeta'] |
---|
821 | if 'lowGamma' in packet['eegPower'].keys(): |
---|
822 | csv[timestamp]['Low Gamma'] = packet['eegPower']['lowGamma'] |
---|
823 | if 'highGamma' in packet['eegPower'].keys(): |
---|
824 | csv[timestamp]['Mid Gamma'] = packet['eegPower']['highGamma'] |
---|
825 | |
---|
826 | if 'poorSignalLevel' in packet.keys(): |
---|
827 | csv[timestamp]['Signal Level'] = packet['poorSignalLevel'] |
---|
828 | |
---|
829 | |
---|
830 | output = header |
---|
831 | |
---|
832 | csv_keys = csv.keys() |
---|
833 | csv_keys.sort() |
---|
834 | |
---|
835 | for key in csv_keys: |
---|
836 | |
---|
837 | row = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % \ |
---|
838 | (csv[key]['Date'], \ |
---|
839 | csv[key]['Time'], \ |
---|
840 | csv[key]['Delta'], \ |
---|
841 | csv[key]['Theta'], \ |
---|
842 | csv[key]['Low Alpha'], \ |
---|
843 | csv[key]['High Alpha'], \ |
---|
844 | csv[key]['Low Beta'], \ |
---|
845 | csv[key]['High Beta'], \ |
---|
846 | csv[key]['Low Gamma'], \ |
---|
847 | csv[key]['Mid Gamma'], \ |
---|
848 | csv[key]['Attention'], \ |
---|
849 | csv[key]['Meditation'], \ |
---|
850 | csv[key]['Signal Level']) |
---|
851 | |
---|
852 | |
---|
853 | output = output + row |
---|
854 | |
---|
855 | |
---|
856 | return(output) |
---|
857 | |
---|
858 | |
---|
859 | ################################################################## |
---|
860 | |
---|
861 | def resetData(self): |
---|
862 | |
---|
863 | self.packets['rawEeg'] = [] |
---|
864 | self.packets['signals'] = [] |
---|
865 | |
---|
866 | self.thinkGearConnectServer.protocol.session_start_timestamp = \ |
---|
867 | time.time() |
---|
868 | |
---|
869 | self.thinkGearConnectServer.protocol.packet_count = 0 |
---|
870 | self.thinkGearConnectServer.protocol.bad_packets = 0 |
---|
871 | |
---|
872 | self.updateProfileSessionStatus() |
---|
873 | |
---|
874 | self.textEditDebugConsole.setText("") |
---|
875 | |
---|
876 | |
---|
877 | ##################################################################### |
---|
878 | |
---|
879 | def convert_seconds_to_datetime(self, duration): |
---|
880 | |
---|
881 | duration_hours = duration / (60 * 60) |
---|
882 | duration_minutes = (duration - (duration_hours * (60 * 60))) / 60 |
---|
883 | duration_seconds = (duration - (duration_hours * (60 * 60)) - (duration_minutes * 60)) |
---|
884 | |
---|
885 | duration_hours = '%i' % duration_hours |
---|
886 | if (len(duration_hours) == 1): |
---|
887 | duration_hours = "0%s" % duration_hours |
---|
888 | |
---|
889 | duration_minutes = '%i' % duration_minutes |
---|
890 | if (len(duration_minutes) == 1): |
---|
891 | duration_minutes = "0%s" % duration_minutes |
---|
892 | |
---|
893 | duration_seconds = '%i' % duration_seconds |
---|
894 | if (len(duration_seconds) == 1): |
---|
895 | duration_seconds = "0%s" % duration_seconds |
---|
896 | |
---|
897 | datetime = '%s:%s:%s' % (duration_hours, duration_minutes, duration_seconds) |
---|
898 | |
---|
899 | return(datetime) |
---|
900 | |
---|
901 | |
---|
902 | ################################################################## |
---|
903 | |
---|
904 | def closeEvent(self, event): |
---|
905 | |
---|
906 | quit_message = "Are you sure you want to exit the program?" |
---|
907 | |
---|
908 | reply = QtGui.QMessageBox.question( \ |
---|
909 | self, \ |
---|
910 | 'Message', \ |
---|
911 | quit_message, \ |
---|
912 | QtGui.QMessageBox.Yes, \ |
---|
913 | QtGui.QMessageBox.No) |
---|
914 | |
---|
915 | if reply == QtGui.QMessageBox.Yes: |
---|
916 | |
---|
917 | if UPDATE_INTERFACE_VIA_TIMER: |
---|
918 | self.updateInterfaceTimer.stop() |
---|
919 | else: |
---|
920 | if self.thinkgearConnectClient != None: |
---|
921 | self.thinkgearConnectClient.disconnectFromHost() |
---|
922 | |
---|
923 | if self.thinkGearConnectServer != None: |
---|
924 | self.thinkGearConnectServer.exitThread() |
---|
925 | |
---|
926 | event.accept() |
---|
927 | |
---|
928 | else: |
---|
929 | event.ignore() |
---|