scietex.current-amplifier-service 0.1.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.
@@ -0,0 +1,5 @@
1
+ """Current amplifier service."""
2
+
3
+ from .version import __version__
4
+
5
+ __all__ = ["__version__"]
@@ -0,0 +1,616 @@
1
+ """Current amplifier worker: a Valkey-backed service that polls and controls
2
+ current amplifier boards.
3
+
4
+ `CurrentAmplifierWorker` extends `ValkeyWorker` and drives one or more EBIC
5
+ v1.0 current-amplifier boards, each over its own RS485 segment. A board is
6
+ driven by a `scietex.hal.current_amplifier` class selected by entry point name;
7
+ the worker seeds its in-memory board registry from the service-owned
8
+ ``current_amplifier.yml`` at startup and reconciles it against the framework's
9
+ merged remote-config section (the L3 ``current_amplifier`` section replaces the
10
+ YAML list wholesale, it is never merged by label). A ``Telemetry`` manager
11
+ publishes a service snapshot every 2 s so the UI can observe the configured/live
12
+ state, and one long-lived poll task per board publishes readings to a per-board
13
+ Valkey stream.
14
+
15
+ Unlike `scietex.vfd_service.vfd_worker`, this worker has no persistent transport
16
+ to open: the EBIC driver connects the serial port once per operation, so
17
+ ``connect()`` is a documented no-op. There is therefore no transport-open flag,
18
+ no connect stage, and no reconnect branch in the poll loop — a failed read is
19
+ only a failed read, and ``_connected`` means "the recent reads succeeded".
20
+ Protocol failures are also ``OSError`` subclasses in this HAL, so inferring a
21
+ dead bus from the exception type would be wrong.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import asyncio
27
+ import inspect
28
+ import logging
29
+ from datetime import datetime, timezone
30
+ from typing import Any, cast
31
+
32
+ import msgspec
33
+ from glide import ConnectionError as GlideConnectionError
34
+ from glide import ExpirySet, ExpiryType, RequestError
35
+ from glide import TimeoutError as GlideTimeoutError
36
+ from scietex.hal.current_amplifier.base.data import AmplifierState
37
+ from scietex.hal.current_amplifier.base.protocol import CurrentAmplifierProtocol
38
+ from scietex.hal.current_amplifier.registry import ENTRY_POINT_GROUP, resolve_driver
39
+ from scietex.hal.serial import ModbusSerialConnectionConfig
40
+ from scietex.service import Manager, ValkeyWorker, ValkeyWorkerConfig
41
+ from scietex.service.valkey._glide import StreamAddOptions, TrimByMaxLen
42
+
43
+ from .config import (
44
+ CURRENT_AMPLIFIER_SECTION,
45
+ CURRENT_AMPLIFIER_SETTINGS_DEFAULTS,
46
+ AmplifierSettings,
47
+ CurrentAmplifierServiceSettings,
48
+ read_current_amplifier_config,
49
+ )
50
+ from .task_handlers import AmplifierControlHandler, MonitoringHandler
51
+ from .telemetry import TELEMETRY_INTERVAL, TELEMETRY_TTL, build_telemetry
52
+
53
+ #: Entry point group under which ``scietex.hal.current_amplifier`` advertises
54
+ #: its drivers. A board configuration stores the entry point name.
55
+ DRIVER_ENTRY_POINT_GROUP: str = ENTRY_POINT_GROUP
56
+
57
+ #: Default cap on the number of entries retained per board's readings stream.
58
+ #: The effective value comes from ``CurrentAmplifierServiceSettings.stream_maxlen``.
59
+ STREAM_MAXLEN: int = 10000
60
+
61
+ #: Default number of consecutive failed reads before a board is reported as
62
+ #: disconnected. The effective value comes from
63
+ #: ``CurrentAmplifierServiceSettings.failure_threshold``.
64
+ CONNECTED_FAILURE_THRESHOLD: int = 3
65
+
66
+
67
+ class AmplifierStats(msgspec.Struct):
68
+ """Per-board counters accumulated by the poll loop.
69
+
70
+ Mutable (no ``frozen=True``): the poll loop updates the fields in place.
71
+ """
72
+
73
+ reading_count: int = 0
74
+ error_count: int = 0
75
+ last_state: AmplifierState | None = None
76
+ last_reading_at: datetime | None = None
77
+ last_error: str | None = None
78
+ # Consecutive failed reads since the last success. A single bus glitch must
79
+ # not flip the board to disconnected, so the poll loop only clears
80
+ # `_connected` once this reaches the configured failure threshold.
81
+ consecutive_failures: int = 0
82
+
83
+
84
+ def _accepts_keyword(driver: type, name: str) -> bool:
85
+ """Whether ``driver.__init__`` accepts a keyword argument called ``name``.
86
+
87
+ Drivers differ in what they take: the EBIC v1.0 driver accepts
88
+ ``relay_settle_s`` as a constructor-only knob, while a future driver may
89
+ not. Passing it unconditionally would make that driver's constructor raise
90
+ ``TypeError`` and the whole board registry fail to build, so the worker
91
+ asks first.
92
+
93
+ A driver that declares ``**kwargs`` accepts anything, which is why the
94
+ variadic check comes before the named-parameter check.
95
+
96
+ Args:
97
+ driver: The resolved driver class.
98
+ name: The keyword argument name to look for.
99
+
100
+ Returns:
101
+ bool: ``True`` when the constructor can be called with ``name=...``.
102
+ """
103
+ try:
104
+ parameters = inspect.signature(driver.__init__).parameters.values()
105
+ except (TypeError, ValueError):
106
+ # A C-level or otherwise uninspectable constructor: assume it does not
107
+ # take the optional keyword rather than risk a TypeError at build time.
108
+ return False
109
+ return any(
110
+ parameter.kind is inspect.Parameter.VAR_KEYWORD
111
+ or (parameter.name == name and parameter.kind is not inspect.Parameter.POSITIONAL_ONLY)
112
+ for parameter in parameters
113
+ )
114
+
115
+
116
+ class CurrentAmplifierWorker(ValkeyWorker):
117
+ """A `ValkeyWorker` that polls and controls one or more current amplifier boards.
118
+
119
+ Settings resolve through the framework's four-layer merge: constructor
120
+ default (L0) < ``current_amplifier.yml`` bootstrap patch (L1, read directly
121
+ here) < framework ``config.yml`` snapshot (L2) < remote
122
+ ``current_amplifier`` section (L3). The section is registered with
123
+ ``bootstrap=None``, so L1 never enters the framework's layer stack; the
124
+ worker reads the YAML itself to seed the initial registry and then
125
+ reconciles against the merged section after ``super().initialize()``. The
126
+ merged ``amplifiers`` list replaces the YAML list entirely — it is not
127
+ merged by label.
128
+
129
+ A board is polled by one long-lived task; it is never connected during
130
+ startup, so an offline board does not block the service. A reconfig at
131
+ runtime is restart-required (the registry is not live-rebuilt).
132
+ """
133
+
134
+ def __init__(self, config: ValkeyWorkerConfig | None = None, *, client_factory=None, theme=None) -> None:
135
+ super().__init__(config, client_factory=client_factory, theme=theme)
136
+ self._settings: CurrentAmplifierServiceSettings | None = None
137
+ self._amplifiers: dict[str, CurrentAmplifierProtocol] = {}
138
+ self._amplifier_settings: dict[str, AmplifierSettings] = {}
139
+ self._monitoring: dict[str, bool] = {}
140
+ self._poll_tasks: dict[str, asyncio.Task[None]] = {}
141
+ self._connected: dict[str, bool] = {}
142
+ self._stats: dict[str, AmplifierStats] = {}
143
+ # Startup guard: the config apply hook runs both during
144
+ # ``super().initialize()`` (L2/L3 delivery, where ``initialize`` itself
145
+ # builds the registry) and at runtime (where a change is restart-
146
+ # required). False until ``initialize`` returns.
147
+ self._startup_complete: bool = False
148
+ self._restart_required: bool = False
149
+ # Telemetry encoding is done with an encoder owned here (the framework's
150
+ # ``__encoder`` is private), and the key is resolved once at
151
+ # construction.
152
+ self._telemetry_encoder = msgspec.msgpack.Encoder()
153
+ self._telemetry_key = f"scietex:{self.service_name}:{self.instance_id}:telemetry"
154
+ self.register_config_settings(
155
+ CURRENT_AMPLIFIER_SECTION,
156
+ CurrentAmplifierServiceSettings,
157
+ apply=self._apply_settings,
158
+ defaults=CURRENT_AMPLIFIER_SETTINGS_DEFAULTS,
159
+ # bootstrap=None is deliberate: the worker reads the YAML itself and
160
+ # seeds L0 from it, so L1 never enters the layer stack and the
161
+ # remote L3 config cleanly replaces it (see config.py module
162
+ # docstring).
163
+ bootstrap=None,
164
+ )
165
+ # Control-lane monitoring switch and data-lane board commands. Both
166
+ # handlers receive the worker by constructor injection: the handler
167
+ # context carries no worker reference.
168
+ self.add_task_handler(MonitoringHandler, worker=self)
169
+ self.add_task_handler(AmplifierControlHandler, worker=self)
170
+
171
+ @property
172
+ def amplifiers(self) -> dict[str, CurrentAmplifierProtocol]:
173
+ """The live board registry keyed by label (the dict itself, not a copy).
174
+
175
+ Mutating callers share the worker's registry; read-only consumers should
176
+ iterate without changing it.
177
+ """
178
+ return self._amplifiers
179
+
180
+ @property
181
+ def amplifier_settings(self) -> dict[str, AmplifierSettings]:
182
+ """The per-label board settings the registry was built from."""
183
+ return self._amplifier_settings
184
+
185
+ @property
186
+ def monitoring(self) -> dict[str, bool]:
187
+ """Per-label poll-loop activity: True while a poll task is scheduled."""
188
+ return self._monitoring
189
+
190
+ @property
191
+ def connected(self) -> dict[str, bool]:
192
+ """Per-label read state tracked by the poll loop."""
193
+ return self._connected
194
+
195
+ @property
196
+ def stats(self) -> dict[str, AmplifierStats]:
197
+ """Per-label counters accumulated by the poll loop."""
198
+ return self._stats
199
+
200
+ @property
201
+ def restart_required(self) -> bool:
202
+ """Whether a post-startup settings apply requires a restart to rebuild the registry."""
203
+ return self._restart_required
204
+
205
+ def _failure_threshold(self) -> int:
206
+ """Consecutive failed reads before a board is reported as disconnected.
207
+
208
+ Falls back to the module default before settings are applied, so a poll
209
+ task that starts early still has a usable bound.
210
+ """
211
+ settings = self._settings
212
+ return settings.failure_threshold if settings is not None else CONNECTED_FAILURE_THRESHOLD
213
+
214
+ def _stream_maxlen(self) -> int:
215
+ """Entries retained per board's readings stream.
216
+
217
+ Falls back to the module default before settings are applied.
218
+ """
219
+ settings = self._settings
220
+ return settings.stream_maxlen if settings is not None else STREAM_MAXLEN
221
+
222
+ async def initialize(self) -> bool:
223
+ """Seed the registry from the YAML, then reconcile against the merged settings.
224
+
225
+ The service-owned YAML is read before ``super().initialize()`` so the
226
+ registry is populated even when no remote config exists; the merged
227
+ section read back afterwards replaces it wholesale when it differs. A
228
+ bad YAML or a board that fails to resolve/construct fails startup: a
229
+ half-working registry must not run.
230
+
231
+ Returns:
232
+ `True` if the framework initialized and the registry is built;
233
+ `False` on any configuration or startup failure.
234
+ """
235
+ self._startup_complete = False
236
+ try:
237
+ raw = read_current_amplifier_config(self.conf_dir)
238
+ except RuntimeError as exc:
239
+ self.logger.error("Failed to read current amplifier configuration: %s", exc)
240
+ return False
241
+ try:
242
+ settings = msgspec.convert(raw, CurrentAmplifierServiceSettings)
243
+ except (msgspec.ValidationError, ValueError) as exc:
244
+ self.logger.error("Invalid current amplifier configuration: %s", exc)
245
+ return False
246
+ try:
247
+ await self._build_amplifiers(settings)
248
+ except ValueError as exc:
249
+ self.logger.error("Failed to build current amplifier registry: %s", exc)
250
+ return False
251
+
252
+ if not await super().initialize():
253
+ return False
254
+
255
+ resolved = self.current_config_settings(CURRENT_AMPLIFIER_SECTION)
256
+ if resolved is not None:
257
+ resolved_settings = cast(CurrentAmplifierServiceSettings, resolved)
258
+ if resolved_settings != settings:
259
+ # L3 wins wholesale: the merged ``amplifiers`` list replaces the
260
+ # YAML-seeded list entirely, it is not merged by label.
261
+ self._apply_settings(resolved_settings)
262
+ try:
263
+ await self._build_amplifiers(resolved_settings)
264
+ except ValueError as exc:
265
+ self.logger.error("Failed to rebuild current amplifier registry from merged settings: %s", exc)
266
+ return False
267
+
268
+ self._startup_complete = True
269
+ self.logger.info("Current amplifier service started: %d board(s)", len(self._amplifiers))
270
+ return True
271
+
272
+ async def cleanup(self) -> None:
273
+ """Cancel poll tasks and close boards, then the framework resources."""
274
+ await self.close_amplifiers()
275
+ await super().cleanup()
276
+
277
+ async def _build_amplifiers(self, settings: CurrentAmplifierServiceSettings) -> None:
278
+ """(Re)build the board registry from the given settings.
279
+
280
+ Idempotent: existing poll tasks are cancelled and existing boards closed
281
+ before the registry is rebuilt. A board is instantiated but not
282
+ connected here — the driver opens its port per read operation, so an
283
+ offline board does not block startup.
284
+
285
+ Args:
286
+ settings: The authoritative settings to build from.
287
+
288
+ Raises:
289
+ ValueError: On a duplicate label, invalid serial settings, an
290
+ unresolvable driver, or an instance that does not satisfy
291
+ `CurrentAmplifierProtocol`.
292
+ """
293
+ await self.close_amplifiers()
294
+ # The registry is built from these settings, so they are the effective
295
+ # ones: the poll loop reads the failure threshold and the stream
296
+ # retention from here rather than from the module defaults.
297
+ self._settings = settings
298
+ self._amplifiers = {}
299
+ self._amplifier_settings = {}
300
+ self._monitoring = {}
301
+ self._connected = {}
302
+ self._stats = {}
303
+
304
+ seen: set[str] = set()
305
+ for board_settings in settings.amplifiers:
306
+ label = board_settings.label
307
+ if label in seen:
308
+ self.logger.error("Duplicate amplifier label %r in configuration", label)
309
+ raise ValueError(f"Duplicate amplifier label {label!r}")
310
+ seen.add(label)
311
+
312
+ driver = resolve_driver(board_settings.driver)
313
+ # The protocol declares no constructor, so cast to `Any` before the
314
+ # dynamic instantiation — the concrete driver's `__init__` signature
315
+ # is unknown statically and validated by the isinstance check below.
316
+ kwargs: dict[str, Any] = {
317
+ "con_params": self._connection_config(board_settings),
318
+ "address": board_settings.address,
319
+ "label": label,
320
+ "logger": self.logger,
321
+ }
322
+ # Only pass the settle delay when configured and when the driver
323
+ # takes it: a driver that declares no such parameter would raise
324
+ # TypeError on construction.
325
+ if board_settings.relay_settle_s is not None:
326
+ if _accepts_keyword(driver, "relay_settle_s"):
327
+ kwargs["relay_settle_s"] = board_settings.relay_settle_s
328
+ else:
329
+ self.logger.warning(
330
+ "Driver %r for amplifier %r does not accept relay_settle_s; "
331
+ "the configured %s s is ignored and the driver keeps its own default.",
332
+ board_settings.driver,
333
+ label,
334
+ board_settings.relay_settle_s,
335
+ )
336
+ amplifier = cast(Any, driver)(**kwargs)
337
+ if not isinstance(amplifier, CurrentAmplifierProtocol):
338
+ self.logger.error(
339
+ "Driver %r for amplifier %r is not a CurrentAmplifierProtocol",
340
+ board_settings.driver,
341
+ label,
342
+ )
343
+ raise ValueError(f"Driver {board_settings.driver!r} for amplifier {label!r} is not a CurrentAmplifierProtocol")
344
+
345
+ self._amplifiers[label] = amplifier
346
+ self._amplifier_settings[label] = board_settings
347
+ self._monitoring[label] = False
348
+ self._connected[label] = False
349
+ self._stats[label] = AmplifierStats()
350
+
351
+ def _connection_config(self, board_settings: AmplifierSettings) -> ModbusSerialConnectionConfig:
352
+ """Build the serial connection config for one board.
353
+
354
+ The serial model validates its own field domains (baud rate, parity,
355
+ framer, stop bits) and raises `ValueError` for an unsupported value;
356
+ that error is re-raised with the board label so a bad config names the
357
+ board instead of failing anonymously. `AmplifierSerialSettings.stopbits`
358
+ is a float, while the serial model accepts only integer stop-bit counts
359
+ and rejects an integral float as the wrong type, so an integral value is
360
+ narrowed back to `int` first.
361
+ """
362
+ serial = board_settings.serial
363
+ stopbits = int(serial.stopbits) if float(serial.stopbits).is_integer() else serial.stopbits
364
+ try:
365
+ return ModbusSerialConnectionConfig(
366
+ port=serial.port,
367
+ baudrate=serial.baudrate,
368
+ bytesize=serial.bytesize,
369
+ parity=serial.parity,
370
+ stopbits=stopbits,
371
+ timeout=serial.timeout,
372
+ framer=serial.framer,
373
+ )
374
+ except ValueError as exc:
375
+ raise ValueError(f"amplifier {board_settings.label!r}: invalid serial settings: {exc}") from exc
376
+
377
+ async def close_amplifiers(self) -> None:
378
+ """Cancel all poll tasks and close every board, swallowing close errors.
379
+
380
+ Used by both ``cleanup`` and the idempotent rebuild in
381
+ ``_build_amplifiers``. A close error is logged and swallowed so a
382
+ teardown failure never aborts shutdown or a rebuild.
383
+ """
384
+ for label, task in list(self._poll_tasks.items()):
385
+ task.cancel()
386
+ self._monitoring[label] = False
387
+ self._connected[label] = False
388
+ self._poll_tasks.clear()
389
+ for label, amplifier in list(self._amplifiers.items()):
390
+ try:
391
+ await amplifier.close()
392
+ except Exception as exc:
393
+ self.logger.warning("Failed to close amplifier %r: %s", label, exc)
394
+
395
+ def _apply_settings(self, settings: CurrentAmplifierServiceSettings) -> None:
396
+ """Apply merged current amplifier settings (sync hook, invoked inline).
397
+
398
+ During startup the hook only stores: `initialize` builds the registry
399
+ from the final merged settings. At runtime a change is only stored and
400
+ flagged restart-required — the registry is not live-rebuilt because the
401
+ framework's ``_restart_required_fields`` only inspects core settings, so
402
+ this service tracks its own restart-required state.
403
+ """
404
+ self._settings = settings
405
+ if not self._startup_complete:
406
+ self.logger.info("Stored current amplifier settings for startup")
407
+ return
408
+ self.logger.warning(
409
+ "Current amplifier settings applied; restart required to rebuild the amplifier registry "
410
+ "(boards are not live-rebuilt)"
411
+ )
412
+ self._restart_required = True
413
+
414
+ def _labels(self, label: str | None) -> list[str]:
415
+ """Resolve a label selector to the list of affected labels.
416
+
417
+ ``None`` selects all boards; an unknown label raises `KeyError`.
418
+ """
419
+ if label is None:
420
+ return list(self._amplifiers)
421
+ if label not in self._amplifiers:
422
+ raise KeyError(f"Unknown amplifier label {label!r}")
423
+ return [label]
424
+
425
+ def start_monitoring(self, label: str | None = None) -> list[str]:
426
+ """Start a poll task for the selected board(s), returning affected labels.
427
+
428
+ ``label=None`` starts every board. A label that is already monitoring is
429
+ a no-op and is not returned. Each started board gets one long-lived poll
430
+ task scheduled on the running loop.
431
+ """
432
+ affected: list[str] = []
433
+ for candidate in self._labels(label):
434
+ if self._monitoring[candidate]:
435
+ continue
436
+ self._monitoring[candidate] = True
437
+ self._poll_tasks[candidate] = asyncio.get_running_loop().create_task(self._poll_amplifier(candidate))
438
+ affected.append(candidate)
439
+ return affected
440
+
441
+ def stop_monitoring(self, label: str | None = None) -> list[str]:
442
+ """Cancel the poll task for the selected board(s), returning affected labels.
443
+
444
+ ``label=None`` stops every board. The task is cancelled (sync — the loop
445
+ is not awaited), removed from ``_poll_tasks``, and the label marked not
446
+ monitoring. Stopping a board that is not monitoring is a no-op.
447
+ """
448
+ affected: list[str] = []
449
+ for candidate in self._labels(label):
450
+ task = self._poll_tasks.pop(candidate, None)
451
+ if task is not None:
452
+ task.cancel()
453
+ if self._monitoring.get(candidate):
454
+ self._monitoring[candidate] = False
455
+ self._connected[candidate] = False
456
+ affected.append(candidate)
457
+ return affected
458
+
459
+ async def _sleep(self, delay: float) -> None:
460
+ """Sleep for ``delay``; a separate method so tests can short-circuit the poll loop."""
461
+ await asyncio.sleep(delay)
462
+
463
+ async def _poll_amplifier(self, label: str) -> None:
464
+ """Poll one board forever: read, publish, repeat.
465
+
466
+ The loop never dies on a board error: a read failure increments the
467
+ board's error counters, logs at WARNING, and continues after the poll
468
+ interval. A successful reading updates the stats and publishes a stream
469
+ entry. The task is expected to be stopped by cancellation
470
+ (``stop_monitoring``/``cleanup``), not by returning.
471
+
472
+ There is no connect stage: the EBIC driver opens its serial port once
473
+ per operation, so the loop reads directly.
474
+ """
475
+ amplifier = self._amplifiers.get(label)
476
+ amplifier_settings = self._amplifier_settings.get(label)
477
+ if amplifier is None or amplifier_settings is None:
478
+ return
479
+ while True:
480
+ try:
481
+ state = await amplifier.read_data()
482
+ except Exception as exc:
483
+ # `connected` means "the board is answering". A single failed
484
+ # read is not enough to report the board as gone — an RS485
485
+ # segment drops the occasional frame — so the flag clears only
486
+ # after the configured number of failures in a row.
487
+ stats = self._stats[label]
488
+ stats.consecutive_failures += 1
489
+ if stats.consecutive_failures >= self._failure_threshold():
490
+ self._connected[label] = False
491
+ self._record_error(label, exc, "read")
492
+ await self._sleep(amplifier_settings.poll_interval)
493
+ continue
494
+
495
+ self._connected[label] = True
496
+ stats = self._stats[label]
497
+ stats.consecutive_failures = 0
498
+ stats.reading_count += 1
499
+ now = datetime.now(timezone.utc)
500
+ stats.last_state = state
501
+ stats.last_reading_at = now
502
+ stats.last_error = None
503
+ await self._publish_reading(label, state, now)
504
+
505
+ await self._sleep(amplifier_settings.poll_interval)
506
+
507
+ def _record_error(self, label: str, exc: Exception, stage: str) -> None:
508
+ """Increment a board's error counters and log a WARNING."""
509
+ stats = self._stats[label]
510
+ stats.error_count += 1
511
+ stats.last_error = str(exc)
512
+ self.logger.log(logging.WARNING, "Failed to %s amplifier %r: %s", stage, label, exc)
513
+
514
+ async def _publish_reading(self, label: str, state: AmplifierState, now: datetime) -> None:
515
+ """Publish one reading to the board's stream.
516
+
517
+ The write is guarded on `self.client`; a glide error is logged at
518
+ WARNING and reported to the transport health, mirroring the telemetry
519
+ loop's error handling. ``filters`` is a tuple of structs, which ``xadd``
520
+ cannot take as a scalar, so it is published as one JSON string.
521
+
522
+ ``preamp_range`` and ``feedback_resistor_ohm`` carry the same value (the
523
+ selected Rf in ohm): the API charts neither, but both the older and the
524
+ newer tooltip spelling must decode.
525
+ """
526
+ client = self.client
527
+ if client is None:
528
+ return
529
+ key = f"scietex:{self.service_name}:{self.instance_id}:current_amplifier:{label}:readings"
530
+ try:
531
+ await client.xadd(
532
+ key,
533
+ [
534
+ (b"ts", now.isoformat().encode()),
535
+ (b"output_voltage_v", encode_value(state.output_voltage_v)),
536
+ (b"output_current_a", encode_value(state.output_current_a)),
537
+ (b"input_current_a", encode_value(state.input_current_a)),
538
+ (b"boost_gain", encode_value(state.boost_gain)),
539
+ (b"feedback_resistor_ohm", encode_value(state.feedback_resistor_ohm)),
540
+ (b"preamp_range", encode_value(state.feedback_resistor_ohm)),
541
+ (b"dc_bias_level", encode_value(state.dc_bias_level)),
542
+ (b"bandwidth_hz", encode_value(state.bandwidth_hz)),
543
+ (b"input_compensation_level", encode_value(state.input_compensation_level)),
544
+ (b"dc_bias_enabled", encode_flag(state.dc_bias_enabled)),
545
+ (b"input_compensation_enabled", encode_flag(state.input_compensation_enabled)),
546
+ (b"input_overcurrent", encode_flag(state.input_overcurrent)),
547
+ (b"output_overload", encode_flag(state.output_overload)),
548
+ (b"inverted", encode_flag(state.inverted)),
549
+ (b"filters", msgspec.json.encode(list(state.filters))),
550
+ (b"transconductance_v_per_a", encode_value(self._transconductance(label, state))),
551
+ ],
552
+ StreamAddOptions(trim=TrimByMaxLen(exact=False, threshold=self._stream_maxlen())),
553
+ )
554
+ except (GlideConnectionError, RequestError, GlideTimeoutError) as exc:
555
+ self.logger.log(logging.WARNING, "Failed to publish reading for amplifier %r: %s", label, exc)
556
+ self._health.report_failure(exc)
557
+
558
+ def _transconductance(self, label: str, state: AmplifierState) -> float | None:
559
+ """``Rf * gain`` for one reading, or ``None`` when either is unknown."""
560
+ feedback = state.feedback_resistor_ohm
561
+ gain = state.boost_gain
562
+ if feedback is None or gain is None:
563
+ return None
564
+ amplifier = self._amplifiers.get(label)
565
+ if amplifier is None:
566
+ return None
567
+ try:
568
+ return amplifier.capabilities.total_transconductance(feedback, gain)
569
+ except ValueError:
570
+ return None
571
+
572
+ @Manager(name="Telemetry")
573
+ async def telemetry_loop(self) -> None:
574
+ """Publish service telemetry to Valkey once per iteration.
575
+
576
+ The manager runtime repeats this body forever with auto-restart on error.
577
+ The write is guarded on `self.client` and runs even when the worker is
578
+ unconfigured, so the UI observes ``configured=false``. Glide errors are
579
+ logged at WARNING and reported to the transport health, matching the
580
+ heartbeat's error handling.
581
+ """
582
+ client = self.client
583
+ if client is not None:
584
+ payload = build_telemetry(self)
585
+ try:
586
+ await client.set(
587
+ self._telemetry_key,
588
+ value=self._telemetry_encoder.encode(payload),
589
+ expiry=ExpirySet(ExpiryType.SEC, TELEMETRY_TTL),
590
+ )
591
+ except (GlideConnectionError, RequestError, GlideTimeoutError) as exc:
592
+ self.logger.log(logging.WARNING, "Failed to publish current amplifier telemetry: %s", exc)
593
+ self._health.report_failure(exc)
594
+ await asyncio.sleep(TELEMETRY_INTERVAL)
595
+
596
+
597
+ def encode_value(value: float | None) -> bytes:
598
+ """Encode a reading value for the stream: ``b""`` for `None`, otherwise ``repr``.
599
+
600
+ ``repr(float)`` round-trips exactly; the API re-parses and computes min/max,
601
+ so truncation (e.g. ``.12g``) would bias every bucket. ``None`` encodes as an
602
+ empty string so a board that does not report a field is distinguishable from
603
+ one reporting zero.
604
+ """
605
+ return b"" if value is None else repr(value).encode()
606
+
607
+
608
+ def encode_flag(value: bool | None) -> bytes:
609
+ """Encode a tri-state flag: ``b"1"``/``b"0"``, or ``b""`` for unknown.
610
+
611
+ ``None`` means the driver cannot report the flag, which must stay
612
+ distinguishable from a reported ``False``.
613
+ """
614
+ if value is None:
615
+ return b""
616
+ return b"1" if value else b"0"