Changeset 362
- Timestamp:
- 03/30/12 16:13:16 (9 years ago)
- Location:
- trunk/Puzzlebox/Synapse
- Files:
-
- 6 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/Puzzlebox/Synapse/Configuration.py
r357 r362 91 91 ##################################################################### 92 92 93 SYNAPSE_SERVER_INTERFACE = '' # listen on all of server's network interfaces 94 SYNAPSE_SERVER_HOST = '*' 95 SYNAPSE_SERVER_PORT = 13854 96 93 97 THINKGEAR_SERVER_INTERFACE = '' # listen on all of server's network interfaces 94 98 #THINKGEAR_SERVER_HOST = '127.0.0.1' … … 117 121 # THINKGEAR_DEVICE_BLUETOOTH_ADDRESS = '00:13:EF:xx:xx:xx' # Linux example 118 122 119 THINKGEAR_DEVICE_ID = None123 #THINKGEAR_DEVICE_ID = None 120 124 121 125 # Timeouts sent to PyBluez … … 133 137 CLIENT_NO_REPLY_WAIT = 5 # how many seconds before considering a component dead 134 138 139 SYNAPSE_DELIMITER = '\r' 135 140 136 141 ##################################################################### -
trunk/Puzzlebox/Synapse/Interface.py
r358 r362 16 16 ### IMPORTS ### 17 17 import os, sys, time 18 #import simplejson as json 19 20 21 import Configuration as configuration 18 19 import Puzzlebox.Synapse.Configuration as configuration 22 20 23 21 if configuration.ENABLE_PYSIDE: … … 64 62 import pickle 65 63 66 # from puzzlebox_synapse_interface_design import Ui_Form67 64 from Interface_Design import Ui_Form as Design 68 65 69 #try: 70 #import Emotiv.Protocol as emotiv_protocol 71 #except: 72 #emotiv_protocol = None 73 74 #import Configuration as configuration 75 import Puzzlebox.Synapse.ThinkGear.Server as synapse_server 66 import Puzzlebox.Synapse.Server as synapse_server 76 67 import Puzzlebox.Synapse.ThinkGear.Client as thinkgear_client 77 68 import Puzzlebox.Synapse.Emotiv.Client as emotiv_client … … 85 76 DEBUG = configuration.DEBUG 86 77 87 THINKGEAR_SERVER_HOST = configuration.THINKGEAR_SERVER_HOST88 THINKGEAR_SERVER_PORT = configuration.THINKGEAR_SERVER_PORT89 90 THINKGEAR_EEG_POWER_BAND_ORDER = configuration.THINKGEAR_EEG_POWER_BAND_ORDER78 SYNAPSE_SERVER_HOST = configuration.SYNAPSE_SERVER_HOST 79 SYNAPSE_SERVER_PORT = configuration.SYNAPSE_SERVER_PORT 80 81 #THINKGEAR_EEG_POWER_BAND_ORDER = configuration.THINKGEAR_EEG_POWER_BAND_ORDER 91 82 92 83 THINKGEAR_EMULATION_MAX_ESENSE_VALUE = \ … … 224 215 225 216 # Display Host for ThinkGear Connect Socket Server 226 self.lineEditSynapseHost.setText( THINKGEAR_SERVER_HOST)217 self.lineEditSynapseHost.setText(SYNAPSE_SERVER_HOST) 227 218 228 219 # Display Port for ThinkGear Connect Socket Server 229 self.lineEditSynapsePort.setText('%i' % THINKGEAR_SERVER_PORT)220 self.lineEditSynapsePort.setText('%i' % SYNAPSE_SERVER_PORT) 230 221 231 222 … … 314 305 315 306 self.synapseServer = \ 316 synapse_server. ThinkgearServer( \307 synapse_server.puzzlebox_synapse_server( \ 317 308 self.log, \ 318 309 server_interface=server_interface, \ 319 310 server_port=server_port, \ 311 device_model=eeg_headset_model, \ 320 312 device_address=device_address, \ 321 device_model=None, \313 #device_model=None, \ 322 314 emulate_headset_data=emulate_headset_data, \ 323 315 DEBUG=DEBUG, \ … … 836 828 837 829 838 if ((self.synapseServer.protocol != None) and839 840 self.tabWidget.indexOf(self.tabControlPanel))):830 #if ((self.synapseServer.protocol != None) and 831 if (self.tabWidget.currentIndex() == \ 832 self.tabWidget.indexOf(self.tabControlPanel)): 841 833 842 834 self.updateProfileSessionStatus() … … 847 839 def processPacketEmotiv(self, packet): 848 840 849 print 850 print "Booyah" 851 print 852 print packet 853 print 854 print 841 if self.DEBUG: 842 print "INFO [Synapse:Interface] Emotiv packet received:" 843 print packet 855 844 856 845 -
trunk/Puzzlebox/Synapse/Server.py
r329 r362 6 6 # For more information please refer to http://www.gnu.org/copyleft/gpl.html 7 7 8 # Old Class Name = puzzle_synapse_server_thinkgear9 10 8 __changelog__ = """\ 11 Last Update: 2012.03. 219 Last Update: 2012.03.30 12 10 """ 13 11 … … 15 13 16 14 import os, sys, time 17 import signal18 import math15 #import signal 16 #import math 19 17 20 18 import simplejson as json 21 19 22 import Configuration as configuration20 import Puzzlebox.Synapse.Configuration as configuration 23 21 24 22 if configuration.ENABLE_PYSIDE: … … 37 35 from PyQt4 import QtCore, QtGui, QtNetwork 38 36 39 40 #try: 41 #import PySide as PyQt4 42 #from PySide import QtCore, QtGui, QtNetwork 43 #except: 44 #print "Using PyQt4 module" 45 #from PyQt4 import QtCore, QtGui, QtNetwork 46 #else: 47 #print "Using PySide module" 48 49 ##from PyQt4 import QtNetwork 50 51 #import Configuration as configuration 52 import Protocol as serial_interface 53 54 ### GLOBALS ### 37 import Puzzlebox.Synapse.ThinkGear.Server as thinkgear_server 38 39 #import Protocol as thinkgear_protocol 40 41 ##################################################################### 42 # Globals 43 ##################################################################### 55 44 56 45 DEBUG = configuration.DEBUG … … 59 48 #COMMUNICATION_MODE = 'Call Parent' 60 49 61 SERVER_INTERFACE = configuration.THINKGEAR_SERVER_INTERFACE 62 SERVER_PORT = configuration.THINKGEAR_SERVER_PORT 50 SERVER_INTERFACE = configuration.SYNAPSE_SERVER_INTERFACE 51 SERVER_PORT = configuration.SYNAPSE_SERVER_PORT 52 DEFAULT_DEVICE_MODEL = 'NeuroSky MindWave' 63 53 THINKGEAR_DEVICE_SERIAL_PORT = configuration.THINKGEAR_DEVICE_SERIAL_PORT 64 THINKGEAR_DEVICE_ID = configuration.THINKGEAR_DEVICE_ID54 #THINKGEAR_DEVICE_ID = configuration.THINKGEAR_DEVICE_ID 65 55 66 56 CLIENT_NO_REPLY_WAIT = configuration.CLIENT_NO_REPLY_WAIT * 1000 … … 69 59 FLASH_SOCKET_POLICY_FILE = configuration.FLASH_SOCKET_POLICY_FILE 70 60 71 DELIMITER = configuration. THINKGEAR_DELIMITER61 DELIMITER = configuration.SYNAPSE_DELIMITER 72 62 73 63 MESSAGE_FREQUENCY_TIMER = 1 * 1000 # 1 Hz (1000 ms) … … 75 65 ENABLE_SIMULATE_HEADSET_DATA = configuration.THINKGEAR_ENABLE_SIMULATE_HEADSET_DATA 76 66 77 BLINK_FREQUENCY_TIMER = configuration.THINKGEAR_BLINK_FREQUENCY_TIMER78 79 DEFAULT_SAMPLE_WAVELENGTH = configuration.THINKGEAR_DEFAULT_SAMPLE_WAVELENGTH80 81 THINKGEAR_EMULATION_MAX_ESENSE_VALUE = \82 configuration.THINKGEAR_EMULATION_MAX_ESENSE_VALUE83 THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE = \84 configuration.THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE85 86 THINKGEAR_ATTENTION_MULTIPLIER = configuration.THINKGEAR_ATTENTION_MULTIPLIER87 THINKGEAR_MEDITATION_MULTIPLIER = configuration.THINKGEAR_MEDITATION_MULTIPLIER88 89 THINKGEAR_EEG_POWER_MULTIPLIERS = configuration.THINKGEAR_EEG_POWER_MULTIPLIERS90 91 DEFAULT_AUTHORIZATION_MESSAGE = \92 {"isAuthorized": True}93 # Tells the client whether the server has authorized94 # access to the user's headset data. The value is95 # either true or false.96 97 DEFAULT_SIGNAL_LEVEL_MESSAGE = \98 {"poorSignalLevel": 0}99 # A quantifier of the quality of the brainwave signal.100 # This is an integer value that is generally in the101 # range of 0 to 200, with 0 indicating a102 # good signal and 200 indicating an off-head state.103 104 DEFAULT_EEG_POWER_MESSAGE = \105 {"eegPower": { \106 'delta': 0, \107 'theta': 0, \108 'lowAlpha': 0, \109 'highAlpha': 0, \110 'lowBeta': 0, \111 'highBeta': 0, \112 'lowGamma': 0, \113 'highGamma': 0, \114 }, \115 } # A container for the EEG powers. These may116 # be either integer or floating-point values.117 # Maximum values are undocumented but assumed to be 65535118 119 DEFAULT_ESENSE_MESSAGE = \120 {"eSense": { \121 'attention': 0, \122 'meditation': 0, \123 }, \124 } # A container for the eSense⢠attributes.125 # These are integer values between 0 and 100,126 # where 0 is perceived as a lack of that attribute127 # and 100 is an excess of that attribute.128 129 DEFAULT_BLINK_MESSAGE = {"blinkStrength": 255}130 # The strength of a detected blink. This is131 # an integer in the range of 0-255.132 133 DEFAULT_RAWEEG_MESSAGE = {"rawEeg": 255}134 # The raw data reading off the forehead sensor.135 # This may be either an integer or a floating-point value.67 #BLINK_FREQUENCY_TIMER = configuration.THINKGEAR_BLINK_FREQUENCY_TIMER 68 69 #DEFAULT_SAMPLE_WAVELENGTH = configuration.THINKGEAR_DEFAULT_SAMPLE_WAVELENGTH 70 71 #THINKGEAR_EMULATION_MAX_ESENSE_VALUE = \ 72 #configuration.THINKGEAR_EMULATION_MAX_ESENSE_VALUE 73 #THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE = \ 74 #configuration.THINKGEAR_EMULATION_MAX_EEG_POWER_VALUE 75 76 #THINKGEAR_ATTENTION_MULTIPLIER = configuration.THINKGEAR_ATTENTION_MULTIPLIER 77 #THINKGEAR_MEDITATION_MULTIPLIER = configuration.THINKGEAR_MEDITATION_MULTIPLIER 78 79 #THINKGEAR_EEG_POWER_MULTIPLIERS = configuration.THINKGEAR_EEG_POWER_MULTIPLIERS 80 81 #DEFAULT_AUTHORIZATION_MESSAGE = \ 82 #{"isAuthorized": True} 83 ## Tells the client whether the server has authorized 84 ## access to the user's headset data. The value is 85 ## either true or false. 86 87 #DEFAULT_SIGNAL_LEVEL_MESSAGE = \ 88 #{"poorSignalLevel": 0} 89 ## A quantifier of the quality of the brainwave signal. 90 ## This is an integer value that is generally in the 91 ## range of 0 to 200, with 0 indicating a 92 ## good signal and 200 indicating an off-head state. 93 94 #DEFAULT_EEG_POWER_MESSAGE = \ 95 #{"eegPower": { \ 96 #'delta': 0, \ 97 #'theta': 0, \ 98 #'lowAlpha': 0, \ 99 #'highAlpha': 0, \ 100 #'lowBeta': 0, \ 101 #'highBeta': 0, \ 102 #'lowGamma': 0, \ 103 #'highGamma': 0, \ 104 #}, \ 105 #} # A container for the EEG powers. These may 106 ## be either integer or floating-point values. 107 ## Maximum values are undocumented but assumed to be 65535 108 109 #DEFAULT_ESENSE_MESSAGE = \ 110 #{"eSense": { \ 111 #'attention': 0, \ 112 #'meditation': 0, \ 113 #}, \ 114 #} # A container for the eSense⢠attributes. 115 ## These are integer values between 0 and 100, 116 ## where 0 is perceived as a lack of that attribute 117 ## and 100 is an excess of that attribute. 118 119 #DEFAULT_BLINK_MESSAGE = {"blinkStrength": 255} 120 ## The strength of a detected blink. This is 121 ## an integer in the range of 0-255. 122 123 #DEFAULT_RAWEEG_MESSAGE = {"rawEeg": 255} 124 ## The raw data reading off the forehead sensor. 125 ## This may be either an integer or a floating-point value. 136 126 137 127 DEFAULT_PACKET = {} 138 DEFAULT_PACKET.update(DEFAULT_EEG_POWER_MESSAGE) 139 DEFAULT_PACKET.update(DEFAULT_SIGNAL_LEVEL_MESSAGE) 140 DEFAULT_PACKET.update(DEFAULT_ESENSE_MESSAGE) 141 142 DEFAULT_RESPONSE_MESSAGE = DEFAULT_SIGNAL_LEVEL_MESSAGE 143 144 ### CLASS MODULE ### 145 146 class ThinkgearServer(QtCore.QThread): 128 #DEFAULT_PACKET.update(DEFAULT_EEG_POWER_MESSAGE) 129 #DEFAULT_PACKET.update(DEFAULT_SIGNAL_LEVEL_MESSAGE) 130 #DEFAULT_PACKET.update(DEFAULT_ESENSE_MESSAGE) 131 132 #DEFAULT_RESPONSE_MESSAGE = DEFAULT_SIGNAL_LEVEL_MESSAGE 133 DEFAULT_RESPONSE_MESSAGE = DEFAULT_PACKET 134 135 ##################################################################### 136 # Classes 137 ##################################################################### 138 139 class puzzlebox_synapse_server(QtCore.QThread): 147 140 148 141 def __init__(self, log, \ 149 142 server_interface=SERVER_INTERFACE, \ 150 143 server_port=SERVER_PORT, \ 144 device_model=DEFAULT_DEVICE_MODEL, \ 151 145 device_address=THINKGEAR_DEVICE_SERIAL_PORT, \ 152 device_id=THINKGEAR_DEVICE_ID, \153 device_model=None, \154 146 emulate_headset_data=ENABLE_SIMULATE_HEADSET_DATA, \ 155 147 DEBUG=DEBUG, \ … … 165 157 self.server_port = server_port 166 158 self.device_address = device_address 167 self.device_id = device_id159 #self.device_id = device_id 168 160 self.device_model = device_model 169 161 self.emulate_headset_data = emulate_headset_data 170 162 171 self.message_frequency_timer = MESSAGE_FREQUENCY_TIMER172 self.blink_frequency_timer = BLINK_FREQUENCY_TIMER163 #self.message_frequency_timer = MESSAGE_FREQUENCY_TIMER 164 #self.blink_frequency_timer = BLINK_FREQUENCY_TIMER 173 165 174 166 self.connection_timestamp = time.time() 175 self.blink_timestamp = time.time()167 #self.blink_timestamp = time.time() 176 168 177 169 self.connections = [] 178 170 self.packet_queue = [] 179 171 180 self.serial_device = None181 self.protocol = None172 #self.serial_device = None 173 #self.protocol = None 182 174 183 175 self.connect(self, \ … … 185 177 self.sendPacketQueue) 186 178 179 self.protocolServers = [] 180 187 181 self.configureEEG() 188 182 … … 190 184 191 185 192 if (self.emulate_headset_data):193 self.emulationTimer = QtCore.QTimer()194 QtCore.QObject.connect(self.emulationTimer, \195 QtCore.SIGNAL("timeout()"), \196 self.emulationEvent)197 self.emulationTimer.start(MESSAGE_FREQUENCY_TIMER)186 #if (self.emulate_headset_data): 187 #self.emulationTimer = QtCore.QTimer() 188 #QtCore.QObject.connect(self.emulationTimer, \ 189 #QtCore.SIGNAL("timeout()"), \ 190 #self.emulationEvent) 191 #self.emulationTimer.start(MESSAGE_FREQUENCY_TIMER) 198 192 199 193 … … 202 196 def configureEEG(self): 203 197 204 if not self.emulate_headset_data: 205 206 self.serial_device = \ 207 serial_interface.SerialDevice( \ 198 print self.device_model 199 200 if (self.device_model == 'NeuroSky MindWave' or \ 201 self.device_model == 'NeuroSky MindSet'): 202 203 self.thinkgearServer = \ 204 thinkgear_server.puzzlebox_synapse_server_thinkgear( \ 208 205 self.log, \ 206 #server_interface=server_interface, \ 207 #server_port=server_port, \ 208 device_model=self.device_model, \ 209 209 device_address=self.device_address, \ 210 DEBUG=self.DEBUG, \ 210 #device_model=None, \ 211 emulate_headset_data=self.emulate_headset_data, \ 212 DEBUG=DEBUG, \ 211 213 parent=self) 212 214 213 self.serial_device.start() 214 215 else: 216 self.serial_device = None 217 218 219 self.protocol = \ 220 serial_interface.ProtocolHandler( \ 221 self.log, \ 222 self.serial_device, \ 223 device_id=self.device_id, \ 224 device_model=self.device_model, \ 225 DEBUG=self.DEBUG, \ 226 parent=self) 227 228 self.protocol.start() 229 230 231 ################################################################## 232 233 def emulationEvent(self): 234 235 self.updateStatus() 236 237 if COMMUNICATION_MODE == 'Emit Signal': 238 self.emitSendPacketSignal() 239 else: 240 self.sendPacketQueue() 215 self.connect(self.thinkgearServer, \ 216 QtCore.SIGNAL("sendPacket()"), \ 217 self.sendPacketQueue) 218 219 self.thinkgearServer.start() 220 221 self.protocolServers.append(self.thinkgearServer) 222 223 224 ################################################################## 225 226 #def emulationEvent(self): 227 228 #self.updateStatus() 229 230 #if COMMUNICATION_MODE == 'Emit Signal': 231 #self.emitSendPacketSignal() 232 #else: 233 #self.sendPacketQueue() 241 234 242 235 … … 366 359 367 360 if self.DEBUG: 368 print "--> [ ThinkGear Emulator] Partial data received (or error:",361 print "--> [%s] Partial data received (or error:" % self.socket.name, 369 362 print e 370 363 print ")." … … 426 419 def sendPacketQueue(self): 427 420 421 print "send" 422 428 423 #if self.DEBUG: 429 424 #print "sendPacketQueue called" … … 461 456 462 457 463 elif (type(data) == type({}) and \ 464 data.has_key('appName') and \ 465 data.has_key('appKey')): 466 authorized = self.authorizeClient(data) 467 468 response = {} 469 response['isAuthorized'] = authorized 470 471 #self.packet_queue.insert(0, response) 458 else: 459 460 for server in self.protocolServers: 461 462 # Accept the first valid response received 463 if response == None: 464 response = server.processData(data) 472 465 473 466 … … 477 470 ################################################################## 478 471 479 def validateChecksum(self, checksum): 480 481 '''The key used by the client application to identify 482 itself. This must be 40 hexadecimal characters, ideally generated 483 using an SHA-1 digest. The appKey is an identifier that is unique 484 to each application, rather than each instance of an application. 485 It is used by the server to bypass the authorization process if a 486 user had previously authorized the requesting client. To reduce 487 the chance of overlap with the appKey of other applications, 488 the appKey should be generated using an SHA-1 digest.''' 489 490 is_valid = True 491 492 hexadecimal_characters = '0123456789abcdef' 493 494 if len(checksum) != 40: 495 is_valid = False 496 else: 497 for character in checksum: 498 if character not in hexadecimal_characters: 499 is_valid = False 500 501 return(is_valid) 502 503 504 ################################################################## 505 506 def authorizeClient(self, data): 507 508 '''The client must initiate an authorization request 509 and the server must authorize the client before the 510 server will start transmitting any headset data.''' 511 512 is_authorized = self.validateChecksum(data['appKey']) 513 514 # A human-readable name identifying the client 515 # application. This can be a maximum of 255 characters. 516 517 if len(data['appName']) > 255: 518 is_authorized = False 519 520 521 return(is_authorized) 522 523 524 ################################################################## 525 526 def calculateWavePoint(self, x, max_height=100, wave_length=10): 527 528 # start at 0, increase to max value at half of one 529 # wavelength, decrease to 0 by end of wavelength 530 y = ( (max_height/2) * \ 531 math.sin ((x-1) * ( math.pi / (wave_length / 2)))) + \ 532 (max_height/2) 533 534 # start at max value, decrease to 0 at half of one 535 # wavelegnth, increase to max by end of wavelength 472 #def validateChecksum(self, checksum): 473 474 #'''The key used by the client application to identify 475 #itself. This must be 40 hexadecimal characters, ideally generated 476 #using an SHA-1 digest. The appKey is an identifier that is unique 477 #to each application, rather than each instance of an application. 478 #It is used by the server to bypass the authorization process if a 479 #user had previously authorized the requesting client. To reduce 480 #the chance of overlap with the appKey of other applications, 481 #the appKey should be generated using an SHA-1 digest.''' 482 483 #is_valid = True 484 485 #hexadecimal_characters = '0123456789abcdef' 486 487 #if len(checksum) != 40: 488 #is_valid = False 489 #else: 490 #for character in checksum: 491 #if character not in hexadecimal_characters: 492 #is_valid = False 493 494 #return(is_valid) 495 496 497 ################################################################## 498 499 #def authorizeClient(self, data): 500 501 #'''The client must initiate an authorization request 502 #and the server must authorize the client before the 503 #server will start transmitting any headset data.''' 504 505 #is_authorized = self.validateChecksum(data['appKey']) 506 507 ## A human-readable name identifying the client 508 ## application. This can be a maximum of 255 characters. 509 510 #if len(data['appName']) > 255: 511 #is_authorized = False 512 513 514 #return(is_authorized) 515 516 517 ################################################################## 518 519 #def calculateWavePoint(self, x, max_height=100, wave_length=10): 520 521 ## start at 0, increase to max value at half of one 522 ## wavelength, decrease to 0 by end of wavelength 536 523 #y = ( (max_height/2) * \ 537 #math. cos (x* ( math.pi / (wave_length / 2)))) + \524 #math.sin ((x-1) * ( math.pi / (wave_length / 2)))) + \ 538 525 #(max_height/2) 539 526 540 541 return(y) 542 543 544 ################################################################## 545 546 def simulateHeadsetData(self): 547 548 response = DEFAULT_PACKET 549 550 response['timestamp'] = time.time() 551 552 time_value = self.connection_timestamp - time.time() 553 554 for key in response.keys(): 555 556 if key == 'poorSignalLevel': 557 pass 558 559 elif key == 'eSense': 560 plot = self.calculateWavePoint( \ 561 time_value, \ 562 max_height=100, \ 563 wave_length=DEFAULT_SAMPLE_WAVELENGTH) 564 565 for each in response[key].keys(): 566 567 if ((each == 'attention') and \ 568 (THINKGEAR_ATTENTION_MULTIPLIER != None)): 569 value = plot * \ 570 THINKGEAR_ATTENTION_MULTIPLIER 571 572 elif ((each == 'meditation') and \ 573 (THINKGEAR_MEDITATION_MULTIPLIER != None)): 574 value = plot * \ 575 THINKGEAR_MEDITATION_MULTIPLIER 576 577 578 value = int(value) 579 580 581 if value < 0: 582 value = 0 583 elif value > 100: 584 value = 100 585 586 response[key][each] = value 587 588 589 elif key == 'eegPower': 590 plot = self.calculateWavePoint( \ 591 time_value, \ 592 max_height=65535, \ 593 wave_length=DEFAULT_SAMPLE_WAVELENGTH) 594 595 for each in response[key].keys(): 596 if ((THINKGEAR_EEG_POWER_MULTIPLIERS != None) and \ 597 (each in THINKGEAR_EEG_POWER_MULTIPLIERS.keys())): 598 value = THINKGEAR_EEG_POWER_MULTIPLIERS[each] * plot 599 else: 600 value = plot 601 response[key][each] = value 602 603 604 return(response) 527 ## start at max value, decrease to 0 at half of one 528 ## wavelegnth, increase to max by end of wavelength 529 ##y = ( (max_height/2) * \ 530 ##math.cos (x * ( math.pi / (wave_length / 2)))) + \ 531 ##(max_height/2) 532 533 534 #return(y) 535 536 537 ################################################################## 538 539 #def simulateHeadsetData(self): 540 541 #response = DEFAULT_PACKET 542 543 #response['timestamp'] = time.time() 544 545 #time_value = self.connection_timestamp - time.time() 546 547 #for key in response.keys(): 548 549 #if key == 'poorSignalLevel': 550 #pass 551 552 #elif key == 'eSense': 553 #plot = self.calculateWavePoint( \ 554 #time_value, \ 555 #max_height=100, \ 556 #wave_length=DEFAULT_SAMPLE_WAVELENGTH) 557 558 #for each in response[key].keys(): 559 560 #if ((each == 'attention') and \ 561 #(THINKGEAR_ATTENTION_MULTIPLIER != None)): 562 #value = plot * \ 563 #THINKGEAR_ATTENTION_MULTIPLIER 564 565 #elif ((each == 'meditation') and \ 566 #(THINKGEAR_MEDITATION_MULTIPLIER != None)): 567 #value = plot * \ 568 #THINKGEAR_MEDITATION_MULTIPLIER 569 570 571 #value = int(value) 572 573 574 #if value < 0: 575 #value = 0 576 #elif value > 100: 577 #value = 100 578 579 #response[key][each] = value 580 581 582 #elif key == 'eegPower': 583 #plot = self.calculateWavePoint( \ 584 #time_value, \ 585 #max_height=65535, \ 586 #wave_length=DEFAULT_SAMPLE_WAVELENGTH) 587 588 #for each in response[key].keys(): 589 #if ((THINKGEAR_EEG_POWER_MULTIPLIERS != None) and \ 590 #(each in THINKGEAR_EEG_POWER_MULTIPLIERS.keys())): 591 #value = THINKGEAR_EEG_POWER_MULTIPLIERS[each] * plot 592 #else: 593 #value = plot 594 #response[key][each] = value 595 596 597 #return(response) 605 598 606 599 … … 622 615 623 616 if (self.parent != None): 624 self.parent.processPacketThinkGear(self.protocol.data_packet) 625 626 627 ################################################################## 628 629 def updateStatus(self): 630 631 # Craft a simulated data packet 632 packet = self.simulateHeadsetData() 633 634 self.packet_queue.append(packet) 635 636 #if (self.parent != None): 637 #self.parent.processPacketThinkGear(packet) 638 639 # Include simulated blinks at desired frequency 640 if ((self.blink_frequency_timer != None) and \ 641 (self.blink_frequency_timer > 0) and \ 642 (time.time() - self.blink_timestamp > \ 643 self.blink_frequency_timer)): 644 645 self.blink_timestamp = time.time() 646 647 packet = DEFAULT_BLINK_MESSAGE 648 649 packet['timestamp'] = self.blink_timestamp 650 617 #self.parent.processPacketThinkGear(self.protocol.data_packet) 618 self.parent.processPacketThinkGear(packet) 619 620 621 ################################################################## 622 623 def processPacketEmotiv(self, packet): 624 625 if self.DEBUG > 2: 626 print packet 627 628 if (packet != {}): 651 629 self.packet_queue.append(packet) 630 631 if COMMUNICATION_MODE == 'Emit Signal': 632 self.emitSendPacketSignal() 633 634 else: 635 self.sendPacketQueue() 636 637 if (self.parent != None): 638 self.parent.processPacketEmotiv(packet) 639 640 641 ################################################################## 642 643 #def updateStatus(self): 644 645 ## Craft a simulated data packet 646 #packet = self.simulateHeadsetData() 647 648 #self.packet_queue.append(packet) 649 650 ##if (self.parent != None): 651 ##self.parent.processPacketThinkGear(packet) 652 653 ## Include simulated blinks at desired frequency 654 #if ((self.blink_frequency_timer != None) and \ 655 #(self.blink_frequency_timer > 0) and \ 656 #(time.time() - self.blink_timestamp > \ 657 #self.blink_frequency_timer)): 658 659 #self.blink_timestamp = time.time() 660 661 #packet = DEFAULT_BLINK_MESSAGE 662 663 #packet['timestamp'] = self.blink_timestamp 664 665 #self.packet_queue.append(packet) 652 666 653 667 … … 661 675 self.exec_() 662 676 663 677 664 678 ################################################################## 665 679 666 680 def exitThread(self, callThreadQuit=True): 667 681 668 if (self.emulate_headset_data): 669 try: 670 self.emulationTimer.stop() 671 except Exception, e: 672 if self.DEBUG: 673 print "ERROR: Exception when stopping emulation timer:", 674 print e 675 676 # Calling exitThread() on protocol first seems to occassionally 677 # create the following error: 678 # RuntimeError: Internal C++ object (PySide.QtNetwork.QTcpSocket) already deleted. 679 # Segmentation fault 680 # ...when program is closed without pressing "Stop" button for EEG 682 #if (self.emulate_headset_data): 683 #try: 684 #self.emulationTimer.stop() 685 #except Exception, e: 686 #if self.DEBUG: 687 #print "ERROR: Exception when stopping emulation timer:", 688 #print e 689 690 691 for server in self.protocolServers: 692 server.exitThread() 693 694 self.socket.close() 695 696 if callThreadQuit: 697 QtCore.QThread.quit(self) 698 699 if self.parent == None: 700 sys.exit() 701 702 703 ################################################################## 704 705 def stop(self): 706 707 self.exitThread() 708 709 710 ################################################################## 711 712 #def resetDevice(self): 713 714 #if self.serial_device != None: 715 #self.serial_device.exitThread() 716 681 717 #if self.protocol != None: 682 718 #self.protocol.exitThread() 683 719 684 # Call disconnect block in protocol first due to above error 685 self.protocol.disconnectHardware() 686 687 if self.serial_device != None: 688 self.serial_device.exitThread() 689 690 if self.protocol != None: 691 self.protocol.exitThread() 692 693 self.socket.close() 694 695 if callThreadQuit: 696 QtCore.QThread.quit(self) 697 698 if self.parent == None: 699 sys.exit() 700 701 702 ################################################################## 703 704 def resetDevice(self): 705 706 if self.serial_device != None: 707 self.serial_device.exitThread() 708 709 if self.protocol != None: 710 self.protocol.exitThread() 711 712 self.configureEEG() 713 720 #self.configureEEG() 721 -
trunk/Puzzlebox/Synapse/ThinkGear/Client.py
r358 r362 25 25 configuration.ENABLE_PYSIDE = False 26 26 else: 27 print "INFO: [Synapse: Client] Using PySide module"27 print "INFO: [Synapse:ThinkGear:Client] Using PySide module" 28 28 29 29 if not configuration.ENABLE_PYSIDE: 30 print "INFO: [Synapse: Client] Using PyQt4 module"30 print "INFO: [Synapse:ThinkGear:Client] Using PyQt4 module" 31 31 from PyQt4 import QtCore, QtGui, QtNetwork 32 32 33 34 #try:35 #import PySide as PyQt436 #from PySide import QtCore, QtGui, QtNetwork37 #except:38 #print "Using PyQt4 module"39 #from PyQt4 import QtCore, QtGui, QtNetwork40 #else:41 #print "Using PySide module"42 43 #from PyQt4 import QtNetwork44 #import simplejson as json45 #import Configuration as configuration46 #import puzzlebox_logger47 33 48 34 ##################################################################### -
trunk/Puzzlebox/Synapse/ThinkGear/Protocol.py
r358 r362 103 103 configuration.ENABLE_PYSIDE = False 104 104 else: 105 print "INFO: [Synapse: Protocol] Using PySide module"105 print "INFO: [Synapse:ThinkGear:Protocol] Using PySide module" 106 106 107 107 if not configuration.ENABLE_PYSIDE: 108 print "INFO: [Synapse: Protocol] Using PyQt4 module"108 print "INFO: [Synapse:ThinkGear:Protocol] Using PyQt4 module" 109 109 from PyQt4 import QtCore 110 110 111 111 112 #try: 113 #import PySide as PyQt4 114 #from PySide import QtCore 115 #except: 116 #print "Using PyQt4 module" 117 #from PyQt4 import QtCore 118 #else: 119 #print "Using PySide module" 120 121 #import Configuration as configuration 122 123 ### GLOBALS ### 112 ##################################################################### 113 # Globals 114 ##################################################################### 124 115 125 116 DEBUG = configuration.DEBUG … … 137 128 THINKGEAR_DEVICE_AUTOCONNECT_INTERVAL = 4 # seconds between attempting 138 129 # to send auto-connect packets 139 THINKGEAR_DEVICE_ID = configuration.THINKGEAR_DEVICE_ID130 #THINKGEAR_DEVICE_ID = configuration.THINKGEAR_DEVICE_ID 140 131 #THINKGEAR_DEFAULT_DEVICE_ID = '\x7d\x68' 141 132 #THINKGEAR_DEFAULT_DEVICE_ID = '\xe4\x68' … … 163 154 DEBUG_PACKET_COUNT = 1024 164 155 165 ### CLASSES ### 156 ##################################################################### 157 # Classes 158 ##################################################################### 166 159 167 160 class puzzlebox_synapse_protocol_thinkgear(QtCore.QThread): … … 169 162 def __init__(self, log, \ 170 163 serial_device, \ 171 device_id=THINKGEAR_DEVICE_ID, \164 #device_id=None, \ 172 165 device_model=None, \ 173 166 DEBUG=DEBUG, \ … … 180 173 self.parent = parent 181 174 182 self.device_id = device_id175 #self.device_id = device_id 183 176 self.device_model = device_model 184 177 -
trunk/Puzzlebox/Synapse/ThinkGear/Server.py
r358 r362 13 13 14 14 import os, sys, time 15 import signal15 #import signal 16 16 import math 17 17 … … 29 29 configuration.ENABLE_PYSIDE = False 30 30 else: 31 print "INFO: [Synapse: Server] Using PySide module"31 print "INFO: [Synapse:ThinkGear:Server] Using PySide module" 32 32 33 33 if not configuration.ENABLE_PYSIDE: 34 print "INFO: [Synapse: Server] Using PyQt4 module"34 print "INFO: [Synapse:ThinkGear:Server] Using PyQt4 module" 35 35 from PyQt4 import QtCore, QtGui, QtNetwork 36 36 … … 48 48 49 49 #import Configuration as configuration 50 import Puzzlebox.Synapse.ThinkGear.Protocol as serial_interface50 import Puzzlebox.Synapse.ThinkGear.Protocol as thinkgear_protocol 51 51 52 52 ### GLOBALS ### … … 57 57 #COMMUNICATION_MODE = 'Call Parent' 58 58 59 SERVER_INTERFACE = configuration.THINKGEAR_SERVER_INTERFACE60 SERVER_PORT = configuration.THINKGEAR_SERVER_PORT59 #SERVER_INTERFACE = configuration.THINKGEAR_SERVER_INTERFACE 60 #SERVER_PORT = configuration.THINKGEAR_SERVER_PORT 61 61 THINKGEAR_DEVICE_SERIAL_PORT = configuration.THINKGEAR_DEVICE_SERIAL_PORT 62 THINKGEAR_DEVICE_ID = configuration.THINKGEAR_DEVICE_ID62 #THINKGEAR_DEVICE_ID = configuration.THINKGEAR_DEVICE_ID 63 63 64 64 CLIENT_NO_REPLY_WAIT = configuration.CLIENT_NO_REPLY_WAIT * 1000 … … 142 142 ### CLASS MODULE ### 143 143 144 class ThinkgearServer(QtCore.QThread):144 class puzzlebox_synapse_server_thinkgear(QtCore.QThread): 145 145 146 146 def __init__(self, log, \ 147 server_interface=SERVER_INTERFACE, \148 server_port=SERVER_PORT, \147 #server_interface=SERVER_INTERFACE, \ 148 #server_port=SERVER_PORT, \ 149 149 device_address=THINKGEAR_DEVICE_SERIAL_PORT, \ 150 device_id=THINKGEAR_DEVICE_ID, \150 #device_id=THINKGEAR_DEVICE_ID, \ 151 151 device_model=None, \ 152 152 emulate_headset_data=ENABLE_SIMULATE_HEADSET_DATA, \ … … 160 160 self.parent = parent 161 161 162 self.server_interface = server_interface163 self.server_port = server_port162 #self.server_interface = server_interface 163 #self.server_port = server_port 164 164 self.device_address = device_address 165 self.device_id = device_id165 #self.device_id = device_id 166 166 self.device_model = device_model 167 167 self.emulate_headset_data = emulate_headset_data 168 169 self.name = 'Synapse:ThinkGear:Server' 168 170 169 171 self.message_frequency_timer = MESSAGE_FREQUENCY_TIMER … … 185 187 self.configureEEG() 186 188 187 self.configureNetwork()189 #self.configureNetwork() 188 190 189 191 … … 203 205 204 206 self.serial_device = \ 205 serial_interface.SerialDevice( \207 thinkgear_protocol.SerialDevice( \ 206 208 self.log, \ 207 209 device_address=self.device_address, \ … … 216 218 217 219 self.protocol = \ 218 serial_interface.puzzlebox_synapse_protocol_thinkgear( \220 thinkgear_protocol.puzzlebox_synapse_protocol_thinkgear( \ 219 221 self.log, \ 220 222 self.serial_device, \ 221 device_id=self.device_id, \223 #device_id=self.device_id, \ 222 224 device_model=self.device_model, \ 223 225 DEBUG=self.DEBUG, \ … … 241 243 ################################################################## 242 244 243 def configureNetwork(self):244 245 # self.blockSize = 0246 self.socket = QtNetwork.QTcpServer()247 self.socket.name = 'ThinkGear Server'248 249 if self.DEBUG:250 print "<---- [%s] Initializing server on %s:%i" % \251 (self.socket.name, self.server_interface, self.server_port)252 253 254 if ((self.server_interface == '') or \255 (self.server_interface == '*')):256 address=QtNetwork.QHostAddress.Any257 else:258 # address=self.server_interface259 address=QtNetwork.QHostAddress(self.server_interface)260 261 262 result = self.socket.listen(address, self.server_port)263 264 265 if not result:266 try:267 QtGui.QMessageBox.information( \268 self.parent, \269 self.socket.name, \270 "Unable to start the server on %s:%i" % \271 (self.server_interface, self.server_port))272 except:273 pass274 275 if self.DEBUG:276 print "ERROR [%s] Unable to start the server:" % self.socket.name,277 print self.socket.errorString()278 279 # self.parent.stopThinkGearConnectServer()280 # self.parent.pushButtonThinkGearConnect.nextCheckState()281 # self.parent.pushButtonThinkGearConnect.toggle()282 # self.parent.pushButtonThinkGearConnect.test.emit(QtCore.SIGNAL("clicked()"))283 284 self.socket.close()285 return286 287 288 self.socket.newConnection.connect(self.processConnection)289 # self.socket.error.connect(self.displayError)290 291 292 ################################################################## 293 294 def deleteDisconnected(self):295 296 connection_index = 0297 298 for connection in self.connections:299 300 try:301 302 if ((connection.state() != QtNetwork.QAbstractSocket.ConnectingState) and \303 (connection.state() != QtNetwork.QAbstractSocket.ConnectedState)):304 305 if self.DEBUG:306 print "- - [%s] Deleting disconnected socket" % self.socket.name307 308 connection.deleteLater()309 # Delete references to disconnected sockets310 del (self.connections[connection_index])311 312 except:313 # Delete references to sockets throwing exceptions314 del (self.connections[connection_index])315 316 connection_index += 1317 318 319 ################################################################## 320 321 def processConnection(self):322 323 clientConnection = self.socket.nextPendingConnection()324 clientConnection.disconnected.connect(self.deleteDisconnected)325 326 self.connections.append(clientConnection)327 328 self.clientConnection = clientConnection329 330 # the next connected client to enter the readyRead state331 # will be processed first332 clientConnection.readyRead.connect(self.processClientConnection)333 334 335 ################################################################## 336 337 def processClientConnection(self):338 339 clientConnection = self.clientConnection340 341 socket_buffer = clientConnection.readAll()342 343 for packet in socket_buffer.split(DELIMITER):344 345 data_to_process = None346 347 if packet != '':348 349 try:350 data_to_process = json.loads(packet.data())351 352 except Exception, e:353 354 # Special socket handling for Flash applications355 if (packet == FLASH_POLICY_FILE_REQUEST):245 #def configureNetwork(self): 246 247 ##self.blockSize = 0 248 #self.socket = QtNetwork.QTcpServer() 249 #self.socket.name = 'ThinkGear Server' 250 251 #if self.DEBUG: 252 #print "<---- [%s] Initializing server on %s:%i" % \ 253 #(self.socket.name, self.server_interface, self.server_port) 254 255 256 #if ((self.server_interface == '') or \ 257 #(self.server_interface == '*')): 258 #address=QtNetwork.QHostAddress.Any 259 #else: 260 ##address=self.server_interface 261 #address=QtNetwork.QHostAddress(self.server_interface) 262 263 264 #result = self.socket.listen(address, self.server_port) 265 266 267 #if not result: 268 #try: 269 #QtGui.QMessageBox.information( \ 270 #self.parent, \ 271 #self.socket.name, \ 272 #"Unable to start the server on %s:%i" % \ 273 #(self.server_interface, self.server_port)) 274 #except: 275 #pass 276 277 #if self.DEBUG: 278 #print "ERROR [%s] Unable to start the server:" % self.socket.name, 279 #print self.socket.errorString() 280 281 ##self.parent.stopThinkGearConnectServer() 282 ##self.parent.pushButtonThinkGearConnect.nextCheckState() 283 ##self.parent.pushButtonThinkGearConnect.toggle() 284 ##self.parent.pushButtonThinkGearConnect.test.emit(QtCore.SIGNAL("clicked()")) 285 286 #self.socket.close() 287 #return 288 289 290 #self.socket.newConnection.connect(self.processConnection) 291 ##self.socket.error.connect(self.displayError) 292 293 294 ################################################################## 295 296 #def deleteDisconnected(self): 297 298 #connection_index = 0 299 300 #for connection in self.connections: 301 302 #try: 303 304 #if ((connection.state() != QtNetwork.QAbstractSocket.ConnectingState) and \ 305 #(connection.state() != QtNetwork.QAbstractSocket.ConnectedState)): 306 307 #if self.DEBUG: 308 #print "- - [%s] Deleting disconnected socket" % self.socket.name 309 310 #connection.deleteLater() 311 ## Delete references to disconnected sockets 312 #del (self.connections[connection_index]) 313 314 #except: 315 ## Delete references to sockets throwing exceptions 316 #del (self.connections[connection_index]) 317 318 #connection_index += 1 319 320 321 ################################################################## 322 323 #def processConnection(self): 324 325 #clientConnection = self.socket.nextPendingConnection() 326 #clientConnection.disconnected.connect(self.deleteDisconnected) 327 328 #self.connections.append(clientConnection) 329 330 #self.clientConnection = clientConnection 331 332 ## the next connected client to enter the readyRead state 333 ## will be processed first 334 #clientConnection.readyRead.connect(self.processClientConnection) 335 336 337 ################################################################## 338 339 #def processClientConnection(self): 340 341 #clientConnection = self.clientConnection 342 343 #socket_buffer = clientConnection.readAll() 344 345 #for packet in socket_buffer.split(DELIMITER): 346 347 #data_to_process = None 348 349 #if packet != '': 350 351 #try: 352 #data_to_process = json.loads(packet.data()) 353 354 #except Exception, e: 355 356 ## Special socket handling for Flash applications 357 #if (packet == FLASH_POLICY_FILE_REQUEST): 356 358 357 if self.DEBUG:358 print "--> [%s] Flash policy file requested" % self.socket.name359 #if self.DEBUG: 360 #print "--> [%s] Flash policy file requested" % self.socket.name 359 361 360 data_to_process = packet.data()361 362 363 else:362 #data_to_process = packet.data() 363 364 365 #else: 364 366 365 if self.DEBUG:366 print "--> [ThinkGear Emulator] Partial data received (or error:",367 print e368 print ")."367 #if self.DEBUG: 368 #print "--> [ThinkGear Emulator] Partial data received (or error:", 369 #print e 370 #print ")." 369 371 370 print "packet data:",371 print packet.data()372 373 374 else:375 376 if self.DEBUG:377 print "--> [%s] Received:" % self.socket.name,378 print data_to_process379 380 381 if (data_to_process != None):382 383 response = self.processData(data_to_process)384 385 if (response != None):372 #print "packet data:", 373 #print packet.data() 374 375 376 #else: 377 378 #if self.DEBUG: 379 #print "--> [%s] Received:" % self.socket.name, 380 #print data_to_process 381 382 383 #if (data_to_process != None): 384 385 #response = self.processData(data_to_process) 386 387 #if (response != None): 386 388 387 self.sendResponse(clientConnection, response)388 389 390 ################################################################## 391 392 def sendResponse(self, connection, response, disconnect_after_sending=False):393 394 # Special socket handling for Flash applications395 if (response == FLASH_SOCKET_POLICY_FILE):396 data = response397 else:398 data = json.dumps(response)399 data = data + DELIMITER400 401 if connection.waitForConnected(CLIENT_NO_REPLY_WAIT):402 403 if self.DEBUG > 1:404 print "<-- [%s] Sending:" % self.socket.name,405 print data406 407 connection.write(data)408 409 connection.waitForBytesWritten(CLIENT_NO_REPLY_WAIT)410 411 if disconnect_after_sending:412 connection.disconnectFromHost()389 #self.sendResponse(clientConnection, response) 390 391 392 ################################################################## 393 394 #def sendResponse(self, connection, response, disconnect_after_sending=False): 395 396 ## Special socket handling for Flash applications 397 #if (response == FLASH_SOCKET_POLICY_FILE): 398 #data = response 399 #else: 400 #data = json.dumps(response) 401 #data = data + DELIMITER 402 403 #if connection.waitForConnected(CLIENT_NO_REPLY_WAIT): 404 405 #if self.DEBUG > 1: 406 #print "<-- [%s] Sending:" % self.socket.name, 407 #print data 408 409 #connection.write(data) 410 411 #connection.waitForBytesWritten(CLIENT_NO_REPLY_WAIT) 412 413 #if disconnect_after_sending: 414 #connection.disconnectFromHost() 413 415 414 416 … … 424 426 def sendPacketQueue(self): 425 427 426 #if self.DEBUG: 427 #print "sendPacketQueue called" 428 429 if self.connections != []: 430 431 while (len(self.packet_queue) > 0): 432 433 packet = self.packet_queue[0] 434 del self.packet_queue[0] 435 436 for connection in self.connections: 437 438 if connection.state() == QtNetwork.QAbstractSocket.ConnectedState: 428 if (self.parent != None): 429 430 for packet in self.packet_queue: 431 self.parent.packet_queue.append(packet) 432 433 #self.parent.sendPacketQueue() 434 435 436 ################################################################## 437 438 #def sendPacketQueue(self): 439 440 ##if self.DEBUG: 441 ##print "sendPacketQueue called" 442 443 #if self.connections != []: 444 445 #while (len(self.packet_queue) > 0): 446 447 #packet = self.packet_queue[0] 448 #del self.packet_queue[0] 449 450 #for connection in self.connections: 451 452 #if connection.state() == QtNetwork.QAbstractSocket.ConnectedState: 439 453 440 self.sendResponse(connection, packet)441 442 443 # if COMMUNICATION_MODE != 'Emit Signal' and (self.parent != None):444 # self.parent.processPacketThinkGear(self.protocol.data_packet)454 #self.sendResponse(connection, packet) 455 456 457 ##if COMMUNICATION_MODE != 'Emit Signal' and (self.parent != None): 458 ##self.parent.processPacketThinkGear(self.protocol.data_packet) 445 459 446 460 … … 459 473 460 474 461 elif (type(data) == type({}) and \475 if (type(data) == type({}) and \ 462 476 data.has_key('appName') and \ 463 477 data.has_key('appKey')): … … 620 634 621 635 if (self.parent != None): 622 self.parent.processPacketThinkGear(self.protocol.data_packet) 636 #self.parent.processPacketThinkGear(self.protocol.data_packet) 637 self.parent.processPacketThinkGear(packet) 623 638 624 639 … … 655 670 656 671 if self.DEBUG: 657 print "<---- [%s] Main thread running" % self. socket.name672 print "<---- [%s] Main thread running" % self.name 658 673 659 674 self.exec_() … … 689 704 self.protocol.exitThread() 690 705 691 self.socket.close()706 #self.socket.close() 692 707 693 708 if callThreadQuit:
Note: See TracChangeset
for help on using the changeset viewer.