1 | #!/usr/bin/env python |
---|
2 | # -*- coding: utf-8 -*- |
---|
3 | # |
---|
4 | # Puzzlebox - Brainstorms - Network - Server - ThinkGear |
---|
5 | # |
---|
6 | # Copyright Puzzlebox Productions, LLC (2010) |
---|
7 | # |
---|
8 | # This code is released under the GNU Pulic License (GPL) version 2 |
---|
9 | # For more information please refer to http://www.gnu.org/copyleft/gpl.html |
---|
10 | # |
---|
11 | # Last Update: 2010.07.01 |
---|
12 | # |
---|
13 | ##################################################################### |
---|
14 | |
---|
15 | import os, sys, time |
---|
16 | import signal |
---|
17 | import math |
---|
18 | |
---|
19 | import simplejson as json |
---|
20 | |
---|
21 | from PyQt4 import QtCore, QtNetwork |
---|
22 | |
---|
23 | import puzzlebox_brainstorms_configuration as configuration |
---|
24 | #import puzzlebox_logger |
---|
25 | |
---|
26 | ##################################################################### |
---|
27 | # Globals |
---|
28 | ##################################################################### |
---|
29 | |
---|
30 | DEBUG = 1 |
---|
31 | |
---|
32 | SERVER_INTERFACE = configuration.THINKGEAR_SERVER_INTERFACE |
---|
33 | SERVER_PORT = configuration.THINKGEAR_SERVER_PORT |
---|
34 | |
---|
35 | CLIENT_NO_REPLY_WAIT = configuration.CLIENT_NO_REPLY_WAIT * 1000 |
---|
36 | |
---|
37 | FLASH_POLICY_FILE_REQUEST = configuration.FLASH_POLICY_FILE_REQUEST |
---|
38 | FLASH_SOCKET_POLICY_FILE = configuration.FLASH_SOCKET_POLICY_FILE |
---|
39 | |
---|
40 | DELIMITER = configuration.THINKGEAR_DELIMITER |
---|
41 | |
---|
42 | MESSAGE_FREQUENCY_TIMER = 1 * 1000 # 1 Hz (1000 ms) |
---|
43 | |
---|
44 | ENABLE_SIMULATE_HEADSET_DATA = True |
---|
45 | |
---|
46 | BLINK_FREQUENCY_TIMER = 6 # blink every 6 seconds |
---|
47 | # (6 seconds is listed by Wikipedia |
---|
48 | # as being the average number of times |
---|
49 | # an adult blinks in a laboratory setting) |
---|
50 | |
---|
51 | DEFAULT_SAMPLE_WAVELENGTH = 30 # number of seconds from 0 to max to 0 for |
---|
52 | # any given detection value below |
---|
53 | |
---|
54 | DEFAULT_AUTHORIZATION_MESSAGE = \ |
---|
55 | {"isAuthorized": True} |
---|
56 | # Tells the client whether the server has authorized |
---|
57 | # access to the user's headset data. The value is |
---|
58 | # either true or false. |
---|
59 | |
---|
60 | DEFAULT_SIGNAL_LEVEL_MESSAGE = \ |
---|
61 | {"poorSignalLevel": 0} |
---|
62 | # A quantifier of the quality of the brainwave signal. |
---|
63 | # This is an integer value that is generally in the |
---|
64 | # range of 0 to 200, with 0 indicating a |
---|
65 | # good signal and 200 indicating an off-head state. |
---|
66 | |
---|
67 | DEFAULT_EEG_POWER_MESSAGE = \ |
---|
68 | {"eegPower": { \ |
---|
69 | 'delta': 0, \ |
---|
70 | 'theta': 0, \ |
---|
71 | 'lowAlpha': 0, \ |
---|
72 | 'highAlpha': 0, \ |
---|
73 | 'lowBeta': 0, \ |
---|
74 | 'highBeta': 0, \ |
---|
75 | 'lowGamma': 0, \ |
---|
76 | 'highGamma': 0, \ |
---|
77 | }, \ |
---|
78 | } # A container for the EEG powers. These may |
---|
79 | # be either integer or floating-point values. |
---|
80 | # Maximum values are undocumented but assumed to be 65535 |
---|
81 | |
---|
82 | DEFAULT_ESENSE_MESSAGE = \ |
---|
83 | {"eSense": { \ |
---|
84 | 'attention': 0, \ |
---|
85 | 'meditation': 0, \ |
---|
86 | }, \ |
---|
87 | } # A container for the eSense⢠attributes. |
---|
88 | # These are integer values between 0 and 100, |
---|
89 | # where 0 is perceived as a lack of that attribute |
---|
90 | # and 100 is an excess of that attribute. |
---|
91 | |
---|
92 | DEFAULT_BLINK_MESSAGE = {"blinkStrength": 255} |
---|
93 | # The strength of a detected blink. This is |
---|
94 | # an integer in the range of 0-255. |
---|
95 | |
---|
96 | DEFAULT_RAWEEG_MESSAGE = {"rawEeg": 255} |
---|
97 | # The raw data reading off the forehead sensor. |
---|
98 | # This may be either an integer or a floating-point value. |
---|
99 | |
---|
100 | DEFAULT_PACKET = {} |
---|
101 | DEFAULT_PACKET.update(DEFAULT_EEG_POWER_MESSAGE) |
---|
102 | DEFAULT_PACKET.update(DEFAULT_SIGNAL_LEVEL_MESSAGE) |
---|
103 | DEFAULT_PACKET.update(DEFAULT_ESENSE_MESSAGE) |
---|
104 | |
---|
105 | DEFAULT_RESPONSE_MESSAGE = DEFAULT_SIGNAL_LEVEL_MESSAGE |
---|
106 | |
---|
107 | ##################################################################### |
---|
108 | # Classes |
---|
109 | ##################################################################### |
---|
110 | |
---|
111 | class puzzlebox_brainstorms_network_server_thinkgear: |
---|
112 | |
---|
113 | def __init__(self, log, \ |
---|
114 | server_interface=SERVER_INTERFACE, \ |
---|
115 | server_port=SERVER_PORT, \ |
---|
116 | DEBUG=DEBUG, \ |
---|
117 | parent=None): |
---|
118 | |
---|
119 | self.log = log |
---|
120 | self.DEBUG = DEBUG |
---|
121 | |
---|
122 | self.server_interface = server_interface |
---|
123 | self.server_port = server_port |
---|
124 | |
---|
125 | self.message_frequency_timer = MESSAGE_FREQUENCY_TIMER |
---|
126 | self.blink_frequency_timer = BLINK_FREQUENCY_TIMER |
---|
127 | |
---|
128 | self.connection_timestamp = time.time() |
---|
129 | self.blink_timestamp = time.time() |
---|
130 | |
---|
131 | self.connections = [] |
---|
132 | self.packet_queue = [] |
---|
133 | |
---|
134 | self.configureNetwork() |
---|
135 | |
---|
136 | self.updateTimer = QtCore.QTimer() |
---|
137 | QtCore.QObject.connect(self.updateTimer, QtCore.SIGNAL("timeout()"), self.timerEvent) |
---|
138 | self.updateTimer.start(MESSAGE_FREQUENCY_TIMER) |
---|
139 | |
---|
140 | |
---|
141 | ################################################################## |
---|
142 | |
---|
143 | def timerEvent(self): |
---|
144 | |
---|
145 | if (self.connections != []): |
---|
146 | |
---|
147 | self.updateStatus() |
---|
148 | self.sendPacketQueue() |
---|
149 | |
---|
150 | |
---|
151 | ################################################################## |
---|
152 | |
---|
153 | def configureNetwork(self): |
---|
154 | |
---|
155 | #self.blockSize = 0 |
---|
156 | self.socket = QtNetwork.QTcpServer() |
---|
157 | self.socket.name = 'ThinkGear Server' |
---|
158 | |
---|
159 | if self.DEBUG: |
---|
160 | print "----> [%s] Initializing server on %s:%i" % \ |
---|
161 | (self.socket.name, self.server_interface, self.server_port) |
---|
162 | |
---|
163 | if (self.server_interface == ''): |
---|
164 | result = self.socket.listen(port=self.server_port) |
---|
165 | else: |
---|
166 | result = self.socket.listen(address=self.server_interface, \ |
---|
167 | port=self.server_port) |
---|
168 | |
---|
169 | if not result: |
---|
170 | if self.DEBUG: |
---|
171 | print "ERROR [%s] Unable to start the server:", self.socket.name, |
---|
172 | print self.socket.errorString() |
---|
173 | |
---|
174 | self.socket.close() |
---|
175 | return |
---|
176 | |
---|
177 | |
---|
178 | self.socket.newConnection.connect(self.processConnection) |
---|
179 | #self.socket.error.connect(self.displayError) |
---|
180 | |
---|
181 | |
---|
182 | ################################################################## |
---|
183 | |
---|
184 | def deleteDisconnected(self): |
---|
185 | |
---|
186 | connection_index = 0 |
---|
187 | |
---|
188 | for connection in self.connections: |
---|
189 | |
---|
190 | #if self.DEBUG: |
---|
191 | #print "Connection state:", |
---|
192 | #print connection.state() |
---|
193 | |
---|
194 | if ((connection.state() != QtNetwork.QAbstractSocket.ConnectingState) and \ |
---|
195 | (connection.state() != QtNetwork.QAbstractSocket.ConnectedState)): |
---|
196 | |
---|
197 | if self.DEBUG: |
---|
198 | print "- - [%s] Deleting disconnected socket" % self.socket.name |
---|
199 | |
---|
200 | connection.deleteLater() |
---|
201 | # Delete references to disconnected sockets |
---|
202 | del (self.connections[connection_index]) |
---|
203 | |
---|
204 | |
---|
205 | connection_index += 1 |
---|
206 | |
---|
207 | |
---|
208 | ################################################################## |
---|
209 | |
---|
210 | def processConnection(self): |
---|
211 | |
---|
212 | clientConnection = self.socket.nextPendingConnection() |
---|
213 | clientConnection.disconnected.connect(self.deleteDisconnected) |
---|
214 | |
---|
215 | self.connections.append(clientConnection) |
---|
216 | |
---|
217 | |
---|
218 | # Wait until client sends authorization request or configuration packet |
---|
219 | while not clientConnection.waitForReadyRead(CLIENT_NO_REPLY_WAIT): |
---|
220 | pass |
---|
221 | |
---|
222 | socket_buffer = clientConnection.readAll() |
---|
223 | |
---|
224 | for packet in socket_buffer.split(DELIMITER): |
---|
225 | |
---|
226 | data_to_process = None |
---|
227 | |
---|
228 | if packet != '': |
---|
229 | |
---|
230 | try: |
---|
231 | data_to_process = json.loads(packet.data()) |
---|
232 | |
---|
233 | except Exception, e: |
---|
234 | |
---|
235 | # Special socket handling for Flash applications |
---|
236 | if (packet == FLASH_POLICY_FILE_REQUEST): |
---|
237 | |
---|
238 | if self.DEBUG: |
---|
239 | print "<-- [%s] Flash policy file requested" % self.socket.name |
---|
240 | |
---|
241 | data_to_process = packet.data() |
---|
242 | |
---|
243 | |
---|
244 | else: |
---|
245 | |
---|
246 | if self.DEBUG: |
---|
247 | print "<-- [ThinkGear Emulator] Partial data received (or error:", |
---|
248 | print e |
---|
249 | print ")." |
---|
250 | |
---|
251 | print "packet data:", |
---|
252 | print packet.data() |
---|
253 | |
---|
254 | |
---|
255 | else: |
---|
256 | |
---|
257 | if self.DEBUG: |
---|
258 | print "<-- [%s] Received:" % self.socket.name, |
---|
259 | print data_to_process |
---|
260 | |
---|
261 | |
---|
262 | if (data_to_process != None): |
---|
263 | |
---|
264 | response = self.processData(data_to_process) |
---|
265 | |
---|
266 | if (response != None): |
---|
267 | |
---|
268 | self.sendResponse(clientConnection, response) |
---|
269 | |
---|
270 | |
---|
271 | ################################################################## |
---|
272 | |
---|
273 | def sendResponse(self, connection, response, disconnect_after_sending=False): |
---|
274 | |
---|
275 | data = json.dumps(response) |
---|
276 | |
---|
277 | if connection.waitForConnected(CLIENT_NO_REPLY_WAIT): |
---|
278 | |
---|
279 | if self.DEBUG: |
---|
280 | print "<-- [%s] Sending:" % self.socket.name, |
---|
281 | print data |
---|
282 | |
---|
283 | connection.write(data) |
---|
284 | |
---|
285 | connection.waitForBytesWritten(CLIENT_NO_REPLY_WAIT) |
---|
286 | |
---|
287 | if disconnect_after_sending: |
---|
288 | connection.disconnectFromHost() |
---|
289 | |
---|
290 | |
---|
291 | ################################################################## |
---|
292 | |
---|
293 | def sendPacketQueue(self): |
---|
294 | |
---|
295 | while (len(self.packet_queue) > 0): |
---|
296 | |
---|
297 | packet = self.packet_queue[0] |
---|
298 | del self.packet_queue[0] |
---|
299 | |
---|
300 | for connection in self.connections: |
---|
301 | |
---|
302 | if connection.state() == QtNetwork.QAbstractSocket.ConnectedState: |
---|
303 | |
---|
304 | self.sendResponse(connection, packet) |
---|
305 | |
---|
306 | |
---|
307 | ################################################################## |
---|
308 | |
---|
309 | def processData(self, data): |
---|
310 | |
---|
311 | response = None |
---|
312 | |
---|
313 | # Special socket handling for Flash applications |
---|
314 | if (data == FLASH_POLICY_FILE_REQUEST): |
---|
315 | |
---|
316 | response = FLASH_SOCKET_POLICY_FILE |
---|
317 | |
---|
318 | self.packet_queue.insert(0, FLASH_SOCKET_POLICY_FILE) |
---|
319 | |
---|
320 | |
---|
321 | elif (type(data) == type({}) and \ |
---|
322 | data.has_key('appName') and \ |
---|
323 | data.has_key('appKey')): |
---|
324 | authorized = self.authorizeClient(data) |
---|
325 | |
---|
326 | response = {} |
---|
327 | response['isAuthorized'] = authorized |
---|
328 | |
---|
329 | self.packet_queue.insert(0, response) |
---|
330 | |
---|
331 | |
---|
332 | return(response) |
---|
333 | |
---|
334 | |
---|
335 | ################################################################## |
---|
336 | |
---|
337 | def validateChecksum(self, checksum): |
---|
338 | |
---|
339 | '''The key used by the client application to identify |
---|
340 | itself. This must be 40 hexadecimal characters, ideally generated |
---|
341 | using an SHA-1 digest. The appKey is an identifier that is unique |
---|
342 | to each application, rather than each instance of an application. |
---|
343 | It is used by the server to bypass the authorization process if a |
---|
344 | user had previously authorized the requesting client. To reduce |
---|
345 | the chance of overlap with the appKey of other applications, |
---|
346 | the appKey should be generated using an SHA-1 digest.''' |
---|
347 | |
---|
348 | is_valid = True |
---|
349 | |
---|
350 | hexadecimal_characters = '0123456789abcdef' |
---|
351 | |
---|
352 | if len(checksum) != 40: |
---|
353 | is_valid = False |
---|
354 | else: |
---|
355 | for character in checksum: |
---|
356 | if character not in hexadecimal_characters: |
---|
357 | is_valid = False |
---|
358 | |
---|
359 | return(is_valid) |
---|
360 | |
---|
361 | |
---|
362 | ################################################################## |
---|
363 | |
---|
364 | def authorizeClient(self, data): |
---|
365 | |
---|
366 | '''The client must initiate an authorization request |
---|
367 | and the server must authorize the client before the |
---|
368 | server will start transmitting any headset data.''' |
---|
369 | |
---|
370 | is_authorized = self.validateChecksum(data['appKey']) |
---|
371 | |
---|
372 | # A human-readable name identifying the client |
---|
373 | # application. This can be a maximum of 255 characters. |
---|
374 | |
---|
375 | if len(data['appName']) > 255: |
---|
376 | is_authorized = False |
---|
377 | |
---|
378 | |
---|
379 | return(is_authorized) |
---|
380 | |
---|
381 | |
---|
382 | ################################################################## |
---|
383 | |
---|
384 | def calculateWavePoint(self, x, max_height=100, wave_length=10): |
---|
385 | |
---|
386 | # start at 0, increase to max value at half of one |
---|
387 | # wavelength, decrease to 0 by end of wavelength |
---|
388 | y = ( (max_height/2) * \ |
---|
389 | math.sin ((x-1) * ( math.pi / (wave_length / 2)))) + \ |
---|
390 | (max_height/2) |
---|
391 | |
---|
392 | # start at max value, decrease to 0 at half of one |
---|
393 | # wavelegnth, increase to max by end of wavelength |
---|
394 | #y = ( (max_height/2) * \ |
---|
395 | #math.cos (x * ( math.pi / (wave_length / 2)))) + \ |
---|
396 | #(max_height/2) |
---|
397 | |
---|
398 | |
---|
399 | return(y) |
---|
400 | |
---|
401 | |
---|
402 | ################################################################## |
---|
403 | |
---|
404 | def simulateHeadsetData(self): |
---|
405 | |
---|
406 | response = DEFAULT_PACKET |
---|
407 | |
---|
408 | time_value = self.connection_timestamp - time.time() |
---|
409 | |
---|
410 | for key in response.keys(): |
---|
411 | |
---|
412 | if key == 'poorSignalLevel': |
---|
413 | pass |
---|
414 | |
---|
415 | elif key == 'eSense': |
---|
416 | plot = self.calculateWavePoint( \ |
---|
417 | time_value, \ |
---|
418 | max_height=100, \ |
---|
419 | wave_length=DEFAULT_SAMPLE_WAVELENGTH) |
---|
420 | |
---|
421 | for each in response[key].keys(): |
---|
422 | response[key][each] = plot |
---|
423 | |
---|
424 | elif key == 'eegPower': |
---|
425 | plot = self.calculateWavePoint( \ |
---|
426 | time_value, \ |
---|
427 | max_height=65535, \ |
---|
428 | wave_length=DEFAULT_SAMPLE_WAVELENGTH) |
---|
429 | |
---|
430 | for each in response[key].keys(): |
---|
431 | response[key][each] = plot |
---|
432 | |
---|
433 | |
---|
434 | return(response) |
---|
435 | |
---|
436 | |
---|
437 | ################################################################## |
---|
438 | |
---|
439 | def updateStatus(self): |
---|
440 | |
---|
441 | if ENABLE_SIMULATE_HEADSET_DATA: |
---|
442 | |
---|
443 | # Craft a simulated data packet |
---|
444 | self.packet_queue.append( \ |
---|
445 | self.simulateHeadsetData() ) |
---|
446 | |
---|
447 | # Include simulated blinks at desired frequency |
---|
448 | if ((self.blink_frequency_timer != None) and \ |
---|
449 | (time.time() - self.blink_timestamp > \ |
---|
450 | self.blink_frequency_timer)): |
---|
451 | |
---|
452 | self.blink_timestamp = time.time() |
---|
453 | |
---|
454 | packet = DEFAULT_BLINK_MESSAGE |
---|
455 | self.packet_queue.append(packet) |
---|
456 | |
---|
457 | |
---|
458 | ##################################################################### |
---|
459 | # Main |
---|
460 | ##################################################################### |
---|
461 | |
---|
462 | if __name__ == '__main__': |
---|
463 | |
---|
464 | # Perform correct KeyboardInterrupt handling |
---|
465 | signal.signal(signal.SIGINT, signal.SIG_DFL) |
---|
466 | |
---|
467 | #log = puzzlebox_logger.puzzlebox_logger(logfile='server_thinkgear') |
---|
468 | log = None |
---|
469 | |
---|
470 | # Collect default settings and command line parameters |
---|
471 | server_interface = SERVER_INTERFACE |
---|
472 | server_port = SERVER_PORT |
---|
473 | |
---|
474 | for each in sys.argv: |
---|
475 | |
---|
476 | if each.startswith("--interface="): |
---|
477 | server_interface = each[ len("--interface="): ] |
---|
478 | if each.startswith("--port="): |
---|
479 | server_port = each[ len("--port="): ] |
---|
480 | |
---|
481 | |
---|
482 | app = QtCore.QCoreApplication(sys.argv) |
---|
483 | |
---|
484 | server = puzzlebox_brainstorms_network_server_thinkgear(log, \ |
---|
485 | server_interface, \ |
---|
486 | server_port, \ |
---|
487 | DEBUG=DEBUG) |
---|
488 | |
---|
489 | sys.exit(app.exec_()) |
---|
490 | |
---|