scietex.dac-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,79 @@
1
+ """DAC Service."""
2
+
3
+ from .config import (
4
+ DAC_SECTION,
5
+ DAC_SETTINGS_DEFAULTS,
6
+ DacDeviceSettings,
7
+ DacServiceSettings,
8
+ read_dac_config,
9
+ )
10
+ from .dac_worker import DacWorker
11
+ from .devices import (
12
+ ChannelNotFound,
13
+ DacDeviceRegistry,
14
+ DeviceConfigError,
15
+ DeviceNotFound,
16
+ DeviceOpenError,
17
+ DeviceUnavailable,
18
+ InvalidParameter,
19
+ UnknownDeviceType,
20
+ )
21
+ from .task_handlers import (
22
+ DacChannelState,
23
+ DacConfigureHandler,
24
+ DacConfigureRequest,
25
+ DacConfigureResponse,
26
+ DacDeviceInfo,
27
+ DacListHandler,
28
+ DacListRequest,
29
+ DacListResponse,
30
+ DacReadHandler,
31
+ DacReadRequest,
32
+ DacReadResponse,
33
+ DacStatusHandler,
34
+ DacStatusRequest,
35
+ DacStatusResponse,
36
+ DacWriteHandler,
37
+ DacWriteRequest,
38
+ DacWriteResponse,
39
+ )
40
+ from .telemetry import DacChannelTelemetry, DacDeviceTelemetry, DacServiceTelemetry
41
+ from .version import __version__
42
+
43
+ __all__ = [
44
+ "__version__",
45
+ "DacWorker",
46
+ "DAC_SECTION",
47
+ "DAC_SETTINGS_DEFAULTS",
48
+ "DacDeviceSettings",
49
+ "DacServiceSettings",
50
+ "DacChannelTelemetry",
51
+ "DacDeviceTelemetry",
52
+ "DacServiceTelemetry",
53
+ "DacDeviceRegistry",
54
+ "ChannelNotFound",
55
+ "DeviceConfigError",
56
+ "DeviceNotFound",
57
+ "DeviceOpenError",
58
+ "DeviceUnavailable",
59
+ "InvalidParameter",
60
+ "UnknownDeviceType",
61
+ "DacChannelState",
62
+ "DacConfigureHandler",
63
+ "DacConfigureRequest",
64
+ "DacConfigureResponse",
65
+ "DacDeviceInfo",
66
+ "DacListHandler",
67
+ "DacListRequest",
68
+ "DacListResponse",
69
+ "DacReadHandler",
70
+ "DacReadRequest",
71
+ "DacReadResponse",
72
+ "DacStatusHandler",
73
+ "DacStatusRequest",
74
+ "DacStatusResponse",
75
+ "DacWriteHandler",
76
+ "DacWriteRequest",
77
+ "DacWriteResponse",
78
+ "read_dac_config",
79
+ ]
@@ -0,0 +1,161 @@
1
+ """Configuration models and YAML loader for the DAC service.
2
+
3
+ `DacServiceSettings` is the concrete constructor (L0) base and the validation
4
+ target of the framework's four-layer config merge:
5
+
6
+ * L0 — `DAC_SETTINGS_DEFAULTS`, the builtins of a default struct instance.
7
+ * L1 — the service-owned ``dac/dac.yml`` bootstrap patch (`read_dac_config`).
8
+ * L2 — the framework's ``config.yml`` snapshot from the last successful apply.
9
+ * L3 — the remote ``dac`` section of a desired-state envelope.
10
+
11
+ The layers are patch dicts merged field by field with the three-state rule: a
12
+ key absent from every layer inherits the value below, a key present with
13
+ ``null`` clears it (so the L0 value resurfaces), and a key present with a value
14
+ sets it. The struct is kept deliberately thin: backend selection, pin routing,
15
+ and part geometry are validated by the HAL constructors in
16
+ `devices.build_dac`, so the YAML schema only constrains types and unknown
17
+ fields.
18
+
19
+ Per-channel sequences are deliberately out of scope for this file: ``reference``
20
+ is one scalar for the whole device (the HAL accepts a per-channel sequence, but
21
+ the config schema does not), and per-channel ``gain``, ``power_down``,
22
+ ``channels``, and ``buffered`` are not exposed at all. Those knobs live on the
23
+ task layer, where a channel index already exists.
24
+
25
+ Device entries are keyed by a **string** device id (``devices: {dac0: {...}}``),
26
+ not an integer. An id names a device in task payloads and telemetry, and a YAML
27
+ mapping key is a string anyway, so an ``int`` key would need silent coercion on
28
+ every hop. `dict[str, DacDeviceSettings]` decodes string keys verbatim and
29
+ round-trips through `msgspec.to_builtins` unchanged.
30
+ """
31
+
32
+ from pathlib import Path
33
+
34
+ import msgspec
35
+
36
+ #: Remote-config section name the settings are registered under.
37
+ DAC_SECTION: str = "dac"
38
+
39
+ #: Subdirectory under the shared config dir that namespaces this service's
40
+ #: files. The framework's ``config.yml`` snapshot and the service-owned
41
+ #: ``dac.yml`` both live here, so services sharing one config dir (the
42
+ #: framework resolves a single dir for all scietex services) cannot collide.
43
+ DAC_CONFIG_SUBDIR: str = "dac"
44
+
45
+ #: Filename of the service-owned L1 bootstrap patch in the config subdirectory.
46
+ DAC_CONFIG_FILE: str = "dac.yml"
47
+
48
+
49
+ class DacDeviceSettings(msgspec.Struct, frozen=True, forbid_unknown_fields=True):
50
+ """One SPI DAC device, keyed by its id in `DacServiceSettings.devices`.
51
+
52
+ ``type`` selects the HAL class through `devices.DAC_PARTS`. Every remaining
53
+ field is optional and forwarded to that class only when set, so the backend
54
+ keywords (``port``/``device`` SPI bus and chip-select) and the shared
55
+ keywords (``reference``, ``label``, ``log_level``) can be mixed as the part
56
+ and its transport require. ``None`` means "not configured": the constructor
57
+ default applies.
58
+
59
+ The trailing fields are part-specific: ``range``/``latch_pin`` for the
60
+ current-output and latched parts, ``load_pin`` for the load-strobed voltage
61
+ parts, and ``r_ab``/``grounded`` for the digital potentiometers. A part that
62
+ does not accept one of them rejects it at build time; the schema stays
63
+ uniform instead of growing 23 variants.
64
+
65
+ ``strobe`` is deliberately absent: the HAL takes a driver object there,
66
+ while a config entry can only carry YAML scalars. Parts that need a load
67
+ line take ``load_pin`` (or ``latch_pin`` for AD420) as an integer GPIO pin
68
+ instead.
69
+ """
70
+
71
+ type: str
72
+ port: int | None = None
73
+ device: int | None = None
74
+ clock_pin: int | str | None = None
75
+ mosi_pin: int | str | None = None
76
+ miso_pin: int | str | None = None
77
+ select_pin: int | str | None = None
78
+ reference: float | None = None
79
+ label: str | None = None
80
+ log_level: str | None = None
81
+ # part-specific parameters
82
+ range: str | None = None
83
+ load_pin: int | str | None = None
84
+ latch_pin: int | str | None = None
85
+ r_ab: float | None = None
86
+ grounded: str | None = None
87
+
88
+
89
+ class DacServiceSettings(msgspec.Struct, frozen=True, forbid_unknown_fields=True):
90
+ """Top-level DAC service settings."""
91
+
92
+ devices: dict[str, DacDeviceSettings] = msgspec.field(default_factory=dict)
93
+
94
+
95
+ #: Concrete L0 base for the framework's layered merge. A field absent from every
96
+ #: layer, or explicitly cleared with ``null``, resolves to the value here.
97
+ DAC_SETTINGS_DEFAULTS: DacServiceSettings = DacServiceSettings()
98
+
99
+
100
+ def read_dac_config(conf_dir: Path | None, *, create_default: bool = True) -> dict[str, object]:
101
+ """Read the L1 bootstrap patch from ``dac/dac.yml`` under the config directory.
102
+
103
+ The service's files are namespaced in a ``dac/`` subdirectory so they do
104
+ not collide with other services sharing the framework's single config dir.
105
+ The file (and, when missing, its directory) is only created when
106
+ ``create_default=True`` (the bootstrap path). A ``None`` or non-directory
107
+ ``conf_dir``, a missing file/directory with ``create_default=False``, or an
108
+ unparseable file each raise `RuntimeError`. An existing-but-invalid file is
109
+ left untouched regardless of ``create_default``.
110
+
111
+ The return value is the raw ``dac.yml`` mapping — the L1 patch the framework
112
+ merges onto the L0 base and validates through `DacServiceSettings`. When the
113
+ file is just created, the builtins of the default struct are returned so the
114
+ patch is equivalent to an empty override.
115
+
116
+ Args:
117
+ conf_dir: Path to the configuration directory.
118
+ create_default: Whether to create the directory and write a default
119
+ ``dac.yml`` when missing. Default ``True``.
120
+
121
+ Returns:
122
+ The parsed ``dac.yml`` mapping as the L1 patch, or the builtins of the
123
+ default `DacServiceSettings` when the file was just created.
124
+
125
+ Raises:
126
+ RuntimeError: If ``conf_dir`` is ``None`` or not a directory, the file
127
+ is missing with ``create_default=False``, or the file cannot be parsed.
128
+ """
129
+ if not isinstance(conf_dir, Path):
130
+ raise RuntimeError("Configuration dir was not set!")
131
+ service_dir = conf_dir / DAC_CONFIG_SUBDIR
132
+ if not service_dir.exists():
133
+ if create_default:
134
+ try:
135
+ service_dir.mkdir(parents=True, exist_ok=True)
136
+ except Exception as exc:
137
+ raise RuntimeError(f"Failed to create configuration directory {service_dir}!") from exc
138
+ else:
139
+ raise RuntimeError(
140
+ f"Configuration directory {service_dir} does not exist and create_default=False (no default generated)."
141
+ )
142
+ elif not service_dir.is_dir():
143
+ raise RuntimeError(f"Provided configuration directory path {service_dir} is not a directory!")
144
+ dac_yml = service_dir.joinpath(DAC_CONFIG_FILE)
145
+ if not dac_yml.exists():
146
+ if create_default:
147
+ settings = DacServiceSettings()
148
+ with open(dac_yml, "wb") as f:
149
+ f.write(msgspec.yaml.encode(settings))
150
+ return msgspec.to_builtins(settings)
151
+ raise RuntimeError(
152
+ f"DAC configuration file {dac_yml} does not exist and create_default=False "
153
+ "(pass create_default=True to generate defaults)."
154
+ )
155
+ try:
156
+ with open(dac_yml, "rb") as f:
157
+ return msgspec.yaml.decode(f.read(), type=dict)
158
+ except Exception as exc:
159
+ raise RuntimeError(
160
+ f"Failed to parse DAC configuration file {dac_yml}. Fix the file or remove it to regenerate defaults."
161
+ ) from exc
@@ -0,0 +1,172 @@
1
+ """DAC worker: a Valkey-backed service that owns a set of SPI converters.
2
+
3
+ `DacWorker` extends `ValkeyWorker` with a live `DacDeviceRegistry`. Settings
4
+ resolve through the framework's four-layer merge: constructor default (L0) <
5
+ ``dac/dac.yml`` bootstrap patch (L1) < framework ``config.yml`` snapshot (L2) <
6
+ remote ``dac`` section (L3). Every apply rebuilds the registry from the merged
7
+ struct; a device that cannot be opened is recorded and the rest keep working.
8
+ A ``Telemetry`` manager publishes the open-device and last-written snapshot
9
+ every 2 s.
10
+ """
11
+
12
+ import asyncio
13
+ import logging
14
+ from typing import cast
15
+
16
+ import msgspec
17
+ from glide import (
18
+ ConnectionError as GlideConnectionError,
19
+ )
20
+ from glide import (
21
+ ExpirySet,
22
+ ExpiryType,
23
+ RequestError,
24
+ )
25
+ from glide import (
26
+ TimeoutError as GlideTimeoutError,
27
+ )
28
+
29
+ from scietex.service import Manager, ValkeyWorker, ValkeyWorkerConfig
30
+
31
+ from .config import (
32
+ DAC_SECTION,
33
+ DAC_SETTINGS_DEFAULTS,
34
+ DacServiceSettings,
35
+ read_dac_config,
36
+ )
37
+ from .devices import DacDeviceRegistry
38
+ from .task_handlers import DacConfigureHandler, DacListHandler, DacReadHandler, DacStatusHandler, DacWriteHandler
39
+ from .telemetry import TELEMETRY_INTERVAL, TELEMETRY_TTL, build_telemetry
40
+
41
+
42
+ class DacWorker(ValkeyWorker):
43
+ """A `ValkeyWorker` that drives the configured SPI DAC devices."""
44
+
45
+ def __init__(self, config: ValkeyWorkerConfig | None = None, *, client_factory=None, theme=None) -> None:
46
+ super().__init__(config, client_factory=client_factory, theme=theme)
47
+ self._settings: DacServiceSettings | None = None
48
+ self._devices = DacDeviceRegistry(self.logger)
49
+ # The apply hook runs during ``initialize`` (L2/L3 delivery) and at
50
+ # runtime. False until ``initialize`` finishes so the hook does not
51
+ # rebuild the registry twice on startup; ``initialize`` rebuilds once
52
+ # from the final merged settings.
53
+ self._startup_complete: bool = False
54
+ # Telemetry encoding is owned here because the framework's encoder is
55
+ # private; the key is resolved once at construction.
56
+ self._telemetry_encoder = msgspec.msgpack.Encoder()
57
+ self._telemetry_key = f"scietex:{self.service_name}:{self.instance_id}:telemetry"
58
+ self.register_config_settings(
59
+ DAC_SECTION,
60
+ DacServiceSettings,
61
+ apply=self._apply_settings,
62
+ defaults=DAC_SETTINGS_DEFAULTS,
63
+ bootstrap=lambda: read_dac_config(self.conf_dir),
64
+ )
65
+ # All handlers share the registry, so a config apply is visible
66
+ # to an in-flight handler without re-registration.
67
+ self.add_task_handler(DacListHandler, devices=self._devices)
68
+ self.add_task_handler(DacConfigureHandler, devices=self._devices)
69
+ self.add_task_handler(DacStatusHandler, devices=self._devices)
70
+ self.add_task_handler(DacReadHandler, devices=self._devices)
71
+ self.add_task_handler(DacWriteHandler, devices=self._devices)
72
+
73
+ @property
74
+ def dac_settings(self) -> DacServiceSettings | None:
75
+ """The effective DAC settings, or `None` before startup."""
76
+ return self._settings
77
+
78
+ @property
79
+ def devices(self) -> DacDeviceRegistry:
80
+ """The live device registry shared with the task handlers."""
81
+ return self._devices
82
+
83
+ async def initialize(self) -> bool:
84
+ """Initialize the framework, then open every configured device.
85
+
86
+ `super().initialize()` seeds the L0+L1 layers (running the ``dac.yml``
87
+ bootstrap provider) and applies the L2/L3 layers, so the merged settings
88
+ are read back via `current_config_settings` afterwards. A bootstrap
89
+ failure is swallowed by the framework's seeder and surfaces as an
90
+ unresolved section, which is the ``None`` guard below. Per-device open
91
+ failures do not fail startup: the registry records them and the worker
92
+ drives the hardware that is present.
93
+
94
+ Returns:
95
+ `True` if the settings resolved and the registry rebuilt, `False`
96
+ on a framework, resolution, or registry-wide failure.
97
+ """
98
+ self._startup_complete = False
99
+ if not await super().initialize():
100
+ return False
101
+
102
+ resolved = self.current_config_settings(DAC_SECTION)
103
+ if resolved is None:
104
+ self.logger.error("DAC settings were not resolved before device startup")
105
+ return False
106
+ settings = cast(DacServiceSettings, resolved)
107
+ try:
108
+ self._devices.rebuild(settings)
109
+ except Exception as exc:
110
+ self.logger.error("Failed to build the DAC device registry: %s", exc)
111
+ return False
112
+ self._settings = settings
113
+ self._startup_complete = True
114
+ return True
115
+
116
+ async def cleanup(self) -> None:
117
+ """Close every open device, then the framework resources."""
118
+ self._startup_complete = False
119
+ self._devices.close()
120
+ await super().cleanup()
121
+
122
+ def _apply_settings(self, settings: DacServiceSettings) -> None:
123
+ """Store merged settings and rebuild the live devices.
124
+
125
+ The hook is synchronous (the framework invokes it inline, before the
126
+ core swap), and `DacDeviceRegistry.rebuild` is synchronous by design.
127
+ During startup the hook only stores: `initialize` rebuilds once from
128
+ the final merged settings to avoid opening every device twice.
129
+
130
+ A registry-wide failure propagates, which the framework reports as a
131
+ failed apply. Per-device failures never propagate: `rebuild` records
132
+ them, logs each at ERROR, and leaves the apply successful. Re-logging
133
+ them here would duplicate that line on every apply.
134
+ """
135
+ if not self._startup_complete:
136
+ self._settings = settings
137
+ return
138
+ self._devices.rebuild(settings)
139
+ self._settings = settings
140
+
141
+ @Manager(name="Telemetry")
142
+ async def telemetry_loop(self) -> None:
143
+ """Publish device telemetry to Valkey once per iteration.
144
+
145
+ The manager runtime repeats this body forever with auto-restart on
146
+ error. The write is guarded on `self.client` and runs even before the
147
+ first configuration, so the UI observes ``configured=false``. Glide
148
+ errors are logged at WARNING and reported to the transport health,
149
+ which drives the reconnect — matching the heartbeat's error handling.
150
+
151
+ The snapshot never touches the bus, unlike the ADC one: DAC channel
152
+ state comes from the registry's last-written cache and the unit from a
153
+ live channel object, so a tick cannot interfere with a write.
154
+ """
155
+ client = self.client
156
+ if client is not None:
157
+ payload = build_telemetry(
158
+ self._settings,
159
+ self._devices,
160
+ service=self.service_name,
161
+ instance_id=self.instance_id,
162
+ )
163
+ try:
164
+ await client.set(
165
+ self._telemetry_key,
166
+ value=self._telemetry_encoder.encode(payload),
167
+ expiry=ExpirySet(ExpiryType.SEC, TELEMETRY_TTL),
168
+ )
169
+ except (GlideConnectionError, RequestError, GlideTimeoutError) as exc:
170
+ self.logger.log(logging.WARNING, "Failed to publish DAC telemetry: %s", exc)
171
+ self._health.report_failure(exc)
172
+ await asyncio.sleep(TELEMETRY_INTERVAL)