scietex.hal.current-amplifier 0.3.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.
- scietex/hal/current_amplifier/__init__.py +10 -0
- scietex/hal/current_amplifier/base/__init__.py +71 -0
- scietex/hal/current_amplifier/base/capabilities.py +541 -0
- scietex/hal/current_amplifier/base/data.py +88 -0
- scietex/hal/current_amplifier/base/errors.py +47 -0
- scietex/hal/current_amplifier/base/protocol.py +411 -0
- scietex/hal/current_amplifier/py.typed +0 -0
- scietex/hal/current_amplifier/registry.py +66 -0
- scietex/hal/current_amplifier/scietex/__init__.py +5 -0
- scietex/hal/current_amplifier/scietex/ebic/__init__.py +5 -0
- scietex/hal/current_amplifier/scietex/ebic/modbus/__init__.py +5 -0
- scietex/hal/current_amplifier/scietex/ebic/modbus/v1/__init__.py +38 -0
- scietex/hal/current_amplifier/scietex/ebic/modbus/v1/client.py +497 -0
- scietex/hal/current_amplifier/scietex/ebic/modbus/v1/constants.py +108 -0
- scietex/hal/current_amplifier/scietex/ebic/modbus/v1/identity.py +80 -0
- scietex/hal/current_amplifier/scietex/ebic/modbus/v1/relaymap.py +347 -0
- scietex/hal/current_amplifier/scietex/ebic/modbus/v1/semantic.py +690 -0
- scietex/hal/current_amplifier/version.py +1 -0
- scietex_hal_current_amplifier-0.3.0.dist-info/METADATA +393 -0
- scietex_hal_current_amplifier-0.3.0.dist-info/RECORD +24 -0
- scietex_hal_current_amplifier-0.3.0.dist-info/WHEEL +5 -0
- scietex_hal_current_amplifier-0.3.0.dist-info/entry_points.txt +3 -0
- scietex_hal_current_amplifier-0.3.0.dist-info/licenses/LICENSE +21 -0
- scietex_hal_current_amplifier-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,690 @@
|
|
|
1
|
+
"""Semantic current-amplifier layer over the EBIC v1.0 relay driver.
|
|
2
|
+
|
|
3
|
+
The raw driver speaks coil indices; the firmware gives those coils no meaning.
|
|
4
|
+
This module owns the relay-to-function map and turns coil levels into the
|
|
5
|
+
current amplifier contract: feedback resistor, boost gain, DC bias, input
|
|
6
|
+
compensation and a state snapshot. Every write is validated before any bus
|
|
7
|
+
traffic. ``Rf`` changes are make-before-break: the target resistor engages
|
|
8
|
+
before the old one releases, so the write order never commands the pre-amp
|
|
9
|
+
feedback loop open and the transimpedance stage is not deliberately left to
|
|
10
|
+
saturate against its output clamp. The driver also waits ``relay_settle_s``
|
|
11
|
+
after the make write — :data:`DEFAULT_RELAY_SETTLE_S` by default, sized from the
|
|
12
|
+
IM03 operate and bounce maxima — so the new relay is closed before the channel
|
|
13
|
+
switch and before the old relay leaves. The physical overlap is therefore
|
|
14
|
+
deterministic rather than a function of relay operate and release times. Two
|
|
15
|
+
``Rf`` of one bank share both terminals, so the transient parallel pair is
|
|
16
|
+
electrically defined. Booster gain changes follow the same
|
|
17
|
+
engage-before-release order with the same settle delay: the gain relays switch
|
|
18
|
+
parallel ``Rg`` resistors of an instrumentation amplifier, so a transiently
|
|
19
|
+
closed pair forms a higher gain, ``G1 + G2 - 1``, rather than an intermediate
|
|
20
|
+
one. ``Rg`` open is exactly unity gain, so the booster cannot saturate in
|
|
21
|
+
either state. The readback still codes a gain one-hot, so a closed pair decodes
|
|
22
|
+
to an undefined gain until the old relay releases. The active channel therefore
|
|
23
|
+
always has at least one engaged ``Rf``: exactly one at rest, transiently two
|
|
24
|
+
during a same-bank swap, never zero.
|
|
25
|
+
|
|
26
|
+
The relay map records the firmware's relay-3 correspondence: ``OUT2`` is the
|
|
27
|
+
low-Z output and ``OUT1`` the high-Z output. The firmware calls relay 3
|
|
28
|
+
independent, so steering it is a driver policy rather than a hardware
|
|
29
|
+
constraint: every channel selection also routes the selected channel's stage-1
|
|
30
|
+
output to the booster, so the amplifier never boosts the unselected channel.
|
|
31
|
+
:meth:`EBICModbusV1Amplifier.set_booster_source` overrides that choice
|
|
32
|
+
explicitly.
|
|
33
|
+
|
|
34
|
+
The layer is a :class:`CurrentAmplifierProtocol` implementation. Its
|
|
35
|
+
capabilities declare the selectable controls the map now fixes; the raw driver
|
|
36
|
+
keeps declaring only static geometry because it exposes coils rather than
|
|
37
|
+
functions.
|
|
38
|
+
|
|
39
|
+
Classes:
|
|
40
|
+
RelayAccess: The relay operations the semantic layer needs from a transport.
|
|
41
|
+
RelayTransitionError: A relay could not be driven to the requested state.
|
|
42
|
+
EBICModbusV1Amplifier: The EBIC v1.0 amplifier driver.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
import asyncio
|
|
46
|
+
import math
|
|
47
|
+
from collections.abc import Callable, Iterable
|
|
48
|
+
from logging import Logger
|
|
49
|
+
from typing import ClassVar, Protocol
|
|
50
|
+
|
|
51
|
+
from scietex.hal.serial import (
|
|
52
|
+
ModbusSerialConnectionConfig,
|
|
53
|
+
SerialConnectionConfig,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
from .....base import (
|
|
57
|
+
Access,
|
|
58
|
+
AmplifierState,
|
|
59
|
+
BoostCapabilities,
|
|
60
|
+
CompensationCapabilities,
|
|
61
|
+
CurrentAmplifierCapabilities,
|
|
62
|
+
CurrentAmplifierProtocol,
|
|
63
|
+
DcBiasCapabilities,
|
|
64
|
+
IndicationCapabilities,
|
|
65
|
+
OutputVoltageCapabilities,
|
|
66
|
+
PreampCapabilities,
|
|
67
|
+
SelectableCapabilities,
|
|
68
|
+
UnexpectedResponse,
|
|
69
|
+
)
|
|
70
|
+
from .client import EBICModbusV1Preamp
|
|
71
|
+
from .constants import DEFAULT_SLAVE_ADDRESS
|
|
72
|
+
from .relaymap import (
|
|
73
|
+
BOOSTER_COILS,
|
|
74
|
+
CHANNEL_COILS,
|
|
75
|
+
GAIN_RELAY,
|
|
76
|
+
RF_CHANNEL,
|
|
77
|
+
RF_OHMS,
|
|
78
|
+
RF_RELAY,
|
|
79
|
+
BiasCompensationSource,
|
|
80
|
+
Relay,
|
|
81
|
+
RelayReadback,
|
|
82
|
+
coil_index,
|
|
83
|
+
coil_level,
|
|
84
|
+
decode_coils,
|
|
85
|
+
engaged_relays,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
_BOOST_GAINS: tuple[float, ...] = (1.0, 3.0, 10.0, 30.0)
|
|
89
|
+
"""The four booster gains, the domain of :meth:`EBICModbusV1Amplifier.set_boost_gain`."""
|
|
90
|
+
|
|
91
|
+
# The board uses TE/AXICOM IM03 relays (2 form C, monostable, 5 VDC coil). TE
|
|
92
|
+
# datasheet 108-98001 Rev. M, "Contact Data", gives an operate time of max 3 ms
|
|
93
|
+
# and a contact bounce time of max 5 ms, so a coil is reliably closed only 8 ms
|
|
94
|
+
# after it is driven. The optional coil-suppression diode delays release, which
|
|
95
|
+
# widens a make-before-break overlap, so it does not raise this floor.
|
|
96
|
+
DEFAULT_RELAY_SETTLE_S: float = 0.008
|
|
97
|
+
"""Default delay after a make write before the writes that depend on it, in seconds."""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class _SettleBarrier:
|
|
101
|
+
"""Marker a step plan places where the relay settle delay belongs."""
|
|
102
|
+
|
|
103
|
+
__slots__ = ()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
_SETTLE_BARRIER = _SettleBarrier()
|
|
107
|
+
"""The settle barrier singleton; identity, not equality, identifies it in a plan."""
|
|
108
|
+
|
|
109
|
+
_PlanStep = tuple[Relay, bool] | _SettleBarrier
|
|
110
|
+
"""One plan element: a relay write or a settle barrier."""
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class RelayAccess(Protocol):
|
|
114
|
+
"""The relay transport the semantic layer drives.
|
|
115
|
+
|
|
116
|
+
The raw :class:`EBICModbusV1Preamp` satisfies this structurally, and so does
|
|
117
|
+
an in-memory fake. A relay level is a raw coil value, not a feature state:
|
|
118
|
+
polarity belongs to the relay map, not to the transport.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
async def connect(self) -> None:
|
|
122
|
+
"""Open the transport."""
|
|
123
|
+
...
|
|
124
|
+
|
|
125
|
+
async def close(self) -> None:
|
|
126
|
+
"""Close the transport."""
|
|
127
|
+
...
|
|
128
|
+
|
|
129
|
+
async def read_relays(self) -> tuple[bool, ...]:
|
|
130
|
+
"""Return all seventeen relay levels in coil order."""
|
|
131
|
+
...
|
|
132
|
+
|
|
133
|
+
async def set_relay(self, index: int, state: bool) -> None:
|
|
134
|
+
"""Drive one relay to a raw coil level."""
|
|
135
|
+
...
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class RelayTransitionError(RuntimeError):
|
|
139
|
+
"""Raised when a relay transition does not reach the requested state.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
operation: The operation that was in flight, such as
|
|
143
|
+
``"select feedback resistor"``.
|
|
144
|
+
failed_coil: The coil whose write raised, or ``None`` when every write
|
|
145
|
+
succeeded but the readback disagreed with the target vector.
|
|
146
|
+
target: The coil vector the operation was driving toward. When a write
|
|
147
|
+
failed it includes the coils already written and the one that
|
|
148
|
+
failed, not the steps that were never attempted.
|
|
149
|
+
observed: The best-effort readback after a failed write, or the
|
|
150
|
+
disagreeing readback after a successful sequence. ``None`` when the
|
|
151
|
+
quiet readback itself failed.
|
|
152
|
+
|
|
153
|
+
Attributes:
|
|
154
|
+
operation (str): The operation that was in flight.
|
|
155
|
+
failed_coil (int | None): The failing coil, or ``None`` for a post-write
|
|
156
|
+
verification mismatch.
|
|
157
|
+
target (tuple[bool, ...]): The intended coil vector.
|
|
158
|
+
observed (tuple[bool, ...] | None): The readback, when one was obtained.
|
|
159
|
+
"""
|
|
160
|
+
|
|
161
|
+
operation: str
|
|
162
|
+
failed_coil: int | None
|
|
163
|
+
target: tuple[bool, ...]
|
|
164
|
+
observed: tuple[bool, ...] | None
|
|
165
|
+
|
|
166
|
+
def __init__(
|
|
167
|
+
self,
|
|
168
|
+
operation: str,
|
|
169
|
+
failed_coil: int | None,
|
|
170
|
+
target: tuple[bool, ...],
|
|
171
|
+
observed: tuple[bool, ...] | None,
|
|
172
|
+
) -> None:
|
|
173
|
+
self.operation = operation
|
|
174
|
+
self.failed_coil = failed_coil
|
|
175
|
+
self.target = target
|
|
176
|
+
self.observed = observed
|
|
177
|
+
if failed_coil is None:
|
|
178
|
+
detail = "post-write verification mismatch"
|
|
179
|
+
else:
|
|
180
|
+
detail = f"writing coil {failed_coil} failed"
|
|
181
|
+
super().__init__(
|
|
182
|
+
f"{operation}: {detail}; target={target!r}, observed={observed!r}"
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class EBICModbusV1Amplifier(CurrentAmplifierProtocol):
|
|
187
|
+
"""Current amplifier contract over the EBIC v1.0 relay board.
|
|
188
|
+
|
|
189
|
+
The driver maps the eight feedback resistors, the four booster gains, the
|
|
190
|
+
bias enable, the compensation enable and the two source selectors onto the
|
|
191
|
+
relay map. It reports the four readable functions in
|
|
192
|
+
:meth:`read_data`; every quantity the board cannot measure stays ``None``.
|
|
193
|
+
|
|
194
|
+
Attributes:
|
|
195
|
+
capabilities: The selectable controls the relay map fixes, plus the
|
|
196
|
+
board's static output range and present-but-unreadable Overcurrent
|
|
197
|
+
comparator.
|
|
198
|
+
relays: The relay transport every operation is forwarded to.
|
|
199
|
+
relay_settle_s: The delay inserted after a make write before the writes
|
|
200
|
+
that depend on it, in seconds.
|
|
201
|
+
"""
|
|
202
|
+
|
|
203
|
+
capabilities: ClassVar[CurrentAmplifierCapabilities] = CurrentAmplifierCapabilities(
|
|
204
|
+
preamp=PreampCapabilities(
|
|
205
|
+
feedback_resistor=SelectableCapabilities(
|
|
206
|
+
access=Access(read=True, write=True),
|
|
207
|
+
options=RF_OHMS,
|
|
208
|
+
),
|
|
209
|
+
max_output_v=5.0,
|
|
210
|
+
),
|
|
211
|
+
boost=BoostCapabilities(
|
|
212
|
+
gain=SelectableCapabilities(
|
|
213
|
+
access=Access(read=True, write=True),
|
|
214
|
+
options=_BOOST_GAINS,
|
|
215
|
+
),
|
|
216
|
+
default_gain=1.0,
|
|
217
|
+
),
|
|
218
|
+
output_voltage=OutputVoltageCapabilities(min_v=-10.0, max_v=10.0),
|
|
219
|
+
dc_bias=DcBiasCapabilities(enabled=Access(read=True, write=True)),
|
|
220
|
+
input_compensation=CompensationCapabilities(
|
|
221
|
+
enabled=Access(read=True, write=True)
|
|
222
|
+
),
|
|
223
|
+
input_overcurrent=IndicationCapabilities(present=True, read=False),
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
relays: RelayAccess
|
|
227
|
+
relay_settle_s: float
|
|
228
|
+
_write_lock: asyncio.Lock
|
|
229
|
+
|
|
230
|
+
# The signature mirrors the raw driver's four parameters and adds the
|
|
231
|
+
# injected transport and the settle delay keyword-only, which a driver that
|
|
232
|
+
# can run without a serial port needs.
|
|
233
|
+
def __init__( # noqa: PLR0913
|
|
234
|
+
self,
|
|
235
|
+
con_params: SerialConnectionConfig | ModbusSerialConnectionConfig | None = None,
|
|
236
|
+
address: int = DEFAULT_SLAVE_ADDRESS,
|
|
237
|
+
label: str = "EBIC Preamp",
|
|
238
|
+
logger: Logger | None = None,
|
|
239
|
+
*,
|
|
240
|
+
relay_driver: RelayAccess | None = None,
|
|
241
|
+
relay_settle_s: float = DEFAULT_RELAY_SETTLE_S,
|
|
242
|
+
) -> None:
|
|
243
|
+
"""
|
|
244
|
+
Initialize the amplifier.
|
|
245
|
+
|
|
246
|
+
Args:
|
|
247
|
+
con_params: Serial port and framing configuration. Ignored when
|
|
248
|
+
``relay_driver`` is given.
|
|
249
|
+
address: Modbus slave address the raw driver answers at.
|
|
250
|
+
label: Human-readable label used by the raw driver in log messages.
|
|
251
|
+
logger: Optional logger for raw transport diagnostics.
|
|
252
|
+
relay_driver: A relay transport to drive instead of opening a serial
|
|
253
|
+
port. An in-memory fake uses this path.
|
|
254
|
+
relay_settle_s: Seconds to wait after a make write before the writes
|
|
255
|
+
that depend on it. ``0`` disables the wait.
|
|
256
|
+
|
|
257
|
+
Raises:
|
|
258
|
+
TypeError: If neither ``con_params`` nor ``relay_driver`` is given,
|
|
259
|
+
since there is then no transport to drive.
|
|
260
|
+
ValueError: If ``relay_settle_s`` is negative or not a number, before
|
|
261
|
+
any bus traffic.
|
|
262
|
+
"""
|
|
263
|
+
# The comparison is written so that a NaN settle time fails it too.
|
|
264
|
+
if not relay_settle_s >= 0:
|
|
265
|
+
raise ValueError(
|
|
266
|
+
f"relay_settle_s must be a non-negative number, got {relay_settle_s!r}"
|
|
267
|
+
)
|
|
268
|
+
if relay_driver is None:
|
|
269
|
+
if con_params is None:
|
|
270
|
+
raise TypeError("con_params or relay_driver is required")
|
|
271
|
+
# The raw driver implements the relay layer and inherits the
|
|
272
|
+
# contract's unimplemented stubs, so a type checker sees it as
|
|
273
|
+
# abstract even though the stubs raise only when called. It is the
|
|
274
|
+
# documented transport for this layer.
|
|
275
|
+
relay_driver = EBICModbusV1Preamp( # ty: ignore[abstract-class-instantiation]
|
|
276
|
+
con_params=con_params,
|
|
277
|
+
address=address,
|
|
278
|
+
label=label,
|
|
279
|
+
logger=logger,
|
|
280
|
+
)
|
|
281
|
+
self.relays = relay_driver
|
|
282
|
+
self.relay_settle_s = relay_settle_s
|
|
283
|
+
self._write_lock = asyncio.Lock()
|
|
284
|
+
|
|
285
|
+
async def connect(self) -> None:
|
|
286
|
+
"""Open the relay transport."""
|
|
287
|
+
await self.relays.connect()
|
|
288
|
+
|
|
289
|
+
async def close(self) -> None:
|
|
290
|
+
"""Close the relay transport."""
|
|
291
|
+
await self.relays.close()
|
|
292
|
+
|
|
293
|
+
# -- state -------------------------------------------------------------
|
|
294
|
+
|
|
295
|
+
async def read_data(self) -> AmplifierState:
|
|
296
|
+
"""
|
|
297
|
+
Return the function state one coil readback encodes.
|
|
298
|
+
|
|
299
|
+
The board reports no output voltage, current or status value, so every
|
|
300
|
+
field beyond the four relay-backed functions stays ``None`` and the
|
|
301
|
+
filter tuple stays empty. ``None`` is not zero and not ``False``: a
|
|
302
|
+
quantity the board cannot measure is unknown, not idle.
|
|
303
|
+
|
|
304
|
+
Returns:
|
|
305
|
+
AmplifierState: The decoded snapshot. A readback whose ``Rf`` or
|
|
306
|
+
gain coding is ambiguous yields ``None`` for that field instead of
|
|
307
|
+
raising.
|
|
308
|
+
"""
|
|
309
|
+
readback = await self._readback()
|
|
310
|
+
return AmplifierState(
|
|
311
|
+
boost_gain=readback.boost_gain,
|
|
312
|
+
feedback_resistor_ohm=readback.feedback_resistor_ohm,
|
|
313
|
+
dc_bias_enabled=readback.dc_bias_enabled,
|
|
314
|
+
input_compensation_enabled=readback.input_compensation_enabled,
|
|
315
|
+
filters=(),
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
async def get_feedback_resistor(self) -> float:
|
|
319
|
+
"""
|
|
320
|
+
Read the selected feedback resistor.
|
|
321
|
+
|
|
322
|
+
Returns:
|
|
323
|
+
float: Resistance in ohm.
|
|
324
|
+
|
|
325
|
+
Raises:
|
|
326
|
+
UnexpectedResponse: If the readback does not name exactly one
|
|
327
|
+
resistor of the selected channel.
|
|
328
|
+
"""
|
|
329
|
+
state = await self.read_data()
|
|
330
|
+
if state.feedback_resistor_ohm is None:
|
|
331
|
+
raise UnexpectedResponse(
|
|
332
|
+
"feedback resistor",
|
|
333
|
+
"the relay readback selects no single resistor of the active channel",
|
|
334
|
+
)
|
|
335
|
+
return state.feedback_resistor_ohm
|
|
336
|
+
|
|
337
|
+
async def get_boost_gain(self) -> float:
|
|
338
|
+
"""
|
|
339
|
+
Read the booster gain.
|
|
340
|
+
|
|
341
|
+
Returns:
|
|
342
|
+
float: The dimensionless gain, ``1.0`` when no gain relay is engaged.
|
|
343
|
+
|
|
344
|
+
Raises:
|
|
345
|
+
UnexpectedResponse: If the gain coding is ambiguous.
|
|
346
|
+
"""
|
|
347
|
+
state = await self.read_data()
|
|
348
|
+
if state.boost_gain is None:
|
|
349
|
+
raise UnexpectedResponse(
|
|
350
|
+
"boost gain",
|
|
351
|
+
"the gain relays are not one-hot, so the gain is undefined",
|
|
352
|
+
)
|
|
353
|
+
return state.boost_gain
|
|
354
|
+
|
|
355
|
+
async def get_dc_bias(self) -> bool:
|
|
356
|
+
"""
|
|
357
|
+
Read the DC bias injection state.
|
|
358
|
+
|
|
359
|
+
Returns:
|
|
360
|
+
bool: Whether bias injection is on.
|
|
361
|
+
|
|
362
|
+
Raises:
|
|
363
|
+
UnexpectedResponse: If the snapshot reports no bias state.
|
|
364
|
+
"""
|
|
365
|
+
state = await self.read_data()
|
|
366
|
+
if state.dc_bias_enabled is None:
|
|
367
|
+
raise UnexpectedResponse("dc bias", "no bias state in the snapshot")
|
|
368
|
+
return state.dc_bias_enabled
|
|
369
|
+
|
|
370
|
+
async def get_input_compensation(self) -> bool:
|
|
371
|
+
"""
|
|
372
|
+
Read the input-capacitance compensation state.
|
|
373
|
+
|
|
374
|
+
Returns:
|
|
375
|
+
bool: Whether compensation is on.
|
|
376
|
+
|
|
377
|
+
Raises:
|
|
378
|
+
UnexpectedResponse: If the snapshot reports no compensation state.
|
|
379
|
+
"""
|
|
380
|
+
state = await self.read_data()
|
|
381
|
+
if state.input_compensation_enabled is None:
|
|
382
|
+
raise UnexpectedResponse(
|
|
383
|
+
"input compensation", "no compensation state in the snapshot"
|
|
384
|
+
)
|
|
385
|
+
return state.input_compensation_enabled
|
|
386
|
+
|
|
387
|
+
# -- contract writes ---------------------------------------------------
|
|
388
|
+
|
|
389
|
+
async def select_feedback_resistor(self, resistance_ohm: float) -> None:
|
|
390
|
+
"""
|
|
391
|
+
Select one feedback resistor.
|
|
392
|
+
|
|
393
|
+
A change engages the target resistor before it releases the old one, so
|
|
394
|
+
the active channel always keeps a feedback path. The driver then waits
|
|
395
|
+
``relay_settle_s`` before the channel relays switch and the booster
|
|
396
|
+
source is steered, so the new relay has settled before the channel write
|
|
397
|
+
moves the circuit onto it. A cross-bank change therefore hands the loop
|
|
398
|
+
to a closed resistor, and the old resistor releases only after that. The
|
|
399
|
+
transient parallel pair holds the loop closed in the meantime.
|
|
400
|
+
|
|
401
|
+
Args:
|
|
402
|
+
resistance_ohm: One of ``RF_OHMS``, in ohm.
|
|
403
|
+
|
|
404
|
+
Raises:
|
|
405
|
+
ValueError: If the value is not a finite whole-numbered one of the
|
|
406
|
+
eight resistors, before any bus traffic.
|
|
407
|
+
RelayTransitionError: If a relay write or the post-write readback
|
|
408
|
+
does not reach the target vector.
|
|
409
|
+
"""
|
|
410
|
+
resistance = _feedback_resistance(resistance_ohm)
|
|
411
|
+
|
|
412
|
+
def plan(current: tuple[bool, ...]) -> list[_PlanStep]:
|
|
413
|
+
return self._feedback_steps(resistance, current)
|
|
414
|
+
|
|
415
|
+
await self._transition("select feedback resistor", plan)
|
|
416
|
+
|
|
417
|
+
async def set_boost_gain(self, gain: float) -> None:
|
|
418
|
+
"""
|
|
419
|
+
Set the booster gain.
|
|
420
|
+
|
|
421
|
+
A change engages the target gain relay before it releases the old one,
|
|
422
|
+
and the driver waits ``relay_settle_s`` in between, so the new relay is
|
|
423
|
+
settled before the old one leaves. The gain relays switch parallel
|
|
424
|
+
``Rg`` elements, so the transient pair overshoots upward to
|
|
425
|
+
``G1 + G2 - 1``: a ``×10`` ↔ ``×30`` change reaches about ``×39`` while
|
|
426
|
+
the incoming relay settles. Unity selects no relay, so moving to it only
|
|
427
|
+
releases the engaged one and never forms a pair. A failed release leaves
|
|
428
|
+
the pair engaged, which decodes as an undefined gain until the old relay
|
|
429
|
+
is released.
|
|
430
|
+
|
|
431
|
+
Args:
|
|
432
|
+
gain: One of ``1.0``, ``3.0``, ``10.0`` or ``30.0``.
|
|
433
|
+
|
|
434
|
+
Raises:
|
|
435
|
+
ValueError: If the gain is not one the board selects, before any bus
|
|
436
|
+
traffic.
|
|
437
|
+
RelayTransitionError: If a relay write or the post-write readback
|
|
438
|
+
does not reach the target vector.
|
|
439
|
+
"""
|
|
440
|
+
if gain not in GAIN_RELAY:
|
|
441
|
+
raise ValueError(
|
|
442
|
+
f"unsupported boost gain {gain!r}; expected one of "
|
|
443
|
+
f"{', '.join(str(value) for value in _BOOST_GAINS)}"
|
|
444
|
+
)
|
|
445
|
+
target = GAIN_RELAY[gain]
|
|
446
|
+
|
|
447
|
+
def plan(current: tuple[bool, ...]) -> list[_PlanStep]:
|
|
448
|
+
steps: list[_PlanStep] = []
|
|
449
|
+
if target is not None:
|
|
450
|
+
steps.append((target, coil_level(target, True)))
|
|
451
|
+
if target not in engaged_relays(current):
|
|
452
|
+
steps.append(_SETTLE_BARRIER)
|
|
453
|
+
for relay in (Relay.GAIN_X3, Relay.GAIN_X10, Relay.GAIN_X30):
|
|
454
|
+
if relay is not target:
|
|
455
|
+
steps.append((relay, coil_level(relay, False)))
|
|
456
|
+
return steps
|
|
457
|
+
|
|
458
|
+
await self._transition("set boost gain", plan)
|
|
459
|
+
|
|
460
|
+
async def set_dc_bias(self, enabled: bool) -> None:
|
|
461
|
+
"""
|
|
462
|
+
Switch DC bias injection on or off.
|
|
463
|
+
|
|
464
|
+
Args:
|
|
465
|
+
enabled: Whether to turn bias injection on.
|
|
466
|
+
|
|
467
|
+
Raises:
|
|
468
|
+
RelayTransitionError: If a relay write or the post-write readback
|
|
469
|
+
does not reach the target vector.
|
|
470
|
+
"""
|
|
471
|
+
|
|
472
|
+
def plan(_current: tuple[bool, ...]) -> list[tuple[Relay, bool]]:
|
|
473
|
+
return [(Relay.BIAS_ENABLE, coil_level(Relay.BIAS_ENABLE, enabled))]
|
|
474
|
+
|
|
475
|
+
await self._transition("set dc bias", plan)
|
|
476
|
+
|
|
477
|
+
async def set_input_compensation(self, enabled: bool) -> None:
|
|
478
|
+
"""
|
|
479
|
+
Switch input-capacitance compensation on or off.
|
|
480
|
+
|
|
481
|
+
Args:
|
|
482
|
+
enabled: Whether to turn compensation on.
|
|
483
|
+
|
|
484
|
+
Raises:
|
|
485
|
+
RelayTransitionError: If a relay write or the post-write readback
|
|
486
|
+
does not reach the target vector.
|
|
487
|
+
"""
|
|
488
|
+
|
|
489
|
+
def plan(_current: tuple[bool, ...]) -> list[tuple[Relay, bool]]:
|
|
490
|
+
return [
|
|
491
|
+
(
|
|
492
|
+
Relay.COMPENSATION_ENABLE,
|
|
493
|
+
coil_level(Relay.COMPENSATION_ENABLE, enabled),
|
|
494
|
+
)
|
|
495
|
+
]
|
|
496
|
+
|
|
497
|
+
await self._transition("set input compensation", plan)
|
|
498
|
+
|
|
499
|
+
# -- non-contract extensions ------------------------------------------
|
|
500
|
+
|
|
501
|
+
async def get_bias_compensation_source(self) -> BiasCompensationSource:
|
|
502
|
+
"""
|
|
503
|
+
Read the source relay 13 selects for bias and compensation.
|
|
504
|
+
|
|
505
|
+
This is not a ``CurrentAmplifierProtocol`` member: the capability model
|
|
506
|
+
has no group for the shared source selector.
|
|
507
|
+
|
|
508
|
+
Returns:
|
|
509
|
+
BiasCompensationSource: ``DAC`` or ``MANUAL``.
|
|
510
|
+
"""
|
|
511
|
+
return (await self._readback()).bias_compensation_source
|
|
512
|
+
|
|
513
|
+
async def set_bias_compensation_source(
|
|
514
|
+
self, source: BiasCompensationSource
|
|
515
|
+
) -> None:
|
|
516
|
+
"""
|
|
517
|
+
Select the shared bias and compensation source.
|
|
518
|
+
|
|
519
|
+
This is not a ``CurrentAmplifierProtocol`` member: the capability model
|
|
520
|
+
has no group for the shared source selector. ``MANUAL`` is the power-on
|
|
521
|
+
state, so writing it on a fresh board changes nothing.
|
|
522
|
+
|
|
523
|
+
Args:
|
|
524
|
+
source: The source to select.
|
|
525
|
+
|
|
526
|
+
Raises:
|
|
527
|
+
ValueError: If ``source`` names no known source.
|
|
528
|
+
RelayTransitionError: If a relay write or the post-write readback
|
|
529
|
+
does not reach the target vector.
|
|
530
|
+
"""
|
|
531
|
+
selected = BiasCompensationSource(source)
|
|
532
|
+
level = selected is BiasCompensationSource.MANUAL
|
|
533
|
+
|
|
534
|
+
def plan(_current: tuple[bool, ...]) -> list[tuple[Relay, bool]]:
|
|
535
|
+
return [(Relay.BIAS_COMP_SOURCE, level)]
|
|
536
|
+
|
|
537
|
+
await self._transition("set bias compensation source", plan)
|
|
538
|
+
|
|
539
|
+
async def get_booster_source(self) -> bool:
|
|
540
|
+
"""
|
|
541
|
+
Read which preamp output feeds the booster.
|
|
542
|
+
|
|
543
|
+
This is not a ``CurrentAmplifierProtocol`` member: the relay reports the
|
|
544
|
+
selector's raw coil, not a contract quantity.
|
|
545
|
+
|
|
546
|
+
Returns:
|
|
547
|
+
bool: ``True`` when ``OUT2`` feeds the booster, ``False`` for
|
|
548
|
+
``OUT1``.
|
|
549
|
+
"""
|
|
550
|
+
return (await self._readback()).booster_source_coil
|
|
551
|
+
|
|
552
|
+
async def set_booster_source(self, out2: bool) -> None:
|
|
553
|
+
"""
|
|
554
|
+
Select which preamp output feeds the booster.
|
|
555
|
+
|
|
556
|
+
This is not a ``CurrentAmplifierProtocol`` member: the relay reports the
|
|
557
|
+
selector's raw coil, not a contract quantity.
|
|
558
|
+
|
|
559
|
+
Args:
|
|
560
|
+
out2: ``True`` to feed ``OUT2`` to the booster, ``False`` for ``OUT1``.
|
|
561
|
+
|
|
562
|
+
Raises:
|
|
563
|
+
RelayTransitionError: If a relay write or the post-write readback
|
|
564
|
+
does not reach the target vector.
|
|
565
|
+
"""
|
|
566
|
+
|
|
567
|
+
def plan(_current: tuple[bool, ...]) -> list[tuple[Relay, bool]]:
|
|
568
|
+
return [(Relay.BOOST_SOURCE, out2)]
|
|
569
|
+
|
|
570
|
+
await self._transition("set booster source", plan)
|
|
571
|
+
|
|
572
|
+
# -- transition engine -------------------------------------------------
|
|
573
|
+
|
|
574
|
+
def _feedback_steps(
|
|
575
|
+
self, resistance: int, current: tuple[bool, ...]
|
|
576
|
+
) -> list[_PlanStep]:
|
|
577
|
+
"""Return the coil-level steps that select ``resistance`` from ``current``.
|
|
578
|
+
|
|
579
|
+
The target relay is engaged first, followed by a settle barrier, so a
|
|
580
|
+
cross-bank change switches the channel only onto a closed resistor. Every
|
|
581
|
+
other ``Rf`` relay is released after that, so a same-bank swap briefly
|
|
582
|
+
closes the parallel pair and the feedback loop never opens. Only the
|
|
583
|
+
eight ``Rf`` relays are considered for release. Deselecting every
|
|
584
|
+
engaged relay would also switch off bias, gain, compensation and the
|
|
585
|
+
channel selectors.
|
|
586
|
+
"""
|
|
587
|
+
target_relay = RF_RELAY[resistance]
|
|
588
|
+
target_channel = RF_CHANNEL[target_relay]
|
|
589
|
+
|
|
590
|
+
rf_relays = set(RF_RELAY.values())
|
|
591
|
+
engaged_rf = [relay for relay in engaged_relays(current) if relay in rf_relays]
|
|
592
|
+
|
|
593
|
+
steps: list[_PlanStep] = []
|
|
594
|
+
if target_relay not in engaged_rf:
|
|
595
|
+
steps.append((target_relay, coil_level(target_relay, True)))
|
|
596
|
+
steps.append(_SETTLE_BARRIER)
|
|
597
|
+
steps.append((Relay.CHANNEL_SELECT, CHANNEL_COILS[target_channel]))
|
|
598
|
+
steps.append((Relay.DESELECTED_FEEDBACK, CHANNEL_COILS[target_channel]))
|
|
599
|
+
steps.append((Relay.BOOST_SOURCE, BOOSTER_COILS[target_channel]))
|
|
600
|
+
for relay in engaged_rf:
|
|
601
|
+
if relay is not target_relay:
|
|
602
|
+
steps.append((relay, coil_level(relay, False)))
|
|
603
|
+
return steps
|
|
604
|
+
|
|
605
|
+
async def _transition(
|
|
606
|
+
self,
|
|
607
|
+
operation: str,
|
|
608
|
+
plan: Callable[[tuple[bool, ...]], Iterable[_PlanStep]],
|
|
609
|
+
) -> None:
|
|
610
|
+
"""Read once, apply a coil-level plan, then verify the result.
|
|
611
|
+
|
|
612
|
+
``plan`` receives the readback the engine just took, so a plan that
|
|
613
|
+
depends on the current state costs no second bus read. A failed write is
|
|
614
|
+
not retried: the half-applied vector is read back and reported. A settle
|
|
615
|
+
barrier sleeps for ``relay_settle_s`` once a write has landed, and never
|
|
616
|
+
sleeps for a plan that writes nothing or when the delay is zero.
|
|
617
|
+
|
|
618
|
+
Args:
|
|
619
|
+
operation: The operation name carried by a
|
|
620
|
+
:class:`RelayTransitionError`.
|
|
621
|
+
plan: Builds the steps from the current coil vector. Each step is a
|
|
622
|
+
relay and the raw coil level to drive it to, or the settle
|
|
623
|
+
barrier marker.
|
|
624
|
+
|
|
625
|
+
Raises:
|
|
626
|
+
RelayTransitionError: If a write raises or the readback after a
|
|
627
|
+
successful write disagrees with the target vector.
|
|
628
|
+
"""
|
|
629
|
+
async with self._write_lock:
|
|
630
|
+
current = list(await self.relays.read_relays())
|
|
631
|
+
target = list(current)
|
|
632
|
+
wrote = False
|
|
633
|
+
for step in plan(tuple(current)):
|
|
634
|
+
if isinstance(step, _SettleBarrier):
|
|
635
|
+
if wrote and self.relay_settle_s > 0:
|
|
636
|
+
await asyncio.sleep(self.relay_settle_s)
|
|
637
|
+
continue
|
|
638
|
+
relay, level = step
|
|
639
|
+
coil = coil_index(relay)
|
|
640
|
+
if target[coil] == level:
|
|
641
|
+
continue
|
|
642
|
+
target[coil] = level
|
|
643
|
+
try:
|
|
644
|
+
await self.relays.set_relay(coil, level)
|
|
645
|
+
wrote = True
|
|
646
|
+
except Exception as exc:
|
|
647
|
+
raise RelayTransitionError(
|
|
648
|
+
operation,
|
|
649
|
+
coil,
|
|
650
|
+
tuple(target),
|
|
651
|
+
await self._read_quietly(),
|
|
652
|
+
) from exc
|
|
653
|
+
if wrote:
|
|
654
|
+
observed = tuple(await self.relays.read_relays())
|
|
655
|
+
if observed != tuple(target):
|
|
656
|
+
raise RelayTransitionError(operation, None, tuple(target), observed)
|
|
657
|
+
|
|
658
|
+
async def _readback(self) -> RelayReadback:
|
|
659
|
+
"""Read the coils once and decode them."""
|
|
660
|
+
return decode_coils(await self.relays.read_relays())
|
|
661
|
+
|
|
662
|
+
async def _read_quietly(self) -> tuple[bool, ...] | None:
|
|
663
|
+
"""Read the coils after a failed write, swallowing a second failure."""
|
|
664
|
+
try:
|
|
665
|
+
return tuple(await self.relays.read_relays())
|
|
666
|
+
except Exception:
|
|
667
|
+
return None
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
def _feedback_resistance(resistance_ohm: float) -> int:
|
|
671
|
+
"""Validate a feedback resistance and return its integer ohm key.
|
|
672
|
+
|
|
673
|
+
Raises:
|
|
674
|
+
ValueError: If the value is not finite, is not a whole number of ohm, or
|
|
675
|
+
names no resistor on the board.
|
|
676
|
+
"""
|
|
677
|
+
if not math.isfinite(resistance_ohm):
|
|
678
|
+
options = ", ".join(str(int(ohm)) for ohm in RF_OHMS)
|
|
679
|
+
raise ValueError(
|
|
680
|
+
f"feedback resistor must be finite, got {resistance_ohm!r}; "
|
|
681
|
+
f"expected one of {options} ohm"
|
|
682
|
+
)
|
|
683
|
+
value = int(resistance_ohm)
|
|
684
|
+
if value != resistance_ohm or value not in RF_RELAY:
|
|
685
|
+
options = ", ".join(str(int(ohm)) for ohm in RF_OHMS)
|
|
686
|
+
raise ValueError(
|
|
687
|
+
f"unsupported feedback resistor {resistance_ohm!r} ohm; "
|
|
688
|
+
f"expected one of {options} ohm"
|
|
689
|
+
)
|
|
690
|
+
return value
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.3.0"
|