forked from walmis/VPforce-TelemFFB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1116 lines (914 loc) · 44.6 KB
/
main.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 file is part of the TelemFFB distribution (https://github.com/walmis/TelemFFB).
# Copyright (c) 2023 Valmantas Palikša.
#
# 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, version 3.
#
# 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 <http://www.gnu.org/licenses/>.
#
import atexit
import glob
import shutil
from traceback_with_variables import print_exc, prints_exc
import argparse
parser = argparse.ArgumentParser(description='Send telemetry data over USB')
# Add destination telemetry address argument
parser.add_argument('--teleplot', type=str, metavar="IP:PORT", default=None,
help='Destination IP:port address for teleplot.fr telemetry plotting service')
parser.add_argument('-p', '--plot', type=str, nargs='+',
help='Telemetry item names to send to teleplot, separated by spaces')
parser.add_argument('-D', '--device', type=str, help='Rhino device USB VID:PID', default="ffff:2055")
parser.add_argument('-r', '--reset', help='Reset all FFB effects', action='store_true')
# Add config file argument, default config.ini
parser.add_argument('-c', '--configfile', type=str, help='Config ini file (default config.ini)', default='config.ini')
parser.add_argument('-o', '--overridefile', type=str, help='User config override file (default = config.user.ini', default='config.user.ini')
parser.add_argument('-s', '--sim', type=str, help='Set simulator options DCS|MSFS|IL2 (default DCS', default="None")
parser.add_argument('-t', '--type', help='FFB Device Type | joystick (default) | pedals | collective', default='joystick')
args = parser.parse_args()
import json
import logging
import sys
import time
import os
sys.path.insert(0, '')
#sys.path.append('/simconnect')
log_folder = './log'
if not os.path.exists(log_folder):
os.makedirs(log_folder)
logname = "".join(["TelemFFB", "_", args.device.replace(":", "-"), "_", os.path.basename(args.configfile), "_", os.path.basename(args.overridefile), ".log"])
log_file = os.path.join(log_folder, logname)
# Create a logger instance
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# Create a formatter for the log messages
formatter = logging.Formatter('%(asctime)s.%(msecs)d - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# Create a StreamHandler to log messages to the console
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(formatter)
# Create a FileHandler to log messages to the log file
file_handler = logging.FileHandler(log_file, mode='w')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
# Add the handlers to the logger
logger.addHandler(console_handler)
logger.addHandler(file_handler)
import re
import argparse
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QMainWindow, QVBoxLayout, QMessageBox, QPushButton, QDialog, \
QRadioButton, QListView, QScrollArea, QHBoxLayout, QAction, QPlainTextEdit, QMenu, QButtonGroup, QFrame
from PyQt5.QtCore import QObject, pyqtSignal, Qt, QCoreApplication, QUrl, QRect, QMetaObject
from PyQt5.QtGui import QFont, QPixmap, QIcon, QDesktopServices
# from PyQt5.QtWidgets import *
# from PyQt5.QtCore import *
# from PyQt5.QtGui import *
import socket
import threading
import aircrafts_dcs
import aircrafts_msfs
import aircrafts_il2
import utils
import subprocess
import traceback
from ffb_rhino import HapticEffect
from configobj import ConfigObj
from sc_manager import SimConnectManager
from il2_telem import IL2Manager
from aircraft_base import effects
effects_translator = utils.EffectTranslator()
script_dir = os.path.dirname(os.path.abspath(__file__))
if os.path.basename(args.configfile) == args.configfile:
# just the filename is present, assume it is in the script directory
# print("Config File is in the script dir")
configfile = os.path.join(script_dir, args.configfile)
else:
# assume is absolute path to file
# print("Config file is absolute path")
configfile = args.configfile
if os.path.basename(args.overridefile) == args.overridefile:
# just the filename is present, assume it is in the script directory
overridefile = os.path.join(script_dir, args.overridefile)
else:
# assume is absolute path to file
overridefile = args.overridefile
if args.teleplot:
logging.info(f"Using {args.teleplot} for plotting")
utils.teleplot.configure(args.teleplot)
#################
################
### Setting _release flag to true will disable all auto-updating and 'WiP' downloads server version checking
### Set the version number to version tag that will be pushed to master repository branch
_release = True # Todo: Validate release flag!
if _release:
version = "v1.0.0"
else:
version = utils.get_version()
min_firmware_version = 'v1.0.15'
global dev_firmware_version
dev_firmware_version = None
_update_available = False
_latest_version = None
_latest_url = None
_current_version = version
class LoggingFilter(logging.Filter):
def __init__(self, keywords):
self.keywords = keywords
def filter(self, record):
# Check if any of the keywords are present in the log message
for keyword in self.keywords:
if keyword in record.getMessage():
# If any keyword is found, prevent the message from being logged
return False
# If none of the keywords are found, allow the message to be logged
return True
# Create a list of keywords to filter
log_filter_strings = [
# "unrecognized Miscellaneous Unit in typefor(POSITION)",
# "Unrecognized event AXIS_CYCLIC_LATERAL_SET",
# "Unrecognized event AXIS_CYCLIC_LONGITUDINAL_SET",
# "Unrecognized event ROTOR_AXIS_TAIL_ROTOR_SET",
# "Unrecognized event AXIS_COLLECTIVE_SET",
]
log_filter = LoggingFilter(log_filter_strings)
console_handler.addFilter(log_filter)
file_handler.addFilter(log_filter)
def format_dict(data, prefix=""):
output = ""
for key, value in data.items():
if isinstance(value, dict):
output += format_dict(value, prefix + key + ".")
else:
output += prefix + key + " = " + str(value) + "\n"
return output
def load_config(filename, raise_errors=True) -> ConfigObj:
if not os.path.sep in filename:
#construct absolute path
config_path = os.path.join(os.path.dirname(__file__), filename)
else:
#filename is absolute path
config_path = filename
try:
config = ConfigObj(config_path, raise_errors=raise_errors)
logging.info(f"Loading Config: {config_path}")
if not os.path.exists(config_path):
logging.warning(f"Configuration file {filename} does not exist")
path = os.path.dirname(config_path)
ini_files = glob.glob(f"{path}/*.ini")
logging.warning(f"Possible ini files in that location are:")
for file in ini_files:
logging.warning(f"{os.path.basename(file)}")
return config
except Exception as e:
logging.error(f"Cannot load config {config_path}: {e}")
err = ConfigObj()
err["EXCEPTION"] = {}
err["EXCEPTION"]["ERROR"] = e
err["system"] = {}
err["system"]["logging_level"] = "DEBUG"
err["system"]["msfs_enabled"] = 0
err["system"]["dcs_enabled"] = 0
return err
_config : ConfigObj = None
_config_mtime = 0
# if update is true, update the current modified time
def config_has_changed(update=False) -> bool:
global _config_mtime
global _config
# "hash" both mtimes together
tm = int(os.path.getmtime(configfile))
if os.path.exists(overridefile):
tm += int(os.path.getmtime(overridefile))
if update:
_config_mtime = tm
if _config_mtime != tm:
_config = None # force reloading config on next get_config call
return True
return False
def get_config() -> ConfigObj:
global _config
# TODO: check if config files changed and reload
if _config: return _config
main = load_config(configfile)
user = load_config(overridefile, raise_errors=False)
if user and main:
main.merge(user)
config_has_changed(update=True)
_config = main
return main
class LogWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Log Console")
self.resize(800, 500)
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.widget = QPlainTextEdit(self.central_widget)
self.widget.setReadOnly(True)
self.widget.setFont(QFont("Courier New"))
layout = QVBoxLayout(self.central_widget)
layout.addWidget(self.widget)
# Create a menu bar
menubar = self.menuBar()
# Create a "Logging" menu
logging_menu = menubar.addMenu("Logging Level")
# Create "Debug Logging" action and add it to the "Logging" menu
debug_action = QAction("Debug Logging", self)
debug_action.triggered.connect(self.set_debug_logging)
logging_menu.addAction(debug_action)
# Create "Normal Logging" action and add it to the "Logging" menu
normal_action = QAction("Normal Logging", self)
normal_action.triggered.connect(self.set_info_logging)
logging_menu.addAction(normal_action)
def set_debug_logging(self):
logger.setLevel(logging.DEBUG)
logging.info(f"Logging level set to DEBUG")
def set_info_logging(self):
logger.setLevel(logging.INFO)
logging.info(f"Logging level set to INFO")
class TelemManager(QObject, threading.Thread):
telemetryReceived = pyqtSignal(object)
currentAircraft: aircrafts_dcs.Aircraft = None
currentAircraftName: str = None
timedOut: bool = True
lastFrameTime: float
numFrames: int = 0
def __init__(self) -> None:
QObject.__init__(self)
threading.Thread.__init__(self, daemon=True)
self._run = True
self._cond = threading.Condition()
self._data = None
self._events = []
self._dropped_frames = 0
self.lastFrameTime = time.perf_counter()
self.frameTimes = []
self.timeout = 0.2
def get_aircraft_config(self, aircraft_name, default_section=None):
config = get_config()
if default_section:
logging.info(f"Loading parameters from '{default_section}' section")
params = utils.sanitize_dict(config[default_section])
else:
params = utils.sanitize_dict(config["default"])
class_name = "Aircraft"
for section,conf in config.items():
# find matching aircraft in config
if re.match(section, aircraft_name):
conf = utils.sanitize_dict(conf)
logging.info(f"Found section [{section}] for aircraft '{aircraft_name}' in config")
class_name = conf.get("type", "Aircraft")
# load params from that class in config
s = ".".join([default_section, class_name] if default_section else [class_name])
logging.info(f"Loading parameters from [{s}] section")
class_params = config.get(s)
if class_params:
class_params = utils.sanitize_dict(class_params)
params.update(class_params)
else:
logging.warning(f"Section [{s}] does not exist")
params.update(conf)
return (params, class_name)
def quit(self):
self._run = False
self.join()
def submitFrame(self, data : bytes):
if type(data) == bytes:
data = data.decode("utf-8")
with self._cond:
if data.startswith("Ev="):
self._events.append(data.lstrip("Ev="))
self._cond.notify()
elif self._data is None:
self._data = data
self._cond.notify() # notify waiting thread of new data
else:
self._dropped_frames += 1
# log dropped frames, this is not necessarily a bad thing
# USB interrupt transfers (1ms) might take longer than one video frame
# we drop frames to keep latency to a minimum
logging.debug(f"Droppped frame (total {self._dropped_frames})")
def process_events(self):
while len(self._events):
ev = self._events.pop(0)
ev = ev.split(";")
if self.currentAircraft:
self.currentAircraft.on_event(*ev)
continue
def process_data(self, data):
data = data.split(";")
telem_data = {}
telem_data["FFBType"] = args.type
self.frameTimes.append(int((time.perf_counter() - self.lastFrameTime)*1000))
if len(self.frameTimes) > 50: self.frameTimes.pop(0)
telem_data["frameTimes"] = [self.frameTimes[-1], max(self.frameTimes)]
self.lastFrameTime = time.perf_counter()
for i in data:
try:
if len(i):
section, conf = i.split("=")
values = conf.split("~")
telem_data[section] = [utils.to_number(v) for v in values] if len(values) > 1 else utils.to_number(conf)
except Exception as e:
traceback.print_exc()
logging.error("Error Parsing Parameter: ", repr(i))
# print(items)
aircraft_name = telem_data.get("N")
data_source = telem_data.get("src", None)
if data_source == "MSFS2020":
module = aircrafts_msfs
sc_aircraft_type = telem_data.get("SimconnectCategory", None)
sc_engine_type = telem_data.get("EngineType", 4)
# 0 = Piston
# 1 = Jet
# 2 = None
# 3 = Helo(Bell) turbine
# 4 = Unsupported
# 5 = Turboprop
elif data_source == "IL2":
module = aircrafts_il2
else:
module = aircrafts_dcs
if aircraft_name and aircraft_name != self.currentAircraftName:
if self.currentAircraft is None or aircraft_name != self.currentAircraftName:
params, cls_name = self.get_aircraft_config(aircraft_name, data_source)
Class = getattr(module, cls_name, None)
logging.debug(f"CLASS={Class.__name__}")
if not Class or Class.__name__ == "Aircraft":
if data_source == "MSFS2020":
if sc_aircraft_type == "Helicopter":
logging.warning(f"Aircraft definition not found, using SimConnect Data (Helicopter Type)")
type_cfg, cls_name = self.get_aircraft_config(aircraft_name, "MSFS2020.Helicopter")
params.update(type_cfg)
Class = module.Helicopter
elif sc_aircraft_type == "Jet":
logging.warning(f"Aircraft definition not found, using SimConnect Data (Jet Type)")
type_cfg, cls_name = self.get_aircraft_config(aircraft_name, "MSFS2020.JetAircraft")
params.update(type_cfg)
Class = module.JetAircraft
elif sc_aircraft_type == "Airplane":
if sc_engine_type == 0: # Piston
logging.warning(f"Aircraft definition not found, using SimConnect Data (Propeller Type)")
type_cfg, cls_name = self.get_aircraft_config(aircraft_name, "MSFS2020.PropellerAircraft")
params.update(type_cfg)
Class = module.PropellerAircraft
if sc_engine_type == 1: # Jet
logging.warning(f"Aircraft definition not found, using SimConnect Data (Jet Type)")
type_cfg, cls_name = self.get_aircraft_config(aircraft_name, "MSFS2020.JetAircraft")
params.update(type_cfg)
Class = module.JetAircraft
elif sc_engine_type == 2: # None
logging.warning(f"Aircraft definition not found, using SimConnect Data (Glider Type)")
type_cfg, cls_name = self.get_aircraft_config(aircraft_name, "MSFS2020.GliderAircraft")
params.update(type_cfg)
Class = module.GliderAircraft
elif sc_engine_type == 3: # Heli
logging.warning(f"Aircraft definition not found, using SimConnect Data (Helo Type)")
type_cfg, cls_name = self.get_aircraft_config(aircraft_name, "MSFS2020.HelicopterAircraft")
params.update(type_cfg)
Class = module.Helicopter
elif sc_engine_type == 5: # Turboprop
logging.warning(f"Aircraft definition not found, using SimConnect Data (Turboprop Type)")
type_cfg, cls_name = self.get_aircraft_config(aircraft_name, "MSFS2020.TurbopropAircraft")
params.update(type_cfg)
Class = module.TurbopropAircraft
else:
logging.warning(f"Aircraft definition not found, using default class for {aircraft_name}")
Class = module.Aircraft
else:
logging.warning(f"Aircraft definition not found, using default class for {aircraft_name}")
Class = module.Aircraft
vpconf_path = utils.winreg_get("SOFTWARE\\VPforce\\RhinoFFB", "path")
if vpconf_path and "vpconf" in params:
logging.info(f"Found VPforce Configurator at {vpconf_path}")
serial = HapticEffect.device.serial
workdir = os.path.dirname(vpconf_path)
env = {}
env["PATH"] = os.environ["PATH"]
logging.info(f"Loading vpconf for aircraft with: {vpconf_path} -config {params['vpconf']} -serial {serial}")
subprocess.call([vpconf_path, "-config", params["vpconf"], "-serial", serial], cwd=workdir, env=env)
logging.info(f"Creating handler for {aircraft_name}: {Class.__module__}.{Class.__name__}")
# instantiate new aircraft handler
self.currentAircraft = Class(aircraft_name)
self.currentAircraft.apply_settings(params)
self.currentAircraftName = aircraft_name
if self.currentAircraft:
if config_has_changed():
logging.info("Configuration has changed, reloading")
params, cls_name = self.get_aircraft_config(aircraft_name, data_source)
self.currentAircraft.apply_settings(params)
try:
_tm = time.perf_counter()
self.currentAircraft._telem_data = telem_data
self.currentAircraft.on_telemetry(telem_data)
telem_data["perf"] = f"{(time.perf_counter() - _tm) * 1000:.3f}ms"
except:
print_exc()
if args.plot:
for item in args.plot:
if item in telem_data:
utils.teleplot.sendTelemetry(item, telem_data[item])
try: # sometime Qt object is destroyed first on exit and this may cause a runtime exception
self.telemetryReceived.emit(telem_data)
except: pass
def on_timeout(self):
if self.currentAircraft and not self.timedOut:
self.currentAircraft.on_timeout()
self.timedOut = True
@prints_exc
def run(self):
global _config
self.timeout = utils.sanitize_dict(_config["system"]).get("telemetry_timeout", 200)/1000
logging.info(f"Telemetry timeout: {self.timeout}")
while self._run:
with self._cond:
if not len(self._events) and not self._data:
if not self._cond.wait(self.timeout):
self.on_timeout()
continue
if len(self._events):
self.process_events()
if self._data:
self.timedOut = False
data = self._data
self._data = None
self.process_data(data)
class NetworkThread(threading.Thread):
def __init__(self, telemetry : TelemManager, host = "", port = 34380, telem_parser = None):
super().__init__()
self._run = True
self._port = port
self._telem = telemetry
self._telem_parser = telem_parser
def run(self):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)
s.settimeout(0.1)
s.bind(("", self._port))
logging.info(f"Listening on UDP :{self._port}")
while self._run:
try:
data, sender = s.recvfrom(4096)
if self._telem_parser is not None:
data = self._telem_parser.process_packet(data)
self._telem.submitFrame(data)
except ConnectionResetError:
continue
except socket.timeout:
continue
def quit(self):
self._run = False
class SimConnectSock(SimConnectManager):
def __init__(self, telem : TelemManager):
super().__init__()
self._telem = telem
def fmt(self, val):
if isinstance(val, list):
return "~".join([str(x) for x in val])
return val
def emit_packet(self, data):
data["src"] = "MSFS2020"
packet = bytes(";".join([f"{k}={self.fmt(v)}" for k, v in data.items()]), "utf-8")
self._telem.submitFrame(packet)
def emit_event(self, event, *args):
# special handling of Open event
if event == "Open":
# Reset all FFB effects on device, ensure we have a clean start
HapticEffect.device.resetEffects()
args = [str(x) for x in args]
self._telem.submitFrame(f"Ev={event};" + ";".join(args))
# Subclass QMainWindow to customize your application's main window
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 400, 700)
if version:
self.setWindowTitle(f"TelemFFB ({args.type}) ({version})")
else:
self.setWindowTitle(f"TelemFFB")
global _update_available
global _latest_version, _latest_url
self.resize(400, 700)
# Get the absolute path of the script's directory
script_dir = os.path.dirname(os.path.abspath(__file__))
# Create a layout for the main window
layout = QVBoxLayout()
notes_row_layout = QHBoxLayout()
# Create the menu bar
menu_frame = QFrame()
menu_frame_layout = QVBoxLayout(menu_frame)
# Create the menu bar
menubar = self.menuBar()
# Set the background color of the menu bar
menubar.setStyleSheet("""
QMenuBar { background-color: #f0f0f0; } /* Set the background color of the menu bar */
QMenu::item:selected { color: red; } /* Set the text color when a menu item is selected */
""")
# Create the "Utilities" menu
utilities_menu = menubar.addMenu('Utilities')
# Add the "Reset" action to the "Utilities" menu
reset_action = QAction('Reset All Effects', self)
reset_action.triggered.connect(self.reset_all_effects)
utilities_menu.addAction(reset_action)
self.update_action = QAction('Update TelemFFB', self)
self.update_action.triggered.connect(self.update_from_menu)
if not _release:
utilities_menu.addAction(self.update_action)
self.update_action.setDisabled(True)
# menubar.setStyleSheet("QMenu::item:selected { color: red; }")
# Create a line beneath the menu bar
line = QFrame()
line.setFrameShape(QFrame.HLine)
line.setFrameShadow(QFrame.Sunken)
# Add the line to the menu frame layout
menu_frame_layout.addWidget(menubar)
menu_frame_layout.addWidget(line)
menu_frame_layout.setContentsMargins(0, 0, 0, 0)
# Set the layout of the menu frame as the main layout
layout.addWidget(menu_frame)
self.notes_label = QLabel()
notes_url = os.path.join(script_dir, '_RELEASE_NOTES.txt')
label_txt = 'Release Notes'
# self.notes_label.setOpenExternalLinks(True)
# Connect the linkActivated signal to the open_file method and pass the URL
self.notes_label.linkActivated.connect(lambda url=notes_url: self.open_file(url))
self.notes_label.setText(f'<a href="{notes_url}">{label_txt}</a>')
self.notes_label.setAlignment(Qt.AlignRight)
self.notes_label.setToolTip(notes_url)
notes_row_layout.addWidget(self.notes_label)
layout.addLayout(notes_row_layout)
# Add a label for the image
# Construct the absolute path of the image file
image_path = os.path.join(script_dir, "image/vpforcelogo.png")
self.image_label = QLabel()
pixmap = QPixmap(image_path)
self.image_label.setPixmap(pixmap)
# Construct the absolute path of the icon file
icon_path = os.path.join(script_dir, "image/vpforceicon.png")
self.setWindowIcon(QIcon(icon_path))
# Add the image label to the layout
layout.addWidget(self.image_label, alignment=Qt.AlignTop | Qt.AlignLeft)
# layout.addWidget(QLabel(f"Config File: {args.configfile}"))
cfg_layout = QHBoxLayout()
self.cfg_label = QLabel()
self.cfg_label.setText(f"Config File: {args.configfile}")
self.cfg_label.setToolTip("You can use a custom configuration file by passing the -c argument to TelemFFB\n\nExample: \"VPForce-TelemFFB.exe -c customconfig.ini\"")
self.ovrd_label = QLabel()
if os.path.exists(args.overridefile):
self.ovrd_label.setText(f"User Override File: {args.overridefile}")
else:
self.ovrd_label.setText(f"User Override File: None")
self.ovrd_label.setToolTip("Rename \'config.user.ini.README\' to \'config.user.ini\' or create a new <custom_name>.user.ini file and pass the name to TelemFFB with the -o argument\n\nExample \"VPForce-TelemFFB.exe -o myconfig.user.ini\" (starting TelemFFB without the override flag will look for the default config.user.ini)")
self.ovrd_label.setAlignment(Qt.AlignLeft)
self.cfg_label.setAlignment(Qt.AlignLeft)
cfg_layout.addWidget(self.cfg_label)
cfg_layout.addWidget(self.ovrd_label)
layout.addLayout(cfg_layout)
cfg = get_config()
dcs_enabled = utils.sanitize_dict(cfg["system"]).get("dcs_enabled", False)
msfs_enabled = utils.sanitize_dict(cfg["system"]).get("msfs_enabled", False)
il2_enabled = utils.sanitize_dict(cfg["system"]).get("il2_enabled", False)
if args.sim == "DCS" or dcs_enabled:
dcs_enabled = 'True'
else:
dcs_enabled = 'False'
if args.sim == "MSFS" or msfs_enabled:
msfs_enabled = 'True'
else:
msfs_enabled = 'False'
if args.sim == "IL2" or il2_enabled:
il2_enabled = 'True'
else:
il2_enabled = 'False'
simlabel = QLabel(f"Sims Enabled: DCS: {dcs_enabled} | MSFS: {msfs_enabled} | IL2: {il2_enabled}")
simlabel.setToolTip("Enable/Disable Sims in config file or use '-s DCS|MSFS' argument to specify")
layout.addWidget(simlabel)
# Add a label and telemetry data label
# layout.addWidget(QLabel("Telemetry"))
self.radio_button_group = QButtonGroup()
radio_row_layout = QHBoxLayout()
self.telem_monitor_radio = QRadioButton("Telemetry Monitor")
self.effect_monitor_radio = QRadioButton("Effects Monitor")
radio_row_layout.addWidget(self.telem_monitor_radio)
radio_row_layout.addWidget(self.effect_monitor_radio)
self.telem_monitor_radio.setChecked(True)
self.radio_button_group.addButton(self.telem_monitor_radio)
self.radio_button_group.addButton(self.effect_monitor_radio)
# self.radio_button_group.buttonClicked.connect(self.update_monitor_window)
layout.addLayout(radio_row_layout)
# Create a scrollable area
scroll_area = QScrollArea()
scroll_area.setWidgetResizable(True)
# Create the QLabel widget and set its properties
if cfg.get("EXCEPTION"):
error = cfg["EXCEPTION"]["ERROR"]
logging.error(f"CONFIG ERROR: {error}")
self.lbl_telem_data = QLabel(f"CONFIG ERROR: {error}")
QMessageBox.critical(None, "CONFIG ERROR", f"Error: {error}")
else:
self.lbl_telem_data = QLabel("Waiting for data...")
self.lbl_telem_data.setTextInteractionFlags(Qt.TextSelectableByMouse)
self.lbl_telem_data.setWordWrap(True)
# Set the QLabel widget as the widget inside the scroll area
scroll_area.setWidget(self.lbl_telem_data)
# Add the scroll area to the layout
layout.addWidget(scroll_area)
edit_button = QPushButton("Edit Config File")
edit_button.setMinimumWidth(200)
edit_button.setMaximumWidth(200)
layout.addWidget(edit_button, alignment=Qt.AlignCenter)
# Create a sub-menu for the button
self.sub_menu = QMenu(edit_button)
primary_config_action = QAction("Primary Config", self)
primary_config_action.triggered.connect(lambda: self.edit_config_file("Primary"))
if os.path.exists(args.overridefile):
user_config_action = QAction("User Config", self)
user_config_action.triggered.connect(lambda: self.edit_config_file("User"))
self.sub_menu.addAction(primary_config_action)
if os.path.exists(args.overridefile):
self.sub_menu.addAction(user_config_action)
# Connect the button's click event to show the sub-menu
edit_button.clicked.connect(self.show_sub_menu)
self.log_button = QPushButton("Open/Hide Log")
self.log_button.setMinimumWidth(200)
self.log_button.setMaximumWidth(200)
self.log_button.clicked.connect(self.toggle_log_window)
layout.addWidget(self.log_button, alignment=Qt.AlignCenter)
# Add the exit button
exit_button = QPushButton("Exit")
exit_button.setMinimumWidth(200) # Set the minimum width
exit_button.setMaximumWidth(200) # Set the maximum width
exit_button.clicked.connect(self.exit_application)
layout.addWidget(exit_button, alignment=Qt.AlignCenter)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
self.layout = QVBoxLayout(central_widget)
link_row_layout = QHBoxLayout()
self.doc_label = QLabel()
doc_url = 'https://docs.google.com/document/d/1YL5DLkiTxlaNx_zKHEYSs25PjmGtQ6_WZDk58_SGt8Y/edit#heading=h.27yzpife8719'
label_txt = 'TelemFFB Documentation'
self.doc_label.setTextInteractionFlags(Qt.TextBrowserInteraction)
self.doc_label.setOpenExternalLinks(True)
self.doc_label.setText(f'<a href="{doc_url}">{label_txt}</a>')
self.doc_label.setToolTip(doc_url)
self.dl_label = QLabel()
if _release:
dl_url = 'https://github.com/walmis/VPforce-TelemFFB/releases'
label_txt = "GitHub Releases"
else:
dl_url = 'https://vpforcecontrols.com/downloads/TelemFFB/?C=M;O=A'
label_txt = 'Download Latest'
self.dl_label.setTextInteractionFlags(Qt.TextBrowserInteraction)
self.dl_label.setOpenExternalLinks(True)
self.dl_label.setText(f'<a href="{dl_url}">{label_txt}</a>')
self.dl_label.setAlignment(Qt.AlignRight)
self.dl_label.setToolTip(dl_url)
link_row_layout.addWidget(self.doc_label)
link_row_layout.addWidget(self.dl_label)
version_row_layout = QHBoxLayout()
self.version_label = QLabel()
if _release:
status_text = f"Release Version {version}"
else:
status_text = "UNKNOWN"
self.version_label.setText(f'Version Status: {status_text}')
self.version_label.setOpenExternalLinks(True)
global dev_firmware_version
self.firmware_label = QLabel()
self.firmware_label.setText(f'Rhino Firmware: {dev_firmware_version}')
self.version_label.setAlignment(Qt.AlignLeft)
self.firmware_label.setAlignment(Qt.AlignRight)
version_row_layout.addWidget(self.version_label)
version_row_layout.addWidget(self.firmware_label)
layout.addLayout(link_row_layout)
layout.addLayout(version_row_layout)
central_widget.setLayout(layout)
def update_version_result(self, vers, url):
global _update_available
global _latest_version
global _latest_url
_latest_version = vers
_latest_url = url
status = False
self.update_action.setDisabled(False)
if vers == "uptodate":
status_text = "Up To Date"
status = False
self.version_label.setText(f'Version Status: {status_text}')
elif vers == "error":
status_text = "UNKNOWN"
status = None
self.version_label.setText(f'Version Status: {status_text}')
else:
# print(_update_available)
_update_available = True
logging.info(f"<<<<Update available - new version={vers}>>>>")
status_text = f"New version <a href='{url}'><b>{vers}</b></a> is available!"
self.version_label.setToolTip(url)
self.version_label.setText(f'Version Status: {status_text}')
self.perform_update(auto=True)
def show_sub_menu(self):
edit_button = self.sender()
self.sub_menu.popup(edit_button.mapToGlobal(edit_button.rect().bottomLeft()))
def open_file(self, url):
try:
file_url = QUrl.fromLocalFile(url)
QDesktopServices.openUrl(file_url)
except Exception as e:
logging.error(f"There was an error opening the file: {str(e)}")
def reset_all_effects(self):
result = QMessageBox.warning(None, "Are you sure?", "*** Only use this if you have effects which are 'stuck' ***\n\n Proceeding will result in the destruction"
" of any effects which are currently being generated by the simulator and may result in requiring a restart of"
" the sim or a new session.\n\n~~ Proceed with caution ~~", QMessageBox.Ok | QMessageBox.Cancel, QMessageBox.Cancel)
if result == QMessageBox.Ok:
try:
HapticEffect.device.resetEffects()
except Exception as error:
pass
def edit_config_file(self, config_type):
script_dir = os.path.dirname(os.path.abspath(__file__))
if config_type == "Primary":
config_file = args.configfile
elif config_type == "User":
config_file = args.overridefile
config_path = os.path.join(script_dir, config_file)
file_url = QUrl.fromLocalFile(config_path)
try:
QDesktopServices.openUrl(file_url)
except:
logging.error(f"There was an error opening the config file")
def toggle_log_window(self):
if d.isVisible():
d.hide()
else:
d.show()
def exit_application(self):
# Perform any cleanup or save operations here
QCoreApplication.instance().quit()
def update_from_menu(self):
if self.perform_update(auto=False):
QCoreApplication.instance().quit()
def update_telemetry(self, data: dict):
try:
items = ""
for k, v in data.items():
if type(v) == float:
items += f"{k}: {v:.3f}\n"
else:
if isinstance(v, list):
v = "[" + ", ".join([f"{x:.3f}" if not isinstance(x, str) else x for x in v]) + "]"
items += f"{k}: {v}\n"
active_effects = ""
for key in effects.dict.keys():
if effects[key].started:
descr = effects_translator.get_translation(key)
if descr not in active_effects:
active_effects = '\n'.join([active_effects, descr])
window_mode = self.radio_button_group.checkedButton()
if window_mode == self.telem_monitor_radio:
self.lbl_telem_data.setText(items)
self.lbl_telem_data.setAlignment(Qt.AlignTop | Qt.AlignLeft)
elif window_mode == self.effect_monitor_radio:
self.lbl_telem_data.setText(active_effects)
self.lbl_telem_data.setAlignment(Qt.AlignTop | Qt.AlignLeft)
except Exception as e:
traceback.print_exc()
def perform_update(self, auto=True):
if _release:
return False
config = get_config()
ignore_auto_updates = utils.sanitize_dict(config["system"]).get("ignore_auto_updates", 0)
if not auto:
ignore_auto_updates = False
update_ans = QMessageBox.No
proceed_ans = QMessageBox.Cancel
is_exe = getattr(sys, 'frozen',
False) # TODO: Make sure to swap these comment-outs before build to commit - this line should be active, next line should be commented out
# is_exe = True
if is_exe and _update_available and not ignore_auto_updates:
# vers, url = utils.fetch_latest_version()
update_ans = QMessageBox.Yes
if auto:
update_ans = QMessageBox.information(self, "Update Available!!",
f"A new version of TelemFFB is available ({_latest_version}).\n\nWould you like to automatically download and install it now?\n\nYou may also update later from the Utilities menu, or the\nnext time TelemFFB starts.\n\n~~ Note ~~ If you no longer wish to see this message on startup,\nyou may enable `ignore_auto_updates` in your user config.\n\nYou will still be able to update via the Utilities menu",
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if update_ans == QMessageBox.Yes:
proceed_ans = QMessageBox.information(self, "TelemFFB Updater",
f"TelemFFB will now exit and launch the updater.\n\nOnce the update is complete, TelemFFB will restart.\n\n~~ Please Note~~~ The primary `config.ini` file will be overwritten. If you\nhave made changes to `config.ini`, please back up the file or move the modifications to a user config file before upgrading.\n\nPress OK to continue",
QMessageBox.Ok | QMessageBox.Cancel, QMessageBox.Cancel)
if proceed_ans == QMessageBox.Ok:
global _current_version
updater_source_path = os.path.join(os.path.dirname(__file__), 'updater', 'updater.exe')
updater_execution_path = os.path.join(os.path.dirname(__file__), 'updater.exe')
# Copy the updater executable with forced overwrite
shutil.copy2(updater_source_path, updater_execution_path)
active_args, unknown_args = parser.parse_known_args()
args_list = [f'--{k}={v}' for k, v in vars(active_args).items() if
v is not None and v != parser.get_default(k)]
call = [updater_execution_path, "--current_version", _current_version] + args_list