-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgearVRC.py
2542 lines (2203 loc) · 109 KB
/
gearVRC.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/python3
################################################################
# Samsung gearVR Controller
################################################################
# This work is based on:
# Gear VRC reverse engineering (Java):
# https://github.com/jsyang/gearvr-controller-webbluetooth
# Gear VRC to UDEV (Python):
# https://github.com/rdady/gear-vr-controller-linux
################################################################
# Prerequisite:
# A) python packages:
# $ sudo pip3 install
# bleak, uvloop, zmq asyncio pyserial-asyncio
# msgpack,re, pathlib, json, numpy
# B Linux) Pair Controller (check README):
# $ bluetoothlctl
# scan on
# pair yourMAC
# trust yourMAC
# connect yourMAC
# B Windows) Pair Controller:
# No command line tools for pairing of BLE devices available
# You will need to manually remove the device from the system
# each time before using it.
################################################################
# IMPORTS
################################################################
import asyncio
import logging
import struct
import argparse
import signal
import math
import time
import numpy as np
import os
from copy import copy
import serial_asyncio
import re
import msgpack
import pathlib
import json
from bleak import BleakClient, BleakScanner
from bleak.backends.characteristic import BleakGATTCharacteristic
from pyIMU.madgwick import Madgwick
from pyIMU.quaternion import Vector3D, Quaternion
from pyIMU.utilities import q2rpy, rpymag2h, qmag2h
from pyIMU.motion import Motion
import zmq
import zmq.asyncio
# Activate uvloop to speed up asyncio
if os.name == 'nt':
from asyncio.windows_events import WindowsSelectorEventLoopPolicy
asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())
else:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
# to run bluetoothctl
if os.name == 'posix': import subprocess
RAD2DEG = 180.0 / math.pi
DEG2RAD = math.pi / 180.0
TWOPI = 2.0*math.pi
BAUDRATE = 115200
ZMQPORT = 5556
ZMQTIMEOUT = 1000 # ms
# Device name:
################################################################
DEVICE_NAME = 'Gear VR Controller(17DB)'
DEVICE_MAC = '2C:BA:BA:2E:17:DB'
BLETIMEOUT = 10.0
# LOCATION
################################################################
DECLINATION = 8.124973426113137 * DEG2RAD # Declination at your location
LATITUDE = 32.253460 # [degrees] Tucson
LONGITUDE = -110.911789 # [degrees] Tucson
ALTITUDE = 730 # [m], Tucson
MAGFIELD = 33078.93064435485 # [nano Tesla] Tucson
MAGFIELD_MAX = 1.2*MAGFIELD/1000. # micro Tesla
MAGFIELD_MIN = 0.8*MAGFIELD/1000. # micro Tesla
# Program Timing:
################################################################
KEEPALIVEINTERVAL = 60. # Every 60 secs send command to keep alive
VIRTUALUPDATEINTERVAL = 1./20. # 20 Hz
REPORTINTERVAL = 1./10. # 10 Hz
# Device commands:
################################################################
CMD_OFF = bytearray(b'\x00\x00') # Turn modes off and stop sending data
CMD_SENSOR = bytearray(b'\x01\x00') # Touchpad and sensor buttons but low rate IMU data
CMD_UNKNOWN_FIRMWARE_UPDATE_FUNC = bytearray(b'\x02\x00') # Initiate firmware update sequence
CMD_CALIBRATE = bytearray(b'\x03\x00') # Initiate calibration: Not sure how to compensate for drift
CMD_KEEP_ALIVE = bytearray(b'\x04\x00') # Keep alive: Not sure about time interval
CMD_UNKNOWN_SETTING = bytearray(b'\x05\x00') # Setting mode: ?
CMD_LPM_ENABLE = bytearray(b'\x06\x00') # ?
CMD_LPM_DISABLE = bytearray(b'\x07\x00') # ?
CMD_VR_MODE = bytearray(b'\x08\x00') # Enable VR mode: high frequency event mode
# Device Supplements:
################################################################
# Virtual wheel (touching the touchpad along its rim)
WHEELDIAMETER = 315 # Touch pad diameter in pixels
WHEELTICKNESS = 25 # Virtual wheel rim thickness in pixels
WHEELRADIUS = WHEELDIAMETER / 2. # Radius of touch pad
WHEELRADIUS2 = WHEELRADIUS**2
RTHRESH2 = (WHEELRADIUS - WHEELTICKNESS)**2
NUMWHEELPOS = 64 # Number of simulated rotating wheel positions
NUMWHEELPOS1_8 = NUMWHEELPOS*1/8
NUMWHEELPOS3_8 = NUMWHEELPOS*3/8
NUMWHEELPOS5_8 = NUMWHEELPOS*5/8
NUMWHEELPOS7_8 = NUMWHEELPOS*7/8
MAXWHEELPOS = NUMWHEELPOS-1
MAXWHEELPOS2 = MAXWHEELPOS/2.0
# Scrolling on virtual touchpad
# We can extend the range of the touchpad by scrolling:
# lifting the finger and moving in same direction again
MINXTOUCH = 0 # min virtual touchpad X
MINYTOUCH = 0
MAXXTOUCH = 1024 # max virtual touchpad X
MAXYTOUCH = 1024
# Motion Detection
# Adjust as it depends on sensor
################################################################
FUZZY_ACCEL_ZERO_MAX = 10.0 # threshold for acceleration activity
FUZZY_ACCEL_ZERO_MIN = 9.5 # threshold for acceleration activity
FUZZY_DELTA_ACCEL_ZERO = 0.04 # threshold for acceleration change
FUZZY_GYRO_ZERO = 0.08 # threshold for gyroscope activity
FUZZY_DELTA_GYRO_ZERO = 0.003 # threshold for gyroscope change
################################################################
# Support Functions
################################################################
def ror(l, n):
'''
split list at position -n and attach right section in front left section
'''
return l[-n:] + l[:-n]
def clamp(val, smallest, largest):
'''
clip val to [smallest, largest]
'''
if val < smallest: return smallest
if val > largest: return largest
return val
def calibrate(data:Vector3D, offset:Vector3D, crosscorr=None, diagonal=False):
'''
IMU calibration
bias is offset so that 0 is in the middle of the range
scale is the gain so that 1 is the maximum value
cross correlation is cross axis sensitivity
the diagonal elements of the cross correlation matrix are the scale
Expects data and bias to be a Vector3D
Expects crosscorr to be 3x3 numpy array
'''
# Bias
d = copy(data) # we do not want input parameter to change globally
d = d-offset
if diagonal:
if crosscorr is not None:
d=Vector3D(d.x*crosscorr[0,0], d.y*crosscorr[1,1], d.z*crosscorr[2,2])
else:
# Cross Correlation
if crosscorr is not None:
d = d.rotate(crosscorr)
return d
def loadCalibration(filename):
'''
Load Calibration file
Data is stored in json format
offset is the bias
crosscorr is the cross correlation matrix
diagonal of crosscorr is the scale
'''
with open(filename, 'r') as file:
d = json.load(file)
center = np.array([d['offset_x'],d['offset_y'],d['offset_z']])
correctionMat = np.empty([3,3])
correctionMat[0,0] = d['cMat_00']
correctionMat[0,1] = d['cMat_01']
correctionMat[0,2] = d['cMat_02']
correctionMat[1,0] = d['cMat_10']
correctionMat[1,1] = d['cMat_11']
correctionMat[1,2] = d['cMat_12']
correctionMat[2,0] = d['cMat_20']
correctionMat[2,1] = d['cMat_21']
correctionMat[2,2] = d['cMat_22']
return center, correctionMat
def saveCalibration(filename, center, correctionMat):
'''Save Calibration Data to JSON file'''
d = {
"offset_x": center[0],
"offset_y": center[1],
"offset_z": center[2],
"cMat_00": correctionMat[0,0],
"cMat_01": correctionMat[0,1],
"cMat_02": correctionMat[0,2],
"cMat_10": correctionMat[1,0],
"cMat_11": correctionMat[1,1],
"cMat_12": correctionMat[1,2],
"cMat_20": correctionMat[2,0],
"cMat_21": correctionMat[2,1],
"cMat_22": correctionMat[2,2]
}
with open(filename, 'w') as file:
json.dump(d, file)
def detectMotion(acc: float, gyr: float, acc_avg: float, gyr_avg:float) -> bool:
'''
# 4 Stage Motion Detection
# ------------------------
1. Acceleration Activity
2. Change in Acceleration
3. Gyration Activity
4. Change in Gyration
Original Code is from FreeIMU Processing example with some modifications and tuning
'''
# ACCELEROMETER
# Absolute value
acc_test = abs(acc) > FUZZY_ACCEL_ZERO_MAX and abs(acc) < FUZZY_ACCEL_ZERO_MIN
# Sudden changes
acc_delta_test = abs(acc_avg - acc) > FUZZY_DELTA_ACCEL_ZERO
# GYROSCOPE
# Absolute value
gyr_test = abs(gyr) > FUZZY_GYRO_ZERO
# Sudden changes
gyr_delta_test = abs(gyr_avg - gyr) > FUZZY_DELTA_GYRO_ZERO
# DEBUG for fine tuning
# print(abs(acc), abs(acc_avg-acc), abs(gyr), abs(gyr_avg-gyr), acc_test, acc_delta_test, gyr_test, gyr_delta_test)
# Combine acceleration test, acceleration deviation test and gyro test
return (acc_test or acc_delta_test or gyr_test or gyr_delta_test)
def check_bluetooth_connected(address):
'''
Check if bluetooth device is already connected
Only on posix
'''
if os.name == 'posix':
try:
output = subprocess.check_output(["bluetoothctl", "info", address], timeout=5, text=True)
lines = output.strip().split("\n")
for line in lines:
if "Connected: yes" in line:
return True
elif "Connected: no" in line:
return False
return False
except:
return False
else:
return False
def disconnect_bluetooth_device(address):
'''
Disconnects bluetooth device
Only on posix
'''
if os.name == 'posix':
try:
output = subprocess.check_output(["bluetoothctl", "disconnect", address], timeout=5, text=True)
return True
except:
return False
else:
return False
def obj2dict(obj):
'''
encoding object variables to nested dictionary
'''
if isinstance(obj, dict):
return {k: obj2dict(v) for k, v in obj.items()}
elif hasattr(obj, '__dict__'):
return obj2dict(vars(obj))
elif isinstance(obj, list):
return [obj2dict(item) for item in obj]
else:
return obj
class dict2obj:
'''
decoding nested dictionary to object
'''
def __init__(self, data):
for key, value in data.items():
if isinstance(value, dict):
setattr(self, key, dict2obj(value))
else:
setattr(self, key, value)
def float_to_hex(f):
'''
Pack float into 8 characters 0..9,A..F
'''
bytes_ = struct.pack('!f', f) # Single precision, big-endian byte order, 4 bytes
hex_strings = [format(byte, '02X') for byte in bytes_] # Convert each byte to a hexadecimal string
return ''.join(hex_strings)
def hex_to_float(hex_chars):
'''
Unpack 8 characters to float
'''
hex_bytes = bytes.fromhex(hex_chars) # Convert hex characters to bytes
return struct.unpack('!f', hex_bytes)[0]
def int_to_hex(n):
'''
Pack integer to 8 characters
'''
bytes_ = n.to_bytes((n.bit_length() + 7) // 8, 'big') # Convert integer to bytes
hex_strings = [format(byte, '02X') for byte in bytes_] # Convert each byte to a hexadecimal string
return ''.join(hex_strings)
def hex_to_int(hex_chars):
'''
Unpack 8 characters to integer
'''
hex_bytes = bytes.fromhex(hex_chars) # Convert hex characters to bytes
return struct.unpack('!i', hex_bytes)[0]
###################################################################
# Data Classes
###################################################################
class gearSystemData(object):
'''System relevant performance data'''
def __init__(self, temperature: float=0.0, battery_level: float =-1.0,
data_rate: int = 0, virtual_rate: int = 0, fusion_rate: int = 0,
zmq_rate: int = 0, serial_rate: int = 0, reporting_rate: int = 0,
fusion: bool=False,
motion: bool=False,
virtual: bool=False,
serial: bool=False) -> None:
self.temperature = temperature
self.battery_level = battery_level
self.data_rate = data_rate
self.virtual_rate = virtual_rate
self.fusion_rate = fusion_rate
self.zmq_rate = zmq_rate
self.serial_rate = serial_rate
self.reporting_rate = reporting_rate
self.fusion = fusion
self.motion = motion
self.virtual = virtual
self.serial = serial
class gearIMUData(object):
'''IMU Data from the sensor'''
def __init__(self,
time: float=0.0,
acc: Vector3D = Vector3D(0.,0.,0.),
gyr: Vector3D = Vector3D(0.,0.,0.),
mag: Vector3D = Vector3D(0.,0.,0.),
moving: bool = True,
magok: bool = False) -> None:
self.time = time
self.acc = acc
self.mag = mag
self.gyr = gyr
self.moving = moving
self.magok = magok
class gearButtonData(object):
'''Button Data from the sensor'''
def __init__(self,
time: float=0.0,
trigger: bool = False, touch: bool = False, back: bool = False, home: bool = False,
volume_up: bool = False, volume_down: bool = False, noButton: bool = True,
touchX: int = 0, touchY: int = 0) -> None:
self.time = time
self.trigger = trigger
self.touch = touch
self.back = back
self.home = home
self.volume_up = volume_up
self.volume_down = volume_down
self.noButton = noButton
self.touchX = touchX
self.touchY = touchY
class gearTouchData(object):
'''Touch Data from the sensor'''
def __init__(self,
time: float=0.0,
touchX: int = 0, touchY: int = 0) -> None:
self.time = time
self.touchX = touchX
self.touchY = touchY
class gearVirtualData(object):
'''Virtual wheel and touchpad data'''
def __init__(self, time: float = 0.,
absX: int = 0, absY: int = 0,
dirUp: bool = False, dirDown: bool = False, dirLeft: bool = False, dirRight: bool = False,
wheelPos: int = 0,
top: bool = False, bottom: bool = False, left: bool = False, right: bool = False, center: bool = False,
clockwise: bool = False, isRotating: bool = False) -> None:
self.time = time
self.absX = absX
self.absY = absY
self.dirUp = dirUp
self.dirDown = dirDown
self.dirLeft = dirLeft
self.dirRight = dirRight
self.wheelPos = wheelPos
self.top = top
self.bottom = bottom
self.left = left
self.right = right
self.center = center
self.clockwise = clockwise
self.isRotating = isRotating
class gearFusionData(object):
'''AHRS fusion data'''
def __init__(self,
time: float = 0.,
acc: Vector3D = Vector3D(0.,0.,0.),
mag: Vector3D = Vector3D(0.,0.,0.),
gyr: Vector3D = Vector3D(0.,0.,0.),
rpy: Vector3D = Vector3D(0.,0.,0.),
heading: float = 0.0,
q: Quaternion = Quaternion(1.,0.,0.,0.)) -> None:
self.time = time
self.acc = acc
self.mag = mag
self.gyr = gyr
self.rpy = rpy
self.heading = heading
self.q = q
class gearMotionData(object):
'''Motion data'''
def __init__(self,
time: float = 0.,
residuals: Vector3D = Vector3D(0.,0.,0.),
velocity: Vector3D = Vector3D(0.,0.,0.),
position: Vector3D = Vector3D(0.,0.,0.),
accBias: Vector3D = Vector3D(0.,0.,0.),
velocityBias: Vector3D = Vector3D(0.,0.,0.),
dtmotion: float = 0.0) -> None:
self.time = time
self.residuals = residuals
self.velocity = velocity
self.position = position
self.dtmotion = dtmotion
self.accBias = accBias
self.velocityBias = velocityBias
##############################################################################
# ZMQWorker
###############################################################################
class zmqWorkerGear():
'''
Receiving data from the GearVR Controller via ZMQ
Primarily useful for third party clients
'''
def __init__(self, logger, zmqPort='tcp://localhost:5556'):
# Signals
self.dataReady = asyncio.Event()
self.finished = asyncio.Event()
self.dataReady.clear()
self.finished.clear()
self.logger = logger
self.zmqPort = zmqPort
self.new_fusion = False
self.new_imu = False
self.new_system = False
self.new_virtual = False
self.new_button = False
self.new_motion = False
self.timeout = False
self.finish_up = False
self.paused = False
self.zmqTimeout = ZMQTIMEOUT
self.logger.log(logging.INFO, 'gearVRC zmqWorker initialized')
async def start(self, stop_event: asyncio.Event):
self.new_system = False
self.new_imu = False
self.new_virtual = False
self.new_fusion = False
self.new_button = False
self.new_motion = False
context = zmq.asyncio.Context()
poller = zmq.asyncio.Poller()
self.data_system = None
self.data_imu = None
self.data_motion = None
self.data_virtual = None
self.data_button = None
self.data_fusion = None
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, b"system")
socket.setsockopt(zmq.SUBSCRIBE, b"imu")
socket.setsockopt(zmq.SUBSCRIBE, b"virtual")
socket.setsockopt(zmq.SUBSCRIBE, b"fusion")
socket.setsockopt(zmq.SUBSCRIBE, b"button")
socket.setsockopt(zmq.SUBSCRIBE, b"motion")
socket.connect(self.zmqPort)
poller.register(socket, zmq.POLLIN)
self.logger.log(logging.INFO, 'gearVRC zmqWorker started on {}'.format(self.zmqPort))
while not self.finish_up:
try:
events = dict(await poller.poll(timeout=self.zmqTimeout))
if socket in events and events[socket] == zmq.POLLIN:
response = await socket.recv_multipart()
if len(response) == 2:
[topic, msg_packed] = response
if topic == b"system":
msg_dict = msgpack.unpackb(msg_packed)
self.data_system = dict2obj(msg_dict)
self.new_system = True
elif topic == b"imu":
msg_dict = msgpack.unpackb(msg_packed)
self.data_imu = dict2obj(msg_dict)
self.new_imu = True
elif topic == b"virtual":
msg_dict = msgpack.unpackb(msg_packed)
self.data_virtual = dict2obj(msg_dict)
self.new_virtual = True
elif topic == b"fusion":
msg_dict = msgpack.unpackb(msg_packed)
self.data_fusion = dict2obj(msg_dict)
self.new_fusion = True
elif topic == b"button":
msg_dict = msgpack.unpackb(msg_packed)
self.data_button = dict2obj(msg_dict)
self.new_button = True
elif topic == b"motion":
msg_dict = msgpack.unpackb(msg_packed)
self.data_motion = dict2obj(msg_dict)
self.new_motion = True
else:
pass # not a topic we need
else:
self.logger.log(
logging.ERROR, 'gearVRC zmqWorker malformed message')
else: # ZMQ TIMEOUT
self.logger.log(logging.ERROR, 'gearVRC zmqWorker timed out')
poller.unregister(socket)
socket.close()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, b"system")
socket.setsockopt(zmq.SUBSCRIBE, b"imu")
socket.setsockopt(zmq.SUBSCRIBE, b"virtual")
socket.setsockopt(zmq.SUBSCRIBE, b"fusion")
socket.setsockopt(zmq.SUBSCRIBE, b"button")
socket.setsockopt(zmq.SUBSCRIBE, b"motion")
socket.connect(self.zmqPort)
poller.register(socket, zmq.POLLIN)
self.new_system = \
self.new_imu = \
self.new_virtual= \
self.new_fusion = \
self.new_button = \
self.new_motion = False
if (self.new_imu and self.new_system):
if self.data_system.fusion:
if self.new_fusion:
if self.data_system.motion:
if self.new_motion:
if self.data_system.virtual:
if self.new_virtual:
if not self.paused: self.dataReady.set()
self.new_system = \
self.new_button = \
self.new_imu = \
self.new_fusion = \
self.new_virtual = \
self.new_motion = False
else:
pass # just wait until we have virtual
else:
if not self.paused: self.dataReady.set()
self.new_system = \
self.new_button = \
self.new_imu = \
self.new_fusion = \
self.new_motion = False
else:
pass # wait for motion
else:
if not self.paused: self.dataReady.set()
self.new_system = \
self.new_button = \
self.new_imu = \
self.new_fusion = False
else:
pass # just wait until we have fusion data
else:
if not self.paused: self.dataReady.set()
self.new_system = \
self.new_button = \
self.new_imu = False
else:
pass # we need imu and system data, lets wiat for both
except:
self.logger.log(logging.ERROR, 'gearVRC zmqWorker error')
poller.unregister(socket)
socket.close()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, b"system")
socket.setsockopt(zmq.SUBSCRIBE, b"imu")
socket.setsockopt(zmq.SUBSCRIBE, b"virtual")
socket.setsockopt(zmq.SUBSCRIBE, b"fusion")
socket.setsockopt(zmq.SUBSCRIBE, b"button")
socket.setsockopt(zmq.SUBSCRIBE, b"motion")
socket.connect(self.zmqPort)
poller.register(socket, zmq.POLLIN)
self.new_system = \
self.new_imu = \
self.new_virtual= \
self.new_fusion = \
self.new_button = \
self.new_motion = False
self.logger.log(logging.DEBUG, 'gearVRC zmqWorker finished')
socket.close()
context.term()
self.finished.set()
def set_zmqPort(self, port):
self.zmqPort = port
def pause(self):
self.paused = not self.paused
#########################################################################################################
# gearVRC
#########################################################################################################
class gearVRC:
def __init__(self, args, logger) -> None:
self.args = args
# Shared States
self.fusion = args.fusion
self.motion = args.motion
self.report = args.report
# ZMQ
self.zmqPortPUB = args.zmqPortPUB
self.zmqPortREP = args.zmqPortREP
# Serial
self.serialport = args.serial
self.baudrate = args.baud
if self.serialport is not None: self.serial = True
else: self.serial = False
# Bluetooth device description
self.device_name = args.name
self.device_address = args.address
# Bluetooth device and client
self.device = None
self.client = None
self.generic_access_profile_service = None
self.device_name_characteristic = None
self.device_information_service = None
self.manufacturer_name_characteristic = None
self.model_number_characteristic = None
self.serial_number_characteristic = None
self.hardware_revision_characteristic = None
self.firmware_version_characteristic = None
self.software_revision_characteristic = None
self.PnP_ID_characteristic = None
self.battery_service = None
self.battery_level_characteristic = None
self.controller_data_service = None
self.controller_data_characteristic = None
self.controller_command_characteristics = None
self.manufacturer_name = ''
self.model_number = ''
self.model_number = ''
self.hardware_revision = ''
self.firmware_revision = ''
self.software_revision = ''
self.pnp_ID = -1
# Controller home button to stop program
self.ESC_reps = args.escreps
self.ESC_timeout = args.esctimeout
# Signals
self.lost_connection = asyncio.Event()
self.processedDataAvailable = asyncio.Event()
self.terminate = asyncio.Event()
# These Signals are easier to deal with without Event
self.connected = False
self.sensorStarted = False
self.finish_up = False
self.paused = False
if logger is not None: self.logger = logger
else: self.logger = logging.getLogger('gearVRC')
self.VRMode = args.vrmode
self.HighResMode = False
# device sensors
self.sensorTime = 0. # There are 3 different times transmitted from the sensor
# self.aTime = 0. # Assuming the earliest time corresponds to IMU
# self.bTime = 0. #
self.delta_sensorTime = 0.
# self.delta_aTime = 0.
# self.delta_bTime = 0.
self.previous_sensorTime = 0.
# self.previous_aTime = 0.
# self.previous_bTime = 0.
# IMU
self.accX = 0. # IMU Accelerometer
self.accY = 0. #
self.accZ = 0. #
self.gyrX = 0. # IMY Gyroscope
self.gyrY = 0. #
self.gyrZ = 0. #
self.magX = 0. # IMU Magnetometer
self.magY = 0. #
self.magZ = 0. #
# Touchpad
self.touchX = 0 # Touchpad Location (up/down)
self.touchY = 0 # (left/right)
# Other
self.temperature = 0. # Device Temperature
self.battery_level = 0 # Device Battery level
# Device buttons
self.touch = False # Touchpad has been pressed
self.trigger = False # Trigger button pressed
self.home = False # Home button pressed
self.back = False # Back button pressed
self.volume_up = False # Volume up button pressed
self.volume_down = False # Volume down button pressed
self.noButton = True # No button was pressed (mutually exclusive with the above)
# ESC sequence
self.previous_home = False
self.home_updateCounts = 0
self.home_pressedTime = time.perf_counter()
# Virtual wheel
self.wheelPos = 0 # Wheel position 0..63
self.previous_wheelPos = 0
self.delta_wheelPos = 0
self.top = False # Wheel touched in top quadrant
self.bottom = False # Wheel touched in bottom quadrant
self.left = False # Wheel touched in left quadrant
self.right = False # Wheel touched in right quadrant
self.center = False # Touchpad touched inside of wheel
self.isRotating = False # Moving along the rim of the wheel
self.clockwise = False # Moving clockwise or counter clockwise
# Scrolling
# Touch pad
self.previous_touchX = 0 # touch pad X
self.previous_touchY = 0 # touch pad Y
self.absX = 0 # Position on virtual touchpad (scrolling)
self.absY = 0 #
self.dirUp = False # Touching pad and moving upwards
self.dirDown = False # Touching pad and moving downwards
self.dirLeft = False # Touching pad and moving to the left
self.dirRight = False # Touching pad and moving to the right
# Timing
###################
self.startTime = 0.
self.runTime = 0.
self.data_deltaTime = 0.
self.data_rate = 0
self.data_updateCounts = 0
self.data_lastTime = time.perf_counter()
self.data_lastTimeRate = time.perf_counter()
self.virtual_deltaTime = 0.
self.virtual_rate = 0
self.virtual_updateCounts = 0
self.virtual_updateInterval = VIRTUALUPDATEINTERVAL
self.virtual_lastTimeRate = time.perf_counter()
self.previous_virtualUpdate = time.perf_counter()
self.fusion_deltaTime = 0.
self.fusion_rate = 0
self.fusion_updateCounts = 0
self.fusion_lastTimeRate = time.perf_counter()
self.previous_fusionTime = time.perf_counter()
self.motion_deltaTime = 0.
self.motion_rate = 0
self.motion_updateCounts = 0
self.motion_lastTimeRate = time.perf_counter()
self.previous_motionTime = time.perf_counter()
self.firstTimeMotion = time.perf_counter()
self.report_deltaTime = 0.
self.report_rate = 0
self.report_updateInterval = REPORTINTERVAL
self.report_updateCounts = 0
self.report_lastTimeRate = time.perf_counter()
self.serial_rate = 0
self.serial_deltaTime = 0.
self.serial_updateCounts = 0
self.zmqPUB_rate = 0
self.zmqPUB_deltaTime = 0.
self.zmqPUB_updateCounts = 0
self.zmqPUB_lastTimeRate = time.perf_counter()
self.current_directory = str(pathlib.Path(__file__).parent.absolute())
# Read Calibration Data
my_file = pathlib.Path(self.current_directory + '/Gyr.json')
if my_file.is_file():
self.logger.log(logging.INFO,'Loading Gyroscope Calibration from File...')
gyr_offset, gyr_crosscorr = loadCalibration(my_file)
else:
self.logger.log(logging.INFO,'Loading default Gyroscope Calibration...')
gyr_crosscorr = np.array(([1.,0.,0.], [0.,1.,0.], [0.,0.,1.]))
gyr_offset = np.array(([-0.01335,-0.01048,0.03801]))
my_file = pathlib.Path(self.current_directory + '/Acc.json')
if my_file.is_file():
self.logger.log(logging.INFO,'Loading Accelerometer Calibration from File...')
acc_offset, acc_crosscorr = loadCalibration(my_file)
else:
self.logger.log(logging.INFO,'Loading default Accelerometer Calibration...')
acc_crosscorr = np.array(([1.,0.,0.], [0.,1.,0.], [0.,0.,1.]))
acc_offset = np.array(([0.,0.,0.]))
my_file = pathlib.Path(self.current_directory + '/Mag.json')
if my_file.is_file():
self.logger.log(logging.INFO,'Loading Magnetometer Calibration from File...')
mag_offset, mag_crosscorr = loadCalibration(my_file)
else:
self.logger.log(logging.INFO,'Loading default Magnetometer Calibration...')
mag_crosscorr = np.array(([1.,0.,0.], [0.,1.,0.], [0.,0.,1.]))
mag_offset = np.array(([-48.492,-222.802,-35.28]))
self.acc_offset = Vector3D(acc_offset)
self.gyr_offset = Vector3D(gyr_offset)
self.mag_offset = Vector3D(mag_offset)
self.acc_crosscorr = acc_crosscorr
self.gyr_crosscorr = gyr_crosscorr
self.mag_crosscorr = mag_crosscorr
self.gyr_offset_updated = False
self.acc = Vector3D(0.,0.,0.)
self.gyr = Vector3D(0.,0.,0.)
self.mag = Vector3D(0.,0.,0.)
self.gyr_average = Vector3D(0.,0.,0.)
self.acc_average = Vector3D(0.,0.,0.)
# Attitude fusion
self.AHRS = Madgwick()
self.q = Quaternion(1.,0.,0.,0.)
self.heading = 0.
self.rpy = Vector3D(0.,0.,0.)
self.acc_cal = Vector3D(0.,0.,0.)
self.gyr_cal = Vector3D(0.,0.,0.)
self.mag_cal = Vector3D(0.,0.,0.)
self.moving = True
self.magok = False
# Motion
self.Position = Motion()
self.residuals = Vector3D(0.,0.,0.)
self.velocity = Vector3D(0.,0.,0.)
self.position = Vector3D(0.,0.,0.)
self.dtmotion = 0.
self.dt = 0.
self.accBias = Vector3D(0.,0.,0.)
self.velocityBias = Vector3D(0.,0.,0.)
# First Time Getting Data
self.firstTimeData = True # want to initialize average acc,mag,gyr with current reading first time
self.sensorIsBooting = True # need to read sensor a few times until we get reasonable data
self.sensorRunInCounts = 0 # for boot up
self.motionIsBooting = True # need to establish averages until we run motion
def update_times(self):
self.home_pressedTime = \
self.data_lastTime = \
self.data_lastTimeRate = \
self.virtual_lastTimeRate = \
self.previous_virtualUpdate = \
self.fusion_lastTimeRate = \
self.previous_fusionTime = \
self.report_lastTimeRate = \
self.zmqPUB_lastTimeRate = \
self.motion_lastTimeRate = \
self.previous_motionTime = \
self.firstTimeMotion = time.perf_counter()
def handle_disconnect(self,client):
self.logger.log(logging.INFO,'Client disconnected, Signaling...')
self.connected=False
self.lost_connection.set()
async def connect_loop(self):
'''
An attempt to remain connected with the device.
Connection Loop:
Scan for Device
Create Client
Connect to Device
Scan for Services & Characteristics
Wait for Disconnection
Attempt Reconnection
Back to Scan for Device
'''
self.logger.log(logging.INFO, 'Starting Connect Task...')
first_time = True
sleep_time = 5.0
while not self.finish_up: # Run for ever
# print('C', end='', flush=True)
# Make sure device is not already connected
# (not available on Windows)
###########################################
if self.device_address is not None:
if check_bluetooth_connected(self.device_address):
self.logger.log(logging.INFO,'Device {} is already connected. Disconnecting...'.format(self.device_name))
if disconnect_bluetooth_device(self.device_address):
self.connected = False
self.logger.log(logging.INFO,'Device {} successfully disconnected'.format(self.device_name))
else:
self.connected = False
# Scan for Device
#################
self.device = None
# try to find device using its name
self.logger.log(logging.INFO,'Searching for {}'.format(self.device_name))