This repository has been archived by the owner on Jul 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
utopiaclient.py
1480 lines (1212 loc) · 53.6 KB
/
utopiaclient.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright (c) 2019 MindAffect B.V.
# Author: Jason Farquhar <jason@mindaffect.nl>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
""" This module contains the message classes for communication with the mindaffect BCI hub and a simple client for connecting to and managing this connection.
"""
import struct
import time
import socket
import sys
class UtopiaMessage:
"""
Class for a generic UtopiaMessage, i.e. the common structure of all messages
"""
def __init__(self, msgID=0, msgName=None, version=0):
""" Class for a generic UtopiaMessage, i.e. the common structure of all messages
Args:
msgID (int, optional): unique message ID. Defaults to 0.
msgName (str, optional): unique message name. Defaults to None.
version (int, optional): message version. Defaults to 0.
"""
self.msgID = msgID
self.msgName = msgName
self.version = version
def __str__(self):
return '%i\n'%(self.msgID)
class TimeStampClock:
"""
Base class for time-stamp sources. Match this prototype to replace the default timestamp source
"""
def getTimeStamp(self):
"""
get the time-stamp in milliseconds ! N.B. **must** fit in an int32!
Returns:
int: the timestamp
"""
return (int(time.perf_counter()*1000) % (1<<31))
class RawMessage(UtopiaMessage):
"""
Class for a raw utopia message, i.e. decoded header but raw payload
"""
msgName="RAW"
def __init__(self, msgID, version, payload):
"""for a raw utopia message, i.e. decoded header but raw payload
Args:
msgID (int, optional): unique message ID. Defaults to 0.
version (int, optional): message version. Defaults to 0.
payload (bytes): the raw payload
Raises:
Exception: if the payload is not bytes
"""
super().__init__(msgID, RawMessage.msgName, version)
self.payload = payload
if hasattr(self.payload, 'encode'):
self.payload = self.payload.encode()
if not isinstance(self.payload, bytes):
raise Exception("Illegal-value")
@classmethod
def fromUtopiaMessage(cls, msg:UtopiaMessage):
"""
Construct a raw-message wrapper from a normal payload message
Args:
msg (UtopiaMessage): the message to make to raw
Returns:
RawMessage: the raw version of this utopia message
"""
return cls(msg.msgID, msg.version, msg.serialize())
def __str__(self):
return '%c(%d) [%i]\n'%(chr(self.msgID), self.msgID, len(self.payload))
def serialize(self):
"""
convert the raw message to the string to make it network ready
Returns:
bytes: the byte serialized version of this raw message
"""
S= struct.pack("<BBH", self.msgID, self.version, len(self.payload))
S = S + self.payload
return S
@classmethod
def deserialize(cls, buf):
"""
Read a raw message from a byte-buffer, return the read message and the number of bytes used from the bytebuffer, or None, 0 if message is mal-formed
Args:
buf (bytes): the byte buffer to read from
Returns:
RawMessage: the decoded raw message
"""
bufsize = len(buf)
if bufsize < 4:
print("Buffer too short for header")
return (None, 0)
(msgID, ver, msgsize) = struct.unpack('<BBH', buf[0:4])
# read the rest of the message
if msgsize > 0:
if bufsize >= 4+msgsize:
payload = buf[4:4+msgsize]
else:
print("Buffer too short for payload: id:{}, ver:{}, sz:{}".format(chr(msgID), ver, msgsize))
return (None, 0)
else:
payload = None
msg=cls(msgID, ver, payload)
return (msg, 4+msgsize)
@classmethod
def deserializeMany(cls, buf):
"""
decode multiple RawMessages from the byte-buffer of data, return the length of data consumed.
Args:
buf (bytes): the byte buffer to read from
Returns:
list-of-RawMessage: the list of decoded raw messages
"""
msgs=[]
nconsumed=0
while nconsumed < len(buf):
(msg, msgconsumed)=RawMessage.deserialize(buf[nconsumed:])
if msg==None or msgconsumed == 0:
break # bug-out if invalid/incomplete message
msgs.append(msg)
nconsumed = nconsumed + msgconsumed
return (msgs, nconsumed)
class Heartbeat(UtopiaMessage):
"""the HEARTBEAT utopia message class
"""
# Static definitions of the class type constants
msgID=ord('H')
msgName="HEARTBEAT"
def __init__(self, timestamp:int=None, statemessage:str=None):
"""the HEARTBEAT utopia message class
Args:
timestamp (int, optional): time-stamp for this message. Defaults to None.
statemessage (str, optional): addition state message string for this heartbeat. Defaults to None.
"""
super().__init__(Heartbeat.msgID, Heartbeat.msgName)
self.timestamp=timestamp
self.statemessage = statemessage
if self.statemessage is not None: # v1 heartbeat with state message string
self.version = 1
def serialize(self):
"""
Returns the contents of this event as a string, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the serialized version of this message
"""
S = struct.pack('<i', int(self.timestamp))
if self.statemessage is not None:
S = S + bytes(self.statemessage, 'utf8')
return S
@staticmethod
def deserialize(buf):
"""Static method to create a HEARTBEAT class from a **PAYLOAD** byte-stream, return the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
Heartbeat: the decoded message
"""
bufsize = len(buf)
if bufsize < 4:
return (None, 0)
(timestamp, ) = struct.unpack('<i', buf[0:4])
if bufsize>4:
statemessage = buf[4:].decode('utf-8')
return (Heartbeat(timestamp,statemessage), len(buf))
else:
return (Heartbeat(timestamp), 4)
def __str__(self):
return "%c(%d) %s %i"%(self.msgID, self.msgID, self.msgName, self.timestamp)
class StimulusEvent(UtopiaMessage):
"""the STIMULUSEVENT utopia message class -- which is used to send information about the current stimulus state of this client to other clients
"""
# Static definitions of the class type constants
msgID=ord('E')
msgName="STIMULUSEVENT"
def __init__(self, timestamp=None, objIDs=None, objState=None):
"""the STIMULUEVENT utopia message class
Args:
timestamp (int, optional): time-stamp for this message. Defaults to None.
objIDs (list-of-int, optional): the unique object ids for these outputs. Defaults to None.
objState (list-of-int, optional): the stimulus state of each output object. Defaults to None.
"""
super().__init__(StimulusEvent.msgID, StimulusEvent.msgName)
self.timestamp=timestamp
self.objIDs=objIDs
self.objState=objState
def serialize(self):
"""Converts this message to a string representation to send over the network
Returns:
bytes: the encoded message
"""
S = struct.pack("<i", int(self.timestamp)) # timestamp
S = S + struct.pack("<B", len(self.objIDs)) # nObj
for objid, objstate in zip(self.objIDs, self.objState):
S = S + struct.pack("<BB", int(objid), int(objstate)) # [objID, objState] pairs
return S
@staticmethod
def deserialize(buf):
"""Static method to create a STIMULUSEVENT class from a **PAYLOAD** byte-stream, return created object and the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 5:
return (None, 0)
(timestamp, nobj) = struct.unpack("<iB", buf[0:5])
if bufsize < 5+nobj*2:
return (None, 0)
objIDs=[]
objState=[]
for i in range(5, len(buf), 2):
(objid, objstate)=struct.unpack("<BB", buf[i:i+2])
objIDs.append(objid)
objState.append(objstate)
msg=StimulusEvent(timestamp, objIDs, objState)
return (msg, 5+nobj*2)
def __str__(self):
return "%s %i"%(self.msgName, self.timestamp) + "".join("(%i, %i)"%(x, y) for x, y in zip(self.objIDs, self.objState))
class PredictedTargetProb(UtopiaMessage):
"""the PREDICTEDTARGETPROB utopia message class -- which is used to communicate the most likely target and the estimate error rate for this prediction.
"""
# Static definitions of the class type constants
msgID=ord('P')
msgName="PREDICTEDTARGETPROB"
def __init__(self, timestamp=None, Yest:int=-1, Perr:float=1.0):
"""the PREDICTEDTARGETPROB utopia message class
Args:
timestamp (int, optional): time-stamp for this message. Defaults to None.
Yest (int, optional): the object ID for the most likely target. Defaults to -1.
Perr (float, optional): the estimated probility that this predicted target is *wrong*. Defaults to 1.0.
"""
super().__init__(PredictedTargetProb.msgID, PredictedTargetProb.msgName)
self.timestamp=timestamp
self.Yest =Yest
self.Perr =Perr
def serialize(self):
"""Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the encoded message
"""
S = struct.pack('<ibf', int(self.timestamp), int(self.Yest), self.Perr)
return S
@staticmethod
def deserialize(buf):
"""Static method to create a MODECHANGE class from a **PAYLOAD** byte-stream, return the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 4:
return (None, 0)
(timestamp, Yest, Perr) = struct.unpack('<ibf', buf[:(4+1+4)])
msg = PredictedTargetProb(timestamp, Yest, Perr)
return (msg, 4)
def __str__(self):
return "%c(%d) %s %i Yest=%d Perr=%f"%(self.msgID, self.msgID, self.msgName, self.timestamp, self.Yest, self.Perr)
class PredictedTargetDist(UtopiaMessage):
"""the PredictedTargetDist utopia message class -- which is used to send information about the current predicted target probabilites for the outputs
"""
# Static definitions of the class type constants
msgID=ord('F')
msgName="PREDICTEDTARGETDIST"
def __init__(self, timestamp=None, objIDs=None, pTgt=None):
"""the PredictedTargetDist utopia message class
Args:
timestamp (int, optional): time-stamp for this message. Defaults to None.
objIDs (list-of-int, optional): list of the objIDs the target probabilities refer to. Defaults to None.
pTgt (list-of-float, optional): the target probabilities for the corrospending object IDs. Defaults to None.
"""
super().__init__(PredictedTargetDist.msgID, PredictedTargetDist.msgName)
self.timestamp=timestamp
self.objIDs=objIDs
self.pTgt=pTgt
def serialize(self):
"""Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the encoded message
"""
S = struct.pack("<i", int(self.timestamp)) # timestamp
S = S + struct.pack("<B", len(self.objIDs)) # nObj
for objid, pTgt in zip(self.objIDs, self.pTgt):
S = S + struct.pack("<Bf", int(objid), float(pTgt)) # [objID, pTgt] pairs
return S
@staticmethod
def deserialize(buf):
"""Static method to create a PREDICTEDTARGETDIST class from a **PAYLOAD** byte-stream, return created object and the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 5:
return (None, 0)
(timestamp, nobj) = struct.unpack("<iB", buf[0:5])
if bufsize < 5+nobj*(1+4):
return (None, 0)
objIDs=[]
pTgt=[]
for i in range(5, len(buf), (1+4)):
(objid, ptgt)=struct.unpack("<Bf", buf[i:i+(1+4)])
objIDs.append(objid)
pTgt.append(ptgt)
msg=PredictedTargetDist(timestamp, objIDs, pTgt)
return (msg, 5+nobj*2)
def __str__(self):
return "%s %i"%(self.msgName, self.timestamp) + "".join("(%i, %f)"%(x, y) for x, y in zip(self.objIDs, self.pTgt))
class DataPacket(UtopiaMessage):
"""the DATAPACKET utopia message class --- which is used to stream raw (time,channels) EEG data packets.
"""
# Static definitions of the class type constants
msgID=ord('D')
msgName="DATAPACKET"
def __init__(self, timestamp=None, samples=None):
"""the DATAPACKET utopia message class --- which is used to stream raw (time,channels) EEG data packets.
Args:
timestamp (int, optional): time-stamp for this message. Defaults to None.
samples (list-of-lists-of-float, optional): (samples,channels) array of the raw EEG data. Defaults to None.
"""
super().__init__(DataPacket.msgID, DataPacket.msgName)
self.timestamp=timestamp
self.samples=samples
def serialize(self):
"""Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the encoded message
"""
S = struct.pack("<i", int(self.timestamp)) # timestamp
S = S + struct.pack("<i", len(self.samples)) # nsamp
for tp in self.samples:
S = S + struct.pack("<%df"%(len(tp)), *tp)
return S
@staticmethod
def deserialize(buf):
"""Static method to create a STIMULUSEVENT class from a **PAYLOAD** byte-stream, return created object and the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 8:
return (None, 0)
timestamp, nsamp = struct.unpack("<ii", buf[0:8])
nch=int((bufsize-8)/(nsamp*4))
samples=[]
for t in range(nsamp):
sampt=struct.unpack_from("<%df"%(nch), buf, 8+t*4*nch)
samples.append(sampt)
msg=DataPacket(timestamp, samples)
return (msg, 8+nsamp*nch*8)
def __str__(self):
ss="%c(%d) %s %i "%(self.msgID, self.msgID, self.msgName, self.timestamp)
ss= ss+ "[%dx%d]"%(len(self.samples), len(self.samples[0]))
for chs in self.samples:
chstr = "".join(["%f, "%(c) for c in chs])
ss = ss + "["+chstr+"]"
return ss
class DataHeader(UtopiaMessage):
"""
the DATAHEADER utopia message class -- which is used to give general meta-information about the EEG stream
"""
# Static definitions of the class type constants
msgID=ord('A')
msgName="DATAHEADER"
def __init__(self, timestamp=None, fsample=None, nchannels=None, labels=None):
"""the DATAHEADER utopia message class
Args:
timestamp (int, optional): the message timestamp in milliseconds. Defaults to None.
fsample (float, optional): the nomional sampling rate of the EEG stream. Defaults to None.
nchannels (int, optional): the number of channels in the data stream. Defaults to None.
labels (list-of-str, optional): the textual names of the data channels. Defaults to None.
"""
super().__init__(DataHeader.msgID, DataHeader.msgName)
self.timestamp=timestamp
self.fsample=fsample
self.nchannels=nchannels
self.labels=labels
def serialize(self):
"""Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the encoded message
"""
S = struct.pack("<i", int(self.timestamp)) # timestamp
S = S + struct.pack("<i", self.nchannels)
S = S + struct.pack("<f", self.fsample)
if self.labels:
# comma separated list of channel names
S = S + bytes(", ".join(self.labels), 'utf-8')
return S
@staticmethod
def deserialize(buf):
"""
Static method to create a HEADER class from a **PAYLOAD** byte-stream, return created object and the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 12:
return (None, 0)
timestamp, nchannels, fsample = struct.unpack("<iif", buf[0:8])
labels = buf[4:].decode('utf-8')
labels = labels.split(", ")
msg=DataHeader(timestamp, nchannels, fsample, labels)
return (msg, bufsize)
def __str__(self):
ss="%c(%d) %s %i "%(self.msgID, self.msgID, self.msgName, self.timestamp)
ss= ss+ "%dch @ %gHz"%(self.nchannels, self.fsample)
ss= ss+ ", ".join(self.labels)
return ss
class NewTarget(UtopiaMessage):
"""
the NEWTARGET utopia message class -- which is used to tell other clients that a new target selection round has begun.
"""
# Static definitions of the class type constants
msgID=ord('N')
msgName="NEWTARGET"
def __init__(self, timestamp=None):
"""the NEWTARGET utopia message class
Args:
timestamp (int, optional): message timestamp in milliseconds. Defaults to None.
"""
super().__init__(NewTarget.msgID, NewTarget.msgName)
self.timestamp=timestamp
def serialize(self):
"""Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the encoded message
"""
S = struct.pack('<i', int(self.timestamp))
return S
@staticmethod
def deserialize(buf):
"""Static method to create a HEARTBEAT class from a **PAYLOAD** byte-stream, return the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 4:
return (None, 0)
(timestamp, ) = struct.unpack('<i', buf[0:4])
msg = NewTarget(timestamp)
return (msg, 4)
def __str__(self):
return "%c(%d) %s %i"%(self.msgID, self.msgID, self.msgName, self.timestamp)
class Selection(UtopiaMessage):
"""the SELECTION utopia message class -- which is used to inform other clients that a particular output has been selected by **this** client.
"""
# Static definitions of the class type constants
msgID=ord('S')
msgName="SELECTION"
def __init__(self, timestamp=None, objID=None):
""" the SELECTION utopia message class
Args:
timestamp (int, optional): message timestamp in milliseconds. Defaults to None.
objID (int, optional): the objID of the selected output. Defaults to None.
"""
super().__init__(Selection.msgID, Selection.msgName)
self.timestamp=timestamp
self.objID =objID
def serialize(self):
"""Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the encoded message
"""
S = struct.pack('<i', int(self.timestamp))
S = S + struct.pack('<B', self.objID)
return S
@staticmethod
def deserialize(buf):
"""Static method to create a SELECTION class from a **PAYLOAD** byte-stream, return the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 5:
return (None, 0)
(timestamp, objID) = struct.unpack('<iB', buf[0:5])
msg = Selection(timestamp, objID)
return (msg, 5)
def __str__(self):
return "%c(%d) %s %i id:%i"%(self.msgID, self.msgID, self.msgName, self.timestamp, self.objID)
class Reset(UtopiaMessage):
"""the RESET utopia message class -- which is used to tell the decoder to reset and clear it's model information.
"""
# Static definitions of the class type constants
msgID=ord('R')
msgName="RESET"
def __init__(self, timestamp=None):
"""the RESET utopia message class
Args:
timestamp (int, optional): message timestamp in milliseconds. Defaults to None.
"""
super().__init__(Reset.msgID, Reset.msgName)
self.timestamp=timestamp
def serialize(self):
"""Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the encoded message
"""
S = struct.pack('<i', int(self.timestamp))
return S
@staticmethod
def deserialize(buf):
"""Static method to create a RESET class from a **PAYLOAD** byte-stream, return the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 4:
return (None, 0)
(timestamp, ) = struct.unpack('<i', buf[0:4])
msg = Reset(timestamp)
return (msg, 4)
def __str__(self):
return "%c(%d) %s %i"%(self.msgID, self.msgID, self.msgName, self.timestamp)
class ModeChange(UtopiaMessage):
"""the MODECHANGE utopia message class -- which is used to tell the decoder to change system modes, for example to switch to calibration-mode.
"""
# Static definitions of the class type constants
msgID=ord('M')
msgName="MODECHANGE"
def __init__(self, timestamp=None, newmode=None):
"""the MODECHANGE utopia message class
Args:
timestamp (int, optional): message timestamp in milliseconds. Defaults to None.
newmode (str, optional): the desired new system mode. Defaults to None.
"""
super().__init__(ModeChange.msgID, ModeChange.msgName)
self.timestamp=timestamp
self.newmode =newmode
def serialize(self):
"""Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the encoded message
"""
S = struct.pack('<i', int(self.timestamp))
S = S + bytes(self.newmode, 'utf-8')
return S
@staticmethod
def deserialize(buf):
"""Static method to create a MODECHANGE class from a **PAYLOAD** byte-stream, return the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 4:
return (None, 0)
(timestamp, ) = struct.unpack('<i', buf[0:4])
newmode = buf[4:].decode('utf-8')
msg = ModeChange(timestamp, newmode)
return (msg, 4)
def __str__(self):
return "%c(%d) %s %i %s"%(self.msgID, self.msgID, self.msgName, self.timestamp, self.newmode)
class Log(UtopiaMessage):
"""the LOG utopia message class -- which is used to send arbitary log messages to the hub
"""
# Static definitions of the class type constants
msgID=ord('L')
msgName="LOG"
def __init__(self, timestamp:int=None, logmsg:str=None):
"""the LOG utopia message class
Args:
timestamp (int, optional): message timestamp in milliseconds. Defaults to None.
logmsg (str, optional): the log message to send. Defaults to None.
"""
super().__init__(Log.msgID, Log.msgName)
self.timestamp=timestamp
self.logmsg =logmsg
def serialize(self):
"""Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the encoded message
"""
S = struct.pack('<i', int(self.timestamp))
S = S + bytes(self.logmsg, 'utf-8')
return S
@staticmethod
def deserialize(buf):
"""Static method to create a MODECHANGE class from a **PAYLOAD** byte-stream, return the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 4:
return (None, 0)
(timestamp, ) = struct.unpack('<i', buf[0:4])
logmsg = buf[4:].decode('utf-8')
msg = ModeChange(timestamp, logmsg)
return (msg, 4)
def __str__(self):
return "%c(%d) %s %i %s"%(self.msgID, self.msgID, self.msgName, self.timestamp, self.logmsg)
class SignalQuality(UtopiaMessage):
"""the SIGNALQUALITY utopia message class -- which is used to send information about the estimated signal to noise for each channel in the data stream
"""
# Static definitions of the class type constants
msgID=ord('Q')
msgName="SIGNALQUALITY"
def __init__(self, timestamp:int=None, signalQuality=None):
"""the SIGNALQUALITY utopia message class
Args:
timestamp (int, optional): [description]. Defaults to None.
signalQuality (list-of-float, optional): signal-quality estimate (noise-to-signal ratio) for each of the EEG channels. Defaults to None.
"""
super().__init__(SignalQuality.msgID, SignalQuality.msgName)
self.timestamp=timestamp
self.signalQuality=signalQuality
def serialize(self):
"""Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the encoded message
"""
S = struct.pack('<i', int(self.timestamp))
S = S + b''.join([ struct.pack('<f', float(q)) for q in self.signalQuality ])
return S
@staticmethod
def deserialize(buf):
"""Static method to create a SIGNALQUALIYT class from a **PAYLOAD** byte-stream, return the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 4:
return (None, 0)
(timestamp, ) = struct.unpack('<i', buf[0:4])
signalQuality = struct.unpack_from('<%df'%((bufsize-4)//4), buf, 4)
# , buf[i:i+4])[0] for i in range(4, bufsize, 4) ]
msg = SignalQuality(timestamp, signalQuality)
return (msg, bufsize)
def __str__(self):
return "%c(%d) %s %i [%s]"%(self.msgID, self.msgID, self.msgName, self.timestamp, ", ".join(["%f"%q for q in self.signalQuality]))
class Subscribe(UtopiaMessage):
"""the SUBSCRIBE utopia message class -- which is used to tell the hub which messages IDs to forward to this client.
"""
# Static definitions of the class type constants
msgID=ord('B')
msgName="SUBSCRIBE"
def __init__(self, timestamp=None, messageIDs=None):
"""the SUBSCRIBE utopia message class
Args:
timestamp ([type], optional): [description]. Defaults to None.
messageIDs ([type], optional): [description]. Defaults to None.
"""
super().__init__(Subscribe.msgID, Subscribe.msgName)
self.timestamp=timestamp
self.messageIDs=messageIDs
def serialize(self):
"""Returns the contents of this event as a byte-stream, ready to send over the network,
or None in case of conversion problems.
Returns:
bytes: the encoded message
"""
S = struct.pack('<i', int(self.timestamp))
if type(self.messageIDs) is str:#str
S = S + bytes(self.messageIDs, 'utf-8')
else:# int->byte
S = S + b''.join([ struct.pack('<b', byte(q)) for q in self.messageIDs ])
return S
@staticmethod
def deserialize(buf):
"""Static method to create a SIGNALQUALITY class from a **PAYLOAD** byte-stream, return the number of bytes consumed from buf
Args:
buf (bytes): the message buffer
Returns:
UtopiaMessage: the decoded message
"""
bufsize = len(buf)
if bufsize < 4:
return (None, 0)
(timestamp, ) = struct.unpack('<i', buf[0:4])
#messageIDs = [ struct.unpack('<i', buf[i:i+4]) for i in range(4, bufsize, 4) ]
messageIDs = struct.unpack_from('<%di'%((bufsize-4)//4), buf, 4)
msg = Subscribe(timestamp, messageIDs)
return (msg, bufsize)
def __str__(self):
return "%c(%d) %s %i [%s]"%(self.msgID, self.msgID, self.msgName, self.timestamp, "{}".format(self.messageIDs))
# Helper functions for dealing with raw-messages -> classes
def decodeRawMessage(msg):
"""decode utopia RawMessages into actual message objects
Args:
msg (RawMessage): the raw message whose payload should be decoded
Returns:
StimulusEvent|Heartbeat|....: the decoded specific message type
"""
if msg.msgID==StimulusEvent.msgID:
decodedmsg, _= StimulusEvent.deserialize(msg.payload)
elif msg.msgID==Heartbeat.msgID:
decodedmsg, _ = Heartbeat.deserialize(msg.payload)
elif msg.msgID==PredictedTargetProb.msgID:
decodedmsg, _ = PredictedTargetProb.deserialize(msg.payload)
elif msg.msgID==PredictedTargetDist.msgID:
decodedmsg, _ = PredictedTargetDist.deserialize(msg.payload)
elif msg.msgID==Selection.msgID:
decodedmsg, _ = Selection.deserialize(msg.payload)
elif msg.msgID==ModeChange.msgID:
decodedmsg, _ = ModeChange.deserialize(msg.payload)
elif msg.msgID==NewTarget.msgID:
decodedmsg, _ = NewTarget.deserialize(msg.payload)
elif msg.msgID==SignalQuality.msgID:
decodedmsg, _ = SignalQuality.deserialize(msg.payload)
elif msg.msgID==Reset.msgID:
decodedmsg, _ = Reset.deserialize(msg.payload)
elif msg.msgID==DataPacket.msgID:
decodedmsg, _ = DataPacket.deserialize(msg.payload)
elif msg.msgID==Subscribe.msgID:
decodedmsg, _ = Subscribe.deserialize(msg.payload)
else:
decodedmsg = msg
return decodedmsg
def decodeRawMessages(msgs):
"""decode utopia RawMessages into actual message objects
Args:
msgs (list-of-RawMessage): list of RawMessages to decode the payload of
Returns:
list-of-messages: list of the fully decoded messages
"""
return [ decodeRawMessage(msg) for msg in msgs ]
def ssdpDiscover(servicetype=None, timeout=3, numretries=1):
"""auto-discover the utopia-hub using ssdp discover messages
Args:
servicetype (str, optional): the SSDP service type to search for. Defaults to None.
timeout (int, optional): timeout in seconds for the discovery. Defaults to 3.
numretries (int, optional): number of times to retry discovery. Defaults to 1.
Returns:
list-of-str: list of the IP addresses of the discovered servers
"""
ssdpgroup = ("239.255.255.250", 1900)
msearchTemplate = "\r\n".join([
'M-SEARCH * HTTP/1.1',
'HOST: {0}:{1}',
'MAN: "ssdp:discover"',
'ST: {st}', 'MX: {mx}', '', ''])
# make and send the discovery message
service= servicetype if servicetype is not None else "ssdp:all"
msearchMessage = msearchTemplate.format(*ssdpgroup, st=service, mx=timeout)
if sys.version_info[0] == 3: msearchMessage = msearchMessage.encode("utf-8")
try:
# make the UDP socket to the multicast group with timeout
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
sock.settimeout(timeout)
except: # abort if cant setup socket
return ()
responses=[]
for _ in range(numretries):
print("Sending query message:\n%s"%(msearchMessage))
try:
sock.sendto(msearchMessage, ssdpgroup)
except: # abort if send fails
return ()
# wait for responses and store the location info for the matching ones
print("Waiting responses")
try:
rsp, addr=sock.recvfrom(8192)
rsp=rsp.decode('utf-8')
print("Got response from: %s\n%s\n"%(addr, rsp))
# does the response contain servertype, if so then we match
location=None
if servicetype is None or servicetype in rsp:
print("Response matches server type: %s"%(servicetype))
# use the message source address as default location
location=addr
# extract the location or IP from the message
for line in rsp.split("\r\n"): # cut into lines
tmp=line.split(":", 1) # cut line into key/val
# is this the key we care about -> then record the value
if len(tmp)>1 and tmp[0].lower()=="LOCATION".lower():
location=tmp[1].strip()
# strip http:// xxxx /stuff
if location.startswith("http://"):
location=location[7:] # strip http
if '/' in location: