-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
353 lines (294 loc) · 11.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
"""Main start module"""
# We need to set OS envs before any Kivy widgets are called
# looking at you Test.
import os
import pathlib
WORKING_PATH = str(pathlib.Path(__file__).parent.absolute())
os.environ["KIVY_HOME"] = WORKING_PATH + "/etc/kivy/"
# Comment the line below out to see logs in terminal
os.environ["KIVY_NO_CONSOLELOG"] = "1"
# Dependent modules and packages
import getopt
import sys
import traceback
from sys import platform
from digitaldash.test import Test
from typing import Optional, Union
from functools import lru_cache
from digitaldash.keProtocol import Serial
(TESTING, ConfigFile) = (False, None)
dataSource: Optional[Test | Serial] = None
opts, args = getopt.getopt(
sys.argv[1:], "tdf:c:", ["test", "development", "file=", "config="]
)
sys.argv = ["main.py"]
for o, arg in opts:
# Development mode runs with debug console - ctr + e to open it in GUI
if o in ("-d", "--development"):
sys.argv = ["main.py -m console"]
elif o in ("-f", "--file"):
dataSource = Test(file="tests/data/rpm_increasing.csv")
elif o in ("-t", "--test"):
TESTING = True
elif o in ("-c", "--config"):
ConfigFile = arg
# Our Kivy deps
from kivy.logger import Logger
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.relativelayout import RelativeLayout
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from kivy.uix.label import Label
from kivy.clock import mainthread, Clock
# Rust import
import libdigitaldash
from digitaldash.digitaldash import buildFromConfig, clearWidgets
from digitaldash.digitaldash import Alert, Dynamic
from _version import __version__
from etc import config
config.setWorkingPath(WORKING_PATH)
if dataSource is None:
try:
dataSource = Serial()
Logger.info("Using serial data source" + str(dataSource))
except Exception as e:
Logger.error("Running without serial data: " + str(e))
class MyHandler(PatternMatchingEventHandler):
"""
Class that handles file watchdog duties.
"""
def __init__(self, DigitalDash):
super(MyHandler, self).__init__()
self.DigitalDash = DigitalDash
patterns = ["*.json"]
def rebuild(self, dt):
Logger.info("Rebuilding config")
try:
buildFromConfig(self.DigitalDash, dataSource)
if self.DigitalDash.data_source:
self.DigitalDash.clock_event = Clock.schedule_interval(
self.DigitalDash.loop, 0
)
# remove from background
self.DigitalDash.remove_version_layout(0)
# Add back our version labels
self.DigitalDash.background.add_widget(
self.DigitalDash.version_layout
)
except Exception as ex:
Logger.error(
f"GUI: {''.join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))}"
)
clearWidgets(self.DigitalDash, background=True)
self.DigitalDash.remove_version_layout(0)
error_label = Label(text=str(ex), pos=(0, 200))
error_layout = RelativeLayout()
error_layout.add_widget(error_label)
self.DigitalDash.background.add_widget(error_layout)
self.DigitalDash.background.add_widget(
self.DigitalDash.version_layout
)
self.DigitalDash.app.add_widget(self.DigitalDash.background)
@mainthread
def on_modified(self, event):
if hasattr(self.DigitalDash, "clock_event"):
self.DigitalDash.clock_event.cancel()
Clock.schedule_once(self.rebuild, 0)
# Load our KV files
for file in os.listdir(WORKING_PATH + "/digitaldash/kv/"):
Builder.load_file(WORKING_PATH + "/digitaldash/kv/" + str(file))
class GUI(App):
"""
Main class that initiates kivy app.
This class instantiates the KE module which will build
the DigitalDash. Main loop is here for updating data within
DigitalDash. The loop will iterate through the **widgets**
array and call the **set_data()** method on each item in the
array. Only add Objects to the **widgets** array if they are
to be updated and have the necessary methods.
"""
success: str
status: str
def __init__(self, **args):
super().__init__()
self.configFile = args.get("configFile")
self.jsonData = args.get("jsonData")
self.WORKING_PATH = WORKING_PATH
self.count = 0
def new(self, configFile=None, data=None):
"""
This method can be used to set any values before the app starts, this is useful for
testing.
"""
if configFile:
self.configFile = configFile
if data:
global dataSource
dataSource = data
def remove_version_layout(self, _dt):
"""
Remove the firmware/gui version label layout, this should be auto
called with the clock schedule_once function.
"""
Logger.info("GUI: Removing firmware/gui version label")
if hasattr(self, "background") and hasattr(self, "version_layout"):
self.background.remove_widget(self.version_layout)
else:
Logger.error(
"GUI: Tried to remove version labels from an object that doesn't have a background attribute"
)
def create_version_layout(self):
if self.data_source:
self.firmware_version = (
f"FW: {self.data_source.get_firmware_version()}"
)
Logger.error(f"VERSION: {self.firmware_version}")
else:
self.firmware_version = "FW: N/A"
self.gui_version = f"GUI: {__version__}"
y_pos = 160
if platform == "linux" or platform == "linux2":
y_pos = 20
self.version_label = Label(
text=f"{self.firmware_version} {self.gui_version}", pos=(0, y_pos)
)
self.version_layout = RelativeLayout()
self.version_layout.add_widget(self.version_label)
def build(self):
"""Called at start of application"""
# Our main application object
self.app = AnchorLayout()
self.data_source = dataSource
self.working_path = WORKING_PATH
observer = Observer()
observer.schedule(
MyHandler(self), WORKING_PATH + "/etc/", recursive=False
)
observer.start()
try:
buildFromConfig(self, dataSource)
except Exception as ex:
Logger.error(
f"GUI: {''.join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))}"
)
self.create_version_layout()
error_label = Label(text=str(ex), pos=(0, 200))
error_layout = RelativeLayout()
error_layout.add_widget(error_label)
self.app.add_widget(error_layout)
self.app.add_widget(self.version_layout)
return self.app
self.create_version_layout()
self.background.add_widget(self.version_layout)
if self.data_source:
self.clock_event = Clock.schedule_interval(self.loop, 0)
return self.app
@lru_cache(maxsize=128)
def rust_check(self, value: float, callback: Union[Alert, Dynamic]):
try:
# Check if any dynamic changes need to be made
if libdigitaldash.check(value, callback.value, callback.op):
return callback
except Exception as ex:
# Check if this is the error config (i.e. PID = "n/a")
# TODO: Do we need this any longer?
if callback.pid.value == "n/a":
Logger.error("GUI: Config file is invalid: %s", ex)
return callback
Logger.error(
"GUI: Firmware did not provide data value for key: %s: %s",
callback.pid.value,
ex,
)
def check_callback(self, callback: Union[Alert, Dynamic], data: dict):
"""
We mainthread this function so that someone with crazy toggle fingers
doesn't beat the race condition.
"""
try:
return self.rust_check(float(data[callback.pid.value]), callback)
except KeyError as ex:
Logger.error(
"GUI: Firmware did not provide expected data value: %s",
ex,
)
return False
except ValueError as ex:
Logger.error(
"GUI: Firmware did not provide expected data value type: %s",
ex,
)
@mainthread
def change(self, app, my_callback):
"""
This method only handles dynamic changing, the alert changing is handled in
the main application loop.
"""
self.current = my_callback.viewId
my_callback.change(self)
def update_values(self, data: dict[float]):
for widget in self.objectsToUpdate:
for obj in widget:
if obj.pid:
try:
obj.setData(data[obj.pid.value])
except Exception:
Logger.error(
"GUI: Firmware did not provide data value for key: %s",
obj.pid.value,
)
else:
# This is for widgets that subscribe to
# updates but don't need any pid data ( Clock ).
obj.set_data(0)
# TODO: Is there a big issue with mainthreading the whole loop?
@mainthread
def loop(self, _dt: float):
if self.first_iteration:
self.first_iteration = False
if dataSource is not None:
(my_callback, data) = (
None,
dataSource.service(app=self, pids=self.pids),
)
# Buffer our alerts and dynamic updates
if self.count > 8:
dynamic_change = False
# Check dynamic gauges before any alerts in case we make a change
for dynamic in self.dynamic_callbacks:
if str(self.current) == str(dynamic.viewId):
pass
else:
my_callback = self.check_callback(dynamic, data)
Logger.debug(
"Checking dynamic callback for PID: %s, OP: %s Value: %s for view %s",
dynamic.pid.value,
dynamic.op,
dynamic.value,
dynamic.viewId,
)
if my_callback:
self.count = 0
self.change(self, my_callback)
dynamic_change = True
break
# Check our alerts if no dynamic changes have occured
if not dynamic_change:
for callback in self.alert_callbacks:
my_callback = self.check_callback(callback, data)
if my_callback:
self.count = 0
if callback.parent is None:
self.alerts.add_widget(my_callback)
elif callback.parent:
self.alerts.remove_widget(callback)
else:
self.count = self.count + 1
self.update_values(data)
if __name__ == "__main__":
Logger.info(f"GUI: Running version: {__version__}")
dd = GUI()
dd.new(configFile=ConfigFile, data=dataSource)
dd.run()