-
Notifications
You must be signed in to change notification settings - Fork 2
/
Pimax_BSAW.py
1838 lines (1597 loc) · 67.1 KB
/
Pimax_BSAW.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
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import argparse
import asyncio
import atexit
import binascii
import configparser
import datetime
import json
import logging
import os
import re
import sys
import threading
import time
from datetime import datetime
from datetime import timedelta
import pywinusb.hid as hid
import wx
import wx.lib
import wx.lib.newevent
import wx.lib.colourdb
import wx.dataview as dv
from bleak import BleakClient
from bleak import _logger as logger
from bleak import discover
from infi.systray import SysTrayIcon
from win10toast import ToastNotifier
LogMsgEvent, EVT_LOG_MSG = wx.lib.newevent.NewEvent()
class MainObj:
def __init__(self):
"""
Init function will initialize the instance with default runtime values
:rtype: object
"""
self.version = "1.5.2"
self.pimax_usb_vendor_id = 0
self.lh_db_file = ""
self.sleep_time_sec_usb_find = 7
self.debug_logs = False
self.debug_bypass_usb = False
self.tray_icon = "pimax.ico"
self.logformat = "%(asctime)s %(levelname)s (%(module)s): %(message)s"
self.hs_label = 'HeadSet'
self.bs1_label = 'BS1'
self.bs2_label = 'BS2'
self.bs_timeout_in_sec = 60
self.bs_disco_sleep = 5
self.toomanynoted = False
self.quit_main = False
self.stations = []
self.bs_serials = []
self.systray = None
self.hsthr = None
self.bs1thr = None
self.bs2thr = None
self.logthr = None
self.toaster = None
self.blelock = False
self.discovery = None
self.disco = True
self.mode = "Auto"
self.panelupdate = "Initializing"
self.panelstatus = [(0, ("Dashboard", "Status", self.panelupdate)), (1, ("", "", ""))]
self.paneldata = [[str(k)] + list(v) for k, v in self.panelstatus]
def set_threads(self, _systray, _hsthr, _bs1thr, _bs2thr, _logthr):
"""
Set infi.systray, headset thread and basestations threads in main instance
:type _logthr: object
:param _bs2thr:
:param _bs1thr:
:param _hsthr:
:type _systray: object
"""
self.systray = _systray
self.hsthr = _hsthr
self.bs1thr = _bs1thr
self.bs2thr = _bs2thr
self.logthr = _logthr
def settoaster(self, _toaster):
"""
Set toaster object in main instance
:type _toaster: object
"""
self.toaster = _toaster
def get_quit_main(self):
"""
Return quit main value from main instance
:return:
"""
return self.quit_main
def get_dashboard_except(self):
self.panelstatus = [(0, ("Dashboard", "Status", self.panelupdate)), (1, ("", "", ""))]
self.paneldata = [[str(k)] + list(v) for k, v in self.panelstatus]
return self.paneldata
def toast_err(self, _msg):
"""
Function to display the error message as a Windows 10 toast notification
:param _msg:
"""
self.toaster.show_toast("PIMAX_BSAW",
_msg,
icon_path=maininst.tray_icon,
duration=5,
threaded=True)
while self.toaster.notification_active(): time.sleep(0.1)
def load_configuration(self, _toaster):
"""
Load configuration file
:param _toaster:
"""
try:
config = configparser.ConfigParser()
config.read('configuration.ini')
logging.debug("Configuration file Headset USB ID: " + config['HeadSet']['USB_VENDOR_ID'])
self.pimax_usb_vendor_id = int(config['HeadSet']['USB_VENDOR_ID'], 0)
conf_bs_timeout_in_sec = int(config['BaseStation']['BS_TIMEOUT_IN_SEC'], 0)
if 30 <= conf_bs_timeout_in_sec <= 120:
self.bs_timeout_in_sec = conf_bs_timeout_in_sec
logging.debug("Configuration file BS timeout: " + config['BaseStation']['bs_timeout_in_sec'])
self.lh_db_file = config['HeadSet']['LH_DB_FILE']
logging.debug("Configuration file LightHouse DB filepath: " + self.lh_db_file)
except Exception as err:
if not self.quit_main:
self.toast_err("Load configuration file exception: " + str(err))
self.quit_main = True
def setstandby(self):
"""
Send standby command to both Basestations
"""
logging.info("Sending Standby to Basestations")
self.bs1thr.setaction("Standby")
self.bs2thr.setaction("Standby")
def setwakeup(self):
"""
Send wakeup command to both Basestations
"""
logging.info("Sending Wakeup to Basestations")
self.bs1thr.setaction("Wakeup")
self.bs2thr.setaction("Wakeup")
def setmode(self):
"""
Send wakeup command to both Basestations
"""
if self.mode == "Auto":
_mode = "Idle"
else:
_mode = "Auto"
self.mode = _mode
logging.info("Set BS mode to " + str(_mode))
self.bs1thr.setmode(_mode)
self.bs2thr.setmode(_mode)
self.mode = _mode
class BaseStations(threading.Thread):
def __init__(self, label, _maininst, _bs_timeout_in_sec, autostart=False):
"""
Init function will initialize the thread with default values and store reference to the main instance
:param label:
:param _maininst:
:param _bs_timeout_in_sec:
:param autostart:
"""
threading.Thread.__init__(self)
self.setDaemon(True)
self.start_orig = self.start
self.start = self.start_local
self.lock = threading.Lock()
self.lock.acquire() # lock until variables are set
self.maininst = _maininst
self.label = label
self.bs_cmd_verify = False
self.bs_cmd_ble_id = "0000cb01-0000-1000-8000-00805f9b34fb"
self.bs_cmd_ble_id_v1 = "0000cb01-0000-1000-8000-00805f9b34fb"
self.bs_cmd_ble_id_v2 = 0x12
self.bs_cmd_id_wakeup_v2 = 0x01
self.bs_cmd_id_sleep_v2 = 0x00
self.bs_cmd_id_wakeup_no_timeout = 0x1200
self.bs_cmd_id_wakeup_default_timeout = 0x1201
self.bs_cmd_id_wakeup_timeout = 0x1202
self.bs_default_id = 0xffffffff
self.bs_timeout_in_sec = _bs_timeout_in_sec
self.bs_loop_sleep = 25
self.bs_loop_retry = 3
self.bs_loop_retry_disconnect = 7
self.bs_disconnects = 0
self.bs_version = 1
self.bs_version_force = 0
self.bs_model = ""
self.bs_manufacturer = ""
self.bs_soc = ""
self.bs_fw = ""
self.bs_fw2 = ""
self.status = "N/A"
self.action = "Off"
self.tlock = True
self.islocked = False
self.ping_cmd = False
self.wakeup_cmd = False
self.sn = 0
self.snhx = ""
self.snshx = "N/A"
self.mac = ""
self.discovered = False
self.connected = False
self.paired = False
self.standby = False
self.errque = []
self.toomanysecs = 180
self.toomanycnt = 20
self.client = None
self.test = 0
self.test2 = 0
self.mode = "Auto"
self.loop = asyncio.new_event_loop()
self.loop.set_debug(maininst.debug_logs)
self.t_wait_loop = 1
self.t_last_cmd = time.time()
self.action = "Wakeup"
self.state = 0
if autostart:
self.start() # automatically start thread on init
def run(self):
"""
Run function called by self.start_orig() will release the lock, run the async function
:rtype: object
"""
self.lock.release()
self.loop.run_until_complete(self.connect_bs(self.loop))
async def connect_bs(self, _loop):
"""
Async function what will loop connection to the BS
:param _loop:
"""
while True:
self.state = self.bs_pre_loop()
prevact = self.action
nextact = self.action
if self.state == 9:
break
elif self.state == 1:
continue
try:
# not implemented yet
# def disconnect_bs_cb(_client):
# logging.debug(self.label + " disconnected MAC={}".format(_client.address))
# self.connected = False
async with BleakClient(self.mac, loop=_loop) as self.client:
# not implemented yet
# client.set_disconnected_callback(disconnect_bs_cb)
await self.client.connect(timeout=10)
if await self.client.is_connected():
logging.debug(self.label + " connected")
self.connected = True
while await self.client.is_connected():
self.state = self.bs_pre_loop()
self.t_wait_loop = self.bs_loop_sleep
if self.state == 9:
logging.debug(self.label + " disconnecting")
await self.client.disconnect()
break
elif self.state == 1:
continue
cmd, prevact, nextact = self.bs_pre_action()
self.purgeerrque()
try:
if len(cmd) < 1:
logging.debug(self.label + " skipping cmd for action=" + prevact + " next=" + nextact)
self.setstatus(prevact)
else:
logging.debug(self.label + " sending cmd for action=" + prevact + " next=" + nextact)
while maininst.blelock:
time.sleep(0.2)
maininst.blelock = True
if self.is_version() == 2:
await self.client.write_gatt_char(self.bs_cmd_ble_id, cmd, self.bs_cmd_verify)
else:
await self.client.write_gatt_char(self.bs_cmd_ble_id, cmd, self.bs_cmd_verify)
maininst.blelock = False
if self.is_standby() and prevact == "Standby":
logging.info(self.label + " set Standby done, status Off")
self.standby = False
self.setstatus("Off")
elif self.wakeup_cmd:
logging.debug(self.label + " set Wakeup flag to False")
self.wakeup_cmd = False
self.setstatus(prevact)
else:
self.setstatus(prevact)
self.action = nextact
self.t_last_cmd = time.time()
except Exception as err:
connected = await self.client.is_connected()
maininst.blelock = False
errmsg = self.label + " action: " + self.action + " exception triggered:" + str(err)
self.bs_proc_err(connected, prevact, nextact, errmsg)
continue
else:
errmsg = self.label + " while " + self.action + " got disconnected: " + str(
self.bs_disconnects)
self.bs_proc_err(False, prevact, nextact, errmsg)
continue
except Exception as err:
errmsg = self.label + " error initiating BLE connection: " + str(err)
self.bs_proc_err(False, prevact, nextact, errmsg)
continue
def bs_proc_err(self, _connected, _prev, _next, _errmsg):
self.t_last_cmd = time.time()
self.t_wait_loop = self.bs_loop_retry
self.action = _prev
self.setstatus(_prev + "-error")
logging.debug(_errmsg)
self.logmanyerrors()
if not _connected:
self.connected = False
self.t_wait_loop = self.bs_loop_retry_disconnect
self.bs_disconnects += 1
def bs_pre_loop(self):
"""
bs_connect pre loop
:return:
"""
if len(self.mac) < 1:
logging.debug(self.label + " not found, skipping keepalive")
time.sleep(2)
return 1
if self.is_standby() and self.is_connected():
logging.debug(self.label + " go to action, standby requested")
self.action = "Standby"
time.sleep(1)
return 0
if maininst.get_quit_main():
logging.debug(self.label + " thread exiting due to quit main, connected=" + str(self.is_connected()))
return 9
if maininst.disco:
logging.debug(self.label + " skipping action due to running discovery")
time.sleep(2)
return 1
if self.tlock:
logging.debug(self.label + " skipping action due to thread lock")
time.sleep(2)
return 1
if not maininst.hsthr.connected:
logging.debug(self.label + " skipping action due to HS Off status")
time.sleep(2)
return 1
if self.action == "":
logging.debug(self.label + " skipping action due to empty action")
time.sleep(2)
return 1
if time.time() - self.t_last_cmd <= self.t_wait_loop:
#logging.debug(self.label + " skipping action due to timer")
time.sleep(1)
return 1
return 0
def bs_pre_action(self):
logging.debug(self.label + " build cmd for action=" + self.action)
_prev = self.action
_next = ""
_exec = self.action
if self.action[-6:] == "-error":
_exec = self.action[:-6]
_next = _exec
elif self.action == "Standby":
_exec = "Standby"
_next = "Off"
elif self.action == "Off":
_exec = ""
_next = ""
elif self.action == "Wakeup":
_exec = "Wakeup"
elif self.wakeup_cmd:
_exec = "Wakeup"
elif self.ping_cmd:
if not self.wakeup_cmd and (time.time() - self.t_last_cmd > self.bs_timeout_in_sec - 5
and not self.ping_cmd):
_exec = "Wakeup"
elif self.ping_cmd:
_exec = "Ping"
if self.mode == "Auto" and _next == "":
_next = "Ping"
if len(_exec) < 1:
return "", _prev, _next
else:
logging.debug(
self.label + " prebuild_cmd=" + _exec)
cmd = self.build_bs_ble_cmd(_exec)
logging.debug(
self.label + " MAC=" + self.mac + " BLE CMD : " + str(binascii.hexlify(cmd)) +
" UUID: " + self.bs_cmd_ble_id)
return cmd, _prev, _next
def build_bs_ble_cmd(self, action):
return self.build_2_bs_ble_cmd(action)
def build_2_bs_ble_cmd(self, action):
"""
Return the BLE command as bytearray based on input action string
:rtype: text
:param action:
:return:
"""
if self.is_version() == 2:
cmd_id = self.bs_cmd_id_wakeup_v2
if action == "Standby":
cmd_id = self.bs_cmd_id_sleep_v2
elif action == "Off":
cmd_id = self.bs_cmd_id_sleep_v2
ba = bytearray()
ba += cmd_id.to_bytes(1, byteorder='big')
logging.debug(
self.label + " build2 action:" + action + " MAC=" + self.mac + " BLE CMD : " + str(binascii.hexlify(ba)))
return ba
else:
cmd_id = self.bs_cmd_id_wakeup_default_timeout
cmd_timeout = self.bs_timeout_in_sec
cmd_bs_id = self.sn
if action == "Wakeup":
cmd_timeout = self.bs_cmd_id_wakeup_timeout
cmd_bs_id = self.bs_default_id
elif action == "Standby":
cmd_id = self.bs_cmd_id_wakeup_timeout
cmd_timeout = 4
ba = bytearray()
ba += cmd_id.to_bytes(2, byteorder='big')
ba += cmd_timeout.to_bytes(2, byteorder='big')
ba += cmd_bs_id.to_bytes(4, byteorder='little')
ba += (0).to_bytes(12, byteorder='big')
logging.debug(
self.label + " build2 action:" + action + " MAC=" + self.mac + " BLE CMD : " + str(
binascii.hexlify(ba)))
return ba
def purgeerrque(self):
t_now = datetime.now()
t_delta = t_now - timedelta(seconds=self.toomanysecs)
for errevt in self.errque:
if (errevt - t_delta).total_seconds() < 0:
self.errque.remove(errevt)
def logmanyerrors(self):
"""
Store errors timestamp in a list
Write warning in log if more than self.toomanycnt errors are logged over self.toomanysecs seconds
:rtype: object
"""
try:
t_now = datetime.now()
self.errque.append(t_now)
if len(self.errque) >= self.toomanycnt:
warningmsg = "Too many errors from " + self.label + " (" + str(self.toomanycnt) + " over "\
+ str(self.toomanysecs)\
+ " seconds), hints: check distance, re-plug BT dongle or re-pair the BS in Windows!"
logging.warning(warningmsg)
if not self.maininst.toomanynoted:
self.maininst.toast_err(warningmsg)
self.maininst.toomanynoted = True
self.errque.clear()
except Exception as err:
logging.error("Too many errors exception: " + str(err))
self.maininst.toast_err("Too many errors exception: " + str(err))
def is_active(self):
if not self.tlock or self.status == "Off" or len(self.mac) < 1:
return True
else:
return False
def getlasterrsecs(self):
if self.errque:
return str((datetime.now()-self.errque[-1]).seconds)
else:
return ""
def setserial(self, serial):
"""
Set BS serial number
:param serial:
"""
if not int(serial):
pass
self.sn = serial
if self.sn == 0:
self.mac = ""
self.snhx = ""
self.snshx = "N/A"
self.paired = False
self.status = "N/A"
self.mac = ""
else:
self.snhx = hex(self.sn)
self.snshx = hex(self.sn)[-4:].upper()
def setpairing(self, _mac, _version):
"""
Set BS pairing
:param _mac:
:param _version:
"""
if not _mac:
pass
self.mac = _mac
if int(_version) == 2:
self.bs_cmd_ble_id = str(UUID(self.bs_cmd_ble_id_v2))
self.bs_version = 2
else:
self.bs_cmd_ble_id = self.bs_cmd_ble_id_v1
self.bs_version = 1
self.setstatus("Discovered")
def setlock(self, _lock):
"""
Set thread lock
:type _lock: object
"""
self.islocked = False
self.tlock = _lock
def setaction(self, _action):
"""
Set standby flag is the BS is connected
"""
if _action == "Standby":
self.setstatus("Standby")
self.standby = True
else:
self.t_last_cmd = time.time() - self.bs_loop_sleep
self.action = "Wakeup"
self.standby = False
self.wakeup_cmd = True
def setmode(self, _mode):
self.mode = _mode
def setstatus(self, _status):
"""
Set BS status
:param _status:
"""
# logging.debug(self.label + " setstatus " + _status)
if _status == "Discovered":
self.wakeup_cmd = False
self.discovered = True
elif _status == "Wakeup-error":
self.wakeup_cmd = False
elif _status == "Ping-error":
self.ping_cmd = False
elif _status == "Ping":
self.ping_cmd = True
elif _status == "Standby":
self.standby = True
self.ping_cmd = False
self.wakeup_cmd = False
if self.status != _status:
if _status == "Discovered":
logging.info(self.label + " v" + str(self.bs_version) + " via BLE")
elif _status == "Wakeup-error":
logging.error(self.label + " error sending Wakeup command")
elif _status == "Wakeup":
logging.info(self.label + " success sending Wakeup command")
elif _status == "Ping-error":
logging.error(self.label + " error sending Ping command")
elif _status == "Ping":
logging.info(self.label + " success sending Ping command")
elif _status == "Standby":
logging.debug(self.label + " set status to Standby")
elif _status == "Off":
logging.debug(self.label + " set status to Off")
self.status = _status
def gettray(self):
"""
Return string to display in system tray hover text
:return:
"""
if self.snshx == "N/A":
return f"{self.label} [{self.snshx}]"
return f"{self.label} [{self.snshx}:{self.status}]"
def getstatus(self):
"""
Return string with the BS status
:return:
"""
return f"{self.status}"
def getshortsnhx(self):
"""
Return string with short hex type serial number
:return:
"""
return f"{self.snshx}"
def getmac(self):
"""
Return string with MAC address
:return:
"""
return f"{self.mac}"
def getserial(self):
"""
Return string with MAC address
:return:
"""
return f"{self.sn}"
def getsnhx(self):
"""
Return string with full hex type serial number
:return:
"""
return f"{self.snhx}"
def getversion(self):
"""
Return string with bs version
:return:
"""
return f"{self.bs_version}"
def is_connected(self):
"""
Return boolean for BLE connected status
:return:
"""
return self.connected
def is_standby(self):
"""
Return boolean for go to standby command
:return:
"""
return bool(self.standby)
def is_version(self):
"""
Return integer for BS version
:return:
"""
return int(self.bs_version)
def start_local(self):
"""
Start the thread with original run and acquire the lock
"""
self.start_orig()
self.lock.acquire()
def destroy(self):
"""
Override the destroy thread adding lock release and loop close
"""
self.lock.release()
self.loop.close()
class HeadSet(threading.Thread):
def __init__(self, label, _maininst, autostart=False):
"""
Init function will initialize the thread with default values and store reference to the main instance
:param label:
:param _maininst:
:param autostart:
"""
threading.Thread.__init__(self)
self.setDaemon(True)
self.start_orig = self.start
self.start = self.start_local
self.lock = threading.Lock()
self.lock.acquire() # lock until variables are set
self.maininst = _maininst
self.label = label
self.status_initial = "N/A"
self.status = self.status_initial
self.tlock = False
self.islocked = False
self.connected = False
self.hs_vendor = ""
self.hs_product = ""
self.dumpusb = False
if autostart:
self.start() # automatically start thread on init
def run(self):
"""
Run function what will check Headset connection via USB
"""
try:
self.lock.release()
while True:
time.sleep(maininst.sleep_time_sec_usb_find)
if maininst.get_quit_main():
logging.debug(self.label + " thread exiting due to quit main")
break
if self.tlock:
logging.debug(self.label + " thread lock active")
self.islocked = True
continue
if maininst.disco:
logging.debug(self.label + " detection paused, discovery running")
self.islocked = True
continue
if self.maininst.debug_bypass_usb:
self.setstatus("DEBUG")
self.islocked = False
continue
self.islocked = False
all_devices = hid.HidDeviceFilter().get_devices()
flt_devices = hid.HidDeviceFilter(vendor_id=self.maininst.pimax_usb_vendor_id).get_devices()
if maininst.debug_logs:
if not self.dumpusb:
self.dumpusb = True
logging.debug("DUMP USB DEVICES:")
for device in all_devices:
device.open()
hs_vendor = str(device.vendor_name) + " (" + str(device.vendor_id) + ")"
hs_product = str(device.product_name) + " (" + str(device.product_id) + ")"
logging.debug("USB V: " + hs_vendor + " P:" + hs_product)
device.close()
if not flt_devices:
logging.debug(self.label + " not found on USB")
self.setstatus("Off")
else:
for device in flt_devices:
try:
device.open()
self.setstatus("On")
logging.debug(self.label + " found on USB: " + str(device))
self.hs_vendor = str(device.vendor_name) + " (" + str(device.vendor_id) + ")"
self.hs_product = str(device.product_name) + " (" + str(device.product_id) + ")"
finally:
device.close()
except Exception as err:
logging.error("Error: %s in %s thread: %s" % (self.__class__.__name__, self.label, str(err)))
def setlock(self, _lock):
"""
Set thread lock
:param _lock:
"""
self.islocked = False
self.tlock = _lock
def gettray(self):
"""
Return string to display in system tray hover text
:return:
"""
return f"{self.label} [{self.status}]"
def getstatus(self):
"""
Return string with Headset status
:return:
"""
return f"{self.status}"
def setstatus(self, _status):
"""
Set Headset status
:param _status:
"""
if _status == "On":
self.connected = True
elif _status == "Off":
self.connected = False
elif _status == "DEBUG":
self.connected = True
if self.status != _status:
if _status == "On":
logging.info(self.label + " is active")
self.maininst.setwakeup()
elif _status == "Off":
logging.info(self.label + " is Off")
if self.status != self.status_initial:
self.maininst.setstandby()
elif _status == "DEBUG":
logging.info(self.label + " is forced On")
self.maininst.setwakeup()
self.status = _status
def isoff(self):
"""
Return true if the headset in connected or in debug mode
:return:
"""
return bool(self.connected)
def destroy(self):
"""
Override the destroy thread adding lock release
"""
self.lock.release()
def start_local(self):
"""
Start the thread with original run and acquire the lock
"""
self.start_orig()
self.lock.acquire()
class WxLogHandler(logging.Handler):
def __init__(self, get_log_dest_func):
"""
Logging handler to redirect messages to the wxPython window
:param get_log_dest_func:
"""
logging.Handler.__init__(self)
self._get_log_dest_func = get_log_dest_func
self.level = logging.DEBUG
def flush(self):
pass
def emit(self, record):
"""
This function will forward the event message to the destination window
:param record:
"""
try:
msg = self.format(record)
event = LogMsgEvent(message=msg, levelname=record.levelname, levelno=record.levelno)
log_dest = self._get_log_dest_func()
def after_func(get_log_dest_func=self._get_log_dest_func, event=event):
_log_dest = get_log_dest_func()
if _log_dest:
wx.PostEvent(_log_dest, event)
wx.CallAfter(after_func)
except Exception as err:
sys.stderr.write("Error: %s failed while emitting a log record (%s): %s\n" % (
self.__class__.__name__, repr(record), str(err)))
class LevelFilter(object):
def __init__(self, level):
"""
Filter for log level
:param level:
"""
self.level = level
def filter(self, record):
"""
Filter will forward only records with a level greater or equal self.level
:type record: object
"""
return record.levelno >= self.level
class LogWnd(wx.Frame):
def __init__(self):
"""
wxPython logging window
"""
#import wx.lib.inspection
#wx.lib.inspection.InspectionTool().Show()
try:
frame_style = wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER
frame_style = frame_style & ~ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)
wx.lib.colourdb.updateColourDB()
self.wxorange = wx.Colour("ORANGE RED")
self.wxdarkgreen = wx.Colour("DARK GREEN")
wx.Frame.__init__(self, None,
title="Status panel", style=frame_style)
self.Bind(EVT_LOG_MSG, self.on_log_msg)
self.Bind(wx.EVT_CLOSE, self.oncloseevt)
self.SetIcon(wx.Icon("pimax.ico"))
(self.display_width_, self.display_height_) = wx.GetDisplaySize()
frame_width = self.display_width_ * 90 / 100
frame_height = self.display_height_ * 85 / 100
self.SetSize(wx.Size(frame_width, frame_height))
panel_width = self.GetClientSize().GetWidth()-2
panel_height = self.GetClientSize().GetHeight()-46
status_width = 500
text_width = panel_width - status_width
text_height = panel_height
if text_width < 1:
text_width = 100
value_width = panel_width - text_width
unit_width = value_width/10
c0_width = int(unit_width*2)
c1_width = int(unit_width*2)
if c0_width < 120:
c0_width = 120
if c1_width < 120:
c1_width = 120
c2_width = int(unit_width*6)
delta = (c0_width+c1_width+c2_width)-value_width
if delta > 10:
c2_width = c2_width - delta
if c2_width < 260:
c2_width = 260
status_width = c0_width + c1_width + c2_width
self.dvc = dv.DataViewCtrl(self,
style=wx.BORDER_THEME
| dv.DV_ROW_LINES # nice alternating bg colors
#| dv.DV_HORIZ_RULES
| dv.DV_VERT_RULES
| dv.DV_MULTIPLE
| dv.DV_NO_HEADER
, size=(status_width, text_height)
)
self.model = StatusModel(getpaneldata())
self.dvc.AssociateModel(self.model)
c0 = self.dvc.AppendTextColumn("Item " + str(c0_width) + " " + str(value_width), 1, width=c0_width, align=wx.ALIGN_RIGHT, mode=dv.DATAVIEW_CELL_INERT)
c1 = self.dvc.AppendTextColumn("Characteristic " + str(c1_width), 2, width=c1_width, align=wx.ALIGN_RIGHT, mode=dv.DATAVIEW_CELL_INERT)
c2 = self.dvc.AppendTextColumn("Value " + str(c2_width-4), 3, width=c2_width-4, align=wx.ALIGN_LEFT, mode=dv.DATAVIEW_CELL_INERT)
for c in self.dvc.Columns:
c.Sortable = False