benchlab-pytools 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. benchlab/__init__.py +14 -0
  2. benchlab/__main__.py +21 -0
  3. benchlab/config/README.md +325 -0
  4. benchlab/config/__init__.py +9 -0
  5. benchlab/config/config_client.py +631 -0
  6. benchlab/config/config_manager.py +495 -0
  7. benchlab/config/config_tool.py +358 -0
  8. benchlab/config/diff.py +163 -0
  9. benchlab/config/examples/complete_config.json +56 -0
  10. benchlab/config/examples/rgb_lighting.json +24 -0
  11. benchlab/config/examples/simple_fan.json +32 -0
  12. benchlab/config/schema.py +138 -0
  13. benchlab/core/README.md +154 -0
  14. benchlab/core/__init__.py +78 -0
  15. benchlab/core/config.py +145 -0
  16. benchlab/core/datasource.py +1209 -0
  17. benchlab/core/datasource_manager.py +418 -0
  18. benchlab/core/device_registry.py +206 -0
  19. benchlab/core/discovery.py +92 -0
  20. benchlab/core/infrastructure.py +309 -0
  21. benchlab/core/process_manager.py +356 -0
  22. benchlab/core/retry.py +85 -0
  23. benchlab/core/shared_serial.py +235 -0
  24. benchlab/core/statistics.py +224 -0
  25. benchlab/csv_log/README.md +206 -0
  26. benchlab/csv_log/__init__.py +5 -0
  27. benchlab/csv_log/csv_logger_enhanced.py +416 -0
  28. benchlab/csv_log/message_batcher.py +361 -0
  29. benchlab/csv_log/requirements.txt +3 -0
  30. benchlab/csv_log/smart_retry.py +466 -0
  31. benchlab/graph/README.md +117 -0
  32. benchlab/graph/__init__.py +5 -0
  33. benchlab/graph/app.py +353 -0
  34. benchlab/graph/requirements.txt +2 -0
  35. benchlab/graph/runner.py +42 -0
  36. benchlab/graph/ui.py +288 -0
  37. benchlab/hwinfo/README.md +135 -0
  38. benchlab/hwinfo/__init__.py +5 -0
  39. benchlab/hwinfo/hwinfo_export.py +386 -0
  40. benchlab/hwinfo/requirements.txt +1 -0
  41. benchlab/launcher.py +387 -0
  42. benchlab/link/.env.EXAMPLE +10 -0
  43. benchlab/link/README.md +172 -0
  44. benchlab/link/__init__.py +1 -0
  45. benchlab/link/link_main.py +479 -0
  46. benchlab/main.py +462 -0
  47. benchlab/menu.py +729 -0
  48. benchlab/menu_classic.py +410 -0
  49. benchlab/mqtt/README.md +201 -0
  50. benchlab/mqtt/__init__.py +5 -0
  51. benchlab/mqtt/mqtt.config_template +2 -0
  52. benchlab/mqtt/mqtt_publisher.py +540 -0
  53. benchlab/mqtt/requirements.txt +3 -0
  54. benchlab/prefs.py +67 -0
  55. benchlab/restapi/.env.example +17 -0
  56. benchlab/restapi/__init__.py +5 -0
  57. benchlab/restapi/favicon.ico +0 -0
  58. benchlab/restapi/readme.md +202 -0
  59. benchlab/restapi/requirements.txt +5 -0
  60. benchlab/restapi/telemetry_api.py +808 -0
  61. benchlab/sources.py +515 -0
  62. benchlab/tools.py +147 -0
  63. benchlab/tui/README.md +266 -0
  64. benchlab/tui/__init__.py +5 -0
  65. benchlab/tui/config.py +477 -0
  66. benchlab/tui/requirements.txt +2 -0
  67. benchlab/tui/tui_core.py +1298 -0
  68. benchlab/tui/tui_main.py +418 -0
  69. benchlab/vu/README.md +64 -0
  70. benchlab/vu/VU-Server/NOTICE.md +13 -0
  71. benchlab/vu/VU-Server/README.md +80 -0
  72. benchlab/vu/VU-Server/Running_from_source_on_linux.md +97 -0
  73. benchlab/vu/VU-Server/__init__.py +0 -0
  74. benchlab/vu/VU-Server/assets/vu1_hello_world.png +0 -0
  75. benchlab/vu/VU-Server/community_applications.md +13 -0
  76. benchlab/vu/VU-Server/config.yaml +9 -0
  77. benchlab/vu/VU-Server/database.py +256 -0
  78. benchlab/vu/VU-Server/dial_driver.py +534 -0
  79. benchlab/vu/VU-Server/dials/Comms_Hub_Gauge.py +78 -0
  80. benchlab/vu/VU-Server/dials/Comms_Hub_Server.py +100 -0
  81. benchlab/vu/VU-Server/dials/__init__.py +0 -0
  82. benchlab/vu/VU-Server/dials/base_logger.py +100 -0
  83. benchlab/vu/VU-Server/installer/inc/icon.ico +0 -0
  84. benchlab/vu/VU-Server/installer/install.nsi +148 -0
  85. benchlab/vu/VU-Server/make_version.py +40 -0
  86. benchlab/vu/VU-Server/pylintrc +628 -0
  87. benchlab/vu/VU-Server/requirements.txt +9 -0
  88. benchlab/vu/VU-Server/serial_driver.py +244 -0
  89. benchlab/vu/VU-Server/server.py +670 -0
  90. benchlab/vu/VU-Server/server_config.py +255 -0
  91. benchlab/vu/VU-Server/server_dial_handler.py +334 -0
  92. benchlab/vu/VU-Server/vu_notifications.py +24 -0
  93. benchlab/vu/VU-Server/www/android-chrome-192x192.png +0 -0
  94. benchlab/vu/VU-Server/www/android-chrome-512x512.png +0 -0
  95. benchlab/vu/VU-Server/www/apple-touch-icon.png +0 -0
  96. benchlab/vu/VU-Server/www/assets/css/demo.css +291 -0
  97. benchlab/vu/VU-Server/www/assets/css/demo.min.css +9 -0
  98. benchlab/vu/VU-Server/www/assets/css/demo.rtl.css +276 -0
  99. benchlab/vu/VU-Server/www/assets/css/demo.rtl.min.css +9 -0
  100. benchlab/vu/VU-Server/www/assets/css/tabler-flags.css +1084 -0
  101. benchlab/vu/VU-Server/www/assets/css/tabler-flags.min.css +9 -0
  102. benchlab/vu/VU-Server/www/assets/css/tabler-flags.rtl.css +1084 -0
  103. benchlab/vu/VU-Server/www/assets/css/tabler-flags.rtl.min.css +9 -0
  104. benchlab/vu/VU-Server/www/assets/css/tabler-payments.css +528 -0
  105. benchlab/vu/VU-Server/www/assets/css/tabler-payments.min.css +9 -0
  106. benchlab/vu/VU-Server/www/assets/css/tabler-payments.rtl.css +528 -0
  107. benchlab/vu/VU-Server/www/assets/css/tabler-payments.rtl.min.css +9 -0
  108. benchlab/vu/VU-Server/www/assets/css/tabler-social.css +10 -0
  109. benchlab/vu/VU-Server/www/assets/css/tabler-social.min.css +8 -0
  110. benchlab/vu/VU-Server/www/assets/css/tabler-social.rtl.css +10 -0
  111. benchlab/vu/VU-Server/www/assets/css/tabler-social.rtl.min.css +8 -0
  112. benchlab/vu/VU-Server/www/assets/css/tabler-vendors.css +1504 -0
  113. benchlab/vu/VU-Server/www/assets/css/tabler-vendors.min.css +9 -0
  114. benchlab/vu/VU-Server/www/assets/css/tabler-vendors.rtl.css +1504 -0
  115. benchlab/vu/VU-Server/www/assets/css/tabler-vendors.rtl.min.css +9 -0
  116. benchlab/vu/VU-Server/www/assets/css/tabler.css +25813 -0
  117. benchlab/vu/VU-Server/www/assets/css/tabler.min.css +13 -0
  118. benchlab/vu/VU-Server/www/assets/css/tabler.rtl.css +25777 -0
  119. benchlab/vu/VU-Server/www/assets/css/tabler.rtl.min.css +13 -0
  120. benchlab/vu/VU-Server/www/assets/css/theme.min.css +261 -0
  121. benchlab/vu/VU-Server/www/assets/img/header.png +0 -0
  122. benchlab/vu/VU-Server/www/assets/img/logo.png +0 -0
  123. benchlab/vu/VU-Server/www/assets/js/dark-theme.js +35 -0
  124. benchlab/vu/VU-Server/www/assets/js/dark-theme.min.js +9 -0
  125. benchlab/vu/VU-Server/www/assets/js/demo.js +132 -0
  126. benchlab/vu/VU-Server/www/assets/js/demo.min.js +9 -0
  127. benchlab/vu/VU-Server/www/assets/js/jquery.min.js +2 -0
  128. benchlab/vu/VU-Server/www/assets/js/tabler.esm.js +7482 -0
  129. benchlab/vu/VU-Server/www/assets/js/tabler.esm.min.js +15 -0
  130. benchlab/vu/VU-Server/www/assets/js/tabler.js +7543 -0
  131. benchlab/vu/VU-Server/www/assets/js/tabler.min.js +15 -0
  132. benchlab/vu/VU-Server/www/assets/js/vu1_api.js +68 -0
  133. benchlab/vu/VU-Server/www/assets/js/vu1_gui_api_key_settings.js +167 -0
  134. benchlab/vu/VU-Server/www/assets/js/vu1_gui_api_keys.js +138 -0
  135. benchlab/vu/VU-Server/www/assets/js/vu1_gui_dial.js +179 -0
  136. benchlab/vu/VU-Server/www/assets/js/vu1_gui_home.js +60 -0
  137. benchlab/vu/VU-Server/www/assets/js/vu1_gui_root.js +125 -0
  138. benchlab/vu/VU-Server/www/favicon-16x16.png +0 -0
  139. benchlab/vu/VU-Server/www/favicon-32x32.png +0 -0
  140. benchlab/vu/VU-Server/www/favicon.ico +0 -0
  141. benchlab/vu/VU-Server/www/favicon.png +0 -0
  142. benchlab/vu/VU-Server/www/index.html +47 -0
  143. benchlab/vu/VU-Server/www/views/api_keys.html +151 -0
  144. benchlab/vu/VU-Server/www/views/dial.html +286 -0
  145. benchlab/vu/VU-Server/www/views/footer.html +27 -0
  146. benchlab/vu/VU-Server/www/views/header.html +86 -0
  147. benchlab/vu/VU-Server/www/views/key_settings.html +132 -0
  148. benchlab/vu/VU-Server/www/views/start.html +124 -0
  149. benchlab/vu/__init__.py +5 -0
  150. benchlab/vu/assets/Barlow-Bold.ttf +0 -0
  151. benchlab/vu/assets/bl_dial_144x200.png +0 -0
  152. benchlab/vu/assets/bl_logo_144x200.png +0 -0
  153. benchlab/vu/devices.py +166 -0
  154. benchlab/vu/requirements.txt +24 -0
  155. benchlab/vu/sensors.py +18 -0
  156. benchlab/vu/vu_dial.config_template +90 -0
  157. benchlab/vu/vu_logo_gen.py +97 -0
  158. benchlab/vu/vu_server.config_template +5 -0
  159. benchlab/vu/vu_server_config.py +40 -0
  160. benchlab/vu/vu_server_manager.py +192 -0
  161. benchlab/vu/vu_tui.py +919 -0
  162. benchlab/vu/vu_updater.py +540 -0
  163. benchlab/wigidash/README.md +182 -0
  164. benchlab/wigidash/__init__.py +5 -0
  165. benchlab/wigidash/assets/Inter-Bold.ttf +0 -0
  166. benchlab/wigidash/assets/Inter.ttf +0 -0
  167. benchlab/wigidash/assets/benchlab.png +0 -0
  168. benchlab/wigidash/benchlab_fleet.py +150 -0
  169. benchlab/wigidash/benchlab_graph.py +517 -0
  170. benchlab/wigidash/benchlab_overview.py +426 -0
  171. benchlab/wigidash/benchlab_telemetry.py +105 -0
  172. benchlab/wigidash/benchlab_ui.py +190 -0
  173. benchlab/wigidash/benchlab_utils.py +182 -0
  174. benchlab/wigidash/requirements.txt +9 -0
  175. benchlab/wigidash/wigidash_device.py +541 -0
  176. benchlab/wigidash/wigidash_manager.py +342 -0
  177. benchlab/wigidash/wigidash_session.py +355 -0
  178. benchlab/wigidash/wigidash_usb.py +247 -0
  179. benchlab/wigidash/wigidash_widget.py +88 -0
  180. benchlab_pytools-3.0.0.dist-info/METADATA +239 -0
  181. benchlab_pytools-3.0.0.dist-info/RECORD +184 -0
  182. benchlab_pytools-3.0.0.dist-info/WHEEL +4 -0
  183. benchlab_pytools-3.0.0.dist-info/entry_points.txt +2 -0
  184. benchlab_pytools-3.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,540 @@
1
+ # vu_updater.py
2
+
3
+ import json
4
+ import logging
5
+ import os
6
+ import signal
7
+ import threading
8
+ import time
9
+ import types
10
+ import zlib
11
+ from pathlib import Path
12
+
13
+ import requests
14
+
15
+ from benchlab.core.datasource_manager import DataSourceManager
16
+ from benchlab.vu.sensors import get_sensor_value
17
+ from benchlab.vu.vu_logo_gen import generate_sensor_logo
18
+ from benchlab.vu.vu_server_manager import (
19
+ start_vu_server, check_vu_server, forward_logs, terminate_vu_server
20
+ )
21
+
22
+ BASE_DIR = Path(__file__).parent
23
+
24
+ VU_SERVER_CONFIG = BASE_DIR / "vu_server.config"
25
+ VU_DIAL_CONFIG = BASE_DIR / "vu_dial.config"
26
+ STANDARD_LOGO = BASE_DIR / "assets" / "bl_logo_144x200.png"
27
+
28
+ VU_DIAL_LAST_MTIME = 0
29
+ previous_dial_cfg = {}
30
+ shutdown_event = threading.Event()
31
+
32
+ # --- Logger ---
33
+ logger = logging.getLogger("vu_updater")
34
+ logger.setLevel(logging.DEBUG)
35
+ _fmt = logging.Formatter(
36
+ "%(asctime)s [%(levelname)s] %(message)s",
37
+ datefmt="%Y-%m-%d %H:%M:%S")
38
+ _ch = logging.StreamHandler()
39
+ _ch.setLevel(logging.INFO)
40
+ _ch.setFormatter(_fmt)
41
+ logger.addHandler(_ch)
42
+ _fh = logging.FileHandler(BASE_DIR / "vu_updater.log", mode="a")
43
+ _fh.setLevel(logging.DEBUG)
44
+ _fh.setFormatter(_fmt)
45
+ logger.addHandler(_fh)
46
+
47
+
48
+ def handle_sigint(signum, frame):
49
+ print("\nCtrl+C pressed. Initiating graceful shutdown...")
50
+ shutdown_event.set()
51
+
52
+
53
+ signal.signal(signal.SIGINT, handle_sigint)
54
+
55
+
56
+ # ---------------------------------------------------------------------------
57
+ # Helpers
58
+ # ---------------------------------------------------------------------------
59
+
60
+ def file_crc32(path: Path) -> str:
61
+ crc = 0
62
+ with path.open("rb") as f:
63
+ while chunk := f.read(65536):
64
+ crc = zlib.crc32(chunk, crc)
65
+ return f"{crc & 0xFFFFFFFF:08X}"
66
+
67
+
68
+ def load_json(path, default=None):
69
+ if Path(path).exists():
70
+ with open(path, "r") as f:
71
+ return json.load(f)
72
+ return default if default is not None else {}
73
+
74
+
75
+ def reload_dial_config():
76
+ global VU_DIAL_LAST_MTIME
77
+ if not VU_DIAL_CONFIG.exists():
78
+ return []
79
+ mtime = VU_DIAL_CONFIG.stat().st_mtime
80
+ if mtime == VU_DIAL_LAST_MTIME:
81
+ return []
82
+ VU_DIAL_LAST_MTIME = mtime
83
+ try:
84
+ new_cfg = load_json(VU_DIAL_CONFIG, default=[])
85
+ except Exception as e:
86
+ logger.error(f"Failed to load vu_dial.config: {e}")
87
+ return []
88
+ changed = []
89
+ for mapping in new_cfg:
90
+ uid = mapping.get("dial_uid")
91
+ if not uid:
92
+ continue
93
+ if mapping != previous_dial_cfg.get(uid, {}):
94
+ changed.append(mapping)
95
+ previous_dial_cfg[uid] = mapping.copy()
96
+ if changed:
97
+ logger.info(f"Detected {len(changed)} dial config changes")
98
+ return changed
99
+
100
+
101
+ # ---------------------------------------------------------------------------
102
+ # VU API client
103
+ # ---------------------------------------------------------------------------
104
+
105
+ class VUClient:
106
+ def __init__(self, server_url, api_key):
107
+ self.server_url = server_url.rstrip("/")
108
+ self.api_key = api_key
109
+
110
+ def _get(self, path, **params):
111
+ params["key"] = self.api_key
112
+ r = requests.get(f"{self.server_url}{path}", params=params, timeout=10)
113
+ r.raise_for_status()
114
+ return r
115
+
116
+ def update_dial(self, dial_uid, value):
117
+ try:
118
+ self._get(f"/api/v0/dial/{dial_uid}/set", value=value)
119
+ except requests.RequestException as e:
120
+ logger.error(f"Failed to update {dial_uid}: {e}")
121
+
122
+ def update_backlight(self, dial_uid, rgb):
123
+ try:
124
+ self._get(f"/api/v0/dial/{dial_uid}/backlight",
125
+ red=rgb[0], green=rgb[1], blue=rgb[2])
126
+ except requests.RequestException as e:
127
+ logger.error(f"Failed to update backlight for {dial_uid}: {e}")
128
+
129
+ def update_name(self, dial_uid, name):
130
+ try:
131
+ self._get(f"/api/v0/dial/{dial_uid}/name", name=name)
132
+ except requests.RequestException as e:
133
+ logger.error(f"Failed to update name {dial_uid}: {e}")
134
+
135
+ def upload_logo(self, dial_uid, logo_path, force=False):
136
+ if not Path(logo_path).exists():
137
+ logger.warning(f"Logo file not found: {logo_path}")
138
+ return
139
+ try:
140
+ url = f"{self.server_url}/api/v0/dial/{dial_uid}/image/set"
141
+ with open(logo_path, "rb") as f:
142
+ r = requests.post(
143
+ url, files={
144
+ "imgfile": f}, params={
145
+ "key": self.api_key, "force": int(force)}, timeout=10)
146
+ r.raise_for_status()
147
+ except requests.RequestException as e:
148
+ logger.error(f"Failed to upload logo {dial_uid}: {e}")
149
+
150
+ def update_dial_easing(self, dial_uid, period, step):
151
+ try:
152
+ self._get(
153
+ f"/api/v0/dial/{dial_uid}/easing/dial",
154
+ period=period,
155
+ step=step)
156
+ except requests.RequestException as e:
157
+ logger.error(f"Failed to set dial easing for {dial_uid}: {e}")
158
+
159
+ def update_backlight_easing(self, dial_uid, period, step):
160
+ try:
161
+ self._get(
162
+ f"/api/v0/dial/{dial_uid}/easing/backlight",
163
+ period=period,
164
+ step=step)
165
+ except requests.RequestException as e:
166
+ logger.error(f"Failed to set backlight easing for {dial_uid}: {e}")
167
+
168
+ def get_dial_image_crc(self, dial_uid: str) -> str:
169
+ try:
170
+ headers = {
171
+ "Authorization": f"Bearer {
172
+ self.api_key}"} if self.api_key else {}
173
+ r = requests.get(
174
+ f"{self.server_url}/api/v0/dial/{dial_uid}/image/crc",
175
+ headers=headers, timeout=10)
176
+ r.raise_for_status()
177
+ return r.json().get("crc", "").upper()
178
+ except requests.RequestException as e:
179
+ logger.warning(f"Failed to get CRC for {dial_uid}: {e}")
180
+ return ""
181
+
182
+
183
+ # ---------------------------------------------------------------------------
184
+ # Main updater
185
+ # ---------------------------------------------------------------------------
186
+
187
+ class BenchlabVUUpdater:
188
+ def __init__(self, server_config: dict, dial_config: list,
189
+ datasource: DataSourceManager):
190
+ self.client = VUClient(
191
+ server_config.get("vu_server_url", "http://localhost:5340"),
192
+ server_config.get("api_key", ""),
193
+ )
194
+ self.interval = server_config.get("update_interval_sec", 1)
195
+ self.mappings = dial_config if isinstance(dial_config, list) else []
196
+ self.datasource = datasource
197
+ self.uploaded_dials: set = set()
198
+ self.standard_logo_path = Path(
199
+ __file__).parent / server_config.get("logo_file", "")
200
+
201
+ if not self.mappings:
202
+ logger.warning(
203
+ "No dial mappings found in vu_dial.config — run "
204
+ "-vuconfig to configure dials. Waiting for config...")
205
+
206
+ # uid → latest telemetry snapshot dict
207
+ self._snapshots: dict = {}
208
+ self._snapshot_lock = threading.Lock()
209
+
210
+ # Start background polling thread
211
+ self._poller = threading.Thread(target=self._poll_loop, daemon=True,
212
+ name="VUTelemetryPoller")
213
+ self._poller.start()
214
+
215
+ def _poll_loop(self):
216
+ """Background thread: keeps _snapshots up to date via
217
+ DataSourceManager."""
218
+ # Discover all UIDs we care about from the mappings
219
+ while not shutdown_event.is_set():
220
+ try:
221
+ raw = self.datasource.list_devices()
222
+ if isinstance(raw, dict):
223
+ uids = list(raw.keys())
224
+ else:
225
+ uids = [d.get("uid") for d in raw if d.get("uid")]
226
+
227
+ for uid in uids:
228
+ try:
229
+ self.datasource.select_device(uid)
230
+ snap = self.datasource.snapshot()
231
+ data = (snap.get("sensor_data")
232
+ or snap.get("all_telemetry", {}).get(uid)
233
+ or {})
234
+ if data:
235
+ with self._snapshot_lock:
236
+ self._snapshots[uid] = data
237
+ except Exception as e:
238
+ logger.debug(f"Poll error for {uid}: {e}")
239
+ except Exception as e:
240
+ logger.warning(f"Device list error: {e}")
241
+
242
+ shutdown_event.wait(self.interval)
243
+
244
+ def _get_telemetry(self, uid: str) -> dict:
245
+ with self._snapshot_lock:
246
+ return self._snapshots.get(uid, {})
247
+
248
+ def normalize_value(self, val, min_val, max_val):
249
+ if val is None or max_val == min_val:
250
+ return 0
251
+ return max(0, min(100, (val - min_val) / (max_val - min_val) * 100))
252
+
253
+ def setup_dial(self, mapping, max_attempts=3):
254
+ dial_uid = mapping.get("dial_uid")
255
+ if not dial_uid or dial_uid in self.uploaded_dials:
256
+ return
257
+
258
+ template_path = Path(__file__).parent / "assets/bl_dial_144x200.png"
259
+ logo_uploaded = False
260
+ for attempt in range(1, max_attempts + 1):
261
+ try:
262
+ logo_file = generate_sensor_logo(
263
+ template_path, mapping["sensor"],
264
+ mapping.get("min", 0), mapping.get("max", 100),
265
+ benchlab_port=mapping.get("benchlab_port"),
266
+ )
267
+ self.client.upload_logo(dial_uid, logo_file)
268
+ logo_uploaded = True
269
+ break
270
+ except Exception as e:
271
+ logger.warning(
272
+ f"[{attempt}] Dynamic logo failed for {dial_uid}: {e}")
273
+ time.sleep(0.2)
274
+
275
+ if not logo_uploaded and self.standard_logo_path.exists():
276
+ try:
277
+ self.client.upload_logo(
278
+ dial_uid, self.standard_logo_path, force=True)
279
+ logo_uploaded = True
280
+ except Exception as e:
281
+ logger.error(
282
+ f"Standard logo upload failed for {dial_uid}: {e}")
283
+
284
+ backlight = mapping.get("backlight", [0, 0, 0])
285
+ for attempt in range(1, max_attempts + 1):
286
+ try:
287
+ self.client.update_backlight(dial_uid, backlight)
288
+ break
289
+ except Exception as e:
290
+ logger.warning(
291
+ f"[{attempt}] Failed to set backlight for {dial_uid}: {e}")
292
+ time.sleep(0.2)
293
+
294
+ for attempt in range(1, max_attempts + 1):
295
+ try:
296
+ self.client.update_dial_easing(
297
+ dial_uid, *mapping.get("easing_dial", [50, 5]))
298
+ self.client.update_backlight_easing(
299
+ dial_uid, *mapping.get("easing_backlight", [50, 5]))
300
+ break
301
+ except Exception as e:
302
+ logger.warning(
303
+ f"[{attempt}] Failed to set easing for {dial_uid}: {e}")
304
+ time.sleep(0.2)
305
+
306
+ name = mapping.get("dial_name")
307
+ if name:
308
+ for attempt in range(1, max_attempts + 1):
309
+ try:
310
+ self.client.update_name(dial_uid, name)
311
+ break
312
+ except Exception as e:
313
+ logger.warning(
314
+ f"[{attempt}] Failed to set name for {dial_uid}: {e}")
315
+ time.sleep(0.2)
316
+
317
+ self.uploaded_dials.add(dial_uid)
318
+ logger.info(f"Setup complete for dial {dial_uid}")
319
+
320
+ def apply_config_changes(self, changed_mappings):
321
+ for mapping in changed_mappings:
322
+ dial_uid = mapping.get("dial_uid")
323
+ if not dial_uid:
324
+ continue
325
+ logger.info(f"Applying changes for {dial_uid}")
326
+ try:
327
+ template_path = Path(__file__).parent / \
328
+ "assets/bl_dial_144x200.png"
329
+ logo_file = generate_sensor_logo(
330
+ template_path, mapping["sensor"],
331
+ mapping.get("min", 0), mapping.get("max", 100),
332
+ benchlab_port=mapping.get("benchlab_port"),
333
+ )
334
+ self.client.upload_logo(dial_uid, logo_file, force=True)
335
+ except Exception as e:
336
+ logger.warning(f"Failed to update logo for {dial_uid}: {e}")
337
+ if self.standard_logo_path.exists():
338
+ self.client.upload_logo(
339
+ dial_uid, self.standard_logo_path, force=True)
340
+
341
+ if mapping.get("dial_name"):
342
+ try:
343
+ self.client.update_name(dial_uid, mapping["dial_name"])
344
+ except Exception as e:
345
+ logger.warning(
346
+ f"Failed to update name for {dial_uid}: {e}")
347
+
348
+ try:
349
+ self.client.update_backlight(
350
+ dial_uid, mapping.get("backlight", [0, 0, 0]))
351
+ except Exception as e:
352
+ logger.warning(
353
+ f"Failed to update backlight for {dial_uid}: {e}")
354
+
355
+ try:
356
+ self.client.update_dial_easing(
357
+ dial_uid, *mapping.get("easing_dial", [50, 5]))
358
+ self.client.update_backlight_easing(
359
+ dial_uid, *mapping.get("easing_backlight", [50, 5]))
360
+ except Exception as e:
361
+ logger.warning(f"Failed to update easing for {dial_uid}: {e}")
362
+
363
+ def poll_and_update(self):
364
+ """Push latest telemetry values to VU dials."""
365
+ # Build uid lookup by benchlab_port
366
+ try:
367
+ raw = self.datasource.list_devices()
368
+ if isinstance(raw, dict):
369
+ port_to_uid = {
370
+ info.get("port"): uid for uid,
371
+ info in raw.items()}
372
+ else:
373
+ port_to_uid = {d.get("port"): d.get("uid") for d in raw}
374
+ except Exception as e:
375
+ logger.warning(f"Could not resolve port→uid map: {e}")
376
+ port_to_uid = {}
377
+
378
+ for mapping in self.mappings:
379
+ port = mapping.get("benchlab_port")
380
+ if not port or port in (None, "", "Unknown"):
381
+ continue
382
+
383
+ uid = port_to_uid.get(port)
384
+ if not uid:
385
+ continue
386
+
387
+ telemetry = self._get_telemetry(uid)
388
+ if not telemetry:
389
+ continue
390
+
391
+ self.setup_dial(mapping)
392
+
393
+ sensor_key = mapping.get("sensor")
394
+ dial_uid = mapping.get("dial_uid")
395
+ if not sensor_key or not dial_uid:
396
+ continue
397
+
398
+ value = get_sensor_value(telemetry, sensor_key)
399
+ value = self.normalize_value(
400
+ value, mapping.get(
401
+ "min", 0), mapping.get(
402
+ "max", 100))
403
+ logger.info(f"{port} -> {sensor_key} = {value:.1f} -> {dial_uid}")
404
+ self.client.update_dial(dial_uid, value)
405
+
406
+
407
+ # ---------------------------------------------------------------------------
408
+ # Entry point
409
+ # ---------------------------------------------------------------------------
410
+
411
+ def run_updater(args=None):
412
+ """Run the VU dial updater.
413
+
414
+ Parameters
415
+ ----------
416
+ args:
417
+ Standard benchlab args namespace. If None, reads from env vars.
418
+ """
419
+ if args is None:
420
+ args = types.SimpleNamespace(
421
+ source=os.environ.get(
422
+ "BENCHLAB_DATA_SOURCE",
423
+ "direct"),
424
+ api_url=os.environ.get(
425
+ "BENCHLAB_API_URL",
426
+ "http://127.0.0.1:8000"),
427
+ mqtt_broker=os.environ.get(
428
+ "MQTT_BROKER",
429
+ "localhost"),
430
+ mqtt_port=int(
431
+ os.environ.get(
432
+ "MQTT_PORT",
433
+ "1883")),
434
+ interval=1.0,
435
+ )
436
+
437
+ logger.info("Launching the BENCHLAB VU Server & Dials")
438
+ time.sleep(1)
439
+ logger.info("Review & update configuration using -vuconfig")
440
+ time.sleep(1)
441
+ logger.info("Checking for VU server...")
442
+
443
+ server_cfg = load_json(VU_SERVER_CONFIG, default={})
444
+ dial_cfg = load_json(VU_DIAL_CONFIG, default=[])
445
+ server_url = server_cfg.get("vu_server_url", "http://localhost:5340")
446
+ api_key = server_cfg.get("api_key", "")
447
+
448
+ server_proc = None
449
+ if check_vu_server(server_url, api_key):
450
+ logger.info(f"VU server already running at {server_url}")
451
+ else:
452
+ server_proc = start_vu_server()
453
+ if server_proc:
454
+ logger.info(f"Started local VU server at {server_url}")
455
+ threading.Thread(
456
+ target=forward_logs, args=(
457
+ server_proc,), daemon=True).start()
458
+ else:
459
+ logger.error(
460
+ "Failed to start local VU server — dial updates "
461
+ "will not work.")
462
+
463
+ time.sleep(1)
464
+
465
+ # Connect datasource
466
+ ds_kwargs = {}
467
+ if args.source in ("fastapi", "fastapi_custom"):
468
+ ds_kwargs["base_url"] = args.api_url
469
+ elif args.source == "mqtt":
470
+ ds_kwargs["broker"] = args.mqtt_broker
471
+ ds_kwargs["port"] = args.mqtt_port
472
+
473
+ datasource = DataSourceManager(source_type=args.source, **ds_kwargs)
474
+ if not datasource.connect():
475
+ logger.error(f"Failed to connect to {args.source} datasource")
476
+ return
477
+
478
+ updater = BenchlabVUUpdater(server_cfg, dial_cfg, datasource)
479
+ logger.info(f"Starting VU dial updater (interval: {updater.interval}s)")
480
+ time.sleep(1)
481
+
482
+ try:
483
+ while not shutdown_event.is_set():
484
+ changed_mappings = reload_dial_config()
485
+ if changed_mappings:
486
+ updater.apply_config_changes(changed_mappings)
487
+ updater.poll_and_update()
488
+ time.sleep(updater.interval)
489
+ finally:
490
+ logger.info("Updater stopping — resetting dials...")
491
+ for m in updater.mappings:
492
+ dial_uid = m.get("dial_uid")
493
+ if dial_uid:
494
+ try:
495
+ updater.client.update_dial(dial_uid, 0)
496
+ updater.client.update_backlight(dial_uid, [0, 0, 0])
497
+ except Exception as e:
498
+ logger.error(f"Failed to reset {dial_uid}: {e}")
499
+
500
+ standard_logo = updater.standard_logo_path
501
+ if standard_logo.exists():
502
+ standard_crc = file_crc32(standard_logo)
503
+ for idx, m in enumerate(updater.mappings, 1):
504
+ dial_uid = m.get("dial_uid")
505
+ if not dial_uid:
506
+ continue
507
+ logger.info(
508
+ f"[{idx}/{len(updater.mappings)}] Restoring logo "
509
+ f"on {dial_uid}")
510
+ try:
511
+ updater.client.upload_logo(
512
+ dial_uid, standard_logo, force=True)
513
+ except Exception as e:
514
+ logger.warning(
515
+ f"Failed to restore logo for {dial_uid}: {e}")
516
+ continue
517
+ start = time.time()
518
+ while time.time() - start < 1:
519
+ try:
520
+ if updater.client.get_dial_image_crc(
521
+ dial_uid) == standard_crc:
522
+ logger.info(f"Logo CRC verified for {dial_uid}")
523
+ break
524
+ except Exception:
525
+ pass
526
+ time.sleep(0.5)
527
+ else:
528
+ logger.warning(f"Timeout verifying logo for {dial_uid}")
529
+
530
+ datasource.disconnect()
531
+
532
+ if server_proc:
533
+ logger.info("Terminating VU server subprocess...")
534
+ terminate_vu_server(server_proc)
535
+
536
+ logger.info("Shutdown complete.")
537
+
538
+
539
+ if __name__ == "__main__":
540
+ run_updater()