etho-python 1.2.6__py3-none-any.whl → 1.3__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.
etho/app.py CHANGED
@@ -10,9 +10,10 @@ import time
10
10
  import psutil
11
11
  import threading
12
12
  import queue
13
+ from codecs import getincrementaldecoder
13
14
 
14
15
  from qtpy import QtWidgets
15
- from qtpy.QtGui import QIcon, QPalette
16
+ from qtpy.QtGui import QIcon, QPalette, QTextCursor
16
17
  from qtpy.QtWidgets import (
17
18
  QApplication,
18
19
  QTableView,
@@ -28,9 +29,10 @@ from qtpy.QtWidgets import (
28
29
  QLabel,
29
30
  QSplitter,
30
31
  QProgressBar,
32
+ QPlainTextEdit,
31
33
  )
32
34
 
33
- from qtpy.QtCore import QAbstractTableModel, Qt, QTimer
35
+ from qtpy.QtCore import QAbstractTableModel, QProcess, Qt, QTimer
34
36
 
35
37
  from pyqtgraph.parametertree import Parameter, ParameterTree
36
38
 
@@ -221,6 +223,54 @@ def kill_child_processes():
221
223
  # os.kill(child.pid, signal.SIGKILL)
222
224
 
223
225
 
226
+ class HardwareDialog(QDialog):
227
+ def __init__(self, parent):
228
+ super().__init__(parent)
229
+ self.setWindowTitle("Hardware")
230
+ self.resize(640, 400)
231
+
232
+ self.status = QLabel("Scanning local hardware…")
233
+ self.results = QPlainTextEdit()
234
+ self.results.setReadOnly(True)
235
+ buttons = QDialogButtonBox(QDialogButtonBox.Close)
236
+ buttons.rejected.connect(self.reject)
237
+
238
+ layout = QVBoxLayout(self)
239
+ layout.addWidget(self.status)
240
+ layout.addWidget(self.results)
241
+ layout.addWidget(buttons)
242
+
243
+ self._decoder = getincrementaldecoder("utf-8")(errors="replace")
244
+ self._scan = QProcess(self)
245
+ self._scan.setProcessChannelMode(QProcess.MergedChannels)
246
+ self._scan.readyReadStandardOutput.connect(self._read_scan_output)
247
+ self._scan.finished.connect(self._scan_finished)
248
+ self._scan.errorOccurred.connect(self._scan_error)
249
+ self._scan.start(sys.executable, ["-X", "utf8", "-u", "-m", "etho.cli", "hardware"])
250
+
251
+ def _read_scan_output(self, *, final=False):
252
+ output = self._decoder.decode(bytes(self._scan.readAllStandardOutput()), final=final)
253
+ cursor = QTextCursor(self.results.document())
254
+ cursor.movePosition(QTextCursor.End)
255
+ cursor.insertText(output)
256
+
257
+ def _scan_finished(self, exit_code, exit_status):
258
+ self._read_scan_output(final=True)
259
+ complete = exit_status == QProcess.NormalExit and exit_code == 0
260
+ self.status.setText("Scan complete." if complete else "Hardware scan failed.")
261
+
262
+ def _scan_error(self, error):
263
+ if error == QProcess.FailedToStart:
264
+ self.status.setText("Could not start the hardware scan.")
265
+ self.results.appendPlainText(self._scan.errorString())
266
+
267
+ def done(self, result):
268
+ if self._scan.state() != QProcess.NotRunning:
269
+ self._scan.kill()
270
+ self._scan.waitForFinished(250)
271
+ super().done(result)
272
+
273
+
224
274
  class RunDialog(QDialog):
225
275
  def __init__(self, stop_event, done_event, queue_total):
226
276
  super().__init__()
@@ -343,6 +393,9 @@ class MainWindow(QMainWindow):
343
393
  # Layout
344
394
  self.layout = QGridLayout()
345
395
  self.layout.addLayout(buttons, 0, 0)
396
+ self.button["Hardware"] = QPushButton("Enumerate hardware")
397
+ self.button["Hardware"].clicked.connect(self.show_hardware)
398
+ self.layout.addWidget(self.button["Hardware"], 1, 0, Qt.AlignBottom)
346
399
  self.refresh_lists(init=True)
347
400
 
348
401
  self.layout.setColumnMinimumWidth(1, 200)
@@ -358,6 +411,11 @@ class MainWindow(QMainWindow):
358
411
  def on_protocol_changed(self, param, changes):
359
412
  self.current_protocol = to_yaml(param)
360
413
 
414
+ def show_hardware(self):
415
+ dialog = HardwareDialog(self)
416
+ dialog.setAttribute(Qt.WA_DeleteOnClose)
417
+ dialog.open()
418
+
361
419
  def refresh_lists(self, init: bool = False):
362
420
  playlist_files = sorted(self.playlist_folder.glob("*.txt"))
363
421
  if len(playlist_files) == 0:
etho/cli.py CHANGED
@@ -1,5 +1,6 @@
1
1
  import defopt
2
2
  import logging
3
+ import math
3
4
  import platform
4
5
  import importlib
5
6
  import yaml
@@ -67,23 +68,35 @@ def res_gui(protocol_folder: Optional[str] = None, playlist_folder: Optional[str
67
68
  return res_app.main(protocol_folder=protocol_folder, playlist_folder=playlist_folder)
68
69
 
69
70
 
70
- def govee(duration: float = 10.0):
71
- """Lists nearby Govee H5075 sensors and their protocol addresses/readings."""
72
- import asyncio
71
+ def hardware(*, ble_duration: float = 10.0):
72
+ """Lists hardware detected by local etho services.
73
73
 
74
- from .services.GOVZeroService import discover_h5075_sensors
74
+ Args:
75
+ ble_duration: Time in seconds to listen for Bluetooth advertisements.
76
+ """
77
+ from .services.hardware import discover_hardware
78
+
79
+ if not math.isfinite(ble_duration) or ble_duration <= 0:
80
+ raise SystemExit("--ble-duration must be a finite number greater than zero.")
81
+
82
+ print(f"Scanning local hardware (Bluetooth scan: {ble_duration:g} seconds)...", flush=True)
83
+ for result in discover_hardware(ble_duration=ble_duration):
84
+ label = f"{result.service} / {result.probe}" if result.probe else result.service
85
+ if result.error is not None:
86
+ message = str(result.error).strip() or type(result.error).__name__
87
+ print(f"{label}: unavailable ({message})", flush=True)
88
+ elif not result.devices:
89
+ print(f"{label}: no devices found", flush=True)
90
+ else:
91
+ print(label)
92
+ for device in result.devices:
93
+ fields = [f"{key}={value}" for key, value in device.protocol.items()]
94
+ if device.details:
95
+ fields.append(device.details)
96
+ suffix = f" ({', '.join(fields)})" if fields else ""
97
+ print(f" {device.name}{suffix}", flush=True)
75
98
 
76
- print(f"Scanning for Govee sensors for {duration:g} seconds...", flush=True)
77
- sensors = asyncio.run(discover_h5075_sensors(duration))
78
- if not sensors:
79
- print("No Govee H5075 sensors found.")
80
- return
81
99
 
82
- print(f"{'Address (use as GOV.address)':<38} {'Name':<16} {'Temperature':>11} {'Humidity':>9}")
83
- for address, name, measurement in sensors:
84
- print(f"{address:<38} {(name or '-'):<16} {measurement.temperature_c:>10.1f}°C {measurement.humidity:>8.1f}%")
85
-
86
-
87
100
  def version(*, debug: bool = False):
88
101
  """Displays system, version, and hardware info.
89
102
 
@@ -238,11 +251,11 @@ def init():
238
251
 
239
252
 
240
253
  def main():
241
- """Command line interface for DAS."""
254
+ """Command line interface for etho."""
242
255
  subcommands = {
243
256
  "version": version,
244
257
  "init": init,
245
- "govee": govee,
258
+ "hardware": hardware,
246
259
  }
247
260
 
248
261
  if client is not None:
@@ -266,3 +279,7 @@ def main():
266
279
 
267
280
  logging.basicConfig(level=logging.INFO, force=True)
268
281
  defopt.run(subcommands, show_defaults=False)
282
+
283
+
284
+ if __name__ == "__main__":
285
+ main()
@@ -1,3 +1,5 @@
1
+ from ctypes import create_string_buffer
2
+
1
3
  from .ZeroService import BaseZeroService
2
4
  import time
3
5
  import threading
@@ -8,7 +10,8 @@ from .. import config as global_config
8
10
  from ..utils.config import undefaultify
9
11
  from ..utils.sound import parse_table, load_sounds, build_playlist
10
12
  from .utils.log_exceptions import for_all_methods, log_exceptions
11
- from .callbacks import callbacks
13
+ from .callbacks import callbacks
14
+ from .hardware import HardwareDevice, HardwareProbe
12
15
  import logging
13
16
  import numpy as np
14
17
 
@@ -21,6 +24,27 @@ except (ImportError, NameError, NotImplementedError) as daqmx_import_error:
21
24
  pass
22
25
 
23
26
 
27
+ def _daqmx_text(getter, *args):
28
+ size = getter(*args, None, 0)
29
+ if size < 0:
30
+ raise RuntimeError(f"NI-DAQmx device query failed with status {size}.")
31
+ if size == 0:
32
+ return ""
33
+
34
+ buffer = create_string_buffer(size)
35
+ getter(*args, buffer, size)
36
+ return buffer.value.decode("utf-8", errors="replace")
37
+
38
+
39
+ def _discover_nidaq():
40
+ from PyDAQmx.DAQmxFunctions import DAQmxGetDevProductType, DAQmxGetSysDevNames
41
+
42
+ devices = [name.strip() for name in _daqmx_text(DAQmxGetSysDevNames).split(",")]
43
+ for device in filter(None, devices):
44
+ model = _daqmx_text(DAQmxGetDevProductType, device.encode())
45
+ yield HardwareDevice(model or "NI-DAQ device", {"device": device})
46
+
47
+
24
48
  @for_all_methods(log_exceptions(logging.getLogger(__name__)))
25
49
  @register_service
26
50
  class DAQ(BaseZeroService):
@@ -31,6 +55,10 @@ class DAQ(BaseZeroService):
31
55
  SERVICE_NAME = "DAQ" # short, uppercase, 3-letter ID of the service (equals class name)
32
56
  CLIENT_START_GROUP = "daq"
33
57
 
58
+ @classmethod
59
+ def hardware_probes(cls, *, ble_duration: float) -> dict[str, HardwareProbe]:
60
+ return {"NI-DAQmx": _discover_nidaq}
61
+
34
62
  @classmethod
35
63
  def setup_client(cls, service_key, service_index, prot, defaults, playlistfile, save_prefix, preview, new_console):
36
64
  if preview:
@@ -45,11 +73,10 @@ class DAQ(BaseZeroService):
45
73
  if prot[service_key].get("port") is None:
46
74
  prot[service_key]["port"] = cls.SERVICE_PORT + service_index
47
75
 
48
- if this["host"] in global_config["ATTENUATION"]:
49
- attenuation = global_config["ATTENUATION"][this["host"]]
76
+ attenuation = global_config.get("ATTENUATION")
77
+ if attenuation and this["host"] in attenuation:
78
+ attenuation = attenuation[this["host"]]
50
79
  logging.info(f"Using attenuation data specific to {this['host']}.")
51
- else:
52
- attenuation = global_config["ATTENUATION"]
53
80
 
54
81
  fs = prot[service_key]["samplingrate"]
55
82
  playlist = parse_table(playlistfile)
@@ -2,7 +2,8 @@
2
2
  from .ZeroService import BaseZeroService # import super class
3
3
  import time # for timer
4
4
  import threading
5
- from . import register_service
5
+ from . import register_service
6
+ from .hardware import HardwareDevice, HardwareProbe
6
7
  from .utils.log_exceptions import for_all_methods, log_exceptions
7
8
  from .dlp import dlp_runners
8
9
  from ..utils.config import undefaultify
@@ -22,6 +23,13 @@ except ImportError as dlp_import_error:
22
23
  pass
23
24
 
24
25
 
26
+ def _discover_projectors():
27
+ from usb.core import find
28
+
29
+ for device in find(find_all=True, idVendor=0x0451, idProduct=0x6401):
30
+ yield HardwareDevice("TI LightCrafter 4500", details=f"USB bus {device.bus}, address {device.address}")
31
+
32
+
25
33
  # decorate all methods in the class so that exceptions are properly logged
26
34
  @for_all_methods(log_exceptions(logging.getLogger(__name__)))
27
35
  @register_service
@@ -32,6 +40,10 @@ class DLP(BaseZeroService):
32
40
  SERVICE_NAME = "DLP" # short, uppercase, 3-letter ID of the service (must equal class name)
33
41
  CLIENT_START_GROUP = "pre"
34
42
 
43
+ @classmethod
44
+ def hardware_probes(cls, *, ble_duration: float) -> dict[str, HardwareProbe]:
45
+ return {"LightCrafter 4500": _discover_projectors}
46
+
35
47
  @classmethod
36
48
  def setup_client(cls, service_key, service_index, prot, defaults, playlistfile, save_prefix, preview, new_console):
37
49
  this = defaults.copy()
@@ -1,4 +1,5 @@
1
1
  from .ZeroService import BaseZeroService
2
+ from functools import partial
2
3
  from pathlib import Path
3
4
  import time
4
5
  import threading
@@ -8,12 +9,19 @@ from .utils.log_exceptions import for_all_methods, log_exceptions
8
9
  import logging
9
10
  from ..services import camera
10
11
  from ..utils.config import undefaultify
11
- from .callbacks import callbacks
12
+ from .callbacks import callbacks
13
+ from .hardware import HardwareDevice, HardwareProbe
12
14
 
13
15
 
14
16
  logger = logging.getLogger(__name__)
15
17
 
16
18
 
19
+ def _discover_cameras(cam_type, enumerate_devices):
20
+ details = "Older FLIR models use cam_type=Spinnaker_OLD" if cam_type == "Spinnaker" else ""
21
+ for identifier, name in enumerate_devices():
22
+ yield HardwareDevice(name, {"cam_type": cam_type, "cam_serialnumber": identifier}, details)
23
+
24
+
17
25
  @for_all_methods(log_exceptions(logger))
18
26
  @register_service
19
27
  class GCM(BaseZeroService):
@@ -22,14 +30,32 @@ class GCM(BaseZeroService):
22
30
  SERVICE_NAME = "GCM" # short, uppercase, 3-letter ID of the service (equals class name)
23
31
  CLIENT_START_GROUP = "pre"
24
32
 
33
+ @classmethod
34
+ def hardware_probes(cls, *, ble_duration: float) -> dict[str, HardwareProbe]:
35
+ return {
36
+ ("Spinnaker and Spinnaker_OLD" if cam_type == "Spinnaker" else cam_type): partial(_discover_cameras, cam_type, backend.enumerate_devices)
37
+ for cam_type, backend in camera.make.items()
38
+ if backend.enumerate_devices is not None
39
+ }
40
+
25
41
  @classmethod
26
42
  def setup_client(cls, service_key, service_index, prot, defaults, playlistfile, save_prefix, preview, new_console):
43
+ maxduration = prot.get("maxduration")
44
+ if not preview and maxduration is None:
45
+ raise ValueError("A GCM recording requires a top-level 'maxduration' in seconds, for example 'maxduration: 60'.")
46
+ duration = 1_000_000 if preview else maxduration + 10
47
+
27
48
  this = defaults.copy()
28
49
  this.update(prot[service_key])
29
50
 
30
51
  if prot[service_key].get("port") is None:
31
52
  prot[service_key]["port"] = cls.SERVICE_PORT + service_index
32
53
 
54
+ params = undefaultify(prot[service_key])
55
+ if params.get("cam_type") == "Webcam":
56
+ # Report warnings in the client before launching the camera process.
57
+ camera.Webcam.ignore_unsupported_settings(params)
58
+
33
59
  service = cls.make(
34
60
  this["serializer"],
35
61
  this["host"],
@@ -38,9 +64,6 @@ class GCM(BaseZeroService):
38
64
  port=prot[service_key]["port"],
39
65
  )
40
66
 
41
- params = undefaultify(prot[service_key])
42
- duration = 1_000_000 if preview else prot["maxduration"] + 10
43
-
44
67
  if preview:
45
68
  params["callbacks"] = {"disp_fast": None}
46
69
 
@@ -90,6 +113,8 @@ class GCM(BaseZeroService):
90
113
  "frame_offy": 0,
91
114
  }
92
115
  params = defaults | params # merge directory - keep existing values in params, only add non-existing from defaults
116
+ if self.cam_type == "Webcam":
117
+ camera.Webcam.ignore_unsupported_settings(params)
93
118
 
94
119
  self.c.roi = [
95
120
  params["frame_offx"],
@@ -97,7 +122,8 @@ class GCM(BaseZeroService):
97
122
  params["frame_width"],
98
123
  params["frame_height"],
99
124
  ]
100
- self.c.exposure = params["shutter_speed"]
125
+ shutter_speed = params.get("shutter_speed") if self.cam_type == "Webcam" else params["shutter_speed"]
126
+ self.c.exposure = shutter_speed
101
127
  self.c.brightness = params["brightness"]
102
128
  self.c.gamma = params["gamma"]
103
129
  self.c.gain = params["gain"]
@@ -111,8 +137,10 @@ class GCM(BaseZeroService):
111
137
  self.c.disable_gpio_strobe() # to prevent the test image producing strobes
112
138
  self.c.external_trigger = False # disable here so test image acq works w/o ext trigger
113
139
  self.c.start()
114
- self.test_image, image_ts, system_ts = self.c.get()
115
- self.c.stop()
140
+ try:
141
+ self.test_image, _, _ = self.c.get()
142
+ finally:
143
+ self.c.stop()
116
144
 
117
145
  self.c.external_trigger = params["external_trigger"]
118
146
 
@@ -138,6 +166,8 @@ class GCM(BaseZeroService):
138
166
  else:
139
167
  task_kwargs = common_task_kwargs
140
168
 
169
+ if self.cam_type == "Webcam" and cb_name == "disp_fast":
170
+ task_kwargs = {**task_kwargs, "row_major_bgr": True}
141
171
  self.callbacks.append(callbacks[cb_name].make_concurrent(task_kwargs=task_kwargs))
142
172
  self.callback_names.append(cb_name)
143
173
 
@@ -153,8 +183,9 @@ class GCM(BaseZeroService):
153
183
  self._worker_thread = threading.Thread(target=self._worker, args=(self._thread_stopper,))
154
184
 
155
185
  iii = self.c.info_imaging()
156
- iii["exposure"] = f"{iii['exposure']:1.2f}ms"
157
- params["exposure"] = f"{params['shutter_speed']/1_000:1.2f}ms"
186
+ if "exposure" in iii:
187
+ iii["exposure"] = f"{iii['exposure']:1.2f}ms"
188
+ params["exposure"] = "auto" if shutter_speed is None else f"{shutter_speed / 1_000:1.2f}ms"
158
189
  params["framerate"] = params["frame_rate"]
159
190
  params["offsetX"], params["offsetY"], params["width"], params["height"] = (
160
191
  params["frame_offx"],
@@ -165,10 +196,7 @@ class GCM(BaseZeroService):
165
196
 
166
197
  hii = self.c.info_hardware()
167
198
  self.log.info(params.__str__())
168
- try:
169
- hii.update({k: v if v is not None else "defaults" for k, v in params["callbacks"].items()})
170
- except AttributeError:
171
- pass
199
+ hii.update({k: v if v is not None else "defaults" for k, v in (params.get("callbacks") or {}).items()})
172
200
  hii["savefilename"] = self.savefilename
173
201
  hii["duration"] = self.duration
174
202
  self.info = {"hardware": hii, "image": (iii, params)}
@@ -194,9 +222,13 @@ class GCM(BaseZeroService):
194
222
  self.prev_framenumber = 0
195
223
  self.log.info("started worker")
196
224
  self.c.enable_gpio_strobe()
197
- self.c.start()
225
+ try:
226
+ self.c.start()
227
+ except ValueError:
228
+ self.log.exception("Camera start failed")
229
+ return
198
230
 
199
- while RUN:
231
+ while RUN and not stop_event.is_set():
200
232
  try:
201
233
  out = self.c.get()
202
234
  if out is None:
@@ -204,6 +236,8 @@ class GCM(BaseZeroService):
204
236
  else:
205
237
  image, image_ts, system_ts = out
206
238
 
239
+ if stop_event.is_set():
240
+ break
207
241
  for callback_name, callback in zip(self.callback_names, self.callbacks):
208
242
  if "timestamps" in callback_name:
209
243
  package = (0, (system_ts, image_ts))
@@ -223,6 +257,9 @@ class GCM(BaseZeroService):
223
257
  except Exception as e:
224
258
  self.log.exception("Error", exc_info=e)
225
259
 
260
+ if self.cam_type == "Webcam":
261
+ self.c.stop()
262
+
226
263
  def finish(self, stop_service=False):
227
264
  self.log.warning("stopping")
228
265
  try:
@@ -237,16 +274,24 @@ class GCM(BaseZeroService):
237
274
  self._thread_timer.cancel()
238
275
 
239
276
  # clean up code here
240
- try:
241
- self.c.close() # not sure this works if BeginAcquistion has not been called
242
- except:
243
- pass
277
+ if getattr(self, "cam_type", None) == "Webcam":
278
+ # Let the capture thread close its own FFmpeg input.
279
+ worker = getattr(self, "_worker_thread", None)
280
+ if worker is not None and worker.is_alive():
281
+ worker.join(timeout=7)
282
+ if worker.is_alive():
283
+ self.log.warning("Webcam capture is still stopping.")
284
+ else:
285
+ try:
286
+ self.c.close() # not sure this works if BeginAcquistion has not been called
287
+ except:
288
+ pass
244
289
 
245
- for callback in self.callbacks:
290
+ callbacks, self.callbacks = getattr(self, "callbacks", []), []
291
+ for callback in callbacks:
246
292
  callback.finish()
247
293
 
248
- # callbacks clean up after themselves now so probably no need for this:
249
- for callback in self.callbacks:
294
+ for callback in callbacks:
250
295
  try:
251
296
  callback.close()
252
297
  except Exception as e:
@@ -5,19 +5,22 @@ import threading
5
5
  import time
6
6
  from dataclasses import dataclass
7
7
  from datetime import datetime
8
+ from functools import partial
8
9
  from typing import Any, Optional
9
10
 
10
11
  import defopt
11
12
 
12
13
  from .ZeroService import BaseZeroService
13
14
  from . import register_service
15
+ from .hardware import HardwareDevice, HardwareProbe
14
16
  from .utils.log_exceptions import for_all_methods, log_exceptions
15
17
 
16
18
  try:
17
19
  from bleak import AdvertisementData, BleakScanner, BLEDevice
18
20
 
19
21
  bleak_import_error = None
20
- except ImportError as bleak_import_error:
22
+ except ImportError as exc:
23
+ bleak_import_error = exc
21
24
  AdvertisementData = Any
22
25
  BLEDevice = Any
23
26
  BleakScanner = None
@@ -98,6 +101,12 @@ async def discover_h5075_sensors(duration: float = 10.0):
98
101
  return sorted((address, name, measurement) for address, (name, measurement) in sensors.items())
99
102
 
100
103
 
104
+ def _discover_govee(duration: float):
105
+ for address, name, measurement in asyncio.run(discover_h5075_sensors(duration)):
106
+ readings = f"{measurement.temperature_c:.1f}°C, {measurement.humidity:.1f}% RH"
107
+ yield HardwareDevice(name or "Govee H5075", {"address": address}, readings)
108
+
109
+
101
110
  @for_all_methods(log_exceptions(logging.getLogger(__name__)))
102
111
  @register_service
103
112
  class GOV(BaseZeroService):
@@ -106,6 +115,10 @@ class GOV(BaseZeroService):
106
115
  SERVICE_NAME = "GOV"
107
116
  CLIENT_START_GROUP = "pre"
108
117
 
118
+ @classmethod
119
+ def hardware_probes(cls, *, ble_duration: float) -> dict[str, HardwareProbe]:
120
+ return {"Govee H5075": partial(_discover_govee, ble_duration)}
121
+
109
122
  @classmethod
110
123
  def setup_client(cls, service_key, service_index, prot, defaults, playlistfile, save_prefix, preview, new_console):
111
124
  if preview:
@@ -9,6 +9,8 @@ import os
9
9
  from typing import Optional, Dict, Any
10
10
  import psutil
11
11
 
12
+ from .hardware import HardwareProbe
13
+
12
14
 
13
15
  class BaseZeroService(abc.ABC, zerorpc.Server):
14
16
  """Define abstract base class for all 0services.
@@ -95,6 +97,11 @@ class BaseZeroService(abc.ABC, zerorpc.Server):
95
97
  def setup_client(cls, *args, **kwargs):
96
98
  raise NotImplementedError(f"{cls.__name__} must implement setup_client() for etho.client.")
97
99
 
100
+ @classmethod
101
+ def hardware_probes(cls, *, ble_duration: float) -> dict[str, HardwareProbe]:
102
+ """Return named local device probes that run without a service instance."""
103
+ return {}
104
+
98
105
  def _init_network_logger(self, head_ip: str = "192.168.1.1", log_level: int = logging.INFO):
99
106
  """Initialize logger that publishes messages over the network format.
100
107
 
etho/services/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- import logging
1
+ from importlib import import_module
2
2
  import re
3
3
  from typing import Dict, Type
4
4
 
@@ -6,6 +6,7 @@ from .ZeroService import BaseZeroService
6
6
 
7
7
 
8
8
  SERVICE_REGISTRY: Dict[str, Type[BaseZeroService]] = {}
9
+ SERVICE_IMPORT_ERRORS: dict[str, Exception] = {}
9
10
  _SUFFIX_RE = re.compile(r"\d+$")
10
11
 
11
12
 
@@ -26,27 +27,37 @@ def service_class_for(service_name: str) -> Type[BaseZeroService]:
26
27
  try:
27
28
  return SERVICE_REGISTRY[base_name]
28
29
  except KeyError:
30
+ if base_name in SERVICE_IMPORT_ERRORS:
31
+ error = SERVICE_IMPORT_ERRORS[base_name]
32
+ raise ValueError(f"Could not load service '{base_name}': {error}") from error
29
33
  available = ", ".join(sorted(SERVICE_REGISTRY))
30
34
  raise ValueError(f"Unknown service '{service_name}'. Available services: {available}.")
31
35
 
32
36
 
33
- from .DLPZeroService import DLP
34
- from .BLTZeroService import BLT
35
- from .GOVZeroService import GOV
36
- from .GCMZeroService import GCM
37
- from .DAQZeroService import DAQ
38
- from .NICounterZeroService import NIC
39
- from .ScanImageTriggerZeroService import SIT
37
+ def _load_builtin_services():
38
+ modules = {
39
+ "DLP": ".DLPZeroService",
40
+ "BLT": ".BLTZeroService",
41
+ "GOV": ".GOVZeroService",
42
+ "GCM": ".GCMZeroService",
43
+ "DAQ": ".DAQZeroService",
44
+ "NIC": ".NICounterZeroService",
45
+ "SIT": ".ScanImageTriggerZeroService",
46
+ }
47
+ for name, module in modules.items():
48
+ try:
49
+ globals()[name] = getattr(import_module(module, __name__), name)
50
+ except Exception as exc:
51
+ SERVICE_REGISTRY.pop(name, None)
52
+ SERVICE_IMPORT_ERRORS[name] = exc
53
+
54
+
55
+ _load_builtin_services()
40
56
 
41
57
 
42
58
  __all__ = [
43
59
  "SERVICE_REGISTRY",
44
60
  "service_base_name",
45
61
  "service_class_for",
46
- "GOV",
47
- "GCM",
48
- "DAQ",
49
- "DLP",
50
- "BLT",
51
- "SIT",
62
+ *(name for name in ("GOV", "GCM", "DAQ", "DLP", "BLT", "SIT") if name in SERVICE_REGISTRY),
52
63
  ]