-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththreespace_api.py
More file actions
3756 lines (3289 loc) · 147 KB
/
Copy paththreespace_api.py
File metadata and controls
3756 lines (3289 loc) · 147 KB
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 python2.7
from __future__ import print_function
""" This module is an API module for ThreeSpace devices.
The ThreeSpace API module is a collection of classes, functions, structures,
and static variables use exclusivly for ThreeSpace devices. This module can
be used with a system running Python 2.5 and newer (including Python 3.x).
"""
__version__ = "2.0.2.3"
__authors__ = [
'"Chris George" <cgeorge@yeitechnology.com>',
'"Dan Morrison" <dmorrison@yeitechnology.com>',
]
import threading
import sys
import serial
import struct
import collections
import traceback
import time
import os
# chose an implementation, depending on os
if os.name == 'nt': # sys.platform == 'win32':
from win32_threespace_utils import *
else:
from threespace_utils import *
print("WARNING: No additional utils are loaded!!!!!!")
### Globals ###
global_file_path = os.getcwd()
global_error = None
global_counter = 0
global_donglist = {}
global_sensorlist = {}
global_broadcaster = None
TSS_TIMESTAMP_SENSOR = 0
TSS_TIMESTAMP_SYSTEM = 1
TSS_TIMESTAMP_NONE = 2
TSS_JOYSTICK = 0
TSS_MOUSE = 2
TSS_BUTTON_LEFT = 0
TSS_BUTTON_RIGHT = 1
### Private ###
_baudrate = 115200
_allowed_baudrates = [1200, 2400, 4800, 9600, 19200, 28800, 38400, 57600, 115200, 230400, 460800, 921600]
_wireless_retries = 5
### Functions ###
if sys.version_info >= (3, 0):
def makeWriteArray(startbyte, index_byte=None, command_byte=None, data=None):
rtn_array = bytearray((startbyte,))
if index_byte is not None:
rtn_array.append(index_byte)
if command_byte is not None:
rtn_array.append(command_byte)
if data is not None:
rtn_array += data
rtn_array.append((sum(rtn_array) - startbyte) % 256) # checksum
_hexDump(rtn_array)
return rtn_array
else:
def makeWriteArray(startbyte, index_byte=None, command_byte=None, data=None):
rtn_array = chr(startbyte)
if index_byte is not None:
rtn_array += chr(index_byte)
if command_byte is not None:
rtn_array += chr(command_byte)
if data is not None:
rtn_array += data
rtn_array += chr((sum(bytearray(rtn_array)) - startbyte) % 256) # checksum
_hexDump(rtn_array)
return rtn_array
def _hexDump(serial_string, header='i'):
if "-d_hex" in sys.argv:
ba = bytearray(serial_string)
print('{0}('.format(header), end='')
for i in range(len(ba)):
if i == len(ba) - 1:
print('0x{0:02x}'.format(ba[i]), end='')
else:
print('0x{0:02x},'.format(ba[i]), end='')
print(')')
def _print(string):
if "-d" in sys.argv:
print(string)
def _echoCallback(sensor, state):
_print('{0}:{1}'.format(sensor, state))
def _generateProtocolHeader(success_failure=False,
timestamp=False,
command_echo=False,
checksum=False,
logical_id=False,
serial_number=False,
data_length=False):
byte = 0
struct_str = '>'
idx_list = []
if success_failure:
byte += 0x1
struct_str += '?'
idx_list.append(0)
if timestamp:
byte += 0x2
struct_str += 'I'
idx_list.append(1)
if command_echo:
byte += 0x4
struct_str += 'B'
idx_list.append(2)
if checksum:
byte += 0x8
struct_str += 'B'
idx_list.append(3)
if logical_id:
byte += 0x10
struct_str += 'B'
idx_list.append(4)
if serial_number:
byte += 0x20
struct_str += 'I'
idx_list.append(5)
if data_length:
byte += 0x40
struct_str += 'B'
idx_list.append(6)
return (byte, struct.Struct(struct_str), idx_list)
def _generateSensorClass(sensor_inst, serial_port, allowed_device_types):
sensor_inst.compatibility = checkSoftwareVersionFromPort(serial_port)
sensor_inst.port_name = serial_port.name
sensor_inst.serial_port_settings = serial_port.getSettingsDict()
sensor_inst.serial_port = serial_port
hardware_version = convertString(sensor_inst.f7WriteRead('getHardwareVersionString'))
dev_type = hardware_version[4:-8].strip()
if dev_type not in allowed_device_types:
raise Exception("This is a %s device, not one of these devices %s!" % (dev_type, allowed_device_types))
sensor_inst.device_type = dev_type
serial_number = sensor_inst.f7WriteRead('getSerialNumber')
sensor_inst.serial_number = serial_number
if dev_type == "DNG":
if serial_number in global_donglist:
rtn_inst = global_donglist[serial_number]
rtn_inst.close()
rtn_inst.compatibility = sensor_inst.compatibility
rtn_inst.port_name = serial_port.name
rtn_inst.serial_port_settings = serial_port.getSettingsDict()
rtn_inst.serial_port = serial_port
return rtn_inst
global_donglist[serial_number] = sensor_inst
else:
if serial_number in global_sensorlist:
rtn_inst = global_sensorlist[serial_number]
rtn_inst.close()
rtn_inst.compatibility = sensor_inst.compatibility
rtn_inst.port_name = serial_port.name
rtn_inst.serial_port_settings = serial_port.getSettingsDict()
rtn_inst.serial_port = serial_port
if "BT" in dev_type:
rtn_inst.serial_port.timeout = 1.5
rtn_inst.serial_port.writeTimeout = 1.5
if "WL" in dev_type:
rtn_inst.switchToWiredMode()
return rtn_inst
if "BT" in dev_type:
sensor_inst.serial_port.timeout = 1.5
sensor_inst.serial_port.writeTimeout = 1.5
elif "WL" in dev_type:
sensor_inst.switchToWiredMode()
global_sensorlist[serial_number] = sensor_inst
return sensor_inst
def parseAxisDirections(axis_byte):
axis_order_num = axis_byte & 7
if axis_order_num == 0:
axis_order = "XYZ"
elif axis_order_num == 1:
axis_order = "XZY"
elif axis_order_num == 2:
axis_order = "YXZ"
elif axis_order_num == 3:
axis_order = "YZX"
elif axis_order_num == 4:
axis_order = "ZXY"
elif axis_order_num == 5:
axis_order = "ZYX"
else:
raise ValueError
neg_x = neg_y = neg_z = False
if (axis_byte & 32) > 0:
neg_x = True
if (axis_byte & 16) > 0:
neg_y = True
if (axis_byte & 8) > 0:
neg_z = True
return axis_order, neg_x, neg_y, neg_z
def generateAxisDirections(axis_order, neg_x=False, neg_y=False, neg_z=False):
axis_order = axis_order.upper()
if axis_order == "XYZ":
axis_byte = 0
elif axis_order == "XZY":
axis_byte = 1
elif axis_order == "YXZ":
axis_byte = 2
elif axis_order == "YZX":
axis_byte = 3
elif axis_order == "ZXY":
axis_byte = 4
elif axis_order == "ZYX":
axis_byte = 5
else:
raise ValueError
if neg_x:
axis_byte = axis_byte | 32
if neg_y:
axis_byte = axis_byte | 16
if neg_z:
axis_byte = axis_byte | 8
return axis_byte
def getSystemWirelessRetries():
return _wireless_retries
def setSystemWirelessRetries(retries):
global _wireless_retries
_wireless_retries = retries
def getDefaultCreateDeviceBaudRate():
return _baudrate
def setDefaultCreateDeviceBaudRate(new_baudrate):
global _baudrate
if new_baudrate in _allowed_baudrates:
_baudrate = new_baudrate
def padProtocolHeader69(header_data, sys_timestamp):
fail_byte, cmd_echo, data_size = header_data
return (fail_byte, sys_timestamp, cmd_echo, None, None, None, data_size)
def padProtocolHeader71(header_data):
fail_byte, timestamp, cmd_echo, data_size = header_data
return (fail_byte, timestamp, cmd_echo, None, None, None, data_size)
def padProtocolHeader85(header_data, sys_timestamp):
fail_byte, cmd_echo, rtn_log_id, data_size = header_data
return (fail_byte, sys_timestamp, cmd_echo, None, rtn_log_id, None, data_size)
def padProtocolHeader87(header_data):
fail_byte, timestamp, cmd_echo, rtn_log_id, data_size = header_data
return (fail_byte, timestamp, cmd_echo, None, rtn_log_id, None, data_size)
### Classes ###
class Broadcaster(object):
def __init__(self):
self.retries = 10
def setRetries(self, retries=10):
self.retries = retries
def sequentialWriteRead(self, command, input_list=None, filter=None):
if filter is None:
filter = list(global_sensorlist.values())
val_list = {}
for i in range(self.retries):
for sensor in reversed(filter):
packet = sensor.writeRead(command, input_list)
if packet[0]: # fail_byte
continue
val_list[sensor.serial_number] = packet
filter.remove(sensor)
if not filter:
break
# _print("##Attempt: {0} complete".format(i))
else:
# _print("sensor failed to succeed")
for sensor in filter:
val_list[sensor.serial_number] = (True, None, None)
return val_list
def writeRead(self, command, input_list=None, filter=None):
q = TSCommandQueue()
if filter is None:
filter = list(global_sensorlist.values())
for sensor in filter:
q.queueWriteRead(sensor, sensor.serial_number, self.retries, command, input_list)
return q.proccessQueue()
def _broadcastMethod(self, filter, method, default=None, *args):
# _print(filter)
if filter is None:
filter = list(global_sensorlist.values())
val_list = {}
for i in range(self.retries):
for sensor in reversed(filter):
packet = getattr(sensor, method)(*args)
if packet is default: # fail_byte
continue
val_list[sensor.serial_number] = packet
filter.remove(sensor)
if not filter:
break
# _print("##Attempt: {0} complete".format(i))
else:
# _print("sensor failed to succeed")
for sensor in filter:
val_list[sensor.serial_number] = default
return val_list
def broadcastMethod(self, method, default=None, args=[], filter=None, callback_func=None):
q = TSCommandQueue()
if filter is None:
filter = list(global_sensorlist.values())
for sensor in filter:
q.queueMethod(getattr(sensor, method),
sensor,
self.retries,
default,
args,
callback_func)
return q.proccessQueue()
def setStreamingSlots(self, slot0='null',
slot1='null',
slot2='null',
slot3='null',
slot4='null',
slot5='null',
slot6='null',
slot7='null',
filter=None,
callback_func=None):
args = (slot0, slot1, slot2, slot3, slot4, slot5, slot6, slot7)
return self.broadcastMethod('setStreamingSlots', False, args, filter, callback_func)
def getStreamingSlots(self, filter=None, callback_func=None):
return self.broadcastMethod('getStreamingSlots', None, [], filter, callback_func)
def startStreaming(self, record_data=False, filter=None, callback_func=None):
return self.broadcastMethod('startStreaming', False, [record_data], filter, callback_func)
def stopStreaming(self, filter=None, callback_func=None):
return self.broadcastMethod('stopStreaming', False, [], filter, callback_func)
def setStreamingTiming(self, interval, duration, delay, delay_offset, filter=None, callback_func=None):
if filter is None:
filter = list(global_sensorlist.values())
else:
filter = list(filter)
val_list = {}
for sensor in reversed(filter):
success = False
for i in range(self.retries):
if sensor.setStreamingTiming(interval, duration, delay):
if callback_func is not None:
callback_func(sensor, True)
success = True
break
# _print("##Attempt: {0} complete".format(i))
if callback_func is not None:
callback_func(sensor, False)
else:
# _print("sensor failed to succeed")
pass
val_list[sensor] = success
filter.remove(sensor)
delay += delay_offset
return val_list
def startRecordingData(self, filter=None, callback_func=None):
if filter is None:
filter = list(global_sensorlist.values())
for sensor in filter:
sensor.record_data = True
if callback_func is not None:
callback_func(sensor, True)
def stopRecordingData(self, filter=None, callback_func=None):
if filter is None:
filter = list(global_sensorlist.values())
for sensor in filter:
sensor.record_data = False
if callback_func is not None:
callback_func(sensor, True)
def debugPrint(self, broadcast_dict):
for sensor, data in broadcast_dict.items():
_print('Sensor {0:08X}: {1}'.format(sensor, data))
class TSCommandQueue(object):
def __init__(self):
self.queue = []
self.return_dict = {}
def queueWriteRead(self, sensor, rtn_key, retries, command, input_list=None):
self.queue.append(("queueWriteRead", sensor, (self.return_dict, rtn_key, retries, command, input_list)))
def queueMethod(self, method_obj, rtn_key, retries, default=None, input_list=None, callback_func=None):
self.queue.append(("queueMethod", (method_obj, rtn_key, retries, default, input_list, callback_func)))
def _queueMethod(self, method_obj, rtn_key, retries, default=None, input_list=None, callback_func=None):
try:
for i in range(retries):
packet = method_obj(*input_list)
if packet is default: # fail_byte
if callback_func is not None:
callback_func(rtn_key, False)
continue
if callback_func is not None:
callback_func(rtn_key, True)
self.return_dict[rtn_key] = packet
break
else:
self.return_dict[rtn_key] = default
except(KeyboardInterrupt):
print('\n! Received keyboard interrupt, quitting threads.\n')
raise KeyboardInterrupt # fix bug where a thread eats the interupt
def createThreads(self):
thread_queue = []
for item in self.queue:
if item[0] == "queueWriteRead":
thread_queue.append(item[1].queueWriteRead(*item[2]))
elif item[0] == "queueMethod":
qThread = threading.Thread(target=self._queueMethod, args=item[1])
thread_queue.append(qThread)
return thread_queue
def proccessQueue(self, clear_queue=False):
thread_queue = self.createThreads()
[qThread.start() for qThread in thread_queue]
[qThread.join() for qThread in thread_queue]
if clear_queue:
self.queue = []
return self.return_dict
# Base class should not be used directly
class _TSBase(object):
command_dict = {
'checkLongCommands': (0x19, 1, '>B', 0, None, 1),
'startStreaming': (0x55, 0, None, 0, None, 1),
'stopStreaming': (0x56, 0, None, 0, None, 1),
'updateCurrentTimestamp': (0x5f, 0, None, 4, '>I', 1),
'setLEDMode': (0xc4, 0, None, 1, '>B', 1),
'getLEDMode': (0xc8, 1, '>B', 0, None, 1),
'_setWiredResponseHeaderBitfield': (0xdd, 0, None, 4, '>I', 1),
'_getWiredResponseHeaderBitfield': (0xde, 4, '>I', 0, None, 1),
'getFirmwareVersionString': (0xdf, 12, '>12s', 0, None, 1),
'commitSettings': (0xe1, 0, None, 0, None, 1),
'softwareReset': (0xe2, 0, None, 0, None, 1),
'getHardwareVersionString': (0xe6, 32, '>32s', 0, None, 1),
'getSerialNumber': (0xed, 4, '>I', 0, None, 1),
'setLEDColor': (0xee, 0, None, 12, '>fff', 1),
'getLEDColor': (0xef, 12, '>fff', 0, None, 1),
'setJoystickAndMousePresentRemoved': (0xfd, 0, None, 2, '>BB', 1),
'getJoystickAndMousePresentRemoved': (0xfe, 2, '>B', 0, None, 1),
'null': (0xff, 0, None, 0, None, 1)
}
def __init__(self, com_port=None, baudrate=_baudrate, timestamp_mode=TSS_TIMESTAMP_SENSOR):
self.protocol_args = {'success_failure': True,
'timestamp': True,
'command_echo': True,
'data_length': True}
if timestamp_mode != TSS_TIMESTAMP_SENSOR:
self.protocol_args['timestamp'] = False
self.timestamp_mode = timestamp_mode
self.baudrate = baudrate
reinit = False
try: # if this is set the class had been there before
check = self.stream_parse
reinit = True
# _print("sensor reinit!!!")
except:
self._setupBaseVariables()
self._setupProtocolHeader(**self.protocol_args)
self._setupThreadedReadLoop()
if reinit:
if self.stream_timing is not None:
self.setStreamingTiming(*self.stream_timing)
if self.stream_slot_cmds is not None:
self.setStreamingSlots(*self.stream_slot_cmds)
def _setupBaseVariables(self):
self.serial_number_hex = '{0:08X}'.format(self.serial_number)
self.stream_timing = None
self.stream_parse = None
self.stream_slot_cmds = ['null'] * 8
self.stream_last_data = None
self.stream_data = []
self.record_data = False
self.data_loop = False
def _setupProtocolHeader(self, success_failure=False,
timestamp=False,
command_echo=False,
checksum=False,
logical_id=False,
serial_number=False,
data_length=False):
protocol_header = _generateProtocolHeader(success_failure,
timestamp,
command_echo,
checksum,
logical_id,
serial_number,
data_length)
protocol_byte, self.header_parse, self.header_idx_lst = protocol_header
d_header = self.f7WriteRead('_getWiredResponseHeaderBitfield')
if d_header != protocol_byte:
self.f7WriteRead('_setWiredResponseHeaderBitfield', protocol_byte)
d_header = self.f7WriteRead('_getWiredResponseHeaderBitfield')
if d_header != protocol_byte:
print("!!!!!fail d_header={0}, protocol_header_byte={1}".format(d_header, protocol_byte))
raise Exception
def _setupThreadedReadLoop(self):
self.read_lock = threading.Condition(threading.Lock())
self.read_queue = collections.deque()
self.read_dict = {}
self.data_loop = True
self.read_thread = threading.Thread(target=self._dataReadLoop)
self.read_thread.daemon = True
self.read_thread.start()
def __repr__(self):
return "<YEI3Space {0}:{1}>".format(self.device_type, self.serial_number_hex)
def __str__(self):
return self.__repr__()
def close(self):
self.data_loop = False
if self.serial_port:
self.serial_port.close()
self.serial_port = None
self.read_thread.join()
def reconnect(self):
self.close()
if not tryPort(self.port_name):
_print("tryport fail")
try:
serial_port = serial.Serial(self.port_name, baudrate=self.baudrate, timeout=0.5, writeTimeout=0.5)
serial_port.applySettingsDict(self.serial_port_settings)
self.serial_port = serial_port
except:
traceback.print_exc()
return False
self._setupProtocolHeader(**self.protocol_args)
self._setupThreadedReadLoop()
if self.stream_timing is not None:
self.setStreamingTiming(*self.stream_timing)
if self.stream_slot_cmds is not None:
self.setStreamingSlots(*self.stream_slot_cmds)
return True
# Wired Old Protocol WriteRead
def f7WriteRead(self, command, input_list=None):
command_args = self.command_dict[command]
cmd_byte, out_len, out_struct, in_len, in_struct, compatibility = command_args
packed_data = None
if in_struct:
if type(input_list) in (list, tuple):
packed_data = struct.pack(in_struct, *input_list)
else:
packed_data = struct.pack(in_struct, input_list)
write_array = makeWriteArray(0xf7, None, cmd_byte, packed_data)
self.serial_port.write(write_array)
if out_struct:
output_data = self.serial_port.read(out_len)
rtn_list = struct.unpack(out_struct, output_data)
if len(rtn_list) != 1:
return rtn_list
return rtn_list[0]
# requires the dataloop, do not call
# Wired New Protocol WriteRead
def f9WriteRead(self, command, input_list=None):
global global_counter
command_args = self.command_dict[command]
cmd_byte, out_len, out_struct, in_len, in_struct, compatibility = command_args
if self.compatibility < compatibility:
raise Exception("Firmware for device on ( %s ) is out of date for this function. Recommend updating to latest firmware." % self.serial_port.name)
packed_data = None
if in_struct:
if type(input_list) in (list, tuple):
packed_data = struct.pack(in_struct, *input_list)
else:
packed_data = struct.pack(in_struct, input_list)
write_array = makeWriteArray(0xf9, None, cmd_byte, packed_data)
self.read_lock.acquire()
uid = global_counter
global_counter += 1
try:
self.serial_port.write(write_array) # release in reader thread
except serial.SerialTimeoutException:
self.read_lock.release()
self.serial_port.close()
# _print("SerialTimeoutException!!!!")
# !!!!!Reconnect
return (True, None, None)
except ValueError:
try:
# _print("trying to open it back up!!!!")
self.serial_port.open()
# _print("aaand open!!!!")
except serial.SerialException:
self.read_lock.release()
# _print("SerialTimeoutException!!!!")
# !!!!!Reconnect
return (True, None, None)
queue_packet = (uid, cmd_byte)
timeout_time = 0.5 + (len(self.read_queue) * 0.150) # timeout increases as queue gets larger
self.read_queue.append(queue_packet)
start_time = time.perf_counter() + timeout_time
read_data = None
while (timeout_time > 0):
self.read_lock.wait(timeout_time)
read_data = self.read_dict.get(uid, None)
if read_data is not None:
break
timeout_time = start_time - time.perf_counter()
# _print("Still waiting {0} {1} {2}".format(uid, command, timeout_time))
else:
# _print("Operation timed out!!!!")
try:
self.read_queue.remove(queue_packet)
except:
traceback.print_exc()
self.read_lock.release()
return (True, None, None)
self.read_lock.release()
del self.read_dict[uid]
header_list, output_data = read_data
fail_byte, timestamp, cmd_echo, ck_sum, rtn_log_id, sn, data_size = header_list
if cmd_echo != cmd_byte:
# _print("!!!!!!!!cmd_echo!=cmd_byte!!!!!")
# _print('cmd_echo= 0x{0:02x} cmd_byte= 0x{1:02x}'.format(cmd_echo, cmd_byte))
return (True, timestamp, None)
rtn_list = None
if not fail_byte:
if out_struct:
rtn_list = struct.unpack(out_struct, output_data)
if len(rtn_list) == 1:
rtn_list = rtn_list[0]
else:
# _print("fail_byte!!!!triggered")
pass
return (fail_byte, timestamp, rtn_list)
writeRead = f9WriteRead
def isConnected(self, try_reconnect=False):
try:
serial = self.getSerialNumber()
if serial is not None:
return True
except:
pass
return False
## generated functions USB and WL_ and DNG and EM_ and DL_ and BT_
## 85(0x55)
def stopStreaming(self):
fail_byte, t_stamp, data = self.writeRead('stopStreaming')
return not fail_byte
## 86(0x56)
def startStreaming(self):
fail_byte, t_stamp, data = self.writeRead('startStreaming')
return not fail_byte
## 95(0x5f)
def updateCurrentTimestamp(self, time, timestamp=False):
fail_byte, t_stamp, data = self.writeRead('updateCurrentTimestamp', time)
if timestamp:
return (not fail_byte, t_stamp)
return not fail_byte
## 196(0xc4)
def setLEDMode(self, mode, timestamp=False):
fail_byte, t_stamp, data = self.writeRead('setLEDMode', mode)
if timestamp:
return (not fail_byte, t_stamp)
return not fail_byte
## 200(0xc8)
def getLEDMode(self, timestamp=False):
fail_byte, t_stamp, data = self.writeRead('getLEDMode')
if timestamp:
return (data, t_stamp)
return data
## 223(0xdf)
def getFirmwareVersionString(self, timestamp=False):
fail_byte, t_stamp, data = self.writeRead('getFirmwareVersionString')
data = convertString(data)
if timestamp:
return (data, t_stamp)
return data
## 225(0xe1)
def commitSettings(self, timestamp=False):
fail_byte, t_stamp, data = self.writeRead('commitSettings')
if timestamp:
return (not fail_byte, t_stamp)
return not fail_byte
## 230(0xe6)
def getHardwareVersionString(self, timestamp=False):
fail_byte, t_stamp, data = self.writeRead('getHardwareVersionString')
data = convertString(data)
if timestamp:
return (data, t_stamp)
return data
## 237(0xed)
def getSerialNumber(self, timestamp=False):
fail_byte, t_stamp, data = self.writeRead('getSerialNumber')
if timestamp:
return (data, t_stamp)
return data
## 238(0xee)
def setLEDColor(self, rgb, timestamp=False):
fail_byte, t_stamp, data = self.writeRead('setLEDColor', rgb)
if timestamp:
return (not fail_byte, t_stamp)
return not fail_byte
## 239(0xef)
def getLEDColor(self, timestamp=False):
fail_byte, t_stamp, data = self.writeRead('getLEDColor')
if timestamp:
return (data, t_stamp)
return data
## 253(0xfd)
def setJoystickAndMousePresentRemoved(self, joystick, mouse, timestamp=False):
arg_list = (joystick, mouse)
fail_byte, t_stamp, data = self.writeRead('setJoystickAndMousePresentRemoved', arg_list)
if timestamp:
return (not fail_byte, t_stamp)
return not fail_byte
## 254(0xfe)
def getJoystickAndMousePresentRemoved(self, timestamp=False):
fail_byte, t_stamp, data = self.writeRead('getJoystickAndMousePresentRemoved')
if timestamp:
return (data, t_stamp)
return data
## END generated functions USB and WL_ and DNG and EM_ and DL_ and BT_
class _TSSensor(_TSBase):
command_dict = _TSBase.command_dict.copy()
command_dict.update({
'getTaredOrientationAsQuaternion': (0x0, 16, '>4f', 0, None, 1),
'getTaredOrientationAsEulerAngles': (0x1, 12, '>fff', 0, None, 1),
'getTaredOrientationAsRotationMatrix': (0x2, 36, '>9f', 0, None, 1),
'getTaredOrientationAsAxisAngle': (0x3, 16, '>4f', 0, None, 1),
'getTaredOrientationAsTwoVector': (0x4, 24, '>6f', 0, None, 1),
'getDifferenceQuaternion': (0x5, 16, '>4f', 0, None, 1),
'getUntaredOrientationAsQuaternion': (0x6, 16, '>4f', 0, None, 1),
'getUntaredOrientationAsEulerAngles': (0x7, 12, '>fff', 0, None, 1),
'getUntaredOrientationAsRotationMatrix': (0x8, 36, '>9f', 0, None, 1),
'getUntaredOrientationAsAxisAngle': (0x9, 16, '>4f', 0, None, 1),
'getUntaredOrientationAsTwoVector': (0xa, 24, '>6f', 0, None, 1),
'getTaredTwoVectorInSensorFrame': (0xb, 24, '>6f', 0, None, 1),
'getUntaredTwoVectorInSensorFrame': (0xc, 24, '>6f', 0, None, 1),
'setEulerAngleDecompositionOrder': (0x10, 0, None, 1, '>B', 1),
'setMagnetoresistiveThreshold': (0x11, 0, None, 16, '>fIff', 3),
'setAccelerometerResistanceThreshold': (0x12, 0, None, 8, '>fI', 3),
'offsetWithCurrentOrientation': (0x13, 0, None, 0, None, 3),
'resetBaseOffset': (0x14, 0, None, 0, None, 3),
'offsetWithQuaternion': (0x15, 0, None, 16, '>4f', 3),
'setBaseOffsetWithCurrentOrientation': (0x16, 0, None, 0, None, 3),
'getAllNormalizedComponentSensorData': (0x20, 36, '>9f', 0, None, 1),
'getNormalizedGyroRate': (0x21, 12, '>fff', 0, None, 1),
'getNormalizedAccelerometerVector': (0x22, 12, '>fff', 0, None, 1),
'getNormalizedCompassVector': (0x23, 12, '>fff', 0, None, 1),
'getAllCorrectedComponentSensorData': (0x25, 36, '>9f', 0, None, 1),
'getCorrectedGyroRate': (0x26, 12, '>fff', 0, None, 1),
'getCorrectedAccelerometerVector': (0x27, 12, '>fff', 0, None, 1),
'getCorrectedCompassVector': (0x28, 12, '>fff', 0, None, 1),
'getCorrectedLinearAccelerationInGlobalSpace': (0x29, 12, '>fff', 0, None, 1),
'getTemperatureC': (0x2b, 4, '>f', 0, None, 1),
'getTemperatureF': (0x2c, 4, '>f', 0, None, 1),
'getConfidenceFactor': (0x2d, 4, '>f', 0, None, 1),
'getAllRawComponentSensorData': (0x40, 36, '>9f', 0, None, 1),
'getRawGyroscopeRate': (0x41, 12, '>fff', 0, None, 1),
'getRawAccelerometerData': (0x42, 12, '>fff', 0, None, 1),
'getRawCompassData': (0x43, 12, '>fff', 0, None, 1),
'_setStreamingSlots': (0x50, 0, None, 8, '>8B', 1),
'_getStreamingSlots': (0x51, 8, '>8B', 0, None, 1),
'_setStreamingTiming': (0x52, 0, None, 12, '>III', 1),
'_getStreamingTiming': (0x53, 12, '>III', 0, None, 1),
'_getStreamingBatch': (0x54, 0, None, 0, None, 1),
'tareWithCurrentOrientation': (0x60, 0, None, 0, None, 1),
'tareWithQuaternion': (0x61, 0, None, 16, '>4f', 1),
'tareWithRotationMatrix': (0x62, 0, None, 36, '>9f', 1),
'setStaticAccelerometerTrustValue': (0x63, 0, None, 4, '>f', 2),
'setConfidenceAccelerometerTrustValues': (0x64, 0, None, 8, '>ff', 2),
'setStaticCompassTrustValue': (0x65, 0, None, 4, '>f', 2),
'setConfidenceCompassTrustValues': (0x66, 0, None, 8, '>ff', 2),
'setDesiredUpdateRate': (0x67, 0, None, 4, '>I', 1),
'setReferenceVectorMode': (0x69, 0, None, 1, '>B', 1),
'setOversampleRate': (0x6a, 0, None, 1, '>B', 1),
'setGyroscopeEnabled': (0x6b, 0, None, 1, '>B', 1),
'setAccelerometerEnabled': (0x6c, 0, None, 1, '>B', 1),
'setCompassEnabled': (0x6d, 0, None, 1, '>B', 1),
'setAxisDirections': (0x74, 0, None, 1, '>B', 1),
'setRunningAveragePercent': (0x75, 0, None, 4, '>f', 1),
'setCompassReferenceVector': (0x76, 0, None, 12, '>fff', 1),
'setAccelerometerReferenceVector': (0x77, 0, None, 12, '>fff', 1),
'resetKalmanFilter': (0x78, 0, None, 0, None, 1),
'setAccelerometerRange': (0x79, 0, None, 1, '>B', 1),
'setFilterMode': (0x7b, 0, None, 1, '>B', 1),
'setRunningAverageMode': (0x7c, 0, None, 1, '>B', 1),
'setGyroscopeRange': (0x7d, 0, None, 1, '>B', 1),
'setCompassRange': (0x7e, 0, None, 1, '>B', 1),
'getTareAsQuaternion': (0x80, 16, '>4f', 0, None, 1),
'getTareAsRotationMatrix': (0x81, 36, '>9f', 0, None, 1),
'getAccelerometerTrustValues': (0x82, 8, '>ff', 0, None, 2),
'getCompassTrustValues': (0x83, 8, '>ff', 0, None, 2),
'getCurrentUpdateRate': (0x84, 4, '>I', 0, None, 1),
'getCompassReferenceVector': (0x85, 12, '>fff', 0, None, 1),
'getAccelerometerReferenceVector': (0x86, 12, '>fff', 0, None, 1),
'getGyroscopeEnabledState': (0x8c, 1, '>B', 0, None, 1),
'getAccelerometerEnabledState': (0x8d, 1, '>B', 0, None, 1),
'getCompassEnabledState': (0x8e, 1, '>B', 0, None, 1),
'getAxisDirections': (0x8f, 1, '>B', 0, None, 1),
'getOversampleRate': (0x90, 1, '>B', 0, None, 1),
'getRunningAveragePercent': (0x91, 4, '>f', 0, None, 1),
'getDesiredUpdateRate': (0x92, 4, '>I', 0, None, 1),
'getAccelerometerRange': (0x94, 1, '>B', 0, None, 1),
'getFilterMode': (0x98, 1, '>B', 0, None, 1),
'getRunningAverageMode': (0x99, 1, '>B', 0, None, 1),
'getGyroscopeRange': (0x9a, 1, '>B', 0, None, 1),
'getCompassRange': (0x9b, 1, '>B', 0, None, 1),
'getEulerAngleDecompositionOrder': (0x9c, 1, '>B', 0, None, 1),
'getMagnetoresistiveThreshold': (0x9d, 16, '>fIff', 0, None, 3),
'getAccelerometerResistanceThreshold': (0x9e, 8, '>fI', 0, None, 3),
'getOffsetOrientationAsQuaternion': (0x9f, 16, '>4f', 0, None, 3),
'setCompassCalibrationCoefficients': (0xa0, 0, None, 48, '>12f', 1),
'setAccelerometerCalibrationCoefficients': (0xa1, 0, None, 48, '>12f', 1),
'getCompassCalibrationCoefficients': (0xa2, 48, '>12f', 0, None, 1),
'getAccelerometerCalibrationCoefficients': (0xa3, 48, '>12f', 0, None, 1),
'getGyroscopeCalibrationCoefficients': (0xa4, 48, '>12f', 0, None, 1),
'beginGyroscopeAutoCalibration': (0xa5, 0, None, 0, None, 1),
'setGyroscopeCalibrationCoefficients': (0xa6, 0, None, 48, '>12f', 1),
'setCalibrationMode': (0xa9, 0, None, 1, '>B', 1),
'getCalibrationMode': (0xaa, 1, '>B', 0, None, 1),
'setOrthoCalibrationDataPointFromCurrentOrientation': (0xab, 0, None, 0, None, 1),
'setOrthoCalibrationDataPointFromVector': (0xac, 0, None, 14, '>BBfff', 1),
'getOrthoCalibrationDataPoint': (0xad, 12, '>fff', 2, '>BB', 1),
'performOrthoCalibration': (0xae, 0, None, 0, None, 1),
'clearOrthoCalibrationData': (0xaf, 0, None, 0, None, 1),
'setSleepMode': (0xe3, 0, None, 1, '>B', 1),
'getSleepMode': (0xe4, 1, '>B', 0, None, 1),
'setJoystickEnabled': (0xf0, 0, None, 1, '>B', 1),
'setMouseEnabled': (0xf1, 0, None, 1, '>B', 1),
'getJoystickEnabled': (0xf2, 1, '>B', 0, None, 1),
'getMouseEnabled': (0xf3, 1, '>B', 0, None, 1),
'setControlMode': (0xf4, 0, None, 3, '>BBB', 1),
'setControlData': (0xf5, 0, None, 7, '>BBBf', 1),
'getControlMode': (0xf6, 1, '>B', 2, '>BB', 1),
'getControlData': (0xf7, 4, '>f', 3, '>BBB', 1),
'setMouseAbsoluteRelativeMode': (0xfb, 0, None, 1, '>B', 1),
'getMouseAbsoluteRelativeMode': (0xfc, 1, '>B', 0, None, 1)
})
reverse_command_dict = dict(map(lambda x: [x[1][0], x[0]], command_dict.items()))
_device_types = ["!BASE"]
def __new__(cls, com_port=None, baudrate=_baudrate, timestamp_mode=TSS_TIMESTAMP_SENSOR):
if com_port:
if type(com_port) is str:
port_name = com_port
elif type(com_port) is ComInfo:
port_name = com_port.com_port
else:
_print("An erronous parameter was passed in")
return None
if baudrate not in _allowed_baudrates:
baudrate = _baudrate
_print("Error baudrate value not allowed. Using default.")
serial_port = serial.Serial(port_name, baudrate=baudrate, timeout=0.5, writeTimeout=0.5)
if serial_port is not None:
new_inst = super(_TSSensor, cls).__new__(cls)
return _generateSensorClass(new_inst, serial_port, _TSSensor._device_types)
_print('Error serial port was not made')
def __init__(self, com_port=None, baudrate=_baudrate, timestamp_mode=TSS_TIMESTAMP_SENSOR):
self.protocol_args = {'success_failure': True,
'timestamp': True,
'command_echo': True,
'data_length': True}
if timestamp_mode != TSS_TIMESTAMP_SENSOR:
self.protocol_args['timestamp'] = False
self.timestamp_mode = timestamp_mode
self.baudrate = baudrate
reinit = False
try: # if this is set the class had been there before
check = self.stream_parse
reinit = True
# _print("sensor reinit!!!")
except:
self._setupBaseVariables()
self.callback_func = None
self._setupProtocolHeader(**self.protocol_args)
self._setupThreadedReadLoop()
self.latest_lock = threading.Condition(threading.Lock())
self.new_data = False
if reinit:
if self.stream_timing is not None:
self.setStreamingTiming(*self.stream_timing)
if self.stream_slot_cmds is not None:
self.setStreamingSlots(*self.stream_slot_cmds)
def _queueWriteRead(self, rtn_dict, rtn_key, retries, command, input_list=None):
try:
for i in range(retries):
packet = self.writeRead(command, input_list)
if packet[0]:
# _print("##Attempt: {0} complete".format(i))
time.sleep(0.1)
continue
rtn_dict[rtn_key] = packet
break
else:
# _print("sensor failed to succeed")
rtn_dict[rtn_key] = (True, None, None)
except(KeyboardInterrupt):
print('\n! Received keyboard interrupt, quitting threads.\n')
raise KeyboardInterrupt # fix bug where a thread eats the interupt
def queueWriteRead(self, rtn_dict, rtn_key, retries, command, input_list=None):
return threading.Thread(target=self._queueWriteRead, args=(rtn_dict, rtn_key, retries, command, input_list))
def _generateStreamParse(self):
stream_string = '>'
if self.stream_slot_cmds is None:
self.getStreamingSlots()
for slot_cmd in self.stream_slot_cmds:
if slot_cmd is not 'null':
out_struct = self.command_dict[slot_cmd][2]
stream_string += out_struct[1:] # stripping the >
self.stream_parse = struct.Struct(stream_string)
# Set streaming batch command
self.command_dict['_getStreamingBatch'] = (0x54, self.stream_parse.size, stream_string, 0, None, 1)
def _parseStreamData(self, protocol_data, output_data):
rtn_list = self.stream_parse.unpack(output_data)
if len(rtn_list) == 1: