asyn_rs/port.rs
1//! Port driver base and trait.
2//!
3//! # I/O Model
4//!
5//! Ports are driven by a `PortActor` running on a dedicated thread.
6//! The actor exclusively owns the driver and processes requests from a channel.
7//!
8//! **Cache path** (default `read_*`/`write_*` methods):
9//! - Default implementations operate on the parameter cache (non-blocking).
10//! - Background tasks update cache via `set_*_param()` + `call_param_callbacks()`.
11//!
12//! **Actor path** (requests submitted via [`crate::port_handle::PortHandle`]):
13//! - Each port gets a dedicated actor thread that dispatches requests to driver methods.
14//! - `can_block` indicates the port may perform blocking I/O.
15
16use std::collections::HashMap;
17use std::sync::Arc;
18use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
19use std::time::{Duration, Instant, SystemTime};
20
21use std::any::Any;
22
23/// C `autoConnectDevice` reconnect throttle window (asynManager.c:713).
24/// A disconnected `auto_connect` device is refused a fresh connect attempt
25/// until this much time has elapsed since its last connect/disconnect
26/// transition or attempt, bounding reconnect storms to one attempt per
27/// window.
28const AUTO_CONNECT_THROTTLE: Duration = Duration::from_secs(2);
29
30/// First autonomous connect-retry delay after a port drops. C
31/// `exceptionDisconnect` arms the port's connect timer at `.01` seconds
32/// (asynManager.c:2181-2182), so the reconnect is attempted essentially
33/// immediately and then backs off to [`DEFAULT_SECONDS_BETWEEN_PORT_CONNECT`].
34const CONNECT_RETRY_INITIAL: Duration = Duration::from_millis(10);
35
36/// C `DEFAULT_SECONDS_BETWEEN_PORT_CONNECT` (asynManager.c:48) — the interval
37/// `portConnectProcessCallback` re-arms the connect timer at after a failed
38/// attempt (asynManager.c:3281).
39const DEFAULT_SECONDS_BETWEEN_PORT_CONNECT: Duration = Duration::from_secs(20);
40
41/// Per-address device state for multi-device ports.
42#[derive(Debug, Clone)]
43pub struct DeviceState {
44 pub connected: bool,
45 pub enabled: bool,
46 pub auto_connect: bool,
47 /// Monotonic instant of the last connect/disconnect transition or
48 /// auto-connect attempt for this device — the anchor for the 2s
49 /// reconnect throttle (C `dpCommon.lastConnectDisconnect`). `None`
50 /// mirrors C's zero-initialised timestamp: the first attempt is
51 /// always permitted.
52 pub last_connect_disconnect: Option<Instant>,
53}
54
55impl Default for DeviceState {
56 fn default() -> Self {
57 Self {
58 connected: true,
59 enabled: true,
60 auto_connect: true,
61 last_connect_disconnect: None,
62 }
63 }
64}
65
66/// One device's end-of-string terminators — C's `eosPvt.eosIn` / `eosPvt.eosOut`
67/// (asynInterposeEos.c:44-52), which exist once per (port, addr).
68#[derive(Debug, Clone, Default)]
69pub struct DeviceEos {
70 /// Input EOS sequence (max 2 bytes). Empty = no input EOS detection.
71 pub input: Vec<u8>,
72 /// Output EOS sequence (max 2 bytes). Empty = no output EOS append.
73 pub output: Vec<u8>,
74}
75
76/// The device an EOS hook's `asynUser` selects — the single owner of the rule,
77/// shared by [`PortDriverBase`] and the EOS interpose so the terminator a
78/// `setInputEos` writes is the one the next `read` on that user applies.
79///
80/// C creates the EOS interpose per (port, addr) and every hook takes the
81/// `asynUser` (asynInterposeEos.c:288-296), so on a multi-device port the addr
82/// picks the instance. On a port that never declared `ASYN_MULTIDEVICE` there
83/// are no devices to pick from: `findDpCommon` (asynManager.c:536-544) and
84/// `findInterface` resolve *every* addr to the port itself, so `asynSetEos`
85/// with addr 0 and with addr -1 must reach the same terminator. That collapse
86/// is what the `-1` key below is.
87pub fn eos_device_key(multi_device: bool, addr: i32) -> i32 {
88 dp_common_key(multi_device, addr).unwrap_or(-1)
89}
90
91/// C `findDpCommon` (asynManager.c:538-545) as a key: which `dpCommon` a
92/// `(port, addr)` pair names. `Some(a)` is that device's own slot; `None` is
93/// the port's — C's `!(pport->attributes&ASYN_MULTIDEVICE) || !pdevice` arm,
94/// which a single-device port and a port-level user both take (`connectDevice`
95/// creates a device node only for `addr >= 0`, asynManager.c:1349-1352).
96///
97/// One function for every consumer of the resolution — connection state, the
98/// trace configuration ([`crate::trace`]) and the EOS terminators
99/// ([`eos_device_key`]) — because C asks it once, in `findDpCommon`, and then
100/// reads *every* field off the one struct it returned: `enabled`, `connected`,
101/// `autoConnect`, `numberConnects`, `lastConnectDisconnect` and `trace`
102/// (through `findTracePvt`, :546-551). Separate copies of the rule are how the
103/// trace mask came to be per-device while `enabled` beside it stayed port-wide.
104pub fn dp_common_key(multi_device: bool, addr: i32) -> Option<i32> {
105 (multi_device && addr >= 0).then_some(addr)
106}
107
108use crate::error::{AsynError, AsynResult, AsynStatus};
109use crate::exception::{AsynException, ExceptionEvent, ExceptionManager};
110use crate::interfaces::InterfaceType;
111use crate::interpose::{
112 EomReason, EosSet, OctetInterpose, OctetInterposeStack, OctetNext, OctetReadResult,
113};
114use crate::interrupt::{InterruptManager, InterruptValue, OctetFanOut};
115use crate::param::{EnumEntry, InterruptReason, ParamList, ParamType, ParamValue};
116use crate::trace::TraceManager;
117use crate::user::{AsynUser, ConnectCheck};
118
119/// C asyn `queueRequest` priority. In asyn-rs this exists as compatibility
120/// metadata only — there is no actual request queue or priority-based scheduling.
121/// Drivers manage their own async tasks directly.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
123pub enum QueuePriority {
124 Low = 0,
125 #[default]
126 Medium = 1,
127 High = 2,
128 /// Connect/disconnect operations — processed even when disabled/disconnected.
129 Connect = 3,
130}
131
132/// Port configuration flags.
133#[derive(Debug, Clone, Copy)]
134pub struct PortFlags {
135 /// True if port supports multiple sub-addresses (ASYN_MULTIDEVICE).
136 pub multi_device: bool,
137 /// True if port can block (ASYN_CANBLOCK).
138 ///
139 /// When `true`, the port gets a dedicated worker thread that serializes I/O via a
140 /// priority queue (matching C asyn's per-port thread model).
141 ///
142 /// When `false`, requests execute synchronously inline on the caller's thread
143 /// (no worker thread is spawned). This is appropriate for non-blocking drivers
144 /// whose `io_*` methods return immediately (e.g., cache-based parameter access).
145 pub can_block: bool,
146 /// True if port can be destroyed via shutdown_port (ASYN_DESTRUCTIBLE).
147 pub destructible: bool,
148}
149
150impl Default for PortFlags {
151 fn default() -> Self {
152 // `destructible: false` is the C asyn convention — see
153 // asynDriver.h:97 (`#define ASYN_DESTRUCTIBLE 0x0004`) — the
154 // attribute is opt-in via `pasynManager->registerPort(..., attr)`
155 // and `asynManager::shutdownPort` refuses to act on ports
156 // that did not opt in. Defaulting to `true` here over-applied
157 // shutdown rights to every driver that built PortFlags via
158 // `..PortFlags::default()`.
159 Self {
160 multi_device: false,
161 can_block: false,
162 destructible: false,
163 }
164 }
165}
166
167/// Base state shared by all port drivers.
168/// Contains the parameter library, interrupt manager, and connection state.
169///
170/// # Interpose concurrency
171///
172/// `interpose_octet` requires `&mut self` for all operations (both `push` and
173/// `dispatch_*`). Since `PortDriverBase` is always behind `Arc<Mutex<dyn PortDriver>>`,
174/// any access to `interpose_octet` requires the port lock. This naturally
175/// serializes interpose modifications with I/O dispatch — no additional
176/// synchronization is needed. **Callers must never modify the interpose stack
177/// without holding the port lock.**
178/// Where a port's `connected` truth lives.
179///
180/// `Own` — the port opens and closes its own link (every driver that dials out:
181/// IP, serial, USB-TMC, VXI-11, …), so its own cell is the truth.
182///
183/// `Shared` — the link belongs to another object and this port merely serves it.
184/// C models the case with a real child port whose `connectIt`/`closeConnection`
185/// the *owner* drives (`drvAsynIPServerPort.c:358-360` — the listener calls
186/// `pasynCommonSyncIO->connectDevice` on the child the moment it hands it a
187/// socket). Sharing the owner's cell is the same thing without the round trip,
188/// and it is what makes "the owner holds a live socket, the port says
189/// disconnected" unrepresentable rather than merely unlikely.
190#[derive(Debug, Clone)]
191enum Connection {
192 Own(bool),
193 Shared(Arc<AtomicBool>),
194}
195
196impl Connection {
197 fn get(&self) -> bool {
198 match self {
199 Connection::Own(c) => *c,
200 Connection::Shared(cell) => cell.load(Ordering::Acquire),
201 }
202 }
203}
204
205pub struct PortDriverBase {
206 pub port_name: String,
207 pub max_addr: usize,
208 pub flags: PortFlags,
209 pub params: ParamList,
210 pub interrupts: InterruptManager,
211 /// Whether the port's transport is up — read it with [`Self::is_connected`],
212 /// move it with [`Self::set_connected`].
213 ///
214 /// It is not a plain `bool` because not every port *owns* its link. An
215 /// IP-server child port serves a socket that lives in the parent's
216 /// [`crate::drivers::ip_server_port::ClientSlot`]: the listener assigns and
217 /// clears it, and the child cannot see either edge. A cached copy therefore
218 /// went stale in exactly the way that matters — the slot held a live client
219 /// while the child port still said `asynDisconnected` and refused every
220 /// read and write, forever (R13-50). Such a port shares the owner's cell
221 /// instead of copying it, so that state cannot be constructed.
222 connected: Connection,
223 /// The last value fanned out to listeners. Memory for the edge detector in
224 /// [`Self::sync_connection_edge`], never an answer to "is the port up?" —
225 /// [`Self::is_connected`] is the only thing that answers that, and it reads
226 /// the truth.
227 last_announced: bool,
228 pub enabled: bool,
229 pub auto_connect: bool,
230 /// C `dpCommon.defunct` (asynManager.c:2284) — the port was torn down via
231 /// `shutdownPort` and is gone for good. Read it with [`Self::is_defunct`].
232 ///
233 /// **Invariant: `defunct ⟹ !enabled`.** C establishes it in `shutdownPort`,
234 /// which clears `enabled` *and* sets `defunct` in the same breath (:2283-2284)
235 /// with the comment that disabling is what short-circuits `queueRequest` —
236 /// and indeed `queueRequest` has no defunct branch at all (:1541-1552): a
237 /// defunct port is refused as a *disabled* one, "port %s disabled". C asks
238 /// `defunct` in nine places, and which dpCommon it asks is what our model
239 /// deviates on: `report` (:1041), `findInterface` (:1487),
240 /// `registerInterrupt` (:2424), `getInterruptPvt` (:2475),
241 /// `addInterruptUser` (:2561) and `removeInterruptUser` (:2603) all read
242 /// `pport->dpc.defunct`, while `enable` (:2238, so the port cannot be
243 /// re-enabled), `lockPort` (:1792) and `shutdownPort`'s own idempotence
244 /// check (:2268) read `findDpCommon`'s.
245 ///
246 /// **We model `defunct` at the port, C at whatever dpCommon the shutting-down
247 /// user resolves to, and on a multi-device port that is observably
248 /// different.** `asynShutdownPort` binds at addr 0
249 /// (asynShellCommands.c:1331), so on an `ASYN_MULTIDEVICE` port C flags
250 /// device 0 and never sets `pport->dpc.defunct` at all. Measured against
251 /// libasyn at pin 731d616e, a port registered
252 /// `ASYN_MULTIDEVICE|ASYN_DESTRUCTIBLE` and shut down through an addr-0
253 /// user still answers `isEnabled`=1 at addr -1 and addr 1, still accepts
254 /// `enable` and `lockPort` there, still hands out the interface from
255 /// `findInterface` (with `drvPvt` now NULL — a latent deref, not a
256 /// refusal), and `asynReport` prints the port normally instead of
257 /// "destroyed". Only the single-device case, where `findDpCommon` resolves
258 /// to the port's own dpc, refuses port-wide the way we always do. Taking
259 /// the port down whole is deliberate: the interfaces C nulls belong to the
260 /// port, so the addresses C leaves enabled are enabled onto a driver that
261 /// is gone.
262 ///
263 /// The field is private so [`Self::shutdown_lifecycle`] is the only way to
264 /// set it, which is what makes the invariant hold by construction: nothing can
265 /// build a port that is defunct but still enabled, so no gate needs to ask
266 /// about defunct to refuse it (R15-50).
267 defunct: bool,
268 /// This port's announcement channel — C `dpCommon.exceptionUserList` plus
269 /// the `notifyPortThread` signal that `announceExceptionOccurred` ends with
270 /// (asynManager.c:611-637). Detachable ([`Self::exception_announcer`]) so a
271 /// worker thread the driver owns — the IP-server accept loop — announces
272 /// through the same counter and the same list as the actor does, instead of
273 /// reaching around them.
274 pub(crate) announcer: ExceptionAnnouncer,
275 pub options: HashMap<String, String>,
276 /// The EOS terminators, keyed per device the way C keys them: an `eosPvt`
277 /// is created per `asynInterposeEosConfig(portName, addr, ...)`
278 /// (asynInterposeEos.c:84-120), and every EOS hook takes the `asynUser`
279 /// that selects it (:288-296). Two devices on one multi-device port hold
280 /// two different terminators — a single port-wide pair could not.
281 ///
282 /// Keyed by [`eos_device_key`], so a port that never declared
283 /// `ASYN_MULTIDEVICE` collapses every addr onto one entry (C's
284 /// `findDpCommon`/`findInterface` resolve any addr to the port itself).
285 eos: HashMap<i32, DeviceEos>,
286 pub interpose_octet: OctetInterposeStack,
287 /// Trace configuration — C `dpCommon.trace`, inited by `dpCommonInit`
288 /// (asynManager.c:528). Same
289 /// owner as [`Self::announcer`]: bound by
290 /// [`crate::services::PortServices::bind`] at port creation.
291 pub(crate) trace: Option<Arc<TraceManager>>,
292 /// C `octetPvt.interruptProcess` — the last argument of
293 /// `pasynOctetBase->initialize` (asynOctetBase.c:161-169). When set, every
294 /// successful octet read fans the data out to the port's octet interrupt
295 /// users (`readIt` → `callInterruptUsers`, :224-238). The stream drivers set
296 /// it — drvAsynIPPort.c:1055, drvAsynSerialPort.c:1125-1126,
297 /// drvAsynSerialPortWin32.c:798-799, drvAsynFTDIPort.cpp:616 — and it is what
298 /// makes a `stringin`/`waveform` with `SCAN="I/O Intr"` on such a port
299 /// process at all. Parameter-cache ports (echoDriver, USBTMC, GPIB,
300 /// IP-server) pass 0 and are unaffected.
301 pub octet_interrupt_process: bool,
302 /// Per-address device state for multi-device ports.
303 pub device_states: HashMap<i32, DeviceState>,
304 /// Timestamp source callback for custom timestamps.
305 pub timestamp_source: Option<Arc<dyn Fn() -> SystemTime + Send + Sync>>,
306 /// Port-level anchor for the 2s auto-reconnect throttle — the
307 /// monotonic instant of the last connect/disconnect transition or
308 /// auto-connect attempt (C `dpCommon.lastConnectDisconnect`). `None`
309 /// = no transition yet, so the first attempt is always permitted.
310 pub last_connect_disconnect: Option<Instant>,
311 /// Deadline for the next *autonomous* connect attempt — the Rust
312 /// equivalent of C's per-port `connectTimer` (`port.connectTimer`,
313 /// asynManager.c:223). `None` = disarmed.
314 ///
315 /// Armed by [`Self::set_connected`] on a disconnect (C
316 /// `exceptionDisconnect`, asynManager.c:2181-2182) and re-armed by the
317 /// actor after a failed attempt; cleared on connect. The actor is what
318 /// services it — see `PortActor::service_connect_timer` — so this field
319 /// is the whole handoff between the transition owner and the timer.
320 pub connect_retry_at: Option<Instant>,
321 /// Back-off between failed autonomous connect attempts. C
322 /// `port.secondsBetweenPortConnect`, initialised to
323 /// `DEFAULT_SECONDS_BETWEEN_PORT_CONNECT` = 20 s (asynManager.c:48, 3249)
324 /// and used to re-arm the timer at asynManager.c:3281.
325 pub seconds_between_port_connect: Duration,
326 /// How many times this port's link has come up — C `dpCommon.numberConnects`
327 /// (asynManager.c:150), incremented by `exceptionConnect` (:2158) and printed
328 /// by `asynReport` (:1057-1060). Its owner is
329 /// [`Self::sync_connection_edge`], the same edge owner that raises the
330 /// exception, so a connect that was never published is never counted.
331 pub number_connects: u64,
332}
333
334/// The one way to announce a port exception — C `announceExceptionOccurred`
335/// (asynManager.c:611-637): fan the event out over the port's exception list and
336/// signal `notifyPortThread` (:635-636).
337///
338/// It is a detachable handle rather than a method on [`PortDriverBase`] because
339/// the announcement is not the actor thread's private business: a driver-owned
340/// worker (the IP-server accept loop) also transitions a device, and C's
341/// `connectionListener` thread announces the same way the port thread does. A
342/// clone of this handle is that capability; it carries the wake counter with it,
343/// so an off-thread announcement still wakes the actor
344/// ([`PortDriverBase::exceptions_announced`]).
345#[derive(Clone)]
346pub struct ExceptionAnnouncer {
347 port_name: String,
348 /// Set once by [`crate::services::PortServices::bind`] at port creation, so
349 /// every clone taken afterwards carries the IOC's exception list.
350 sink: Option<Arc<ExceptionManager>>,
351 /// Shared so a clone's announcement is visible to the actor's count.
352 announced: Arc<AtomicU64>,
353}
354
355impl ExceptionAnnouncer {
356 fn new(port_name: &str) -> Self {
357 Self {
358 port_name: port_name.to_string(),
359 sink: None,
360 announced: Arc::new(AtomicU64::new(0)),
361 }
362 }
363
364 /// Announce. A port with no sink still counts the announcement — C's
365 /// fan-out over an empty list still signals the port thread — so the count
366 /// moves before the sink is consulted.
367 pub fn announce(&self, exception: AsynException, addr: i32) {
368 self.announced.fetch_add(1, Ordering::Release);
369 if let Some(ref sink) = self.sink {
370 sink.announce(&ExceptionEvent {
371 port_name: self.port_name.clone(),
372 exception,
373 addr,
374 });
375 }
376 }
377
378 fn count(&self) -> u64 {
379 self.announced.load(Ordering::Acquire)
380 }
381}
382
383impl PortDriverBase {
384 pub fn new(port_name: &str, max_addr: usize, flags: PortFlags) -> Self {
385 Self {
386 port_name: port_name.to_string(),
387 max_addr: max_addr.max(1),
388 flags,
389 params: ParamList::new(max_addr),
390 interrupts: InterruptManager::new(256),
391 connected: Connection::Own(true),
392 last_announced: true,
393 enabled: true,
394 auto_connect: true,
395 defunct: false,
396 announcer: ExceptionAnnouncer::new(port_name),
397 options: HashMap::new(),
398 eos: HashMap::new(),
399 interpose_octet: OctetInterposeStack::new(flags.multi_device),
400 trace: None,
401 octet_interrupt_process: false,
402 device_states: HashMap::new(),
403 timestamp_source: None,
404 last_connect_disconnect: None,
405 connect_retry_at: None,
406 seconds_between_port_connect: DEFAULT_SECONDS_BETWEEN_PORT_CONNECT,
407 number_connects: 0,
408 }
409 }
410
411 /// The EOS entry the given `asynUser` addr selects — see [`eos_device_key`].
412 pub fn eos_key(&self, addr: i32) -> i32 {
413 eos_device_key(self.flags.multi_device, addr)
414 }
415
416 /// This device's input EOS. An addr that has never been configured has an
417 /// empty terminator, C's zero-initialised `eosPvt.eosInLen`.
418 pub fn input_eos(&self, addr: i32) -> &[u8] {
419 self.eos
420 .get(&self.eos_key(addr))
421 .map_or(&[][..], |e| &e.input)
422 }
423
424 /// This device's output EOS (see [`Self::input_eos`]).
425 pub fn output_eos(&self, addr: i32) -> &[u8] {
426 self.eos
427 .get(&self.eos_key(addr))
428 .map_or(&[][..], |e| &e.output)
429 }
430
431 /// Store this device's input terminator in the base's cache — the write
432 /// companion of [`Self::input_eos`], for a driver that implements C's
433 /// `asynOctet::setInputEos` itself instead of leaving it NULL for
434 /// `asynInterposeEos` to serve. A multiDevice port has no choice: C
435 /// refuses to install the interpose there at all (asynOctetBase.c:149-153).
436 pub fn set_input_eos(&mut self, addr: i32, eos: &[u8]) {
437 self.eos_entry(addr).input = eos.to_vec();
438 }
439
440 /// The output half of [`Self::set_input_eos`].
441 pub fn set_output_eos(&mut self, addr: i32, eos: &[u8]) {
442 self.eos_entry(addr).output = eos.to_vec();
443 }
444
445 /// The write owner for this device's terminators — the queryable cache the
446 /// EOS readback (`get_input_eos`, the binary-suppress save/restore) reads.
447 /// The forward to the interpose stack lives in the `PortDriver` hook and in
448 /// the two public setters above.
449 fn eos_entry(&mut self, addr: i32) -> &mut DeviceEos {
450 let key = self.eos_key(addr);
451 self.eos.entry(key).or_default()
452 }
453
454 /// Announce an exception through the global exception manager (if injected).
455 ///
456 /// C `announceExceptionOccurred` (asynManager.c:611-637) ends by signalling
457 /// `notifyPortThread` on a CANBLOCK port (:635-636) — the announcement *is* a
458 /// port-thread wake, which is why `asynEnable(port,1)` on a down port ends in
459 /// a connect attempt. [`Self::exceptions_announced`] is how the actor sees
460 /// that signal, so the count moves here and nowhere else: a port with no
461 /// exception sink still announced (C's fan-out over an empty list still
462 /// signals), so the count is bumped before the sink is even consulted.
463 pub fn announce_exception(&self, exception: AsynException, addr: i32) {
464 self.announcer.announce(exception, addr);
465 }
466
467 /// A clone of this port's announcement capability, for a worker thread the
468 /// driver owns. See [`ExceptionAnnouncer`].
469 pub fn exception_announcer(&self) -> ExceptionAnnouncer {
470 self.announcer.clone()
471 }
472
473 /// Bind the IOC's exception list. [`crate::services::PortServices::bind`] is
474 /// the production caller; tests that drive a driver without a runtime use it
475 /// to stand in for that binding.
476 pub(crate) fn bind_exception_sink(&mut self, sink: Arc<ExceptionManager>) {
477 self.announcer.sink = Some(sink);
478 }
479
480 /// How many exceptions this port has announced. Monotonic; the actor compares
481 /// it against the value it last saw to decide whether C would have signalled
482 /// `notifyPortThread` (asynManager.c:635-636).
483 pub fn exceptions_announced(&self) -> u64 {
484 self.announcer.count()
485 }
486
487 /// How many callbacks are registered on this port's exception list — the
488 /// `exceptionUsers` count `reportPrintPort` prints (asynManager.c:1068-1072).
489 /// `asynReport` itself is the iocsh command (asynShellCommands.c:587); it
490 /// reaches this through `asynManager`'s own `report` (:1136).
491 pub fn exception_callback_count(&self) -> usize {
492 self.announcer
493 .sink
494 .as_ref()
495 .map_or(0, |m| m.callback_count())
496 }
497
498 /// Query whether the port is connected — the truth, wherever it lives.
499 pub fn is_connected(&self) -> bool {
500 self.connected.get()
501 }
502
503 /// The port's initial connection state, set while it is being constructed and
504 /// before it can have a listener. Not a transition: no exception fan-out, no
505 /// retry timer, no `lastConnectDisconnect` stamp. Every *transition* after
506 /// construction goes through [`Self::set_connected`].
507 ///
508 /// A port whose link is owned elsewhere has no initial state of its own to
509 /// set — the owner's cell already holds it — so this is a no-op there rather
510 /// than a silent overwrite of the owner's truth.
511 pub fn init_connected(&mut self, connected: bool) {
512 if let Connection::Own(c) = &mut self.connected {
513 *c = connected;
514 self.last_announced = connected;
515 }
516 }
517
518 /// Bind this port's connection to a cell owned by another object, making that
519 /// cell the port's truth from now on — see [`Connection::Shared`]. Called at
520 /// construction by a port that serves someone else's link (the IP-server
521 /// child port and its `ClientSlot`).
522 pub(crate) fn share_connection(&mut self, cell: Arc<AtomicBool>) {
523 self.last_announced = cell.load(Ordering::Acquire);
524 self.connected = Connection::Shared(cell);
525 }
526
527 /// C `asynPrint(pasynUserSelf, mask, ...)` — the port's own diagnostic
528 /// channel, gated by this port's trace mask and routed to this port's
529 /// trace file.
530 ///
531 /// Public because the drivers that need it are not all in this crate. C's
532 /// drivers are separate modules too (`drvModbusAsyn.cpp`,
533 /// `drvAsynIPPort.c`) and every one of them reports a fault it cannot
534 /// return — a poller has no caller to return to — by `asynPrint`ing it at
535 /// `ASYN_TRACE_ERROR`. With the [`TraceManager`] reachable only inside
536 /// this crate, an out-of-crate driver had no way to say anything at all,
537 /// and the failures it could not return became silent.
538 ///
539 /// A port whose services were never bound has no trace manager and the
540 /// call is a no-op; that is the same port that has no trace file to write
541 /// to and no mask to consult.
542 pub fn trace_print(&self, mask: crate::trace::TraceMask, msg: &str) {
543 if let Some(trace) = &self.trace {
544 trace.output(&self.port_name, mask, msg);
545 }
546 }
547
548 /// Single owner-API for the port-level `connected` transition.
549 ///
550 /// C parity: `exceptionConnect` (asynManager.c:2151-2160) and
551 /// `exceptionDisconnect` (:2174-2185) fire
552 /// `asynExceptionConnect` only when the state actually changes.
553 /// All driver code that toggles connection state MUST go through
554 /// this helper — the `connected` cell is private precisely so that a driver
555 /// cannot assign it and then hand-roll an `announce_exception(Connect, -1)`,
556 /// which bypasses the edge guard and fans spurious duplicates out to
557 /// listeners (CA gateway shadow tasks, asynRecord, monitor relays).
558 ///
559 /// On a port whose link is owned elsewhere (`Connection::Shared`) the write
560 /// is not this port's to make — the owner already moved the truth — so the
561 /// call reduces to publishing whatever edge that produced.
562 ///
563 /// Returns `true` if the state actually changed (a fan-out
564 /// happened); `false` if the call was a no-op.
565 pub fn set_connected(&mut self, connected: bool) -> bool {
566 if let Connection::Own(c) = &mut self.connected {
567 *c = connected;
568 }
569 self.sync_connection_edge()
570 }
571
572 /// Publish the port's connection edge if the truth has moved since the last
573 /// fan-out: the single owner of `exceptionConnect` (asynManager.c:2142-2161)
574 /// and `exceptionDisconnect` (:2165-2188), of the interpose stack's connection
575 /// reset and of the retry timer.
576 ///
577 /// [`Self::set_connected`] is one caller. The other is the actor, on a port
578 /// whose link is owned elsewhere: the owner (an IP-server listener assigning a
579 /// slot) moves the truth without this port's actor running, and C fans that
580 /// edge out from the owner's thread — `pasynCommonSyncIO->connectDevice` on
581 /// the child (drvAsynIPServerPort.c:358-360). Here it is published when the
582 /// child's actor next touches the port, which is the moment it can matter.
583 ///
584 /// Returns `true` if an edge was published.
585 pub fn sync_connection_edge(&mut self) -> bool {
586 let connected = self.connected.get();
587 if self.last_announced == connected {
588 return false;
589 }
590 self.last_announced = connected;
591 if !connected {
592 // C `exceptionDisconnect` stamps `lastConnectDisconnect` on
593 // every disconnect (asynManager.c:2184) so the auto-reconnect
594 // throttle measures from the moment the link dropped.
595 self.last_connect_disconnect = Some(Instant::now());
596 // ...and arms the port's connect timer at .01 s when the port is
597 // auto-connect (asynManager.c:2181-2182), which is what makes the
598 // reconnect *autonomous*: it does not wait for queued traffic.
599 if self.auto_connect {
600 self.connect_retry_at = Some(Instant::now() + CONNECT_RETRY_INITIAL);
601 }
602 } else {
603 // C `exceptionConnect` counts the connects it publishes
604 // (`++pdpCommon->numberConnects`, asynManager.c:2158) — the count
605 // `asynReport` prints, and the operator's only way to see a port that
606 // is flapping. It belongs to this owner because C increments it in the
607 // same function that raises the exception, so a connect that never
608 // fanned out is never counted.
609 self.number_connects += 1;
610 // The link is up — nothing left to retry. (C leaves the timer
611 // running and lets `portConnectTimerCallback` no-op on the
612 // `!connected` guard, asynManager.c:3258; disarming here is the
613 // same observable behaviour without the pointless wakeup.)
614 self.connect_retry_at = None;
615 }
616 // The interpose stack is a subscriber of this transition, exactly as
617 // in C: `asynInterposeEos` registers an exception callback
618 // (asynInterposeEos.c:110) and drops its read-ahead buffer +
619 // partial-EOS match on `asynExceptionConnect`
620 // (asynInterposeEos.c:142-151). Both C edges — `exceptionConnect`
621 // (asynManager.c:2158) and `exceptionDisconnect` (asynManager.c:2185)
622 // — raise that same exception, so both edges reset here. Driving the
623 // hook from this owner (rather than from an out-of-band subscriber)
624 // keeps it impossible to change `connected` without the stack
625 // hearing about it: `interpose_octet` and `connected` live in the
626 // same struct behind the same lock.
627 self.interpose_octet.connection_changed();
628 self.announce_exception(AsynException::Connect, -1);
629 true
630 }
631
632 /// Per-address variant — for multi-device ports. Same edge
633 /// guarantee as [`Self::set_connected`].
634 ///
635 /// Deliberately does *not* reset the interpose stack. In C each
636 /// interpose is installed on one (port, addr) pair and registers its
637 /// exception callback on that address's `dpCommon`, so a device-level
638 /// connect exception only resets *that* device's interpose
639 /// (asynManager.c:611-625 fans out per-`dpCommon`). `interpose_octet`
640 /// here is port-scoped, so clearing it from a per-device transition
641 /// would discard read-ahead belonging to the port's other addresses.
642 /// The port-level transition owner [`Self::set_connected`] carries the
643 /// reset.
644 pub fn set_addr_connected(&mut self, addr: i32, connected: bool) -> bool {
645 // C reaches both levels through one `exceptionConnect`, and
646 // `findDpCommon` is what decides which: an addr the port resolves to
647 // its own `dpCommon` is a PORT transition, and the port owner carries
648 // the interpose reset and the retry timer that belong to it.
649 let Some(addr) = self.dp_addr(addr) else {
650 return self.set_connected(connected);
651 };
652 let was = self.device_state(addr).connected;
653 if was == connected {
654 return false;
655 }
656 self.device_state(addr).connected = connected;
657 if !connected {
658 // Per-device disconnect stamp — same throttle anchor as the
659 // port-level path (C `exceptionDisconnect`, asynManager.c:2184).
660 self.device_state(addr).last_connect_disconnect = Some(Instant::now());
661 }
662 self.announce_exception(AsynException::Connect, addr);
663 true
664 }
665
666 /// 2.0s auto-reconnect throttle gate — C `autoConnectDevice`
667 /// (asynManager.c:712-713, 729-730).
668 ///
669 /// Returns `true` when a fresh auto-connect attempt is permitted:
670 /// either no transition has been recorded yet (mirrors C's
671 /// zero-initialised `lastConnectDisconnect`, whose diff against `now`
672 /// is effectively infinite), or at least `AUTO_CONNECT_THROTTLE` has
673 /// elapsed since the last transition or attempt. A disconnected
674 /// `auto_connect` device that just dropped — or whose previous
675 /// reconnect just failed — is refused until the window passes, so a
676 /// burst of N queued requests triggers at most one full connect
677 /// attempt per window instead of N back-to-back attempts.
678 ///
679 /// Uses monotonic [`Instant`], not wall clock: the throttle is purely
680 /// internal timing, never serialised, so it must be immune to NTP
681 /// steps. `addr` selects the anchor via [`Self::is_device_addr`].
682 pub fn auto_connect_throttle_ok(&self, addr: i32, now: Instant) -> bool {
683 let last = if self.is_device_addr(addr) {
684 self.device_states
685 .get(&addr)
686 .and_then(|d| d.last_connect_disconnect)
687 } else {
688 self.last_connect_disconnect
689 };
690 match last {
691 None => true,
692 Some(t) => now.saturating_duration_since(t) >= AUTO_CONNECT_THROTTLE,
693 }
694 }
695
696 /// Does `addr` name a *device* on this port, or the port itself?
697 ///
698 /// C `findDpCommon` resolves a `pasynUser` to `&pdevice->dpc` only when
699 /// the port is multi-device AND the user is bound to a real address;
700 /// otherwise to `&pport->dpc` (a connectDevice with `addr < 0` leaves
701 /// `pdevice` null). This is the one owner of that resolution, so the
702 /// throttle read [`Self::auto_connect_throttle_ok`] and the throttle
703 /// write [`Self::stamp_auto_connect_attempt`] can never disagree about
704 /// which anchor an address refers to. Keying on the address (rather than
705 /// on `multi_device` alone) is what lets a multi-device port hold a
706 /// *port-level* anchor at `addr = -1`: the old form sent `-1` into
707 /// `device_states`, inventing a phantom device whose anchor no
708 /// disconnect ever stamped.
709 pub fn is_device_addr(&self, addr: i32) -> bool {
710 self.dp_addr(addr).is_some()
711 }
712
713 /// The dpCommon slot this port resolves `addr` to — [`dp_common_key`]
714 /// against the port's own `ASYN_MULTIDEVICE` attribute. The single owner
715 /// of the resolution for every connection-state read and write below.
716 pub fn dp_addr(&self, addr: i32) -> Option<i32> {
717 dp_common_key(self.flags.multi_device, addr)
718 }
719
720 /// C `findDpCommon(puserPvt)->enabled` (asynManager.c:2352) — what
721 /// `pasynManager->isEnabled` answers for this address.
722 pub fn dp_enabled(&self, addr: i32) -> bool {
723 self.device(addr).map_or(self.enabled, |ds| ds.enabled)
724 }
725
726 /// C `findDpCommon(puserPvt)->connected` (asynManager.c:2340) — what
727 /// `pasynManager->isConnected` answers for this address.
728 pub fn dp_connected(&self, addr: i32) -> bool {
729 self.device(addr)
730 .map_or_else(|| self.is_connected(), |ds| ds.connected)
731 }
732
733 /// C `findDpCommon(puserPvt)->autoConnect` (asynManager.c:2370) — what
734 /// `pasynManager->isAutoConnect` answers for this address.
735 pub fn dp_auto_connect(&self, addr: i32) -> bool {
736 self.device(addr)
737 .map_or(self.auto_connect, |ds| ds.auto_connect)
738 }
739
740 /// Single owner for the post-attempt throttle stamp. C
741 /// `autoConnectDevice` stamps `lastConnectDisconnect` immediately after
742 /// every `connectAttempt`, success or failure (asynManager.c:718,
743 /// 735), so the window restarts from the end of the attempt — a failed
744 /// reconnect is not retried until the throttle elapses again.
745 pub fn stamp_auto_connect_attempt(&mut self, addr: i32, now: Instant) {
746 if self.is_device_addr(addr) {
747 self.device_state(addr).last_connect_disconnect = Some(now);
748 } else {
749 self.last_connect_disconnect = Some(now);
750 }
751 }
752
753 /// Query whether the port is enabled.
754 pub fn is_enabled(&self) -> bool {
755 self.enabled
756 }
757
758 /// Single owner-API for the port-level `enabled` transition.
759 ///
760 /// C `enable` (asynManager.c:2222-2249) refuses a shut-down port:
761 /// when `defunct` it returns `asynDisabled` *without* touching
762 /// `enabled` and *without* firing the `asynExceptionEnable` fan-out.
763 /// Otherwise it sets `enabled` and announces unconditionally (no
764 /// state-change guard). The actor's `SetEnable` op is a lifecycle op
765 /// that bypasses [`Self::check_ready`], so this guard is the only
766 /// thing that stops a defunct port from being re-enabled or fanning
767 /// out a spurious exception — it must live here, in the one owner of
768 /// the transition.
769 pub fn set_enabled(&mut self, enabled: bool) -> AsynResult<()> {
770 if self.defunct {
771 return Err(Self::shut_down_error());
772 }
773 self.enabled = enabled;
774 self.announce_exception(AsynException::Enable, -1);
775 Ok(())
776 }
777
778 /// Per-address variant — same defunct refusal as [`Self::set_enabled`].
779 /// `defunct` is modelled at the port level (a shut-down port takes its
780 /// devices with it), so a defunct port refuses per-device enable/disable
781 /// too, matching C's `dpCommon.defunct` check on the resolved device.
782 pub fn set_addr_enabled(&mut self, addr: i32, enabled: bool) -> AsynResult<()> {
783 // C `enable` writes `findDpCommon(puserPvt)->enabled` (asynManager.c:2245),
784 // so an addr that resolves to the port's own slot is the port's enable —
785 // not a device entry no reader would ever resolve to.
786 let Some(addr) = self.dp_addr(addr) else {
787 return self.set_enabled(enabled);
788 };
789 if self.defunct {
790 return Err(Self::shut_down_error());
791 }
792 self.device_state(addr).enabled = enabled;
793 self.announce_exception(AsynException::Enable, addr);
794 Ok(())
795 }
796
797 /// Query whether auto-connect is enabled.
798 pub fn is_auto_connect(&self) -> bool {
799 self.auto_connect
800 }
801
802 /// Toggle the auto-connect flag at runtime.
803 ///
804 /// C parity: `autoConnectAsyn` (asynManager.c:2310-2324) always
805 /// fires `asynExceptionAutoConnect` regardless of prior state
806 /// (no state-change guard). Mirror that — every call announces.
807 /// Driver constructors that initialise `base.auto_connect`
808 /// directly during `PortDriver::new()` keep the silent path
809 /// (the port is not yet registered, so no listeners exist).
810 pub fn set_auto_connect(&mut self, yes: bool) {
811 self.auto_connect = yes;
812 // A DEVIATION from the pinned C, adopting asyn PR #217
813 // (`87918f5e06b7`, "Queue connect timer on autoconnect enable"):
814 // flipping auto-connect ON while the port is down starts the connect
815 // timer, so the flip alone brings the port up. That PR is UNMERGED —
816 // it is on no upstream branch, so `autoConnectAsyn` at the pin
817 // (asynManager.c:2310-2324) sets `autoConnect` and announces, and
818 // nothing else; its `:2322-2324` are `exceptionOccurred` and the
819 // return. Stock asyn's only autonomous attempt is the one
820 // exception-wake pass — one try, then silence until traffic or a
821 // disconnect edge arms the timer (:2181-2182).
822 if yes && !self.connected.get() {
823 self.connect_retry_at = Some(Instant::now() + CONNECT_RETRY_INITIAL);
824 }
825 self.announce_exception(AsynException::AutoConnect, -1);
826 }
827
828 /// Per-address variant — for multi-device ports. C parity:
829 /// `autoConnectAsyn` walks dpCommon via findDpCommon so a per-
830 /// device pasynUser hits the device's dpc, otherwise the port's
831 /// dpc (asynManager.c:2314 + findDpCommon).
832 pub fn set_auto_connect_addr(&mut self, addr: i32, yes: bool) {
833 // Same `findDpCommon` split as [`Self::set_addr_enabled`]
834 // (asynManager.c:2314).
835 let Some(addr) = self.dp_addr(addr) else {
836 self.set_auto_connect(yes);
837 return;
838 };
839 let device_down = {
840 let dev = self.device_state(addr);
841 dev.auto_connect = yes;
842 !dev.connected
843 };
844 // Same PR #217 deviation as `set_auto_connect`, and the PR keys its
845 // check on the dpCommon `findDpCommon` resolved — the DEVICE's —
846 // while the timer it starts is the port's.
847 if yes && device_down {
848 self.connect_retry_at = Some(Instant::now() + CONNECT_RETRY_INITIAL);
849 }
850 self.announce_exception(AsynException::AutoConnect, addr);
851 }
852
853 /// Query whether the port has been marked defunct via
854 /// [`Self::shutdown_lifecycle`] — once true the port is gone for
855 /// good, mirroring C asynManager.c:2266-2269.
856 pub fn is_defunct(&self) -> bool {
857 self.defunct
858 }
859
860 /// The one place a shut-down port is named in an error message, and the
861 /// only one C has: `enable` on a defunct device (asynManager.c:2236-2241).
862 /// Every other gate refuses a defunct port as a disabled one.
863 fn shut_down_error() -> AsynError {
864 AsynError::Status {
865 status: AsynStatus::Disabled,
866 message: "asynManager:enable: port has been shut down".to_string(),
867 }
868 }
869
870 /// C `queueRequest`'s gate (asynManager.c:1541-1552), and the single owner
871 /// of the two refusals it is built from.
872 ///
873 /// They are independent, and the [`ConnectCheck`] the caller hands in
874 /// selects between them — it can waive the *connected* refusal and nothing
875 /// else. There is no argument, op class or priority that waives
876 /// [`Self::check_enabled`]: C's `if(!pport->dpc.enabled) return asynDisabled`
877 /// (:1541-1546) sits *above* `checkPortConnect` and is reached by every
878 /// request, and its port thread refuses to run anything at all on a disabled
879 /// port (`portThread`, :806-809).
880 ///
881 /// The `ConnectCheck` can only come from [`AsynUser::connect_check`], so the
882 /// waiver is available exactly to the requests C gives it to.
883 ///
884 /// Its refusal is [`AsynError::QueueRefused`], not [`AsynError::Status`]:
885 /// C's refusal is `queueRequest`'s *return value*, so the callback never
886 /// runs and nothing it implies happened. A caller must be able to tell that
887 /// from a driver error raised *inside* a callback that did run — the record
888 /// writes the refusal to ERRS and stops, where a driver error still gets the
889 /// callback's readback and `monitorStatus` tail (asynRecord.c:571-578 vs
890 /// :788-900). This is the only place that stamps it.
891 pub fn check_queue(&self, addr: i32, connect: ConnectCheck) -> AsynResult<()> {
892 self.check_queue_inner(addr, connect)
893 .map_err(AsynError::into_queue_refusal)
894 }
895
896 /// The gate's body, before the refusal is stamped as a queue refusal.
897 ///
898 /// Three blocks, in C's order:
899 ///
900 /// 1. `!pport->dpc.enabled → asynDisabled` (:1541-1546) — port level,
901 /// unconditional, reached by every request.
902 /// 2. `checkPortConnect && !pport->dpc.connected → asynDisconnected`
903 /// (:1547-1552) — port level, waived by the request's own user. (C's
904 /// `checkPortConnect == FALSE` reads *no* connected flag: the port thread
905 /// drains the Connect queue before it ever calls `autoConnectDevice`,
906 /// :811-855.)
907 /// 3. The **device** block (:1553-1575), which C runs only for a
908 /// *synchronous* port: it sits bodily inside
909 /// `if(!(pport->attributes & ASYN_CANBLOCK))` at :1553. A CANBLOCK port's
910 /// device-level enabled/connected checks belong to the port THREAD
911 /// (:875-886), which does something else entirely with them — a disabled
912 /// device's request *waits in the queue* (`continue`), it is not refused
913 /// — so applying them here refused requests C parks (R15-47). Every real
914 /// transport port is CANBLOCK.
915 fn check_queue_inner(&self, addr: i32, connect: ConnectCheck) -> AsynResult<()> {
916 self.check_enabled()?;
917 if connect == ConnectCheck::Required {
918 self.check_port_connected()?;
919 }
920 if !self.flags.can_block {
921 // C :1561-1567 — the device-enabled refusal in the synchronous block
922 // is *not* conditioned on `checkPortConnect`; only the connected one
923 // below is (:1568).
924 self.check_device_enabled(addr)?;
925 if connect == ConnectCheck::Required {
926 self.check_device_connected(addr)?;
927 }
928 }
929 Ok(())
930 }
931
932 /// The unconditional half of the queue gate: a disabled port refuses every
933 /// request (asynManager.c:1541-1546).
934 ///
935 /// There is no defunct branch here, and there is none in C's `queueRequest`
936 /// either: `shutdownPort` clears `enabled` alongside setting `defunct`
937 /// (:2283-2284) precisely so this one check answers for both. The invariant
938 /// `defunct ⟹ !enabled` (see the field doc) is what makes that sound.
939 pub fn check_enabled(&self) -> AsynResult<()> {
940 if !self.enabled {
941 return Err(AsynError::Status {
942 status: AsynStatus::Disabled,
943 message: format!("port {} disabled", self.port_name),
944 });
945 }
946 Ok(())
947 }
948
949 /// The port-level connected refusal (asynManager.c:1547-1552).
950 pub fn check_port_connected(&self) -> AsynResult<()> {
951 if !self.is_connected() {
952 return Err(AsynError::Status {
953 status: AsynStatus::Disconnected,
954 message: format!("port {} not connected", self.port_name),
955 });
956 }
957 Ok(())
958 }
959
960 /// The device-level enabled refusal, C's text verbatim
961 /// (asynManager.c:1561-1567). Its *use* differs by port class, which is why
962 /// it is a check and not a gate: `queueRequest` returns it on a synchronous
963 /// port, while on a CANBLOCK port the same condition makes `portThread` park
964 /// the request instead (:875). Both callers ask this one function.
965 ///
966 /// A port that is not `ASYN_MULTIDEVICE`, or an address with no device state,
967 /// resolves to the port's own `dpCommon` in C's `findDpCommon` — already
968 /// checked above — so there is nothing device-level left to refuse.
969 pub fn check_device_enabled(&self, addr: i32) -> AsynResult<()> {
970 if let Some(ds) = self.device(addr) {
971 if !ds.enabled {
972 return Err(AsynError::Status {
973 status: AsynStatus::Disabled,
974 // C's double space is verbatim (asynManager.c:1564).
975 message: format!("port {} or device {} not enabled", self.port_name, addr),
976 });
977 }
978 }
979 Ok(())
980 }
981
982 /// The device-level connected refusal (asynManager.c:1568-1575). Same
983 /// split as [`Self::check_device_enabled`]: `queueRequest` returns it on a
984 /// synchronous port; on a CANBLOCK port `portThread` answers the same
985 /// condition with the request's timeout callback (:884-885).
986 pub fn check_device_connected(&self, addr: i32) -> AsynResult<()> {
987 if let Some(ds) = self.device(addr) {
988 if !ds.connected {
989 return Err(AsynError::Status {
990 status: AsynStatus::Disconnected,
991 message: format!("port {} or device {} not connected", self.port_name, addr),
992 });
993 }
994 }
995 Ok(())
996 }
997
998 /// The device `addr` resolves to, or `None` when C's `findDpCommon` would
999 /// resolve it to the port's own `dpCommon` (not multi-device, or no device
1000 /// created at that address).
1001 fn device(&self, addr: i32) -> Option<&DeviceState> {
1002 self.dp_addr(addr).and_then(|a| self.device_states.get(&a))
1003 }
1004
1005 /// Check that the port is enabled, connected, and not defunct.
1006 /// Returns `Err(Disabled)`, `Err(Disconnected)`, or `Err(Disabled)`
1007 /// (defunct => permanently disabled) otherwise.
1008 pub fn check_ready(&self) -> AsynResult<()> {
1009 self.check_enabled()?;
1010 self.check_port_connected()
1011 }
1012
1013 /// Run the C `shutdownPort` lifecycle (asynManager.c:2251-2308):
1014 ///
1015 /// 1. Refuse if the port did not opt into `ASYN_DESTRUCTIBLE`
1016 /// (returns `Err(Status::Error)`).
1017 /// 2. Short-circuit if already defunct (idempotent — returns Ok).
1018 /// 3. Set `enabled = false`, `defunct = true` — every subsequent
1019 /// request through [`Self::check_ready`] fails.
1020 /// 4. Broadcast `AsynException::Shutdown` so registered observers
1021 /// (CA gateways, monitor sinks) tear down their handles.
1022 ///
1023 /// Drivers should call this from their own shutdown plumbing and
1024 /// then release any hardware-owned resources via their
1025 /// [`PortDriver::shutdown`] implementation. Callers from outside
1026 /// the runtime can drive the same lifecycle via
1027 /// [`crate::manager::PortManager::shutdown_port`].
1028 pub fn shutdown_lifecycle(&mut self) -> AsynResult<()> {
1029 if self.defunct {
1030 // Idempotent — C asynManager.c:2266-2269 returns asynSuccess.
1031 return Ok(());
1032 }
1033 if !self.flags.destructible {
1034 return Err(AsynError::Status {
1035 status: AsynStatus::Error,
1036 message: format!(
1037 "port {} does not support shutting down (ASYN_DESTRUCTIBLE not set)",
1038 self.port_name
1039 ),
1040 });
1041 }
1042 self.enabled = false;
1043 // The invariant is `defunct ⟹ !enabled` on *every* dpCommon this port
1044 // owns, not only the port's own. Clearing the device slots here is what
1045 // makes it hold by construction: [`Self::device_state`] seeds a new slot
1046 // from the port's now-false `enabled`, and [`Self::set_addr_enabled`]
1047 // refuses while defunct, so nothing can raise a slot back — and
1048 // [`Self::dp_enabled`] needs no defunct branch to answer correctly.
1049 // Without this, a slot that happened to exist before the shutdown kept
1050 // `enabled = true`, so `isEnabled(ADDR)` answered true on a port that is
1051 // gone while `isEnabled(-1)` answered false — the same read disagreeing
1052 // with itself depending on whether anything had ever touched that
1053 // address.
1054 for ds in self.device_states.values_mut() {
1055 ds.enabled = false;
1056 }
1057 self.defunct = true;
1058 self.announce_exception(AsynException::Shutdown, -1);
1059 Ok(())
1060 }
1061
1062 /// Check that port + device address are both ready — the whole of C's
1063 /// synchronous-port gate (asynManager.c:1541-1575) in one call. Drivers that
1064 /// re-check inside their own I/O use it; the queue gate reaches the same
1065 /// checks through [`Self::check_queue`], which splits them by port class.
1066 pub fn check_ready_addr(&self, addr: i32) -> AsynResult<()> {
1067 self.check_ready()?;
1068 self.check_device_enabled(addr)?;
1069 self.check_device_connected(addr)
1070 }
1071
1072 /// Get or create a device state for the given address.
1073 ///
1074 /// A device created here inherits the port's own `dpCommon`, as C's
1075 /// `locateDevice` does: `dpCommonInit(pport, pdevice, pport->dpc.autoConnect)`
1076 /// (asynManager.c:586). Defaulting `auto_connect` to `true` on a
1077 /// manual-connect port would make `asynReport`'s per-device
1078 /// `autoConnect Yes` a lie, and would hand `autoConnectDevice` a device it
1079 /// may reconnect on a port whose operator turned auto-connect off.
1080 ///
1081 /// `enabled` and `connected` are seeded the same way, and for a stronger
1082 /// reason: until this slot exists the reads [`Self::dp_enabled`] /
1083 /// [`Self::dp_connected`] answer from the port's own, so seeding from
1084 /// anything else would let an unrelated write — disabling a device on a
1085 /// disconnected port, say — flip what a *different* field of that device
1086 /// reports. The slot's creation is then invisible: every field starts at
1087 /// the value the read it replaces was already giving.
1088 /// `pub(crate)`, not `pub`: this hands out the raw slot, so a caller that
1089 /// wrote through it would skip the `asynException` fan-out C raises from
1090 /// `enable` / `exceptionConnect` (asynManager.c:2247, 2158) *and* could
1091 /// create a device on a port that has none — a state C cannot represent,
1092 /// since `locateDevice` refuses to allocate one unless
1093 /// `attributes&ASYN_MULTIDEVICE` (:576). Outside callers use the three
1094 /// owners [`Self::set_addr_connected`], [`Self::set_addr_enabled`] and
1095 /// [`Self::set_auto_connect_addr`], each of which resolves the addr first.
1096 pub(crate) fn device_state(&mut self, addr: i32) -> &mut DeviceState {
1097 let seed = DeviceState {
1098 connected: self.is_connected(),
1099 enabled: self.enabled,
1100 auto_connect: self.auto_connect,
1101 last_connect_disconnect: None,
1102 };
1103 self.device_states.entry(addr).or_insert(seed)
1104 }
1105
1106 /// Check if a specific device address is connected.
1107 pub fn is_device_connected(&self, addr: i32) -> bool {
1108 self.dp_connected(addr)
1109 }
1110
1111 /// Set a specific device address as connected.
1112 ///
1113 /// C parity: announce only on actual transition
1114 /// (asynManager.c:2151-2160 — `exceptionConnect` rejects
1115 /// already-connected; we keep an Ok return for idempotency but
1116 /// suppress the duplicate fan-out so subscribers don't see
1117 /// spurious connect events). Thin wrapper over
1118 /// [`Self::set_addr_connected`] for callers that prefer the
1119 /// directional verb.
1120 pub fn connect_addr(&mut self, addr: i32) {
1121 self.set_addr_connected(addr, true);
1122 }
1123
1124 /// Set a specific device address as disconnected.
1125 ///
1126 /// C parity: announce only on actual transition
1127 /// (asynManager.c:2174-2185). Thin wrapper over
1128 /// [`Self::set_addr_connected`].
1129 pub fn disconnect_addr(&mut self, addr: i32) {
1130 self.set_addr_connected(addr, false);
1131 }
1132
1133 /// Enable a specific device address. Convenience facade over the
1134 /// guarded owner [`Self::set_addr_enabled`]; a defunct port no-ops.
1135 pub fn enable_addr(&mut self, addr: i32) {
1136 let _ = self.set_addr_enabled(addr, true);
1137 }
1138
1139 /// Disable a specific device address. Convenience facade over the
1140 /// guarded owner [`Self::set_addr_enabled`]; a defunct port no-ops.
1141 pub fn disable_addr(&mut self, addr: i32) {
1142 let _ = self.set_addr_enabled(addr, false);
1143 }
1144
1145 /// Set a custom timestamp source callback.
1146 pub fn register_timestamp_source<F>(&mut self, source: F)
1147 where
1148 F: Fn() -> SystemTime + Send + Sync + 'static,
1149 {
1150 self.timestamp_source = Some(Arc::new(source));
1151 }
1152
1153 /// Drop a registered source — C `unregisterTimeStampSource`
1154 /// (asynManager.c:334), which restores `defaultTimeStampSource` (:332).
1155 pub fn unregister_timestamp_source(&mut self) {
1156 self.timestamp_source = None;
1157 }
1158
1159 /// Get current timestamp from the registered source, or SystemTime::now().
1160 pub fn current_timestamp(&self) -> SystemTime {
1161 self.timestamp_source
1162 .as_ref()
1163 .map_or_else(SystemTime::now, |f| f())
1164 }
1165
1166 pub fn create_param(&mut self, name: &str, param_type: ParamType) -> AsynResult<usize> {
1167 self.params.create_param(name, param_type)
1168 }
1169
1170 pub fn find_param(&self, name: &str) -> Option<usize> {
1171 self.params.find_param(name)
1172 }
1173
1174 // --- Convenience param accessors ---
1175
1176 pub fn set_int32_param(&mut self, index: usize, addr: i32, value: i32) -> AsynResult<()> {
1177 self.params.set_int32(index, addr, value)
1178 }
1179
1180 pub fn get_int32_param(&self, index: usize, addr: i32) -> AsynResult<i32> {
1181 self.params.get_int32(index, addr)
1182 }
1183
1184 /// Strict variant — returns [`AsynError::ParamUndefined`] when the
1185 /// cache entry has never been set (C parity for `asynParamUndefined`).
1186 /// See [`crate::param::ParamList::get_int32_strict`].
1187 pub fn get_int32_param_strict(&self, index: usize, addr: i32) -> AsynResult<i32> {
1188 self.params.get_int32_strict(index, addr)
1189 }
1190
1191 pub fn set_int64_param(&mut self, index: usize, addr: i32, value: i64) -> AsynResult<()> {
1192 self.params.set_int64(index, addr, value)
1193 }
1194
1195 pub fn get_int64_param(&self, index: usize, addr: i32) -> AsynResult<i64> {
1196 self.params.get_int64(index, addr)
1197 }
1198
1199 /// Strict variant — see [`crate::param::ParamList::get_int64_strict`].
1200 pub fn get_int64_param_strict(&self, index: usize, addr: i32) -> AsynResult<i64> {
1201 self.params.get_int64_strict(index, addr)
1202 }
1203
1204 pub fn set_float64_param(&mut self, index: usize, addr: i32, value: f64) -> AsynResult<()> {
1205 self.params.set_float64(index, addr, value)
1206 }
1207
1208 pub fn get_float64_param(&self, index: usize, addr: i32) -> AsynResult<f64> {
1209 self.params.get_float64(index, addr)
1210 }
1211
1212 /// Strict variant — see [`crate::param::ParamList::get_float64_strict`].
1213 pub fn get_float64_param_strict(&self, index: usize, addr: i32) -> AsynResult<f64> {
1214 self.params.get_float64_strict(index, addr)
1215 }
1216
1217 pub fn set_string_param(
1218 &mut self,
1219 index: usize,
1220 addr: i32,
1221 value: impl Into<Vec<u8>>,
1222 ) -> AsynResult<()> {
1223 self.params.set_string(index, addr, value)
1224 }
1225
1226 pub fn get_string_param(&self, index: usize, addr: i32) -> AsynResult<&[u8]> {
1227 self.params.get_string(index, addr)
1228 }
1229
1230 /// Strict variant — see [`crate::param::ParamList::get_string_strict`].
1231 pub fn get_string_param_strict(&self, index: usize, addr: i32) -> AsynResult<&[u8]> {
1232 self.params.get_string_strict(index, addr)
1233 }
1234
1235 /// Set a UInt32Digital parameter. `interrupt_mask` mirrors C
1236 /// `setUIntDigitalParam(.., interruptMask)` (asynPortDriver.cpp:1369,
1237 /// 1381): bits to force into the I/O Intr callback mask even when the
1238 /// stored value did not change. Pass `0` for a plain value set (the
1239 /// 3-arg C overload, asynPortDriver.cpp:1347).
1240 pub fn set_uint32_param(
1241 &mut self,
1242 index: usize,
1243 addr: i32,
1244 value: u32,
1245 mask: u32,
1246 interrupt_mask: u32,
1247 ) -> AsynResult<()> {
1248 self.params
1249 .set_uint32(index, addr, value, mask, interrupt_mask)
1250 }
1251
1252 pub fn get_uint32_param(&self, index: usize, addr: i32) -> AsynResult<u32> {
1253 self.params.get_uint32(index, addr)
1254 }
1255
1256 /// Strict variant — see [`crate::param::ParamList::get_uint32_strict`].
1257 pub fn get_uint32_param_strict(&self, index: usize, addr: i32) -> AsynResult<u32> {
1258 self.params.get_uint32_strict(index, addr)
1259 }
1260
1261 pub fn get_enum_param(&self, index: usize, addr: i32) -> AsynResult<(usize, Arc<[EnumEntry]>)> {
1262 self.params.get_enum(index, addr)
1263 }
1264
1265 pub fn set_enum_index_param(
1266 &mut self,
1267 index: usize,
1268 addr: i32,
1269 value: usize,
1270 ) -> AsynResult<()> {
1271 self.params.set_enum_index(index, addr, value)
1272 }
1273
1274 pub fn set_enum_choices_param(
1275 &mut self,
1276 index: usize,
1277 addr: i32,
1278 choices: Arc<[EnumEntry]>,
1279 ) -> AsynResult<()> {
1280 self.params.set_enum_choices(index, addr, choices)
1281 }
1282
1283 pub fn get_generic_pointer_param(
1284 &self,
1285 index: usize,
1286 addr: i32,
1287 ) -> AsynResult<Arc<dyn Any + Send + Sync>> {
1288 self.params.get_generic_pointer(index, addr)
1289 }
1290
1291 pub fn set_generic_pointer_param(
1292 &mut self,
1293 index: usize,
1294 addr: i32,
1295 value: Arc<dyn Any + Send + Sync>,
1296 ) -> AsynResult<()> {
1297 self.params.set_generic_pointer(index, addr, value)
1298 }
1299
1300 pub fn set_param_timestamp(
1301 &mut self,
1302 index: usize,
1303 addr: i32,
1304 ts: SystemTime,
1305 ) -> AsynResult<()> {
1306 self.params.set_timestamp(index, addr, ts)
1307 }
1308
1309 pub fn set_param_status(
1310 &mut self,
1311 index: usize,
1312 addr: i32,
1313 status: AsynStatus,
1314 alarm_status: u16,
1315 alarm_severity: u16,
1316 ) -> AsynResult<()> {
1317 self.params
1318 .set_param_status(index, addr, status, alarm_status, alarm_severity)
1319 }
1320
1321 pub fn get_param_status(&self, index: usize, addr: i32) -> AsynResult<(AsynStatus, u16, u16)> {
1322 self.params.get_param_status(index, addr)
1323 }
1324
1325 /// C `asynPortDriver::reportParams` (asynPortDriver.cpp:1799-1809) — the
1326 /// parameter block of the driver's report.
1327 ///
1328 /// `details` is the level `report` was called with, **unshifted**: C hands
1329 /// `reportParams` the same number it got (:3693), and the level decides one
1330 /// thing only — how many address lists are printed (`details >= 2` → all
1331 /// `maxAddr` of them, else list 0 alone, :1804). The values are *not* a
1332 /// deeper level: `paramVal::report` prints name, type, value and status for
1333 /// every parameter at every level (paramVal.cpp:296-372).
1334 ///
1335 /// Passing `level - 1` here put the whole block one level late — `asynReport
1336 /// 1` printed a bare count where C prints every parameter with its value, and
1337 /// values only appeared at 3 (R16-46/47).
1338 pub fn report_params(&self, out: &mut dyn std::fmt::Write, details: i32) {
1339 use std::fmt::Write as _;
1340 let num_addr = if details >= 2 {
1341 self.max_addr.max(1)
1342 } else {
1343 1
1344 };
1345 for addr in 0..num_addr {
1346 let _ = writeln!(out, "Parameter list {addr}");
1347 self.params.report(out, addr as i32);
1348 }
1349 }
1350
1351 /// Push an interpose layer onto the **port's** octet I/O stack — C
1352 /// `interposeInterface(portName, -1, ...)`, which every driver's own
1353 /// configure-time install is (the layer serves every device on the port).
1354 ///
1355 /// **Concurrency**: requires `&mut self`, which means the caller must hold
1356 /// the port lock (`Arc<Mutex<dyn PortDriver>>`). This ensures
1357 /// interpose modifications are serialized with I/O dispatch.
1358 pub fn install_octet_interpose(&mut self, layer: Box<dyn OctetInterpose>) {
1359 self.install_octet_interpose_addr(crate::interpose::PORT_CHAIN, layer);
1360 }
1361
1362 /// Push an interpose layer onto the stack of the device `addr` names — C
1363 /// `interposeInterface(portName, addr, ...)` (asynManager.c:2190-2220), which
1364 /// is what the `asynInterposeEcho` / `asynInterposeDelay` iocsh commands call
1365 /// (asynInterposeEcho.c:176, asynInterposeDelay.c:187,200). On a port that is
1366 /// not multi-device every addr resolves to the port itself.
1367 pub fn install_octet_interpose_addr(&mut self, addr: i32, layer: Box<dyn OctetInterpose>) {
1368 self.interpose_octet.install(addr, layer);
1369 }
1370
1371 /// Flush changed parameters as interrupt notifications.
1372 /// Equivalent to C asyn's callParamCallbacks().
1373 pub fn call_param_callbacks(&mut self, addr: i32) -> AsynResult<()> {
1374 // C asynPortDriver.cpp:838 — `callCallbacks` returns before the loop
1375 // AND before `flags.clear()` (:871) while `interruptAccept` is false,
1376 // so every callback fired during IOC build is a no-op that PRESERVES
1377 // the accumulated changed-flags. Returning here, ahead of `take_changed`
1378 // (which both reads and clears), is that early return: a driver's
1379 // acquisition/array task can call this before `iocInit` has wired the
1380 // `_RBV` records, and a read-only seed must survive to the one-shot
1381 // flush the scan facility fires when the gate goes true.
1382 if !epics_libcom_rs::runtime::interrupt_accept::interrupts_accepted() {
1383 return Ok(());
1384 }
1385 let changed = self.params.take_changed(addr)?;
1386 let now = self.current_timestamp();
1387 for reason in changed {
1388 let value = self.params.get_value(reason, addr)?.clone();
1389 // C asynPortDriver.cpp:845 — callCallbacks skips firing for an
1390 // undefined param even though its changed flag is consumed
1391 // (flags.clear() at :871). A status/alarm change or bare
1392 // mark_changed on a never-set scalar must not emit an I/O Intr.
1393 // Array/generic-pointer params have no callCallbacks analog
1394 // (:846-865 switch is scalar-only) and Rust fires them as a
1395 // read-trigger regardless, so gate scalars only.
1396 if !value.is_array() && !self.params.is_param_defined(reason, addr).unwrap_or(false) {
1397 continue;
1398 }
1399 let ts = self.params.get_timestamp(reason, addr)?.unwrap_or(now);
1400 // C parity: read the accumulated callback mask and reset it
1401 // (asynPortDriver.cpp:854-855 fires uint32Callback then sets
1402 // uInt32CallbackMask = 0). The flush is the single owner of
1403 // this consume, so accumulated bits never leak to the next.
1404 let uint32_mask = self
1405 .params
1406 .take_uint32_interrupt_mask(reason, addr)
1407 .unwrap_or(0);
1408 // C parity: asynPortDriver.cpp:633-637 sets
1409 // `pInterrupt->pasynUser->auxStatus/alarmStatus/alarmSeverity`
1410 // from the param's stored status before invoking each
1411 // subscriber callback. Pull those here so subscribers see
1412 // the same triplet C consumers do.
1413 let (aux_status, alarm_status, alarm_severity) = self
1414 .params
1415 .get_param_status(reason, addr)
1416 .unwrap_or((AsynStatus::Success, 0, 0));
1417 self.interrupts.notify(InterruptValue {
1418 reason,
1419 addr,
1420 value,
1421 timestamp: ts,
1422 uint32_changed_mask: uint32_mask,
1423 aux_status,
1424 alarm_status,
1425 alarm_severity,
1426 // Untyped: a single cached value per (reason,addr) reaches
1427 // every subscribing interface (the pre-per-interface path).
1428 iface: None,
1429 });
1430 }
1431 Ok(())
1432 }
1433
1434 /// Flush a single parameter's changed flag and notify if dirty.
1435 /// Use this instead of `call_param_callbacks` when you want to avoid
1436 /// flushing unrelated parameters (e.g. rapidly-updating CP-linked params).
1437 pub fn call_param_callback(&mut self, addr: i32, reason: usize) -> AsynResult<()> {
1438 // C `interruptAccept` gate — see `call_param_callbacks`: preserve the
1439 // changed-flag (do not `take_changed_single`) until the IOC accepts
1440 // interrupts, so a pre-`iocInit` flush cannot strand a seeded value.
1441 if !epics_libcom_rs::runtime::interrupt_accept::interrupts_accepted() {
1442 return Ok(());
1443 }
1444 if self.params.take_changed_single(reason, addr)? {
1445 let value = self.params.get_value(reason, addr)?.clone();
1446 // C asynPortDriver.cpp:845 — see `call_param_callbacks`: an
1447 // undefined scalar consumes its changed flag but fires no
1448 // callback. Array/generic-pointer triggers fire regardless.
1449 if !value.is_array() && !self.params.is_param_defined(reason, addr).unwrap_or(false) {
1450 return Ok(());
1451 }
1452 let now = self.current_timestamp();
1453 let ts = self.params.get_timestamp(reason, addr)?.unwrap_or(now);
1454 // C parity: read the accumulated callback mask and reset it
1455 // (asynPortDriver.cpp:854-855 fires uint32Callback then sets
1456 // uInt32CallbackMask = 0). The flush is the single owner of
1457 // this consume, so accumulated bits never leak to the next.
1458 let uint32_mask = self
1459 .params
1460 .take_uint32_interrupt_mask(reason, addr)
1461 .unwrap_or(0);
1462 // C parity: see `call_param_callbacks` above.
1463 let (aux_status, alarm_status, alarm_severity) = self
1464 .params
1465 .get_param_status(reason, addr)
1466 .unwrap_or((AsynStatus::Success, 0, 0));
1467 self.interrupts.notify(InterruptValue {
1468 reason,
1469 addr,
1470 value,
1471 timestamp: ts,
1472 uint32_changed_mask: uint32_mask,
1473 aux_status,
1474 alarm_status,
1475 alarm_severity,
1476 // Untyped (see `call_param_callbacks`).
1477 iface: None,
1478 });
1479 }
1480 Ok(())
1481 }
1482
1483 /// Mark a parameter as changed without modifying its value.
1484 ///
1485 /// Use this to trigger I/O Intr on params whose data is served via
1486 /// `read_*_array()` overrides rather than the param cache (e.g. pixel data).
1487 pub fn mark_param_changed(&mut self, index: usize, addr: i32) -> AsynResult<()> {
1488 self.params.mark_changed(index, addr)
1489 }
1490
1491 /// Fire one per-interface I/O Intr callback carrying an interface-typed value.
1492 ///
1493 /// `call_param_callbacks` stores **one** value per `(reason, addr)` and
1494 /// notifies it untyped, so every record on that reason — whatever its DTYP's
1495 /// interface — receives the same value. For a driver whose single raw datum
1496 /// is exposed on several asyn interfaces at once (e.g. a Modbus register read
1497 /// by an `asynInt32` ai, an `asynUInt32Digital` bi, and an `asynFloat64` ai
1498 /// simultaneously), that collapse delivers a wrong-typed value to all but one
1499 /// of them. C's `drvModbusAsyn::readPoller` instead decodes the one register
1500 /// block **separately per interface** and invokes each interface's own
1501 /// interrupt list — `interruptStart` on `uInt32Digital`/`int32`/`float64`
1502 /// at drvModbusAsyn.cpp:1674/1716/1788. This is the analogue: the driver
1503 /// decodes per interface and fires each value tagged with its `iface`, so the
1504 /// interrupt filter routes it only to records on that interface
1505 /// ([`InterruptFilter::iface`](crate::interrupt::InterruptFilter::iface)). `uint32_changed_mask` is the changed-bit
1506 /// mask for the `UInt32Digital` interface (a record's `@asynMask` gates on it,
1507 /// `asynPortDriver.cpp:720`); pass `0` for the other interfaces, whose
1508 /// subscribers carry no mask filter.
1509 ///
1510 /// `aux_status` is the device I/O status this fire carries (C
1511 /// `pInterrupt->pasynUser->auxStatus`, set on every callback the poller
1512 /// emits — `drvModbusAsyn.cpp:1699/1738/1774/1810/1845/1880/1916`). A driver whose
1513 /// last acquisition failed still fires its interrupt lists, with the failing
1514 /// status, so I/O-Intr records go to READ/INVALID instead of freezing on the
1515 /// last good value; pass [`AsynStatus::Success`] on a clean acquisition.
1516 pub fn notify_interface_value(
1517 &self,
1518 reason: usize,
1519 addr: i32,
1520 iface: InterfaceType,
1521 value: ParamValue,
1522 uint32_changed_mask: u32,
1523 aux_status: AsynStatus,
1524 ) {
1525 let ts = self.current_timestamp();
1526 self.interrupts.notify(InterruptValue {
1527 reason,
1528 addr,
1529 value,
1530 timestamp: ts,
1531 uint32_changed_mask,
1532 aux_status,
1533 alarm_status: 0,
1534 alarm_severity: 0,
1535 iface: Some(iface),
1536 });
1537 }
1538}
1539
1540/// Result of resolving a record's driver-info string at bind time — the
1541/// asyn-rs analogue of what C `drvUserCreate` writes into `pasynUser`.
1542///
1543/// `reason` is the shared parameter index (every record with the same drvInfo
1544/// resolves to it). The remaining fields carry **per-record** driver state the
1545/// lookup derived from this particular drvInfo string (C stashes the same in
1546/// `pasynUser->drvUser`), which the binding applies to that record's I/O.
1547#[derive(Debug, Default)]
1548pub struct DrvUserInfo {
1549 /// Shared parameter index for this drvInfo (C `pasynUser->reason`).
1550 pub reason: usize,
1551 /// Optional per-record octet length cap — the asyn-rs home for C's
1552 /// `modbusDrvUser_t.len` (`drvUserCreate` parses `TYPE=N`; `getStringLen`
1553 /// caps the asyn octet `maxLen` to it, drvModbusAsyn.cpp:2367-2377). `None`
1554 /// when the drvInfo carried no cap; the binding then uses the record buffer
1555 /// length alone. The binding applies `min(buffer_len, cap)`.
1556 pub max_octet_len: Option<usize>,
1557}
1558
1559impl DrvUserInfo {
1560 /// A resolution carrying only the shared reason and no per-record cap — the
1561 /// default-lookup result.
1562 pub fn from_reason(reason: usize) -> Self {
1563 Self {
1564 reason,
1565 ..Self::default()
1566 }
1567 }
1568}
1569
1570/// Everything a binding tells the driver when it resolves a drvInfo string —
1571/// the asyn-rs analogue of the `pasynUser` C `drvUserCreate` receives.
1572///
1573/// This is one carrier rather than a widening argument list because the bind
1574/// request has already grown once (`addr`, for C `checkOffset`) and is now
1575/// growing again (`iface`): a driver that resolves a drvInfo needs to know
1576/// *how the record will use the parameter*, not just its name. The struct is
1577/// `#[non_exhaustive]` so the next field is additive — build it with
1578/// [`DrvUserRequest::new`] and the builder methods.
1579#[derive(Debug, Clone, PartialEq, Eq)]
1580#[non_exhaustive]
1581pub struct DrvUserRequest {
1582 /// The record's driver-info string (C `pasynUser->drvUser` input).
1583 pub drv_info: String,
1584 /// The record's asyn `addr`, so a multi-device driver can reject an
1585 /// out-of-range address at bind time (C `drvUserCreate` `checkOffset`,
1586 /// drvModbusAsyn.cpp:378-384).
1587 pub addr: i32,
1588 /// The asyn interface the record will actually read and write this
1589 /// parameter through, derived from its DTYP (`asynFloat64` → [`InterfaceType::Float64`]).
1590 ///
1591 /// An on-demand driver (C Autoparam lazy creation) must create the
1592 /// parameter with the type the record will read it as, or every value the
1593 /// record takes from it is a coerced type mismatch: C
1594 /// `adsAsynPortDriver::getRecordInfoFromDrvInfo` derives the parameter's
1595 /// asyn type from the bound record's DTYP for exactly this reason — the
1596 /// same PLC symbol may bind as `asynInt32` from one record and
1597 /// `asynFloat64` from another.
1598 ///
1599 /// `None` when the bind has no record behind it (a port-level
1600 /// [`crate::sync_io`] resolve, a driver-to-driver handle call): the driver
1601 /// then has no record type to honour and falls back to its own default.
1602 pub iface: Option<InterfaceType>,
1603}
1604
1605impl DrvUserRequest {
1606 /// A bind request for `drv_info` at `addr` with no record interface — the
1607 /// port-level resolve.
1608 pub fn new(drv_info: impl Into<String>, addr: i32) -> Self {
1609 Self {
1610 drv_info: drv_info.into(),
1611 addr,
1612 iface: None,
1613 }
1614 }
1615
1616 /// Attach the bound record's asyn interface. Accepts an
1617 /// [`InterfaceType`] or an `Option<InterfaceType>`.
1618 pub fn with_iface(mut self, iface: impl Into<Option<InterfaceType>>) -> Self {
1619 self.iface = iface.into();
1620 self
1621 }
1622}
1623
1624/// Port driver trait. All methods have default implementations that operate
1625/// on the parameter cache (no actual I/O).
1626///
1627/// Drivers performing real hardware I/O should:
1628/// 1. Run I/O in a background task (e.g., tokio::spawn)
1629/// 2. Update parameters via `base_mut().set_*_param()` + `call_param_callbacks()`
1630/// 3. Let the default `read_*` methods return cached values
1631///
1632/// # LockPort/UnlockPort
1633///
1634/// C asyn provides `lockPort`/`unlockPort` for direct mutex locking. In asyn-rs,
1635/// the port is always behind `Arc<Mutex<dyn PortDriver>>`, so callers hold the
1636/// parking_lot mutex directly. For multi-request exclusive access, use
1637/// `BlockProcess`/`UnblockProcess` via the worker queue.
1638/// C `epicsTimeToStrftime(buff, ..., "%Y/%m/%d %H:%M:%S.%03f", &timeStamp)` —
1639/// the port timestamp line of `asynPortDriver::report` (asynPortDriver.cpp:3682-3684).
1640/// Local time, as `epicsTimeToStrftime` renders it.
1641fn format_timestamp(ts: SystemTime) -> String {
1642 chrono::DateTime::<chrono::Local>::from(ts)
1643 .format("%Y/%m/%d %H:%M:%S%.3f")
1644 .to_string()
1645}
1646
1647/// C's `details >= 3` block: one line per registered interrupt client
1648/// (`reportInterrupt`, asynPortDriver.cpp:1870-1894, called once per interface at
1649/// :3695-3708). C prints the callback and userPvt pointers with each client; Rust
1650/// mailboxes have no such pointers, so the line carries what identifies a client
1651/// here — the interface it bound, the address and reason it filtered on, and the
1652/// uint32 mask when it set one.
1653fn report_interrupt_clients(out: &mut dyn std::fmt::Write, base: &PortDriverBase) {
1654 use std::fmt::Write as _;
1655 for f in base.interrupts.clients() {
1656 let iface = f
1657 .iface
1658 .map_or("any", |i: crate::interfaces::InterfaceType| {
1659 i.interrupt_label()
1660 });
1661 let addr = f.addr.map_or("any".to_string(), |a| a.to_string());
1662 let reason = f.reason.map_or("any".to_string(), |r| r.to_string());
1663 let _ = write!(
1664 out,
1665 " {iface} callback client addr={addr}, reason={reason}"
1666 );
1667 if let Some(mask) = f.uint32_mask {
1668 let _ = write!(out, ", mask=0x{mask:x}");
1669 }
1670 let _ = writeln!(out);
1671 }
1672}
1673
1674/// C `showFailure` (asynOctetBase.c:370-380) — the message every Fail stub
1675/// produces: the port name, the method, and `not implemented`, returned as
1676/// `asynError`.
1677fn eos_not_implemented(port: &str, method: &str) -> AsynError {
1678 AsynError::Status {
1679 status: AsynStatus::Error,
1680 message: format!("{port} {method} not implemented"),
1681 }
1682}
1683
1684/// C's `switch (eoslen)` refusal, verbatim: `"%s illegal eoslen %d"` with the
1685/// port name and the length (asynInterposeEos.c:301-302, :354-355).
1686fn illegal_eoslen(port: &str, eoslen: usize) -> AsynError {
1687 AsynError::Status {
1688 status: AsynStatus::Error,
1689 message: format!("{port} illegal eoslen {eoslen}"),
1690 }
1691}
1692
1693pub trait PortDriver: Send + Sync + 'static {
1694 fn base(&self) -> &PortDriverBase;
1695 fn base_mut(&mut self) -> &mut PortDriverBase;
1696
1697 // --- AsynCommon ---
1698
1699 /// The trivial driver's `pasynCommon->connect`: C's own does its transport
1700 /// work and then calls `pasynManager->exceptionConnect(pasynUser)`, which
1701 /// resolves the slot it marks connected through `findDpCommon` on that same
1702 /// user (asynManager.c:2142-2162). So the addr the request carries selects
1703 /// the slot here too — [`PortDriverBase::set_addr_connected`] is the one
1704 /// owner of that resolution, and a user addressing no device marks the
1705 /// port's own. A driver that overrides this owns its transport's shape.
1706 fn connect(&mut self, user: &AsynUser) -> AsynResult<()> {
1707 // Single owner-API: edge-guarded fire is in PortDriverBase::set_connected.
1708 self.base_mut().set_addr_connected(user.addr, true);
1709 Ok(())
1710 }
1711
1712 fn disconnect(&mut self, user: &AsynUser) -> AsynResult<()> {
1713 self.base_mut().set_addr_connected(user.addr, false);
1714 Ok(())
1715 }
1716
1717 /// C `enable(pasynUser, 1)` (asynManager.c:2224-2251): ONE call, whose
1718 /// `findDpCommon(puserPvt)` picks the device's `dpCommon` or the port's from
1719 /// the addr the caller's user carries (:538-545). There is no second,
1720 /// device-only entry point in C and none here: [`PortDriverBase::
1721 /// set_addr_enabled`] is that resolution, and a user addressing no device
1722 /// lands on the port's own slot.
1723 fn enable(&mut self, user: &AsynUser) -> AsynResult<()> {
1724 // C `enable` refuses a defunct port (asynManager.c:2236-2241);
1725 // the guard lives in the single owner.
1726 self.base_mut().set_addr_enabled(user.addr, true)
1727 }
1728
1729 fn disable(&mut self, user: &AsynUser) -> AsynResult<()> {
1730 self.base_mut().set_addr_enabled(user.addr, false)
1731 }
1732
1733 fn connect_addr(&mut self, user: &AsynUser) -> AsynResult<()> {
1734 self.base_mut().connect_addr(user.addr);
1735 Ok(())
1736 }
1737
1738 fn disconnect_addr(&mut self, user: &AsynUser) -> AsynResult<()> {
1739 self.base_mut().disconnect_addr(user.addr);
1740 Ok(())
1741 }
1742
1743 fn get_option(&self, key: &str) -> AsynResult<String> {
1744 self.base()
1745 .options
1746 .get(key)
1747 .cloned()
1748 .ok_or_else(|| AsynError::OptionNotFound(key.to_string()))
1749 }
1750
1751 /// C `asynOption::setOption(void *drvPvt, asynUser *pasynUser, key, val)`.
1752 ///
1753 /// `user` is the caller's, and its `timeout` is the one that bounds any wire
1754 /// traffic the option write causes — an RFC 2217 negotiation on a COM port
1755 /// runs under it (`asynInterposeCom.c:475,495`). The option layer has no
1756 /// timeout of its own: an asynRecord option put negotiates under TMOT, an
1757 /// iocsh `asynSetOption` under its own 2 s (`asynShellCommands.c:119`).
1758 fn set_option(&mut self, _user: &mut AsynUser, key: &str, value: &str) -> AsynResult<()> {
1759 self.base_mut()
1760 .options
1761 .insert(key.to_string(), value.to_string());
1762 Ok(())
1763 }
1764
1765 /// The driver's own report — C `asynCommon::report`, which the manager calls
1766 /// last (`reportPrintPort`, asynManager.c:1113-1122) after printing the port's
1767 /// manager-level state itself.
1768 ///
1769 /// So this prints only what the *driver* owns. The port's enable / connect /
1770 /// queue / lock / exception / trace state is the manager's to print and is
1771 /// printed by `crate::port_actor::PortActor::report_port`; duplicating it
1772 /// here would give the operator two answers to the same question, from two
1773 /// owners, with no rule for which one wins.
1774 ///
1775 /// The default is C++ `asynPortDriver::report` (asynPortDriver.cpp:3677-3710):
1776 /// the port name; at `details >= 1` the timestamp, the EOS terminators *if the
1777 /// driver registered the octet interface* (`pasynStdInterfaces->octet.pinterface`,
1778 /// :3685) and the parameter library; at `details >= 3` the interrupt clients
1779 /// (:3695-3708).
1780 ///
1781 /// The report goes to `out`, C's `FILE *fp` — the driver never picks the
1782 /// stream. `crate::port_actor::PortActor::report_port` is the one owner that
1783 /// does, and it picks stdout, as `asynReport` does (asynShellCommands.c:589).
1784 fn report(&self, out: &mut dyn std::fmt::Write, level: i32) {
1785 use std::fmt::Write as _;
1786 let base = self.base();
1787 let _ = writeln!(out, "Port: {}", base.port_name);
1788 if level >= 1 {
1789 let _ = writeln!(
1790 out,
1791 " Timestamp: {}",
1792 format_timestamp(base.current_timestamp())
1793 );
1794 // C prints the EOS pair only when the driver registered `asynOctet`
1795 // (:3685) — on a port with no octet interface the two terminators are
1796 // the constructor's zeroed fields, and reporting them invents an EOS
1797 // the port cannot have.
1798 if self.has_octet_interface() {
1799 // C escapes the terminator with `epicsStrPrintEscaped` (:3687,
1800 // :3690) — the whole libCom table, not just CR and LF. A private
1801 // two-case table wrote a binary terminator (`\x03`, ESC, TAB, NUL)
1802 // raw into stdout (R16-48); [`crate::escape`] is the one owner.
1803 let input = base.input_eos(0);
1804 let output = base.output_eos(0);
1805 let _ = writeln!(
1806 out,
1807 " Input EOS[{}]: {}",
1808 input.len(),
1809 crate::escape::print_escaped(input)
1810 );
1811 let _ = writeln!(
1812 out,
1813 " Output EOS[{}]: {}",
1814 output.len(),
1815 crate::escape::print_escaped(output)
1816 );
1817 }
1818 // C hands its own level straight to `reportParams` (:3693).
1819 base.report_params(out, level);
1820 }
1821 // There is no options block: `asynPortDriver::report` never prints one
1822 // (asynPortDriver.cpp:3677-3710), and it could not — `asynOption` is a
1823 // get/set pair keyed by a string the *driver* defines, with nothing to
1824 // enumerate. The `option: k = v` lines this printed at `details >= 2` had
1825 // no C source and no fixed key set to be complete over: they listed
1826 // whatever happened to have been written through `setOption`, which is not
1827 // the port's option state (R16-49).
1828 if level >= 3 {
1829 report_interrupt_clients(out, base);
1830 }
1831 }
1832
1833 /// Whether this driver registered `asynOctet` — C's
1834 /// `pasynStdInterfaces->octet.pinterface != NULL`, which is set from the
1835 /// constructor's `interfaceMask` (asynPortDriver.cpp:4062). The Rust analogue
1836 /// of that mask is [`Self::capabilities`].
1837 fn has_octet_interface(&self) -> bool {
1838 self.capabilities()
1839 .iter()
1840 .any(|c| c.interface_type() == crate::interfaces::InterfaceType::Octet)
1841 }
1842
1843 // --- Scalar I/O (cache-based defaults, timeout not applicable) ---
1844
1845 // Cache-based defaults do NOT check connection state (C parity).
1846 // The port actor checks check_ready_addr() before dispatching, matching
1847 // C asyn where asynManager checks connection before calling the driver.
1848
1849 // Default reads use the STRICT getter: an undefined parameter must
1850 // surface as ParamUndefined, not success/0. C parity — the default
1851 // asynPortDriver::read{Int32,Int64,Float64,Octet,UInt32Digital}
1852 // (asynPortDriver.cpp) calls get{Integer,Integer64,Double,String,
1853 // UIntDigital}Param, and every paramVal getter throws
1854 // ParamValNotDefined → asynParamUndefined for an unset value
1855 // (paramVal.cpp:152,181,235,264,292). devAsyn* then routes that status
1856 // through asynStatusToEpicsAlarm(READ_ALARM, INVALID_ALARM) instead of
1857 // updating RVAL/clearing UDF (e.g. devAsynUInt32Digital.c:898-901,
1858 // devAsynInt32.c:844-847). The lax get_*_param accessors stay for
1859 // internal callers that explicitly want default-zero behavior.
1860
1861 fn read_int32(&mut self, user: &AsynUser) -> AsynResult<i32> {
1862 self.base().params.get_int32_strict(user.reason, user.addr)
1863 }
1864
1865 fn write_int32(&mut self, user: &mut AsynUser, value: i32) -> AsynResult<()> {
1866 self.base_mut()
1867 .params
1868 .set_int32(user.reason, user.addr, value)?;
1869 self.base_mut().call_param_callbacks(user.addr)
1870 }
1871
1872 fn read_int64(&mut self, user: &AsynUser) -> AsynResult<i64> {
1873 self.base().params.get_int64_strict(user.reason, user.addr)
1874 }
1875
1876 fn write_int64(&mut self, user: &mut AsynUser, value: i64) -> AsynResult<()> {
1877 self.base_mut()
1878 .params
1879 .set_int64(user.reason, user.addr, value)?;
1880 self.base_mut().call_param_callbacks(user.addr)
1881 }
1882
1883 /// C `asynInt32Base.c:99` default: report `low = high = 0` so a
1884 /// driver that does not implement getBounds makes convertAi/convertAo
1885 /// skip the LINEAR ESLO/EOFF computation (`devAsynInt32.c:444`).
1886 fn get_bounds_int32(&self, _user: &AsynUser) -> AsynResult<(i32, i32)> {
1887 Ok((0, 0))
1888 }
1889
1890 /// C `asynInt64Base.c:99` default: report `low = high = 0` (see
1891 /// `get_bounds_int32`).
1892 fn get_bounds_int64(&self, _user: &AsynUser) -> AsynResult<(i64, i64)> {
1893 Ok((0, 0))
1894 }
1895
1896 fn read_float64(&mut self, user: &AsynUser) -> AsynResult<f64> {
1897 self.base()
1898 .params
1899 .get_float64_strict(user.reason, user.addr)
1900 }
1901
1902 fn write_float64(&mut self, user: &mut AsynUser, value: f64) -> AsynResult<()> {
1903 self.base_mut()
1904 .params
1905 .set_float64(user.reason, user.addr, value)?;
1906 self.base_mut().call_param_callbacks(user.addr)
1907 }
1908
1909 fn read_octet(&mut self, user: &AsynUser, buf: &mut [u8]) -> AsynResult<usize> {
1910 let bytes = self
1911 .base()
1912 .params
1913 .get_string_strict(user.reason, user.addr)?;
1914 let n = bytes.len().min(buf.len());
1915 buf[..n].copy_from_slice(&bytes[..n]);
1916 Ok(n)
1917 }
1918
1919 fn write_octet(&mut self, user: &mut AsynUser, data: &[u8]) -> AsynResult<usize> {
1920 self.base_mut()
1921 .params
1922 .set_string(user.reason, user.addr, data.to_vec())?;
1923 self.base_mut().call_param_callbacks(user.addr)?;
1924 Ok(data.len())
1925 }
1926
1927 fn read_uint32_digital(&mut self, user: &AsynUser, mask: u32) -> AsynResult<u32> {
1928 let val = self
1929 .base()
1930 .params
1931 .get_uint32_strict(user.reason, user.addr)?;
1932 Ok(val & mask)
1933 }
1934
1935 fn write_uint32_digital(
1936 &mut self,
1937 user: &mut AsynUser,
1938 value: u32,
1939 mask: u32,
1940 ) -> AsynResult<()> {
1941 // The asynUInt32Digital write interface carries no forced interrupt
1942 // mask — changed bits derive from value^old (interrupt_mask = 0).
1943 self.base_mut()
1944 .params
1945 .set_uint32(user.reason, user.addr, value, mask, 0)?;
1946 self.base_mut().call_param_callbacks(user.addr)
1947 }
1948
1949 /// Configure rising / falling interrupt masks for a
1950 /// UInt32Digital parameter. C parity:
1951 /// `asynPortDriver::setInterruptUInt32Digital`
1952 /// (`asynPortDriver.cpp:2346-2369`) → routes to
1953 /// `paramList::setUInt32Interrupt`. The default delegates to the
1954 /// param store; drivers that need to push the configuration to
1955 /// hardware (e.g. real GPIB cards toggling SRQ enable) override
1956 /// it.
1957 fn set_interrupt_uint32_digital(
1958 &mut self,
1959 user: &AsynUser,
1960 mask: u32,
1961 reason: InterruptReason,
1962 ) -> AsynResult<()> {
1963 self.base_mut()
1964 .params
1965 .set_uint32_interrupt(user.reason, user.addr, mask, reason)
1966 }
1967
1968 /// Clear bits from rising AND falling masks. C parity:
1969 /// `asynPortDriver::clearInterruptUInt32Digital`
1970 /// (`asynPortDriver.cpp:2392-2415`). Mirrors C — the call does
1971 /// not take an `interruptReason`; both masks are cleared.
1972 fn clear_interrupt_uint32_digital(&mut self, user: &AsynUser, mask: u32) -> AsynResult<()> {
1973 self.base_mut()
1974 .params
1975 .clear_uint32_interrupt(user.reason, user.addr, mask)
1976 }
1977
1978 /// Read the configured rising / falling / combined mask. C
1979 /// parity: `asynPortDriver::getInterruptUInt32Digital`
1980 /// (`asynPortDriver.cpp:2438-2461`).
1981 fn get_interrupt_uint32_digital(
1982 &self,
1983 user: &AsynUser,
1984 reason: InterruptReason,
1985 ) -> AsynResult<u32> {
1986 self.base()
1987 .params
1988 .get_uint32_interrupt(user.reason, user.addr, reason)
1989 }
1990
1991 // --- Enum I/O (cache-based defaults) ---
1992
1993 fn read_enum(&mut self, user: &AsynUser) -> AsynResult<(usize, Arc<[EnumEntry]>)> {
1994 self.base().params.get_enum(user.reason, user.addr)
1995 }
1996
1997 fn write_enum(&mut self, user: &mut AsynUser, index: usize) -> AsynResult<()> {
1998 self.base_mut()
1999 .params
2000 .set_enum_index(user.reason, user.addr, index)?;
2001 self.base_mut().call_param_callbacks(user.addr)
2002 }
2003
2004 fn write_enum_choices(
2005 &mut self,
2006 user: &mut AsynUser,
2007 choices: Arc<[EnumEntry]>,
2008 ) -> AsynResult<()> {
2009 self.base_mut()
2010 .params
2011 .set_enum_choices(user.reason, user.addr, choices)?;
2012 self.base_mut().call_param_callbacks(user.addr)
2013 }
2014
2015 // --- GenericPointer I/O (cache-based defaults) ---
2016
2017 fn read_generic_pointer(&mut self, user: &AsynUser) -> AsynResult<Arc<dyn Any + Send + Sync>> {
2018 self.base()
2019 .params
2020 .get_generic_pointer(user.reason, user.addr)
2021 }
2022
2023 fn write_generic_pointer(
2024 &mut self,
2025 user: &mut AsynUser,
2026 value: Arc<dyn Any + Send + Sync>,
2027 ) -> AsynResult<()> {
2028 self.base_mut()
2029 .params
2030 .set_generic_pointer(user.reason, user.addr, value)?;
2031 self.base_mut().call_param_callbacks(user.addr)
2032 }
2033
2034 // --- Array I/O (default: not supported) ---
2035
2036 fn read_float64_array(&mut self, _user: &AsynUser, _buf: &mut [f64]) -> AsynResult<usize> {
2037 Err(AsynError::InterfaceNotSupported("asynFloat64Array".into()))
2038 }
2039
2040 fn write_float64_array(&mut self, user: &AsynUser, data: &[f64]) -> AsynResult<()> {
2041 self.base_mut()
2042 .params
2043 .set_float64_array(user.reason, user.addr, data.to_vec())?;
2044 self.base_mut().call_param_callbacks(user.addr)
2045 }
2046
2047 fn read_int32_array(&mut self, _user: &AsynUser, _buf: &mut [i32]) -> AsynResult<usize> {
2048 Err(AsynError::InterfaceNotSupported("asynInt32Array".into()))
2049 }
2050
2051 fn write_int32_array(&mut self, user: &AsynUser, data: &[i32]) -> AsynResult<()> {
2052 self.base_mut()
2053 .params
2054 .set_int32_array(user.reason, user.addr, data.to_vec())?;
2055 self.base_mut().call_param_callbacks(user.addr)
2056 }
2057
2058 fn read_int8_array(&mut self, _user: &AsynUser, _buf: &mut [i8]) -> AsynResult<usize> {
2059 Err(AsynError::InterfaceNotSupported("asynInt8Array".into()))
2060 }
2061
2062 fn write_int8_array(&mut self, user: &AsynUser, data: &[i8]) -> AsynResult<()> {
2063 self.base_mut()
2064 .params
2065 .set_int8_array(user.reason, user.addr, data.to_vec())?;
2066 self.base_mut().call_param_callbacks(user.addr)
2067 }
2068
2069 fn read_int16_array(&mut self, _user: &AsynUser, _buf: &mut [i16]) -> AsynResult<usize> {
2070 Err(AsynError::InterfaceNotSupported("asynInt16Array".into()))
2071 }
2072
2073 fn write_int16_array(&mut self, user: &AsynUser, data: &[i16]) -> AsynResult<()> {
2074 self.base_mut()
2075 .params
2076 .set_int16_array(user.reason, user.addr, data.to_vec())?;
2077 self.base_mut().call_param_callbacks(user.addr)
2078 }
2079
2080 fn read_int64_array(&mut self, _user: &AsynUser, _buf: &mut [i64]) -> AsynResult<usize> {
2081 Err(AsynError::InterfaceNotSupported("asynInt64Array".into()))
2082 }
2083
2084 fn write_int64_array(&mut self, user: &AsynUser, data: &[i64]) -> AsynResult<()> {
2085 self.base_mut()
2086 .params
2087 .set_int64_array(user.reason, user.addr, data.to_vec())?;
2088 self.base_mut().call_param_callbacks(user.addr)
2089 }
2090
2091 fn read_float32_array(&mut self, _user: &AsynUser, _buf: &mut [f32]) -> AsynResult<usize> {
2092 Err(AsynError::InterfaceNotSupported("asynFloat32Array".into()))
2093 }
2094
2095 fn write_float32_array(&mut self, user: &AsynUser, data: &[f32]) -> AsynResult<()> {
2096 self.base_mut()
2097 .params
2098 .set_float32_array(user.reason, user.addr, data.to_vec())?;
2099 self.base_mut().call_param_callbacks(user.addr)
2100 }
2101
2102 // --- I/O methods (worker thread calls these) ---
2103 // Default: delegate to cache-based read_*/write_* for backward compat.
2104 // Real I/O drivers override these for actual hardware access.
2105
2106 fn io_read_octet(&mut self, user: &AsynUser, buf: &mut [u8]) -> AsynResult<usize> {
2107 self.read_octet(user, buf)
2108 }
2109
2110 /// Octet read that also reports the end-of-message reason — C
2111 /// parity for `asynOctet::read(... int *eomReason)`
2112 /// (`asynOctet.h:38-40`). The default implementation delegates to
2113 /// [`Self::io_read_octet`] and reconstructs a synthetic
2114 /// [`EomReason`]: `CNT` when the buffer filled, `empty` otherwise.
2115 /// Drivers that have native EOM information
2116 /// (`asynOctetSyncIO::read`, GPIB END, EOS match) must
2117 /// override this method so consumers — `asynRecord::EOMR`,
2118 /// `asynOctetSyncIO::read` mirrors — receive the real flags.
2119 fn io_read_octet_eom(
2120 &mut self,
2121 user: &AsynUser,
2122 buf: &mut [u8],
2123 ) -> AsynResult<(usize, EomReason)> {
2124 let cap = buf.len();
2125 let n = self.io_read_octet(user, buf)?;
2126 let eom = if n >= cap && cap > 0 {
2127 EomReason::CNT
2128 } else {
2129 EomReason::empty()
2130 };
2131 Ok((n, eom))
2132 }
2133
2134 fn io_write_octet(&mut self, user: &mut AsynUser, data: &[u8]) -> AsynResult<usize> {
2135 self.write_octet(user, data)
2136 }
2137
2138 fn io_read_int32(&mut self, user: &AsynUser) -> AsynResult<i32> {
2139 self.read_int32(user)
2140 }
2141
2142 fn io_write_int32(&mut self, user: &mut AsynUser, value: i32) -> AsynResult<()> {
2143 self.write_int32(user, value)
2144 }
2145
2146 fn io_read_int64(&mut self, user: &AsynUser) -> AsynResult<i64> {
2147 self.read_int64(user)
2148 }
2149
2150 fn io_write_int64(&mut self, user: &mut AsynUser, value: i64) -> AsynResult<()> {
2151 self.write_int64(user, value)
2152 }
2153
2154 fn io_read_float64(&mut self, user: &AsynUser) -> AsynResult<f64> {
2155 self.read_float64(user)
2156 }
2157
2158 fn io_write_float64(&mut self, user: &mut AsynUser, value: f64) -> AsynResult<()> {
2159 self.write_float64(user, value)
2160 }
2161
2162 fn io_read_uint32_digital(&mut self, user: &AsynUser, mask: u32) -> AsynResult<u32> {
2163 self.read_uint32_digital(user, mask)
2164 }
2165
2166 fn io_write_uint32_digital(
2167 &mut self,
2168 user: &mut AsynUser,
2169 value: u32,
2170 mask: u32,
2171 ) -> AsynResult<()> {
2172 self.write_uint32_digital(user, value, mask)
2173 }
2174
2175 fn io_flush(&mut self, _user: &mut AsynUser) -> AsynResult<()> {
2176 Ok(())
2177 }
2178
2179 // --- Octet EOS (delegates to interpose stack by default) ---
2180 //
2181 // ## EOS connect-wait policy (C asyn issue #103)
2182 //
2183 // C asyn `asynOctetSyncIO::setInputEos` / `setOutputEos`
2184 // (`asynOctetSyncIO.c:300-321`, `:346-367`) bracket the driver call in
2185 // `lockPort`/`unlockPort`. `lockPort` is a plain mutex take —
2186 // `defunct` check, then `synchronousLock` (asynManager.c:1789-1798) —
2187 // and waits for no connection, so an EOS set blocks only behind
2188 // whoever else holds the port. The connect wait lives elsewhere:
2189 // `registerPort` calls `waitConnect(pport->pconnectUser,
2190 // pasynBase->autoConnectTimeout)` on an autoConnect port
2191 // (asynManager.c:2135), and `waitConnect` `epicsEventWaitWithTimeout`s
2192 // on a connect event signalled from an exception handler (:3292-3336).
2193 // That is what issue #103 sees: IOC startup pausing for the whole
2194 // autoConnect timeout when the device is off-line.
2195 //
2196 // The Rust path here is purely in-memory: `set_input_eos` and
2197 // `set_output_eos` write the bytes into `PortDriverBase` and the
2198 // EOS interpose stack reads from those fields at next read/write
2199 // time. No port lock, no connect-wait — so neither stall can reach an
2200 // EOS call here. If a future refactor introduces a connect-gated EOS
2201 // path (e.g. a driver that owns the EOS state inside its
2202 // connect()-allocated resource), authors MUST keep the wait optional /
2203 // bounded so the connect-wait failure mode doesn't return.
2204
2205 // Every hook takes the `asynUser`, because in C every one of them does
2206 // (`asynOctet::setInputEos(void *ppvt, asynUser *pasynUser, ...)`,
2207 // asynOctetBase.h; asynInterposeEos.c:288-296) and the addr it carries is
2208 // what picks the device's terminator. A port-wide EOS could not hold two.
2209
2210 /// The default is C's **Fail stub**, not a silent cache. `initOverride`
2211 /// swaps a NULL `setInputEos` for `setInputEosFail` (asynOctetBase.c:115),
2212 /// which answers `"<port> setInputEos not implemented"` and `asynError`
2213 /// (:370-380, :401-403) — and serial, IP, IP-server and FTDI really do
2214 /// leave it NULL (drvAsynSerialPort.c:1003, drvAsynIPPort.c:1049-1051,
2215 /// drvAsynIPServerPort.c:118-123, drvAsynFTDIPort.cpp:610-612). What
2216 /// makes IEOS work on those ports is `asynInterposeEos`, installed above
2217 /// the driver by `asynOctetBase::initialize` when `processEosIn` is set
2218 /// (:169-171) — so the terminator is accepted exactly when a layer takes
2219 /// it, and refused otherwise. A `noProcessEos` port reporting success and
2220 /// then never terminating is the failure this refusal exists to make loud.
2221 ///
2222 /// A driver with its own EOS methods overrides this, which is the Rust
2223 /// shape of a non-NULL entry in C's `asynOctet` table.
2224 fn set_input_eos(&mut self, user: &AsynUser, eos: &[u8]) -> AsynResult<()> {
2225 // Single write owner for input EOS: the per-device cache is what
2226 // `get_input_eos` and the binary-suppress save/restore read, and the
2227 // same value is forwarded to the interpose stack so an installed
2228 // `EosInterpose` actually terminates *this device's* reads on it.
2229 let addr = user.addr;
2230 let port = self.base().port_name.clone();
2231 let base = self.base_mut();
2232 // The length rule belongs to the layer that stores the terminator
2233 // (asynInterposeEos.c:299-303), so a port with no EOS support answers
2234 // "not implemented" for every length, exactly as its Fail stub does,
2235 // and a layer that owns the terminator refuses an illegal one without
2236 // storing it.
2237 match base.interpose_octet.set_input_eos(addr, eos) {
2238 EosSet::NotTaken => return Err(eos_not_implemented(&port, "setInputEos")),
2239 EosSet::IllegalLength => return Err(illegal_eoslen(&port, eos.len())),
2240 EosSet::Stored => {}
2241 }
2242 base.eos_entry(addr).input = eos.to_vec();
2243 Ok(())
2244 }
2245
2246 fn get_input_eos(&self, user: &AsynUser) -> Vec<u8> {
2247 self.base().input_eos(user.addr).to_vec()
2248 }
2249
2250 /// The output half of [`Self::set_input_eos`] — C `setOutputEosFail`
2251 /// (asynOctetBase.c:117, :409-411).
2252 fn set_output_eos(&mut self, user: &AsynUser, eos: &[u8]) -> AsynResult<()> {
2253 // Single write owner for output EOS (see `set_input_eos`): cache per
2254 // device and forward to the interpose stack so `EosInterpose` appends
2255 // the terminator on that device's writes.
2256 let addr = user.addr;
2257 let port = self.base().port_name.clone();
2258 let base = self.base_mut();
2259 match base.interpose_octet.set_output_eos(addr, eos) {
2260 EosSet::NotTaken => return Err(eos_not_implemented(&port, "setOutputEos")),
2261 EosSet::IllegalLength => return Err(illegal_eoslen(&port, eos.len())),
2262 EosSet::Stored => {}
2263 }
2264 base.eos_entry(addr).output = eos.to_vec();
2265 Ok(())
2266 }
2267
2268 fn get_output_eos(&self, user: &AsynUser) -> Vec<u8> {
2269 self.base().output_eos(user.addr).to_vec()
2270 }
2271
2272 // --- asynGpib (IEEE-488 bus control) ---
2273 //
2274 // The four command methods of C's `asynGpib` interface (asynGpibDriver.h:47-51),
2275 // which asynGpib.c passes straight through to the driver's `asynGpibPort`
2276 // (asynGpib.c:472-496). A driver that implements them declares
2277 // [`crate::interfaces::Capability::Gpib`], and that declaration is what a
2278 // client's `findInterface(asynGpibType)` answers — asynRecord reads it into
2279 // GPIBIV and refuses UCMD/ACMD when it is 0 (asynRecord.c:1232-1241,
2280 // :1647-1651).
2281 //
2282 // The defaults refuse: a port that has not declared the capability can only
2283 // be reached here by a caller that skipped the registry, and C has nothing
2284 // to call in that case (the interface pointer is NULL).
2285 //
2286 // Not ported: the `asynGpibPort` methods that exist solely to drive
2287 // asynGpib's SRQ poll thread — `srqStatus`, `srqEnable`, `serialPollBegin`,
2288 // `serialPoll`, `serialPollEnd` (asynGpibDriver.h:88-92), plus `pollAddr` /
2289 // `srqHappened` (asynGpib.c:498-559, 633-656). Nothing in this tree polls
2290 // SRQ; asynRecord's own "Serial Poll" ACMD does not use them (it sends SPE,
2291 // reads one octet, sends SPD — asynRecord.c:1717-1746).
2292
2293 /// C `asynGpib::universalCmd` — send one universal command byte with ATN
2294 /// asserted (asynGpib.c:480-484, `vxiUniversalCmd` drvVxi11.c:1406-1424).
2295 fn gpib_universal_cmd(&mut self, _user: &mut AsynUser, _cmd: u8) -> AsynResult<()> {
2296 Err(AsynError::Status {
2297 status: AsynStatus::Error,
2298 message: "port has no asynGpib interface".into(),
2299 })
2300 }
2301
2302 /// C `asynGpib::addressedCmd` — send an addressed-command frame with ATN
2303 /// asserted (asynGpib.c:472-478, `vxiAddressedCmd` drvVxi11.c:1360-1404).
2304 /// The frame is built by [`crate::interfaces::gpib::addressed_request`].
2305 fn gpib_addressed_cmd(&mut self, _user: &mut AsynUser, _data: &[u8]) -> AsynResult<()> {
2306 Err(AsynError::Status {
2307 status: AsynStatus::Error,
2308 message: "port has no asynGpib interface".into(),
2309 })
2310 }
2311
2312 /// C `asynGpib::ifc` — assert Interface Clear (asynGpib.c:486-490).
2313 fn gpib_ifc(&mut self, _user: &mut AsynUser) -> AsynResult<()> {
2314 Err(AsynError::Status {
2315 status: AsynStatus::Error,
2316 message: "port has no asynGpib interface".into(),
2317 })
2318 }
2319
2320 /// C `asynGpib::ren` — set the Remote Enable line (asynGpib.c:492-496).
2321 fn gpib_ren(&mut self, _user: &mut AsynUser, _enable: bool) -> AsynResult<()> {
2322 Err(AsynError::Status {
2323 status: AsynStatus::Error,
2324 message: "port has no asynGpib interface".into(),
2325 })
2326 }
2327
2328 // --- Lifecycle ---
2329
2330 /// Called when the port is being shut down. Drivers override this
2331 /// to release hardware resources. Matches C asynPortDriver::shutdownPortDriver().
2332 fn shutdown(&mut self) -> AsynResult<()> {
2333 Ok(())
2334 }
2335
2336 // --- drvUser ---
2337
2338 /// Resolve a record's bind request ([`DrvUserRequest`]: drvInfo string, asyn
2339 /// `addr`, and the record's asyn interface) to a [`DrvUserInfo`] — the
2340 /// asyn-rs analogue of C `drvUserCreate`.
2341 ///
2342 /// Takes `&mut self` so a driver can register a parameter on demand from the
2343 /// resolved drvInfo (C Autoparam lazy creation) rather than requiring it be
2344 /// declared up front. Such a driver must create the parameter with the type
2345 /// the record will read it as — [`DrvUserRequest::iface`] — the way C
2346 /// `adsAsynPortDriver::getRecordInfoFromDrvInfo` derives the parameter's
2347 /// asyn type from the bound record's DTYP.
2348 ///
2349 /// [`DrvUserRequest::addr`] lets a multi-device driver reject an
2350 /// out-of-range address at bind time (C `drvUserCreate` runs `checkOffset`,
2351 /// drvModbusAsyn.cpp:378-384) instead of alarming on every I/O.
2352 ///
2353 /// Default: look up the shared reason by parameter name; ignore the rest.
2354 fn drv_user_create(&mut self, req: &DrvUserRequest) -> AsynResult<DrvUserInfo> {
2355 let reason = self
2356 .base()
2357 .params
2358 .find_param(&req.drv_info)
2359 .ok_or_else(|| AsynError::ParamNotFound(req.drv_info.clone()))?;
2360 Ok(DrvUserInfo::from_reason(reason))
2361 }
2362
2363 // --- Capabilities ---
2364
2365 /// Declare the capabilities this driver supports.
2366 /// Default implementation includes all scalar read/write operations.
2367 fn capabilities(&self) -> Vec<crate::interfaces::Capability> {
2368 crate::interfaces::default_capabilities()
2369 }
2370
2371 /// Check if this driver supports a specific capability.
2372 fn supports(&self, cap: crate::interfaces::Capability) -> bool {
2373 self.capabilities().contains(&cap)
2374 }
2375
2376 fn init(&mut self) -> AsynResult<()> {
2377 Ok(())
2378 }
2379}
2380
2381/// The driver sitting at the **bottom** of a port's octet interpose chain — C's
2382/// driver-registered `asynOctet` interface, the one `interposeInterface` keeps
2383/// as `pPrev` when it pushes a layer on top (asynManager.c:2190-2220).
2384///
2385/// A driver never knows it is being interposed in C: `findInterface` hands the
2386/// caller the topmost layer, and the layer calls down. The Rust equivalent of
2387/// "the caller" is the port actor, so the chain runs there
2388/// ([`octet_read_chain`] and friends) and the driver's `io_*_octet` are the raw
2389/// device transfer, nothing more.
2390struct DriverOctetLink<'a> {
2391 driver: &'a mut dyn PortDriver,
2392}
2393
2394impl OctetNext for DriverOctetLink<'_> {
2395 /// C `asynOctetBase::readIt` (asynOctetBase.c:224-238): call the driver's
2396 /// own `read`, and on success fan the result out to the port's octet
2397 /// interrupt users.
2398 ///
2399 /// This is *below* the EOS layer by construction, and that is the whole
2400 /// point. C interposes `octetBase` directly on the driver
2401 /// (asynOctetBase.c:156-159) and only then pushes `asynInterposeEos` on top
2402 /// of it (:170-171), so the stack is `EOS → octetBase → driver`: every
2403 /// interrupt user sees the RAW DRIVER CHUNK — terminator included, with the
2404 /// driver's own CNT/END eomReason — and gets one callback per lower-level
2405 /// read, not one per EOS-completed message. Firing above the chain (as the
2406 /// port actor used to) handed an I/O-Intr record `"abc"`/EOMR=EOS where C
2407 /// hands it `"abc\r\n"`/EOMR=CNT|END.
2408 fn read(&mut self, user: &AsynUser, buf: &mut [u8]) -> AsynResult<OctetReadResult> {
2409 let (nbytes_transferred, eom_reason) = self.driver.io_read_octet_eom(user, buf)?;
2410 if self.driver.base().octet_interrupt_process {
2411 let raw = &buf[..nbytes_transferred];
2412 // C's rule for a device read: `addr` decides, `reason` is never
2413 // consulted (asynOctetBase.c:202-210). `reason` still rides on the
2414 // value — C leaves `pasynUser->reason` on the callback's user — but
2415 // it selects nobody.
2416 self.driver.base().interrupts.notify_octet(
2417 OctetFanOut::ByAddr(user.addr),
2418 InterruptValue {
2419 reason: user.reason,
2420 addr: user.addr,
2421 value: ParamValue::Octet(raw.to_vec()),
2422 timestamp: SystemTime::now(),
2423 iface: Some(InterfaceType::Octet),
2424 ..Default::default()
2425 },
2426 );
2427 }
2428 Ok(OctetReadResult {
2429 nbytes_transferred,
2430 eom_reason,
2431 })
2432 }
2433
2434 fn write(&mut self, user: &mut AsynUser, data: &[u8]) -> AsynResult<usize> {
2435 self.driver.io_write_octet(user, data)
2436 }
2437
2438 fn flush(&mut self, user: &mut AsynUser) -> AsynResult<()> {
2439 self.driver.io_flush(user)
2440 }
2441}
2442
2443/// Run `f` with the port's chain and the driver below it, both borrowed at once.
2444///
2445/// The chain lives inside the driver (`base.interpose_octet`) while the driver
2446/// is the chain's base, so the two are lifted apart for the duration of one
2447/// transfer and the chain is put straight back. The actor owns the driver and is
2448/// the only caller, so no other code can observe the port between the take and
2449/// the restore.
2450fn with_octet_chain<T>(
2451 driver: &mut dyn PortDriver,
2452 f: impl FnOnce(&mut OctetInterposeStack, &mut DriverOctetLink<'_>) -> T,
2453) -> T {
2454 let multi_device = driver.base().flags.multi_device;
2455 let mut chain = std::mem::replace(
2456 &mut driver.base_mut().interpose_octet,
2457 OctetInterposeStack::new(multi_device),
2458 );
2459 let result = {
2460 let mut link = DriverOctetLink {
2461 driver: &mut *driver,
2462 };
2463 f(&mut chain, &mut link)
2464 };
2465 driver.base_mut().interpose_octet = chain;
2466 result
2467}
2468
2469/// One octet read on the port: through every interpose layer installed on the
2470/// addressed device, ending at the driver.
2471///
2472/// C `asynOctet::read` on the interface `findInterface` resolves — which is the
2473/// outermost interpose whenever one is installed. The chain belongs to the
2474/// **port**, not to the driver: `asynInterposeEos` / `asynInterposeEcho` /
2475/// `asynInterposeDelay` are pushed by the manager (asynManager.c:2190-2220) and
2476/// the driver below is not consulted and cannot opt out. Dispatching inside each
2477/// driver instead — as this crate did — made the chain per-driver opt-in, so the
2478/// EOS layer `drvAsynFTDIPortConfigure` installs (drvAsynFTDIPort.cpp:622-623,
2479/// ftdi.rs) was never run by anything.
2480pub(crate) fn octet_read_chain(
2481 driver: &mut dyn PortDriver,
2482 user: &AsynUser,
2483 buf: &mut [u8],
2484) -> AsynResult<(usize, EomReason)> {
2485 with_octet_chain(driver, |chain, link| chain.dispatch_read(user, buf, link))
2486 .map(|r| (r.nbytes_transferred, r.eom_reason))
2487}
2488
2489/// One octet write on the port, through the addressed device's chain
2490/// (see [`octet_read_chain`]).
2491pub(crate) fn octet_write_chain(
2492 driver: &mut dyn PortDriver,
2493 user: &mut AsynUser,
2494 data: &[u8],
2495) -> AsynResult<usize> {
2496 with_octet_chain(driver, |chain, link| chain.dispatch_write(user, data, link))
2497}
2498
2499/// One octet flush on the port, through the addressed device's chain — C
2500/// `asynInterposeEos::flushIt` resets the layer's read-ahead buffer and then
2501/// flushes the layer below (asynInterposeEos.c:256-268), which only happens if
2502/// the flush enters the chain at the top (see [`octet_read_chain`]).
2503pub(crate) fn octet_flush_chain(
2504 driver: &mut dyn PortDriver,
2505 user: &mut AsynUser,
2506) -> AsynResult<()> {
2507 with_octet_chain(driver, |chain, link| chain.dispatch_flush(user, link))
2508}
2509
2510#[cfg(test)]
2511mod tests {
2512 use super::*;
2513
2514 /// A driver whose `io_read_octet_eom` hands back one scripted chunk per
2515 /// call, with the driver-level eomReason C would report (CNT when the
2516 /// caller's buffer filled, END never — a stream driver has no message
2517 /// boundary). The EOS layer above it is what turns chunks into messages.
2518 struct ChunkDriver {
2519 base: PortDriverBase,
2520 chunks: Vec<Vec<u8>>,
2521 next: usize,
2522 }
2523
2524 impl ChunkDriver {
2525 fn new(chunks: Vec<&[u8]>) -> Self {
2526 let mut base = PortDriverBase::new("chunk", 1, PortFlags::default());
2527 base.octet_interrupt_process = true;
2528 base.init_connected(true);
2529 Self {
2530 base,
2531 chunks: chunks.into_iter().map(|c| c.to_vec()).collect(),
2532 next: 0,
2533 }
2534 }
2535 }
2536
2537 impl PortDriver for ChunkDriver {
2538 fn base(&self) -> &PortDriverBase {
2539 &self.base
2540 }
2541 fn base_mut(&mut self) -> &mut PortDriverBase {
2542 &mut self.base
2543 }
2544 fn io_read_octet_eom(
2545 &mut self,
2546 _user: &AsynUser,
2547 buf: &mut [u8],
2548 ) -> AsynResult<(usize, EomReason)> {
2549 let chunk = self.chunks.get(self.next).cloned().unwrap_or_default();
2550 self.next += 1;
2551 let n = chunk.len().min(buf.len());
2552 buf[..n].copy_from_slice(&chunk[..n]);
2553 let eom = if n == buf.len() {
2554 EomReason::CNT
2555 } else {
2556 EomReason::empty()
2557 };
2558 Ok((n, eom))
2559 }
2560 }
2561
2562 /// The octet interrupt fan-out runs BELOW the interpose chain, at the
2563 /// driver link — C's `asynOctetBase::readIt` (asynOctetBase.c:224-238),
2564 /// which is interposed directly on the driver (:156-159) with the EOS layer
2565 /// pushed on top of it (:170-171).
2566 ///
2567 /// Two boundaries, both invisible when the fan-out ran above the chain:
2568 /// (1) the payload an interrupt user receives is the RAW driver chunk —
2569 /// terminator included — not the EOS-stripped message the caller gets; and
2570 /// (2) a message assembled from two lower-level reads fires TWO callbacks,
2571 /// one per driver read, not one per completed message.
2572 #[test]
2573 fn octet_interrupt_fans_out_below_the_interpose_chain() {
2574 use crate::interpose::eos::EosInterpose;
2575 use crate::interrupt::{InterruptFilter, InterruptValue};
2576 use std::sync::{Arc, Mutex};
2577
2578 // The message "abc\r\n" arrives split across two driver reads.
2579 let mut drv = ChunkDriver::new(vec![b"ab", b"c\r\n"]);
2580 drv.base_mut()
2581 .install_octet_interpose(Box::new(EosInterpose::default()));
2582 drv.set_input_eos(&AsynUser::default(), b"\r\n").unwrap();
2583
2584 let seen: Arc<Mutex<Vec<Vec<u8>>>> = Arc::new(Mutex::new(Vec::new()));
2585 let seen_cb = seen.clone();
2586 let _sub = drv.base().interrupts.register_sync_callback(
2587 InterruptFilter::default(),
2588 move |iv: &InterruptValue| {
2589 if let ParamValue::Octet(s) = &iv.value {
2590 seen_cb.lock().unwrap().push(s.clone());
2591 }
2592 },
2593 );
2594
2595 let user = AsynUser::default();
2596 let mut buf = [0u8; 32];
2597 let (n, eom) = octet_read_chain(&mut drv, &user, &mut buf).unwrap();
2598
2599 // The CALLER gets the EOS-terminated message, terminator stripped.
2600 assert_eq!(&buf[..n], b"abc");
2601 assert!(eom.contains(EomReason::EOS), "caller sees EOS, got {eom:?}");
2602
2603 // The INTERRUPT USERS get the raw driver chunks, terminator included,
2604 // one callback per lower-level read.
2605 assert_eq!(
2606 *seen.lock().unwrap(),
2607 vec![b"ab".to_vec(), b"c\r\n".to_vec()],
2608 "each driver read fans out its raw chunk"
2609 );
2610 }
2611
2612 /// A device answer is bytes. C's octet callback hands the subscriber
2613 /// `pasynUser`'s buffer verbatim (`asynOctetBase.c:224-238`) and
2614 /// `asynPortDriver::doCallbacksOctet` hands it `val.c_str()`
2615 /// (asynPortDriver.cpp:2011-2027) — a `char *`, which carries any byte.
2616 /// Carrying the payload in a Rust `String` could not: the fan-out decoded
2617 /// it lossily, so a binary protocol's `0x80..=0xff` reached every I/O Intr
2618 /// record as U+FFFD (`ef bf bd`), longer than the byte it replaced and no
2619 /// longer the device's answer.
2620 #[test]
2621 fn an_octet_interrupt_carries_a_non_utf8_device_byte_verbatim() {
2622 use crate::interrupt::{InterruptFilter, InterruptValue};
2623 use std::sync::{Arc, Mutex};
2624
2625 // A Modbus-shaped answer: a high byte, an embedded NUL, a lone 0xff.
2626 const RAW: &[u8] = &[0x01, 0x80, 0x00, 0xfe, 0xff, 0x41];
2627 let mut drv = ChunkDriver::new(vec![RAW]);
2628
2629 let seen: Arc<Mutex<Vec<Vec<u8>>>> = Arc::new(Mutex::new(Vec::new()));
2630 let seen_cb = seen.clone();
2631 let _sub = drv.base().interrupts.register_sync_callback(
2632 InterruptFilter::default(),
2633 move |iv: &InterruptValue| {
2634 if let ParamValue::Octet(bytes) = &iv.value {
2635 seen_cb.lock().unwrap().push(bytes.clone());
2636 }
2637 },
2638 );
2639
2640 let user = AsynUser::default();
2641 let mut buf = [0u8; 32];
2642 let (n, _eom) = octet_read_chain(&mut drv, &user, &mut buf).unwrap();
2643
2644 assert_eq!(&buf[..n], RAW, "the caller gets the device bytes");
2645 assert_eq!(
2646 *seen.lock().unwrap(),
2647 vec![RAW.to_vec()],
2648 "so does the interrupt user — no lossy decode on the fan-out"
2649 );
2650 }
2651
2652 /// The `interruptAccept` gate: a `call_param_callbacks` fired before the
2653 /// IOC accepts interrupts must PRESERVE the changed-flag, not consume it,
2654 /// so a value seeded at construction still reaches the record on the
2655 /// one-shot flush the scan facility fires at `iocInit`. C
2656 /// `asynPortDriver.cpp:838` returns before `flags.clear()` (`:871`) while
2657 /// `interruptAccept` is false.
2658 ///
2659 /// Before this gate existed, the first `call_param_callbacks` — a driver's
2660 /// own acquisition/array task can fire it before the `_RBV` records
2661 /// subscribe — cleared the flag, and a read-only seed
2662 /// (`Manufacturer`, `MaxSizeX`) was lost for the life of the process.
2663 ///
2664 /// This mutates a process-global flag; nextest isolates each test in its
2665 /// own process, so it does not race with the crate's other port tests.
2666 #[test]
2667 fn call_param_callbacks_before_interrupt_accept_preserves_the_seed() {
2668 use crate::interrupt::{InterruptFilter, InterruptValue};
2669 use epics_libcom_rs::runtime::interrupt_accept::set_interrupts_accepted;
2670 use std::sync::{Arc, Mutex};
2671
2672 let mut base = PortDriverBase::new("gate", 1, PortFlags::default());
2673 let val = base.create_param("VAL", ParamType::Int32).unwrap();
2674
2675 let seen: Arc<Mutex<Vec<i32>>> = Arc::new(Mutex::new(Vec::new()));
2676 let sink = seen.clone();
2677 let _sub = base.interrupts.register_sync_callback(
2678 InterruptFilter {
2679 reason: Some(val),
2680 addr: Some(0),
2681 uint32_mask: None,
2682 iface: None,
2683 },
2684 move |iv: &InterruptValue| {
2685 if let ParamValue::Int32(v) = &iv.value {
2686 sink.lock().unwrap().push(*v);
2687 }
2688 },
2689 );
2690
2691 // Pre-iocInit: interrupts not accepted. The subscriber exists (the
2692 // record registered), the driver seeds a read-only value, and its own
2693 // task fires a callback — which must deliver NOTHING and leave the flag
2694 // pending.
2695 set_interrupts_accepted(false);
2696 base.set_int32_param(val, 0, 640).unwrap();
2697 base.call_param_callbacks(0).unwrap();
2698 assert!(
2699 seen.lock().unwrap().is_empty(),
2700 "a callback fired before interruptAccept must not deliver — got {:?}",
2701 *seen.lock().unwrap()
2702 );
2703
2704 // iocInit accepts interrupts; the flush the scan facility now performs
2705 // delivers the preserved seed exactly once.
2706 set_interrupts_accepted(true);
2707 base.call_param_callbacks(0).unwrap();
2708 assert_eq!(
2709 *seen.lock().unwrap(),
2710 vec![640],
2711 "the seed preserved across the gated call must reach the subscriber \
2712 once interrupts are accepted"
2713 );
2714 }
2715
2716 struct TestDriver {
2717 base: PortDriverBase,
2718 }
2719
2720 impl TestDriver {
2721 fn new() -> Self {
2722 // These tests exercise `call_param_callbacks` delivery with no
2723 // `iocInit` to open the interruptAccept gate. Establish the
2724 // precondition a real port has by the time records process — the
2725 // scan facility has run `scan_run` — which is the direct analogue
2726 // of C's non-IOC translation unit that unit tests link with
2727 // `interruptAccept = 1` (`asynPortDriver.cpp:23-25`). The seed-
2728 // preservation regression test builds its own `PortDriverBase` and
2729 // drives the gate itself, so it is unaffected.
2730 epics_libcom_rs::runtime::interrupt_accept::set_interrupts_accepted(true);
2731 let mut base = PortDriverBase::new("test", 1, PortFlags::default());
2732 base.create_param("VAL", ParamType::Int32).unwrap();
2733 base.create_param("TEMP", ParamType::Float64).unwrap();
2734 base.create_param("MSG", ParamType::Octet).unwrap();
2735 base.create_param("BITS", ParamType::UInt32Digital).unwrap();
2736 Self { base }
2737 }
2738 }
2739
2740 impl PortDriver for TestDriver {
2741 fn base(&self) -> &PortDriverBase {
2742 &self.base
2743 }
2744 fn base_mut(&mut self) -> &mut PortDriverBase {
2745 &mut self.base
2746 }
2747 }
2748
2749 #[test]
2750 fn test_default_read_write_int32() {
2751 let mut drv = TestDriver::new();
2752 let mut user = AsynUser::new(0);
2753 drv.write_int32(&mut user, 42).unwrap();
2754 let user = AsynUser::new(0);
2755 assert_eq!(drv.read_int32(&user).unwrap(), 42);
2756 }
2757
2758 #[test]
2759 fn test_default_read_write_float64() {
2760 let mut drv = TestDriver::new();
2761 let mut user = AsynUser::new(1);
2762 drv.write_float64(&mut user, 3.14).unwrap();
2763 let user = AsynUser::new(1);
2764 assert!((drv.read_float64(&user).unwrap() - 3.14).abs() < 1e-10);
2765 }
2766
2767 #[test]
2768 fn test_default_read_write_octet() {
2769 let mut drv = TestDriver::new();
2770 let mut user = AsynUser::new(2);
2771 drv.write_octet(&mut user, b"hello").unwrap();
2772 let user = AsynUser::new(2);
2773 let mut buf = [0u8; 32];
2774 let n = drv.read_octet(&user, &mut buf).unwrap();
2775 assert_eq!(&buf[..n], b"hello");
2776 }
2777
2778 #[test]
2779 fn test_default_read_write_uint32() {
2780 let mut drv = TestDriver::new();
2781 let mut user = AsynUser::new(3);
2782 drv.write_uint32_digital(&mut user, 0xFF, 0x0F).unwrap();
2783 let user = AsynUser::new(3);
2784 assert_eq!(drv.read_uint32_digital(&user, 0xFF).unwrap(), 0x0F);
2785 }
2786
2787 #[test]
2788 fn test_connect_disconnect() {
2789 let mut drv = TestDriver::new();
2790 let user = AsynUser::default();
2791 assert!(drv.base().is_connected());
2792 drv.disconnect(&user).unwrap();
2793 assert!(!drv.base().is_connected());
2794 drv.connect(&user).unwrap();
2795 assert!(drv.base().is_connected());
2796 }
2797
2798 #[test]
2799 fn test_drv_user_create() {
2800 let mut drv = TestDriver::new();
2801 assert_eq!(
2802 drv.drv_user_create(&DrvUserRequest::new("VAL", 0))
2803 .unwrap()
2804 .reason,
2805 0
2806 );
2807 assert_eq!(
2808 drv.drv_user_create(&DrvUserRequest::new("TEMP", 0))
2809 .unwrap()
2810 .reason,
2811 1
2812 );
2813 assert!(
2814 drv.drv_user_create(&DrvUserRequest::new("NOPE", 0))
2815 .is_err()
2816 );
2817 }
2818
2819 #[test]
2820 fn test_call_param_callbacks() {
2821 let mut drv = TestDriver::new();
2822 let mut rx = drv.base_mut().interrupts.subscribe_async();
2823
2824 drv.base_mut().set_int32_param(0, 0, 100).unwrap();
2825 drv.base_mut().set_float64_param(1, 0, 2.0).unwrap();
2826 drv.base_mut().call_param_callbacks(0).unwrap();
2827
2828 let v1 = rx.try_recv().unwrap();
2829 assert_eq!(v1.reason, 0);
2830 let v2 = rx.try_recv().unwrap();
2831 assert_eq!(v2.reason, 1);
2832 assert!(rx.try_recv().is_err());
2833 }
2834
2835 #[test]
2836 fn flush_skips_undefined_scalar_but_keeps_array_trigger() {
2837 // C asynPortDriver.cpp:845 — a status/alarm change (or bare
2838 // mark_changed) on a never-set scalar consumes the changed flag
2839 // but fires no callback. Array/generic-pointer triggers have no
2840 // callCallbacks analog (:846-865 switch is scalar-only) and must
2841 // still fire even while undefined.
2842 let mut drv = TestDriver::new();
2843 let arr = drv
2844 .base_mut()
2845 .create_param("ARR", ParamType::Int32Array)
2846 .unwrap();
2847 let mut rx = drv.base_mut().interrupts.subscribe_async();
2848
2849 // Status change on the never-set scalar VAL (index 0): marks it
2850 // changed but it stays undefined.
2851 drv.base_mut()
2852 .params
2853 .set_param_status(0, 0, AsynStatus::Error, 0, 0)
2854 .unwrap();
2855 // Mark the never-set array param changed: an override-served trigger.
2856 drv.base_mut().mark_param_changed(arr, 0).unwrap();
2857
2858 drv.base_mut().call_param_callbacks(0).unwrap();
2859
2860 // Only the array trigger is delivered; the undefined scalar is gated.
2861 let iv = rx.try_recv().unwrap();
2862 assert_eq!(
2863 iv.reason, arr,
2864 "array trigger must still fire while undefined"
2865 );
2866 assert!(
2867 rx.try_recv().is_err(),
2868 "undefined scalar must not emit an I/O Intr"
2869 );
2870
2871 // Once the scalar is defined, a subsequent change does fire.
2872 drv.base_mut().set_int32_param(0, 0, 7).unwrap();
2873 drv.base_mut().call_param_callbacks(0).unwrap();
2874 let iv2 = rx.try_recv().unwrap();
2875 assert_eq!(iv2.reason, 0, "defined scalar must fire");
2876 }
2877
2878 #[test]
2879 fn uint32_callback_mask_does_not_leak_across_flushes() {
2880 // C resets uInt32CallbackMask = 0 after each uint32Callback
2881 // (asynPortDriver.cpp:855): a second flush must deliver only the
2882 // bits changed since the first, never the accumulated history.
2883 let mut drv = TestDriver::new();
2884 let mut rx = drv.base_mut().interrupts.subscribe_async();
2885
2886 // flush 1: change bit 0 on BITS (param index 3).
2887 drv.base_mut()
2888 .params
2889 .set_uint32(3, 0, 0x01, 0x01, 0)
2890 .unwrap();
2891 drv.base_mut().call_param_callbacks(0).unwrap();
2892 let iv1 = rx.try_recv().unwrap();
2893 assert_eq!(iv1.reason, 3);
2894 assert_eq!(iv1.uint32_changed_mask, 0x01);
2895
2896 // flush 2: change bit 1 only — must deliver 0x02, not 0x03.
2897 drv.base_mut()
2898 .params
2899 .set_uint32(3, 0, 0x02, 0x02, 0)
2900 .unwrap();
2901 drv.base_mut().call_param_callbacks(0).unwrap();
2902 let iv2 = rx.try_recv().unwrap();
2903 assert_eq!(
2904 iv2.uint32_changed_mask, 0x02,
2905 "second flush must not leak flush-1 bits via an un-reset mask"
2906 );
2907 assert_eq!(
2908 drv.base().params.get_uint32_interrupt_mask(3, 0).unwrap(),
2909 0,
2910 "the flush must consume (reset) the callback mask"
2911 );
2912 }
2913
2914 #[test]
2915 fn test_call_param_callbacks_propagates_aux_status_and_alarm() {
2916 // C parity: asynPortDriver.cpp:633-637 writes the param's stored
2917 // status / alarmStatus / alarmSeverity onto the subscriber's
2918 // pasynUser before invoking the callback. The Rust port carries
2919 // those fields on InterruptValue.
2920 let mut drv = TestDriver::new();
2921 let mut rx = drv.base_mut().interrupts.subscribe_async();
2922
2923 drv.base_mut().set_int32_param(0, 0, 99).unwrap();
2924 drv.base_mut()
2925 .params
2926 .set_param_status(0, 0, crate::error::AsynStatus::Timeout, 4, 2)
2927 .unwrap();
2928 drv.base_mut().call_param_callbacks(0).unwrap();
2929
2930 let iv = rx.try_recv().unwrap();
2931 assert_eq!(iv.reason, 0);
2932 assert!(matches!(iv.aux_status, crate::error::AsynStatus::Timeout));
2933 assert_eq!(iv.alarm_status, 4);
2934 assert_eq!(iv.alarm_severity, 2);
2935 }
2936
2937 #[test]
2938 fn test_call_param_callback_single_propagates_aux_status() {
2939 // Mirror for the single-flush path (call_param_callback).
2940 let mut drv = TestDriver::new();
2941 let mut rx = drv.base_mut().interrupts.subscribe_async();
2942
2943 drv.base_mut().set_int32_param(0, 0, 1).unwrap();
2944 drv.base_mut()
2945 .params
2946 .set_param_status(0, 0, crate::error::AsynStatus::Disconnected, 7, 3)
2947 .unwrap();
2948 drv.base_mut().call_param_callback(0, 0).unwrap();
2949
2950 let iv = rx.try_recv().unwrap();
2951 assert!(matches!(
2952 iv.aux_status,
2953 crate::error::AsynStatus::Disconnected
2954 ));
2955 assert_eq!(iv.alarm_status, 7);
2956 assert_eq!(iv.alarm_severity, 3);
2957 }
2958
2959 #[test]
2960 fn test_no_callback_for_unchanged() {
2961 let mut drv = TestDriver::new();
2962 let mut rx = drv.base_mut().interrupts.subscribe_async();
2963
2964 drv.base_mut().set_int32_param(0, 0, 5).unwrap();
2965 drv.base_mut().call_param_callbacks(0).unwrap();
2966 let _ = rx.try_recv().unwrap(); // consume
2967
2968 // Set same value — no interrupt
2969 drv.base_mut().set_int32_param(0, 0, 5).unwrap();
2970 drv.base_mut().call_param_callbacks(0).unwrap();
2971 assert!(rx.try_recv().is_err());
2972 }
2973
2974 #[test]
2975 fn test_array_not_supported_by_default() {
2976 let mut drv = TestDriver::new();
2977 let user = AsynUser::new(0);
2978 let mut buf = [0f64; 10];
2979 assert!(drv.read_float64_array(&user, &mut buf).is_err());
2980 assert!(drv.write_float64_array(&user, &[1.0]).is_err());
2981 }
2982
2983 #[test]
2984 fn test_option_set_get() {
2985 let mut drv = TestDriver::new();
2986 drv.set_option(&mut AsynUser::default(), "baud", "9600")
2987 .unwrap();
2988 assert_eq!(drv.get_option("baud").unwrap(), "9600");
2989 drv.set_option(&mut AsynUser::default(), "baud", "115200")
2990 .unwrap();
2991 assert_eq!(drv.get_option("baud").unwrap(), "115200");
2992 }
2993
2994 #[test]
2995 fn test_option_not_found() {
2996 let drv = TestDriver::new();
2997 let err = drv.get_option("nonexistent").unwrap_err();
2998 assert!(matches!(err, AsynError::OptionNotFound(_)));
2999 }
3000
3001 #[test]
3002 fn test_report_no_panic() {
3003 let mut drv = TestDriver::new();
3004 drv.set_option(&mut AsynUser::default(), "testkey", "testval")
3005 .unwrap();
3006 drv.base_mut().set_int32_param(0, 0, 42).unwrap();
3007 for level in 0..=3 {
3008 let mut out = String::new();
3009 drv.report(&mut out, level);
3010 }
3011 }
3012
3013 #[test]
3014 fn test_callback_uses_param_timestamp() {
3015 let mut drv = TestDriver::new();
3016 let mut rx = drv.base_mut().interrupts.subscribe_async();
3017
3018 let custom_ts = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000);
3019 drv.base_mut().set_int32_param(0, 0, 77).unwrap();
3020 drv.base_mut().set_param_timestamp(0, 0, custom_ts).unwrap();
3021 drv.base_mut().call_param_callbacks(0).unwrap();
3022
3023 let v = rx.try_recv().unwrap();
3024 assert_eq!(v.reason, 0);
3025 assert_eq!(v.timestamp, custom_ts);
3026 }
3027
3028 #[test]
3029 fn test_default_read_write_enum() {
3030 use crate::param::EnumEntry;
3031
3032 let mut base = PortDriverBase::new("test_enum", 1, PortFlags::default());
3033 base.create_param("MODE", ParamType::Enum).unwrap();
3034
3035 struct EnumDriver {
3036 base: PortDriverBase,
3037 }
3038 impl PortDriver for EnumDriver {
3039 fn base(&self) -> &PortDriverBase {
3040 &self.base
3041 }
3042 fn base_mut(&mut self) -> &mut PortDriverBase {
3043 &mut self.base
3044 }
3045 }
3046
3047 let mut drv = EnumDriver { base };
3048 let choices: Arc<[EnumEntry]> = Arc::from(vec![
3049 EnumEntry {
3050 string: "Off".into(),
3051 value: 0,
3052 severity: 0,
3053 },
3054 EnumEntry {
3055 string: "On".into(),
3056 value: 1,
3057 severity: 0,
3058 },
3059 ]);
3060 let mut user = AsynUser::new(0);
3061 drv.write_enum_choices(&mut user, choices).unwrap();
3062 drv.write_enum(&mut user, 1).unwrap();
3063 let (idx, ch) = drv.read_enum(&AsynUser::new(0)).unwrap();
3064 assert_eq!(idx, 1);
3065 assert_eq!(ch[1].string, "On");
3066 }
3067
3068 #[test]
3069 fn test_enum_callback() {
3070 use crate::param::{EnumEntry, ParamValue};
3071
3072 // Post-`iocInit` precondition — see `TestDriver::new`.
3073 epics_libcom_rs::runtime::interrupt_accept::set_interrupts_accepted(true);
3074 let mut base = PortDriverBase::new("test_enum_cb", 1, PortFlags::default());
3075 base.create_param("MODE", ParamType::Enum).unwrap();
3076 let mut rx = base.interrupts.subscribe_async();
3077
3078 struct EnumDriver {
3079 base: PortDriverBase,
3080 }
3081 impl PortDriver for EnumDriver {
3082 fn base(&self) -> &PortDriverBase {
3083 &self.base
3084 }
3085 fn base_mut(&mut self) -> &mut PortDriverBase {
3086 &mut self.base
3087 }
3088 }
3089
3090 let mut drv = EnumDriver { base };
3091 let choices: Arc<[EnumEntry]> = Arc::from(vec![
3092 EnumEntry {
3093 string: "A".into(),
3094 value: 0,
3095 severity: 0,
3096 },
3097 EnumEntry {
3098 string: "B".into(),
3099 value: 1,
3100 severity: 0,
3101 },
3102 ]);
3103 drv.base_mut()
3104 .set_enum_choices_param(0, 0, choices)
3105 .unwrap();
3106 drv.base_mut().set_enum_index_param(0, 0, 1).unwrap();
3107 drv.base_mut().call_param_callbacks(0).unwrap();
3108
3109 let v = rx.try_recv().unwrap();
3110 assert_eq!(v.reason, 0);
3111 assert!(matches!(v.value, ParamValue::Enum { index: 1, .. }));
3112 }
3113
3114 #[test]
3115 fn test_default_read_write_generic_pointer() {
3116 let mut base = PortDriverBase::new("test_gp", 1, PortFlags::default());
3117 base.create_param("PTR", ParamType::GenericPointer).unwrap();
3118
3119 struct GpDriver {
3120 base: PortDriverBase,
3121 }
3122 impl PortDriver for GpDriver {
3123 fn base(&self) -> &PortDriverBase {
3124 &self.base
3125 }
3126 fn base_mut(&mut self) -> &mut PortDriverBase {
3127 &mut self.base
3128 }
3129 }
3130
3131 let mut drv = GpDriver { base };
3132 let data: Arc<dyn std::any::Any + Send + Sync> = Arc::new(99i32);
3133 let mut user = AsynUser::new(0);
3134 drv.write_generic_pointer(&mut user, data).unwrap();
3135 let val = drv.read_generic_pointer(&AsynUser::new(0)).unwrap();
3136 assert_eq!(*val.downcast_ref::<i32>().unwrap(), 99);
3137 }
3138
3139 #[test]
3140 fn test_generic_pointer_callback() {
3141 use crate::param::ParamValue;
3142
3143 // Post-`iocInit` precondition — see `TestDriver::new`.
3144 epics_libcom_rs::runtime::interrupt_accept::set_interrupts_accepted(true);
3145 let mut base = PortDriverBase::new("test_gp_cb", 1, PortFlags::default());
3146 base.create_param("PTR", ParamType::GenericPointer).unwrap();
3147 let mut rx = base.interrupts.subscribe_async();
3148
3149 struct GpDriver {
3150 base: PortDriverBase,
3151 }
3152 impl PortDriver for GpDriver {
3153 fn base(&self) -> &PortDriverBase {
3154 &self.base
3155 }
3156 fn base_mut(&mut self) -> &mut PortDriverBase {
3157 &mut self.base
3158 }
3159 }
3160
3161 let mut drv = GpDriver { base };
3162 let data: Arc<dyn std::any::Any + Send + Sync> = Arc::new(vec![1, 2, 3]);
3163 drv.base_mut()
3164 .set_generic_pointer_param(0, 0, data)
3165 .unwrap();
3166 drv.base_mut().call_param_callbacks(0).unwrap();
3167
3168 let v = rx.try_recv().unwrap();
3169 assert_eq!(v.reason, 0);
3170 assert!(matches!(v.value, ParamValue::GenericPointer(_)));
3171 }
3172
3173 #[test]
3174 fn test_interpose_push_requires_lock() {
3175 use crate::interpose::{OctetInterpose, OctetNext, OctetReadResult};
3176 use parking_lot::Mutex;
3177 use std::sync::Arc;
3178
3179 struct NoopInterpose;
3180 impl OctetInterpose for NoopInterpose {
3181 fn read(
3182 &mut self,
3183 user: &AsynUser,
3184 buf: &mut [u8],
3185 next: &mut dyn OctetNext,
3186 ) -> AsynResult<OctetReadResult> {
3187 next.read(user, buf)
3188 }
3189 fn write(
3190 &mut self,
3191 user: &mut AsynUser,
3192 data: &[u8],
3193 next: &mut dyn OctetNext,
3194 ) -> AsynResult<usize> {
3195 next.write(user, data)
3196 }
3197 fn flush(&mut self, user: &mut AsynUser, next: &mut dyn OctetNext) -> AsynResult<()> {
3198 next.flush(user)
3199 }
3200 }
3201
3202 let port: Arc<Mutex<dyn PortDriver>> = Arc::new(Mutex::new(TestDriver::new()));
3203
3204 {
3205 let mut guard = port.lock();
3206 guard
3207 .base_mut()
3208 .install_octet_interpose(Box::new(NoopInterpose));
3209 assert_eq!(guard.base().interpose_octet.len(), 1);
3210 }
3211 }
3212
3213 /// The `set_input_eos` write owner must forward the terminator to an
3214 /// installed `EosInterpose`, not just cache it in `base.input_eos` —
3215 /// otherwise a runtime IEOS change never terminates reads (the F7 gap).
3216 #[test]
3217 fn test_set_input_eos_reaches_installed_interpose() {
3218 use crate::interpose::eos::EosInterpose;
3219 use crate::interpose::{EomReason, OctetNext, OctetReadResult};
3220
3221 struct RawSource {
3222 data: Vec<u8>,
3223 pos: usize,
3224 }
3225 impl OctetNext for RawSource {
3226 fn read(&mut self, _u: &AsynUser, buf: &mut [u8]) -> AsynResult<OctetReadResult> {
3227 let avail = self.data.len() - self.pos;
3228 let n = avail.min(buf.len());
3229 buf[..n].copy_from_slice(&self.data[self.pos..self.pos + n]);
3230 self.pos += n;
3231 Ok(OctetReadResult {
3232 nbytes_transferred: n,
3233 eom_reason: EomReason::CNT,
3234 })
3235 }
3236 fn write(&mut self, _u: &mut AsynUser, data: &[u8]) -> AsynResult<usize> {
3237 Ok(data.len())
3238 }
3239 fn flush(&mut self, _u: &mut AsynUser) -> AsynResult<()> {
3240 Ok(())
3241 }
3242 }
3243
3244 let mut drv = TestDriver::new();
3245 drv.base_mut()
3246 .install_octet_interpose(Box::new(EosInterpose::default()));
3247
3248 // Set IEOS through the driver trait: caches in base AND must reach
3249 // the interpose.
3250 drv.set_input_eos(&AsynUser::default(), b"\n").unwrap();
3251 assert_eq!(drv.base().input_eos(0), b"\n");
3252
3253 let user = AsynUser::default();
3254 // "ab\n" exactly: the EOS read returns "ab" and leaves no read-ahead
3255 // in the interpose buffer, so the cleared-EOS read below genuinely
3256 // reads the next source fresh.
3257 let mut src = RawSource {
3258 data: b"ab\n".to_vec(),
3259 pos: 0,
3260 };
3261 let mut buf = [0u8; 16];
3262 let r = drv
3263 .base_mut()
3264 .interpose_octet
3265 .dispatch_read(&user, &mut buf, &mut src)
3266 .unwrap();
3267 assert_eq!(&buf[..r.nbytes_transferred], b"ab");
3268 assert!(r.eom_reason.contains(EomReason::EOS));
3269
3270 // Clearing IEOS (binary-suppress path) must also reach the interpose:
3271 // the read then passes through with no EOS termination.
3272 drv.set_input_eos(&AsynUser::default(), b"").unwrap();
3273 assert_eq!(drv.base().input_eos(0), b"");
3274 let mut src2 = RawSource {
3275 data: b"xy\nz".to_vec(),
3276 pos: 0,
3277 };
3278 let mut buf2 = [0u8; 16];
3279 let r2 = drv
3280 .base_mut()
3281 .interpose_octet
3282 .dispatch_read(&user, &mut buf2, &mut src2)
3283 .unwrap();
3284 assert_eq!(&buf2[..r2.nbytes_transferred], b"xy\nz");
3285 assert!(!r2.eom_reason.contains(EomReason::EOS));
3286 }
3287
3288 /// R14-49: the EOS hooks take the `asynUser`, so a multi-device port holds
3289 /// one terminator per device — C's `eosPvt` is created per (port, addr)
3290 /// (asynInterposeEos.c:84-120) and every hook takes the user that selects it
3291 /// (:288-296). A port-wide pair could not answer two devices.
3292 #[test]
3293 fn each_device_on_a_multi_device_port_holds_its_own_eos() {
3294 struct MultiDriver {
3295 base: PortDriverBase,
3296 }
3297 impl PortDriver for MultiDriver {
3298 fn base(&self) -> &PortDriverBase {
3299 &self.base
3300 }
3301 fn base_mut(&mut self) -> &mut PortDriverBase {
3302 &mut self.base
3303 }
3304
3305 // A multiDevice port cannot carry `asynInterposeEos` — C refuses
3306 // to install it (asynOctetBase.c:149-153) — so such a driver owns
3307 // its EOS methods, which is the non-NULL `asynOctet` entry the
3308 // Fail-stub default stands in for (R18-71).
3309 fn set_input_eos(&mut self, user: &AsynUser, eos: &[u8]) -> AsynResult<()> {
3310 self.base.set_input_eos(user.addr, eos);
3311 Ok(())
3312 }
3313 fn set_output_eos(&mut self, user: &AsynUser, eos: &[u8]) -> AsynResult<()> {
3314 self.base.set_output_eos(user.addr, eos);
3315 Ok(())
3316 }
3317 }
3318 let mut drv = MultiDriver {
3319 base: PortDriverBase::new(
3320 "eos_multi",
3321 4,
3322 PortFlags {
3323 multi_device: true,
3324 ..PortFlags::default()
3325 },
3326 ),
3327 };
3328
3329 let dev1 = AsynUser::default().with_addr(1);
3330 let dev2 = AsynUser::default().with_addr(2);
3331 drv.set_input_eos(&dev1, b"\n").unwrap();
3332 drv.set_output_eos(&dev1, b"\r\n").unwrap();
3333 drv.set_input_eos(&dev2, b";").unwrap();
3334
3335 assert_eq!(drv.get_input_eos(&dev1), b"\n");
3336 assert_eq!(drv.get_input_eos(&dev2), b";");
3337 assert_eq!(drv.get_output_eos(&dev1), b"\r\n");
3338 // A device that was never configured has no terminator — C's
3339 // zero-initialised `eosInLen`.
3340 assert!(
3341 drv.get_input_eos(&AsynUser::default().with_addr(3))
3342 .is_empty()
3343 );
3344 assert!(drv.get_output_eos(&dev2).is_empty());
3345 }
3346
3347 /// The other boundary: a port that never declared `ASYN_MULTIDEVICE` has no
3348 /// devices to key by — C's `findDpCommon` (asynManager.c:536-544) and
3349 /// `findInterface` resolve *every* addr to the port itself, so
3350 /// `asynSetEos(port, -1, ...)` and a record at ADDR 0 must reach the same
3351 /// terminator. Splitting them by raw addr would leave the record reading
3352 /// with no EOS at all.
3353 #[test]
3354 fn a_single_device_port_collapses_every_addr_onto_one_eos() {
3355 let mut drv = TestDriver::new();
3356 // A single-device port takes its EOS from `asynInterposeEos`, which C
3357 // installs above the driver when the port is configured with
3358 // `processEosIn/Out` (asynOctetBase.c:170-172); without it the
3359 // driver's own NULL method answers "not implemented" (R18-71).
3360 drv.base
3361 .install_octet_interpose(Box::new(crate::interpose::eos::EosInterpose::default()));
3362 drv.set_input_eos(&AsynUser::default().with_addr(-1), b"\n")
3363 .unwrap();
3364 assert_eq!(drv.get_input_eos(&AsynUser::default().with_addr(0)), b"\n");
3365 assert_eq!(drv.get_input_eos(&AsynUser::default().with_addr(7)), b"\n");
3366 }
3367
3368 /// R18-71. C's `asynOctetBase::initOverride` (asynOctetBase.c:115-118)
3369 /// replaces a NULL `setInputEos`/`setOutputEos` with a Fail stub, and the
3370 /// stub calls `showFailure` (:370-380) — `asynError` and
3371 /// `"<port> <method> not implemented"`. A `noProcessEos` port therefore
3372 /// *refuses* a terminator; it does not accept one and then never
3373 /// terminate. The two boundaries are the whole rule: no layer at all, and
3374 /// a layer that takes only one direction (`asynInterposeEosConfig` stores
3375 /// both flags, asynInterposeEos.c:128-138). C delegates only the *input*
3376 /// direction down when `processEosIn == 0` — setInputEos :293-295,
3377 /// getInputEos :318-320; its output pair (:344-363, :365-390) has no
3378 /// `processEosOut` test and stores unconditionally, that flag gating
3379 /// `writeIt` alone (:161-163).
3380 #[test]
3381 fn a_port_with_no_eos_layer_refuses_a_terminator() {
3382 use crate::interpose::eos::{EosConfig, EosInterpose};
3383
3384 // Boundary 1: no layer took it — both directions are Fail stubs.
3385 let mut bare = TestDriver::new();
3386 let err = bare
3387 .set_input_eos(&AsynUser::default(), b"\n")
3388 .expect_err("a noProcessEos port must refuse IEOS");
3389 assert_eq!(
3390 err.to_string(),
3391 AsynError::Status {
3392 status: AsynStatus::Error,
3393 message: "test setInputEos not implemented".to_string(),
3394 }
3395 .to_string()
3396 );
3397 let err = bare
3398 .set_output_eos(&AsynUser::default(), b"\r\n")
3399 .expect_err("a noProcessEos port must refuse OEOS");
3400 assert!(
3401 err.to_string().contains("setOutputEos not implemented"),
3402 "{err}"
3403 );
3404 // Refused means nothing was cached: a later read must not silently
3405 // believe the port terminates.
3406 assert!(bare.get_input_eos(&AsynUser::default()).is_empty());
3407 assert!(bare.get_output_eos(&AsynUser::default()).is_empty());
3408
3409 // Boundary 2: the layer takes input only — and OEOS still lands.
3410 // C's `setOutputEos` (:344-363) has no `processEosOut` test; the flag
3411 // gates `writeIt` alone (:161-163), so the terminator is stored, read
3412 // back, and simply never appended.
3413 let mut half = TestDriver::new();
3414 half.base_mut()
3415 .install_octet_interpose(Box::new(EosInterpose::with_processing(
3416 EosConfig::default(),
3417 true,
3418 false,
3419 )));
3420 half.set_input_eos(&AsynUser::default(), b"\n").unwrap();
3421 assert_eq!(half.get_input_eos(&AsynUser::default()), b"\n");
3422 half.set_output_eos(&AsynUser::default(), b"\r\n")
3423 .expect("processOut = 0 still stores OEOS");
3424 assert_eq!(half.get_output_eos(&AsynUser::default()), b"\r\n");
3425
3426 // Boundary 3: a length the storing layer refuses. C's `switch
3427 // (eoslen)` answers `"<port> illegal eoslen <n>"` *before* assigning
3428 // (:299-310, :352-362), so the terminator already stored still stands.
3429 let err = half
3430 .set_output_eos(&AsynUser::default(), b"\r\n\0")
3431 .expect_err("eoslen 3 is past eosOut[2]");
3432 assert!(err.to_string().contains("test illegal eoslen 3"), "{err}");
3433 assert_eq!(half.get_output_eos(&AsynUser::default()), b"\r\n");
3434 let err = half
3435 .set_input_eos(&AsynUser::default(), b"abc")
3436 .expect_err("eoslen 3 is past eosIn[2]");
3437 assert!(err.to_string().contains("test illegal eoslen 3"), "{err}");
3438 assert_eq!(half.get_input_eos(&AsynUser::default()), b"\n");
3439
3440 // Boundary 4: no layer at all refuses every length with the Fail
3441 // stub's words, not the length rule's — the rule belongs to the layer
3442 // that stores, and there is none.
3443 let err = bare
3444 .set_output_eos(&AsynUser::default(), b"\r\n\0")
3445 .expect_err("a noProcessEos port refuses whatever the length");
3446 assert!(
3447 err.to_string().contains("setOutputEos not implemented"),
3448 "{err}"
3449 );
3450 }
3451
3452 /// R6-46 owner path: `set_connected` is the single transition owner, so
3453 /// every driver that reconnects through it (serial, IP, prologix …) gets
3454 /// the interpose reset for free. C wires this as an exception callback
3455 /// (`asynInterposeEos.c:110,142-151`); here the owner drives the stack
3456 /// directly. Boundaries: both edges reset (C's `asynExceptionConnect`
3457 /// fires from `exceptionConnect` AND `exceptionDisconnect`), and a
3458 /// no-op call (same state) must not.
3459 #[test]
3460 fn set_connected_resets_interpose_link_state() {
3461 use crate::interpose::{OctetInterpose, OctetNext, OctetReadResult};
3462 use std::sync::Arc;
3463 use std::sync::atomic::{AtomicUsize, Ordering};
3464
3465 struct CountingInterpose(Arc<AtomicUsize>);
3466 impl OctetInterpose for CountingInterpose {
3467 fn read(
3468 &mut self,
3469 user: &AsynUser,
3470 buf: &mut [u8],
3471 next: &mut dyn OctetNext,
3472 ) -> AsynResult<OctetReadResult> {
3473 next.read(user, buf)
3474 }
3475 fn write(
3476 &mut self,
3477 user: &mut AsynUser,
3478 data: &[u8],
3479 next: &mut dyn OctetNext,
3480 ) -> AsynResult<usize> {
3481 next.write(user, data)
3482 }
3483 fn flush(&mut self, user: &mut AsynUser, next: &mut dyn OctetNext) -> AsynResult<()> {
3484 next.flush(user)
3485 }
3486 fn connection_changed(&mut self) {
3487 self.0.fetch_add(1, Ordering::Relaxed);
3488 }
3489 }
3490
3491 let resets = Arc::new(AtomicUsize::new(0));
3492 let mut base = PortDriverBase::new("reset_test", 1, PortFlags::default());
3493 base.install_octet_interpose(Box::new(CountingInterpose(resets.clone())));
3494
3495 // Port starts connected. Disconnect edge → reset (C exceptionDisconnect).
3496 assert!(base.set_connected(false));
3497 assert_eq!(resets.load(Ordering::Relaxed), 1);
3498
3499 // Redundant call, no state change → no fan-out, no reset.
3500 assert!(!base.set_connected(false));
3501 assert_eq!(resets.load(Ordering::Relaxed), 1);
3502
3503 // Reconnect edge → reset again (C exceptionConnect).
3504 assert!(base.set_connected(true));
3505 assert_eq!(resets.load(Ordering::Relaxed), 2);
3506 }
3507
3508 #[test]
3509 fn test_default_read_write_int64() {
3510 let mut base = PortDriverBase::new("test_i64", 1, PortFlags::default());
3511 base.create_param("BIG", ParamType::Int64).unwrap();
3512
3513 struct I64Driver {
3514 base: PortDriverBase,
3515 }
3516 impl PortDriver for I64Driver {
3517 fn base(&self) -> &PortDriverBase {
3518 &self.base
3519 }
3520 fn base_mut(&mut self) -> &mut PortDriverBase {
3521 &mut self.base
3522 }
3523 }
3524
3525 let mut drv = I64Driver { base };
3526 let mut user = AsynUser::new(0);
3527 drv.write_int64(&mut user, i64::MAX).unwrap();
3528 assert_eq!(drv.read_int64(&AsynUser::new(0)).unwrap(), i64::MAX);
3529 }
3530
3531 #[test]
3532 fn test_get_bounds_int64_default() {
3533 let base = PortDriverBase::new("test_bounds", 1, PortFlags::default());
3534 struct BoundsDriver {
3535 base: PortDriverBase,
3536 }
3537 impl PortDriver for BoundsDriver {
3538 fn base(&self) -> &PortDriverBase {
3539 &self.base
3540 }
3541 fn base_mut(&mut self) -> &mut PortDriverBase {
3542 &mut self.base
3543 }
3544 }
3545 let drv = BoundsDriver { base };
3546 let (lo, hi) = drv.get_bounds_int64(&AsynUser::default()).unwrap();
3547 // C asynInt64Base.c:99 default: *low = *high = 0 (so a driver
3548 // that does not implement getBounds skips LINEAR ESLO/EOFF).
3549 assert_eq!(lo, 0);
3550 assert_eq!(hi, 0);
3551 }
3552
3553 #[test]
3554 fn test_per_addr_device_state() {
3555 let mut base = PortDriverBase::new(
3556 "multi",
3557 4,
3558 PortFlags {
3559 multi_device: true,
3560 can_block: false,
3561 destructible: true,
3562 },
3563 );
3564 base.create_param("V", ParamType::Int32).unwrap();
3565
3566 // Default: all connected
3567 assert!(base.is_device_connected(0));
3568 assert!(base.is_device_connected(1));
3569
3570 // Disable addr 1
3571 base.device_state(1).enabled = false;
3572 assert!(base.check_ready_addr(0).is_ok());
3573 let err = base.check_ready_addr(1).unwrap_err();
3574 assert!(format!("{err}").contains("not enabled"));
3575
3576 // Disconnect addr 2
3577 base.device_state(2).connected = false;
3578 let err = base.check_ready_addr(2).unwrap_err();
3579 assert!(format!("{err}").contains("not connected"));
3580 }
3581
3582 #[test]
3583 fn test_per_addr_single_device_ignored() {
3584 let mut base = PortDriverBase::new("single", 1, PortFlags::default());
3585 base.create_param("V", ParamType::Int32).unwrap();
3586 // For single-device, per-addr check passes even if no device state
3587 assert!(base.check_ready_addr(0).is_ok());
3588 }
3589
3590 #[test]
3591 fn test_timestamp_source() {
3592 let mut base = PortDriverBase::new("ts_test", 1, PortFlags::default());
3593 base.create_param("V", ParamType::Int32).unwrap();
3594
3595 let fixed_ts = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(999999);
3596 base.register_timestamp_source(move || fixed_ts);
3597
3598 assert_eq!(base.current_timestamp(), fixed_ts);
3599 }
3600
3601 #[test]
3602 fn test_timestamp_source_in_callbacks() {
3603 // Post-`iocInit` precondition — see `TestDriver::new`.
3604 epics_libcom_rs::runtime::interrupt_accept::set_interrupts_accepted(true);
3605 let mut base = PortDriverBase::new("ts_cb", 1, PortFlags::default());
3606 base.create_param("V", ParamType::Int32).unwrap();
3607 let mut rx = base.interrupts.subscribe_async();
3608
3609 let fixed_ts = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(123456);
3610 base.register_timestamp_source(move || fixed_ts);
3611
3612 struct TsDriver {
3613 base: PortDriverBase,
3614 }
3615 impl PortDriver for TsDriver {
3616 fn base(&self) -> &PortDriverBase {
3617 &self.base
3618 }
3619 fn base_mut(&mut self) -> &mut PortDriverBase {
3620 &mut self.base
3621 }
3622 }
3623 let mut drv = TsDriver { base };
3624 drv.base_mut().set_int32_param(0, 0, 42).unwrap();
3625 drv.base_mut().call_param_callbacks(0).unwrap();
3626
3627 let v = rx.try_recv().unwrap();
3628 // Should use fixed_ts since no per-param timestamp is set
3629 assert_eq!(v.timestamp, fixed_ts);
3630 }
3631
3632 #[test]
3633 fn test_queue_priority_connect() {
3634 assert!(QueuePriority::Connect > QueuePriority::High);
3635 }
3636
3637 #[test]
3638 fn test_port_flags_destructible_default_is_opt_in() {
3639 // C asyn parity: ASYN_DESTRUCTIBLE (0x0004, asynDriver.h:97) is
3640 // a `registerPort` attribute that callers opt into. Default
3641 // must be false so drivers don't accidentally accept a
3642 // shutdownPort call. PortDriver authors that want shutdown
3643 // support set `destructible: true` explicitly.
3644 let flags = PortFlags::default();
3645 assert!(
3646 !flags.destructible,
3647 "destructible must be opt-in (C parity)"
3648 );
3649 }
3650
3651 #[test]
3652 fn shutdown_lifecycle_refuses_non_destructible() {
3653 let mut base = PortDriverBase::new(
3654 "p_nondestr",
3655 1,
3656 PortFlags {
3657 multi_device: false,
3658 can_block: false,
3659 destructible: false,
3660 },
3661 );
3662 match base.shutdown_lifecycle() {
3663 Err(AsynError::Status { message, .. }) => {
3664 assert!(message.contains("ASYN_DESTRUCTIBLE"), "msg={message}");
3665 }
3666 other => panic!("expected ASYN_DESTRUCTIBLE refusal, got {other:?}"),
3667 }
3668 assert!(
3669 !base.is_defunct(),
3670 "non-destructible port must not flip defunct"
3671 );
3672 assert!(base.is_enabled(), "non-destructible port must stay enabled");
3673 }
3674
3675 #[test]
3676 fn shutdown_lifecycle_marks_destructible_defunct_and_idempotent() {
3677 let mut base = PortDriverBase::new(
3678 "p_destr",
3679 1,
3680 PortFlags {
3681 multi_device: false,
3682 can_block: false,
3683 destructible: true,
3684 },
3685 );
3686 assert!(base.is_enabled());
3687 assert!(!base.is_defunct());
3688 base.shutdown_lifecycle().unwrap();
3689 assert!(
3690 !base.is_enabled(),
3691 "shutdown_lifecycle must flip enabled=false"
3692 );
3693 assert!(
3694 base.is_defunct(),
3695 "shutdown_lifecycle must flip defunct=true"
3696 );
3697 // Idempotent — second call is Ok and leaves state unchanged.
3698 base.shutdown_lifecycle().unwrap();
3699 assert!(base.is_defunct());
3700 // A shut-down port is refused by the queue gate as a *disabled* one:
3701 // C's `queueRequest` has no defunct branch (asynManager.c:1541-1552),
3702 // it only sees the `enabled=FALSE` that `shutdownPort` left behind
3703 // (:2283). "port %s disabled" is the message an operator gets.
3704 match base.check_ready() {
3705 Err(AsynError::Status { status, message }) => {
3706 assert_eq!(status, AsynStatus::Disabled);
3707 assert_eq!(message, "port p_destr disabled");
3708 }
3709 other => panic!("expected the disabled refusal, got {other:?}"),
3710 }
3711 // The one place C names the shutdown is `enable` (:2236-2241).
3712 match base.set_enabled(true) {
3713 Err(AsynError::Status { status, message }) => {
3714 assert_eq!(status, AsynStatus::Disabled);
3715 assert_eq!(message, "asynManager:enable: port has been shut down");
3716 }
3717 other => panic!("expected the shut-down refusal, got {other:?}"),
3718 }
3719 }
3720
3721 // --- Phase 2B: per-addr connect/disconnect/enable/disable ---
3722
3723 #[test]
3724 fn test_connect_addr() {
3725 let mut base = PortDriverBase::new(
3726 "multi_conn",
3727 4,
3728 PortFlags {
3729 multi_device: true,
3730 can_block: false,
3731 destructible: true,
3732 },
3733 );
3734 base.create_param("V", ParamType::Int32).unwrap();
3735
3736 base.disconnect_addr(1);
3737 assert!(!base.is_device_connected(1));
3738 assert!(base.check_ready_addr(1).is_err());
3739
3740 base.connect_addr(1);
3741 assert!(base.is_device_connected(1));
3742 assert!(base.check_ready_addr(1).is_ok());
3743 }
3744
3745 #[test]
3746 fn test_enable_disable_addr() {
3747 let mut base = PortDriverBase::new(
3748 "multi_en",
3749 4,
3750 PortFlags {
3751 multi_device: true,
3752 can_block: false,
3753 destructible: true,
3754 },
3755 );
3756 base.create_param("V", ParamType::Int32).unwrap();
3757
3758 base.disable_addr(2);
3759 let err = base.check_ready_addr(2).unwrap_err();
3760 assert!(format!("{err}").contains("not enabled"));
3761
3762 base.enable_addr(2);
3763 assert!(base.check_ready_addr(2).is_ok());
3764 }
3765
3766 #[test]
3767 fn test_port_level_overrides_addr() {
3768 let mut base = PortDriverBase::new(
3769 "multi_override",
3770 4,
3771 PortFlags {
3772 multi_device: true,
3773 can_block: false,
3774 destructible: true,
3775 },
3776 );
3777 base.create_param("V", ParamType::Int32).unwrap();
3778
3779 // Port-level disabled overrides addr-level enabled
3780 base.enabled = false;
3781 base.enable_addr(0); // addr 0 is enabled, but port is disabled
3782 let err = base.check_ready_addr(0).unwrap_err();
3783 assert!(format!("{err}").contains("disabled"));
3784 }
3785
3786 #[test]
3787 fn test_per_addr_exception_announced() {
3788 use std::sync::atomic::{AtomicI32, Ordering};
3789
3790 let mut base = PortDriverBase::new(
3791 "multi_exc",
3792 4,
3793 PortFlags {
3794 multi_device: true,
3795 can_block: false,
3796 destructible: true,
3797 },
3798 );
3799 base.create_param("V", ParamType::Int32).unwrap();
3800
3801 let exc_mgr = Arc::new(crate::exception::ExceptionManager::new());
3802 base.bind_exception_sink(exc_mgr.clone());
3803
3804 let last_addr = Arc::new(AtomicI32::new(-99));
3805 let last_addr2 = last_addr.clone();
3806 exc_mgr.add_callback(move |event| {
3807 last_addr2.store(event.addr, Ordering::Relaxed);
3808 });
3809
3810 base.disconnect_addr(3);
3811 assert_eq!(last_addr.load(Ordering::Relaxed), 3);
3812
3813 base.enable_addr(2);
3814 assert_eq!(last_addr.load(Ordering::Relaxed), 2);
3815 }
3816
3817 /// C parity (asynManager.c:2151-2160 exceptionConnect,
3818 /// :2174-2185 exceptionDisconnect): redundant connect/disconnect
3819 /// on a port already in that state must NOT fan out a duplicate
3820 /// `asynExceptionConnect`. Subscribers depend on the event
3821 /// edge — duplicate fan-out causes them to e.g. re-subscribe or
3822 /// re-arm timers that should fire exactly once per transition.
3823 #[test]
3824 fn test_connect_disconnect_announce_only_on_transition() {
3825 use std::sync::atomic::{AtomicUsize, Ordering};
3826
3827 let mut base = PortDriverBase::new(
3828 "edge",
3829 4,
3830 PortFlags {
3831 multi_device: true,
3832 can_block: false,
3833 destructible: true,
3834 },
3835 );
3836 base.create_param("V", ParamType::Int32).unwrap();
3837 let exc_mgr = Arc::new(crate::exception::ExceptionManager::new());
3838 base.bind_exception_sink(exc_mgr.clone());
3839
3840 let connect_hits = Arc::new(AtomicUsize::new(0));
3841 let hits2 = connect_hits.clone();
3842 exc_mgr.add_callback(move |event| {
3843 if event.exception == AsynException::Connect {
3844 hits2.fetch_add(1, Ordering::Relaxed);
3845 }
3846 });
3847
3848 // device starts connected by DeviceState::default — a redundant
3849 // connect_addr is a no-op.
3850 base.connect_addr(2);
3851 assert_eq!(
3852 connect_hits.load(Ordering::Relaxed),
3853 0,
3854 "redundant connect_addr must not fan out"
3855 );
3856
3857 // First transition fires once.
3858 base.disconnect_addr(2);
3859 assert_eq!(connect_hits.load(Ordering::Relaxed), 1);
3860
3861 // Redundant disconnect is silent.
3862 base.disconnect_addr(2);
3863 assert_eq!(
3864 connect_hits.load(Ordering::Relaxed),
3865 1,
3866 "redundant disconnect_addr must not fan out"
3867 );
3868
3869 // Re-connect fires the transition.
3870 base.connect_addr(2);
3871 assert_eq!(connect_hits.load(Ordering::Relaxed), 2);
3872 }
3873
3874 /// C parity: `autoConnectAsyn` (asynManager.c:2310-2324) fires
3875 /// `asynExceptionAutoConnect` unconditionally — even setting the
3876 /// same value as the current one. Rust mirrors that so observers
3877 /// can refresh their UI after a re-confirmation, not just an edge.
3878 #[test]
3879 fn test_set_auto_connect_fires_unconditionally() {
3880 use std::sync::atomic::{AtomicUsize, Ordering};
3881
3882 let mut base = PortDriverBase::new("ac", 1, PortFlags::default());
3883 let exc_mgr = Arc::new(crate::exception::ExceptionManager::new());
3884 base.bind_exception_sink(exc_mgr.clone());
3885 let hits = Arc::new(AtomicUsize::new(0));
3886 let hits2 = hits.clone();
3887 exc_mgr.add_callback(move |event| {
3888 if event.exception == AsynException::AutoConnect {
3889 hits2.fetch_add(1, Ordering::Relaxed);
3890 }
3891 });
3892 // base.auto_connect defaults to true — setting true again
3893 // still must fire (no state-change guard in C).
3894 base.set_auto_connect(true);
3895 base.set_auto_connect(false);
3896 base.set_auto_connect(false);
3897 assert_eq!(hits.load(Ordering::Relaxed), 3);
3898 }
3899
3900 /// asyn PR #217 (asynManager.c:2322-2324): enabling auto-connect on a
3901 /// down port/device arms the connect timer; a connected port, or a
3902 /// flip to OFF, arms nothing. Pre-fix no flip armed the timer, so a
3903 /// never-connected port enabled late made one exception-wake attempt
3904 /// and then sat silent.
3905 #[test]
3906 fn auto_connect_enable_arms_connect_timer_boundaries() {
3907 // dropped while auto-connect was OFF (the disconnect edge arms
3908 // nothing then, port.rs sync_connection_edge), enabled late →
3909 // the flip itself must arm
3910 let mut base = PortDriverBase::new("act", 1, PortFlags::default());
3911 base.set_auto_connect(false);
3912 base.set_connected(false);
3913 assert!(base.connect_retry_at.is_none());
3914 base.set_auto_connect(true);
3915 assert!(base.connect_retry_at.is_some());
3916
3917 // down + OFF → untouched (C's timer callback no-ops on
3918 // !autoConnect; the flip itself must not arm)
3919 let mut base = PortDriverBase::new("act2", 1, PortFlags::default());
3920 base.set_auto_connect(false);
3921 base.set_connected(false);
3922 base.set_auto_connect(false);
3923 assert!(base.connect_retry_at.is_none());
3924
3925 // connected + ON → nothing to retry (a fresh base is born
3926 // `Connection::Own(true)`)
3927 let mut base = PortDriverBase::new("act3", 1, PortFlags::default());
3928 base.set_auto_connect(true);
3929 assert!(base.connect_retry_at.is_none());
3930
3931 // device down + ON via the addr variant → the PORT timer arms,
3932 // keyed on the device's dpCommon exactly as C's findDpCommon
3933 // resolution is; the port itself stays connected
3934 let multi = PortFlags {
3935 multi_device: true,
3936 ..PortFlags::default()
3937 };
3938 let mut base = PortDriverBase::new("act4", 2, multi);
3939 base.device_state(1).connected = false;
3940 assert!(base.connect_retry_at.is_none());
3941 base.set_auto_connect_addr(1, true);
3942 assert!(base.connect_retry_at.is_some());
3943
3944 // the same call on a SINGLE-device port is a port write, because
3945 // `findDpCommon` has no device to give it (asynManager.c:541-544): the
3946 // port is connected, so it arms nothing at all.
3947 let mut base = PortDriverBase::new("act5", 2, PortFlags::default());
3948 base.set_auto_connect_addr(1, true);
3949 assert!(base.connect_retry_at.is_none());
3950 assert!(
3951 base.dp_auto_connect(1),
3952 "and it landed on the port's own slot"
3953 );
3954 }
3955
3956 #[test]
3957 fn auto_connect_throttle_gate_boundaries() {
3958 // C autoConnectDevice 2.0s gate (asynManager.c:712-713). Boundary
3959 // cases, not narrative: never-stamped, exactly-2s, just-under-2s.
3960 let mut base = PortDriverBase::new("thr", 1, PortFlags::default());
3961
3962 // No transition recorded yet => always permitted (C's
3963 // zero-initialised lastConnectDisconnect).
3964 let t0 = Instant::now();
3965 assert!(base.auto_connect_throttle_ok(-1, t0));
3966
3967 // Stamp at t0; only `+` arithmetic on Instant (no `- Duration`,
3968 // which panics on Windows when uptime < the span).
3969 base.last_connect_disconnect = Some(t0);
3970 // elapsed 0 < 2s => refused.
3971 assert!(!base.auto_connect_throttle_ok(-1, t0));
3972 // elapsed just under 2s => refused.
3973 assert!(!base.auto_connect_throttle_ok(-1, t0 + Duration::from_millis(1999)));
3974 // elapsed exactly 2s => permitted (>=).
3975 assert!(base.auto_connect_throttle_ok(-1, t0 + Duration::from_secs(2)));
3976 // elapsed well past => permitted.
3977 assert!(base.auto_connect_throttle_ok(-1, t0 + Duration::from_secs(5)));
3978 }
3979
3980 #[test]
3981 fn auto_connect_throttle_stamps_on_disconnect_not_connect() {
3982 // C exceptionDisconnect stamps lastConnectDisconnect (asynManager.c
3983 // :2184); exceptionConnect does not (:2157-2159). Mirror both edges.
3984 let mut base = PortDriverBase::new("thr", 1, PortFlags::default());
3985 // Starts connected, no stamp.
3986 assert!(base.last_connect_disconnect.is_none());
3987
3988 // Disconnect edge stamps.
3989 assert!(base.set_connected(false));
3990 assert!(base.last_connect_disconnect.is_some());
3991
3992 // Clear, then connect edge must NOT re-stamp.
3993 base.last_connect_disconnect = None;
3994 assert!(base.set_connected(true));
3995 assert!(base.last_connect_disconnect.is_none());
3996 }
3997
3998 #[test]
3999 fn auto_connect_throttle_per_device_anchor() {
4000 // Multi-device ports throttle per address (C dpCommon is per-device).
4001 let flags = PortFlags {
4002 multi_device: true,
4003 ..PortFlags::default()
4004 };
4005 let mut base = PortDriverBase::new("thr", 4, flags);
4006 let t0 = Instant::now();
4007
4008 // addr 1 disconnect stamps only addr 1's anchor.
4009 assert!(base.set_addr_connected(1, false));
4010 assert!(base.device_state(1).last_connect_disconnect.is_some());
4011 // addr 1 is throttled; addr 2 (never stamped) is still permitted.
4012 assert!(!base.auto_connect_throttle_ok(1, t0));
4013 assert!(base.auto_connect_throttle_ok(2, t0));
4014
4015 // Post-attempt stamp restarts addr 2's window.
4016 base.stamp_auto_connect_attempt(2, t0);
4017 assert!(!base.auto_connect_throttle_ok(2, t0));
4018 assert!(base.auto_connect_throttle_ok(2, t0 + Duration::from_secs(2)));
4019 }
4020
4021 #[test]
4022 fn set_enabled_refuses_defunct_port() {
4023 use std::sync::atomic::{AtomicUsize, Ordering};
4024 // C `enable` on a defunct port: asynDisabled, no `enabled` toggle,
4025 // no asynExceptionEnable fan-out (asynManager.c:2236-2241).
4026 let flags = PortFlags {
4027 destructible: true,
4028 ..PortFlags::default()
4029 };
4030 let mut base = PortDriverBase::new("def", 1, flags);
4031 let exc_mgr = Arc::new(crate::exception::ExceptionManager::new());
4032 base.bind_exception_sink(exc_mgr.clone());
4033 let enable_hits = Arc::new(AtomicUsize::new(0));
4034 let h = enable_hits.clone();
4035 exc_mgr.add_callback(move |event| {
4036 if event.exception == AsynException::Enable {
4037 h.fetch_add(1, Ordering::Relaxed);
4038 }
4039 });
4040
4041 // Shut the port down → defunct (shutdown sets enabled=false).
4042 base.shutdown_lifecycle().unwrap();
4043 assert!(base.is_defunct());
4044 assert!(!base.is_enabled());
4045
4046 let err = base.set_enabled(true).unwrap_err();
4047 match err {
4048 AsynError::Status { status, .. } => assert_eq!(status, AsynStatus::Disabled),
4049 other => panic!("expected Disabled, got {other:?}"),
4050 }
4051 assert!(!base.is_enabled(), "defunct port must not re-enable");
4052 assert_eq!(
4053 enable_hits.load(Ordering::Relaxed),
4054 0,
4055 "no Enable exception may fire on a defunct port"
4056 );
4057 }
4058
4059 #[test]
4060 fn set_addr_enabled_refuses_defunct_port() {
4061 use std::sync::atomic::{AtomicUsize, Ordering};
4062 let flags = PortFlags {
4063 multi_device: true,
4064 destructible: true,
4065 ..PortFlags::default()
4066 };
4067 let mut base = PortDriverBase::new("def", 4, flags);
4068 let exc_mgr = Arc::new(crate::exception::ExceptionManager::new());
4069 base.bind_exception_sink(exc_mgr.clone());
4070 let enable_hits = Arc::new(AtomicUsize::new(0));
4071 let h = enable_hits.clone();
4072 exc_mgr.add_callback(move |event| {
4073 if event.exception == AsynException::Enable {
4074 h.fetch_add(1, Ordering::Relaxed);
4075 }
4076 });
4077
4078 base.shutdown_lifecycle().unwrap();
4079
4080 let err = base.set_addr_enabled(1, false).unwrap_err();
4081 match err {
4082 AsynError::Status { status, .. } => assert_eq!(status, AsynStatus::Disabled),
4083 other => panic!("expected Disabled, got {other:?}"),
4084 }
4085 // The guard returns before `device_state(addr)` would insert an
4086 // entry, so the refused call mutates no per-device state.
4087 assert!(
4088 !base.device_states.contains_key(&1),
4089 "refused per-device enable must not create device state"
4090 );
4091 // The `()` convenience facade also no-ops on a defunct port.
4092 base.disable_addr(1);
4093 assert!(!base.device_states.contains_key(&1));
4094 assert_eq!(
4095 enable_hits.load(Ordering::Relaxed),
4096 0,
4097 "no Enable exception may fire on a defunct port"
4098 );
4099 }
4100
4101 /// The `defunct ⟹ !enabled` invariant is over every dpCommon the port
4102 /// owns, so `dp_enabled` must answer the same at every address. The two
4103 /// boundaries are the two ways a device slot can be in the map at
4104 /// shutdown time: one that already existed, and one created afterwards.
4105 #[test]
4106 fn shutdown_lifecycle_disables_every_device_dp_common() {
4107 let flags = PortFlags {
4108 multi_device: true,
4109 destructible: true,
4110 ..PortFlags::default()
4111 };
4112
4113 // Boundary 1: a slot that exists before the shutdown.
4114 let mut base = PortDriverBase::new("shut", 4, flags);
4115 base.set_addr_enabled(1, true).unwrap();
4116 assert!(base.device_states.contains_key(&1));
4117 base.shutdown_lifecycle().unwrap();
4118 assert!(!base.dp_enabled(1), "pre-existing device slot must go down");
4119 assert!(!base.dp_enabled(-1), "the port's own dpCommon goes down");
4120 assert!(!base.dp_enabled(0));
4121
4122 // Boundary 2: no slot at shutdown, one created afterwards — the seed
4123 // in `device_state` takes the port's `enabled`, which is now false.
4124 let mut base = PortDriverBase::new("shut2", 4, flags);
4125 base.shutdown_lifecycle().unwrap();
4126 assert!(!base.dp_enabled(1));
4127 assert!(
4128 !base.device_state(1).enabled,
4129 "a slot seeded after the shutdown must come up disabled"
4130 );
4131 }
4132
4133 /// C parity: `asynPortDriver::setInterruptUInt32Digital` /
4134 /// `clearInterruptUInt32Digital` / `getInterruptUInt32Digital`
4135 /// (`asynPortDriver.cpp:2346-2461`) route through paramList. The
4136 /// PortDriver trait default delegates to the param store; we
4137 /// verify the round-trip end-to-end through the trait surface.
4138 #[test]
4139 fn test_port_driver_uint32_interrupt_round_trip() {
4140 struct UInt32Drv {
4141 base: PortDriverBase,
4142 }
4143 impl PortDriver for UInt32Drv {
4144 fn base(&self) -> &PortDriverBase {
4145 &self.base
4146 }
4147 fn base_mut(&mut self) -> &mut PortDriverBase {
4148 &mut self.base
4149 }
4150 }
4151
4152 let mut base = PortDriverBase::new("uint32_int", 1, PortFlags::default());
4153 let idx = base
4154 .params
4155 .create_param("BITS", ParamType::UInt32Digital)
4156 .unwrap();
4157 let mut drv = UInt32Drv { base };
4158 let user = AsynUser::new(idx).with_addr(0);
4159
4160 drv.set_interrupt_uint32_digital(&user, 0xF0, InterruptReason::ZeroToOne)
4161 .unwrap();
4162 drv.set_interrupt_uint32_digital(&user, 0x0F, InterruptReason::OneToZero)
4163 .unwrap();
4164 assert_eq!(
4165 drv.get_interrupt_uint32_digital(&user, InterruptReason::Both)
4166 .unwrap(),
4167 0xFF
4168 );
4169 drv.clear_interrupt_uint32_digital(&user, 0x11).unwrap();
4170 assert_eq!(
4171 drv.get_interrupt_uint32_digital(&user, InterruptReason::ZeroToOne)
4172 .unwrap(),
4173 0xE0
4174 );
4175 assert_eq!(
4176 drv.get_interrupt_uint32_digital(&user, InterruptReason::OneToZero)
4177 .unwrap(),
4178 0x0E
4179 );
4180 }
4181
4182 /// C parity: the default `read_int32` / `read_int64` / `read_float64` /
4183 /// `read_octet` / `read_uint32_digital` must surface an *unset*
4184 /// parameter as `ParamUndefined`, not success/0. The default
4185 /// `asynPortDriver::read{Int32,Int64,Float64,Octet,UInt32Digital}` calls
4186 /// `get{Integer,Integer64,Double,String,UIntDigital}Param`, every
4187 /// `paramVal` getter throws `ParamValNotDefined` → `asynParamUndefined`
4188 /// for an unset value (paramVal.cpp:152,181,235,264,292), and the
4189 /// `devAsyn*` device support routes that status through
4190 /// `asynStatusToEpicsAlarm(READ_ALARM, INVALID_ALARM)`. After a write
4191 /// the same reads succeed with the stored value.
4192 #[test]
4193 fn default_scalar_reads_report_undefined_until_set() {
4194 struct AllTypesDrv {
4195 base: PortDriverBase,
4196 }
4197 impl PortDriver for AllTypesDrv {
4198 fn base(&self) -> &PortDriverBase {
4199 &self.base
4200 }
4201 fn base_mut(&mut self) -> &mut PortDriverBase {
4202 &mut self.base
4203 }
4204 }
4205
4206 let mut base = PortDriverBase::new("undef_read", 1, PortFlags::default());
4207 let i32_idx = base.params.create_param("I32", ParamType::Int32).unwrap();
4208 let i64_idx = base.params.create_param("I64", ParamType::Int64).unwrap();
4209 let f64_idx = base.params.create_param("F64", ParamType::Float64).unwrap();
4210 let oct_idx = base.params.create_param("OCT", ParamType::Octet).unwrap();
4211 let u32_idx = base
4212 .params
4213 .create_param("BITS", ParamType::UInt32Digital)
4214 .unwrap();
4215 let mut drv = AllTypesDrv { base };
4216
4217 // Unset → every default scalar read is ParamUndefined, NOT Ok(0).
4218 assert!(matches!(
4219 drv.read_int32(&AsynUser::new(i32_idx).with_addr(0)),
4220 Err(AsynError::ParamUndefined(_))
4221 ));
4222 assert!(matches!(
4223 drv.read_int64(&AsynUser::new(i64_idx).with_addr(0)),
4224 Err(AsynError::ParamUndefined(_))
4225 ));
4226 assert!(matches!(
4227 drv.read_float64(&AsynUser::new(f64_idx).with_addr(0)),
4228 Err(AsynError::ParamUndefined(_))
4229 ));
4230 let mut buf = [0u8; 16];
4231 assert!(matches!(
4232 drv.read_octet(&AsynUser::new(oct_idx).with_addr(0), &mut buf),
4233 Err(AsynError::ParamUndefined(_))
4234 ));
4235 assert!(matches!(
4236 drv.read_uint32_digital(&AsynUser::new(u32_idx).with_addr(0), 0xFFFF_FFFF),
4237 Err(AsynError::ParamUndefined(_))
4238 ));
4239
4240 // After a write the same reads succeed with the stored value.
4241 drv.base_mut().params.set_int32(i32_idx, 0, 7).unwrap();
4242 drv.base_mut().params.set_int64(i64_idx, 0, 9).unwrap();
4243 drv.base_mut().params.set_float64(f64_idx, 0, 1.5).unwrap();
4244 drv.base_mut()
4245 .params
4246 .set_string(oct_idx, 0, b"hi".to_vec())
4247 .unwrap();
4248 drv.base_mut()
4249 .params
4250 .set_uint32(u32_idx, 0, 0x05, 0xFFFF_FFFF, 0)
4251 .unwrap();
4252
4253 assert_eq!(
4254 drv.read_int32(&AsynUser::new(i32_idx).with_addr(0))
4255 .unwrap(),
4256 7
4257 );
4258 assert_eq!(
4259 drv.read_int64(&AsynUser::new(i64_idx).with_addr(0))
4260 .unwrap(),
4261 9
4262 );
4263 assert_eq!(
4264 drv.read_float64(&AsynUser::new(f64_idx).with_addr(0))
4265 .unwrap(),
4266 1.5
4267 );
4268 let n = drv
4269 .read_octet(&AsynUser::new(oct_idx).with_addr(0), &mut buf)
4270 .unwrap();
4271 assert_eq!(&buf[..n], b"hi");
4272 assert_eq!(
4273 drv.read_uint32_digital(&AsynUser::new(u32_idx).with_addr(0), 0xFFFF_FFFF)
4274 .unwrap(),
4275 0x05
4276 );
4277 }
4278
4279 /// R16-47: the parameter block is one level *late* no longer.
4280 ///
4281 /// C `asynPortDriver::report` hands `reportParams` the level it was given,
4282 /// unchanged (asynPortDriver.cpp:3693); `reportParams` prints list 0 at any
4283 /// level and all `maxAddr` lists at `details >= 2` (:1804); and
4284 /// `paramVal::report` prints name, type, value and status for every parameter
4285 /// at every level (paramVal.cpp:296-372). Passing `level - 1` made
4286 /// `asynReport 1` print a bare count, and values appear only at 3.
4287 ///
4288 /// One case per threshold boundary: details 0 (no block), 1 (list 0, with
4289 /// values), 2 (every address list).
4290 #[test]
4291 fn report_prints_the_parameter_block_at_the_c_detail_levels() {
4292 struct Drv {
4293 base: PortDriverBase,
4294 }
4295 impl PortDriver for Drv {
4296 fn base(&self) -> &PortDriverBase {
4297 &self.base
4298 }
4299 fn base_mut(&mut self) -> &mut PortDriverBase {
4300 &mut self.base
4301 }
4302 }
4303
4304 let mut base = PortDriverBase::new(
4305 "rep",
4306 2,
4307 PortFlags {
4308 multi_device: true,
4309 ..PortFlags::default()
4310 },
4311 );
4312 let n = base.params.create_param("N", ParamType::Int32).unwrap();
4313 let x = base.params.create_param("X", ParamType::Float64).unwrap();
4314 let s_idx = base.params.create_param("S", ParamType::Octet).unwrap();
4315 let bits = base
4316 .params
4317 .create_param("BITS", ParamType::UInt32Digital)
4318 .unwrap();
4319 base.params.set_int32(n, 0, 7).unwrap();
4320 base.params.set_float64(x, 0, 0.1 + 0.2).unwrap();
4321 base.params.set_string(s_idx, 0, b"hello".to_vec()).unwrap();
4322 base.params.set_uint32(bits, 0, 0xa5, 0xff, 0).unwrap();
4323 base.params
4324 .set_uint32_interrupt(bits, 0, 0x0f, InterruptReason::ZeroToOne)
4325 .unwrap();
4326 // Addr 1 is left untouched: its parameters must report as undefined.
4327 let drv = Drv { base };
4328
4329 // details 0 — C prints the port line and stops (:3678-3680).
4330 let mut out = String::new();
4331 drv.report(&mut out, 0);
4332 assert!(
4333 !out.contains("Parameter"),
4334 "details 0 has no parameter block: {out}"
4335 );
4336
4337 // details 1 — list 0, the count, and every parameter WITH its value.
4338 let mut out = String::new();
4339 drv.report(&mut out, 1);
4340 assert!(
4341 out.contains("Parameter list 0\nNumber of parameters is: 4\n"),
4342 "C's paramList::report header (asynPortDriver.cpp:887): {out}"
4343 );
4344 assert!(
4345 out.contains("Parameter 0 type=asynInt32, name=N, value=7, status=0\n"),
4346 "{out}"
4347 );
4348 // C's `%g`: six significant digits, so 0.1+0.2 is `0.3`, not
4349 // `0.30000000000000004`.
4350 assert!(
4351 out.contains("Parameter 1 type=asynFloat64, name=X, value=0.3, status=0\n"),
4352 "{out}"
4353 );
4354 assert!(
4355 out.contains("Parameter 2 type=string, name=S, value=hello, status=0\n"),
4356 "C calls an octet parameter `string` (paramVal.cpp:328): {out}"
4357 );
4358 assert!(
4359 out.contains(
4360 "Parameter 3 type=asynUInt32Digital, name=BITS, value=0xa5, status=0, \
4361 risingMask=0xf, fallingMask=0x0, callbackMask=0xa5\n"
4362 ),
4363 "C prints the three masks with the value (paramVal.cpp:314-316): {out}"
4364 );
4365 assert!(
4366 !out.contains("Parameter list 1"),
4367 "below details 2 C reports one address list (asynPortDriver.cpp:1804): {out}"
4368 );
4369
4370 // details 2 — every address list, and addr 1 is undefined.
4371 let mut out = String::new();
4372 drv.report(&mut out, 2);
4373 assert!(out.contains("Parameter list 1\n"), "{out}");
4374 assert!(
4375 out.contains("Parameter 0 type=asynInt32, name=N, value is undefined\n"),
4376 "an unset parameter prints C's undefined line (paramVal.cpp:304): {out}"
4377 );
4378 }
4379
4380 /// R16-48: the report escapes a terminator the way C does — the whole libCom
4381 /// table, not just CR and LF.
4382 ///
4383 /// C prints the EOS pair with `epicsStrPrintEscaped` (asynPortDriver.cpp:3687,
4384 /// 3690), whose table is `\a \b \f \n \r \t \v \\ \' \"`, the byte itself
4385 /// when `isprint`, and `\xNN` otherwise (epicsString.c:230-269). The report's
4386 /// own two-case table wrote a binary terminator raw into stdout.
4387 #[test]
4388 fn report_escapes_the_eos_with_the_c_table() {
4389 struct Drv {
4390 base: PortDriverBase,
4391 }
4392 impl PortDriver for Drv {
4393 fn base(&self) -> &PortDriverBase {
4394 &self.base
4395 }
4396 fn base_mut(&mut self) -> &mut PortDriverBase {
4397 &mut self.base
4398 }
4399 fn capabilities(&self) -> Vec<crate::interfaces::Capability> {
4400 crate::interfaces::octet_transport_capabilities()
4401 }
4402 }
4403
4404 let mut base = PortDriverBase::new("eos_rep", 1, PortFlags::default());
4405 // See `a_single_device_port_collapses_every_addr_onto_one_eos`: the
4406 // EOS layer is what makes a terminator settable at all (R18-71).
4407 base.install_octet_interpose(Box::new(crate::interpose::eos::EosInterpose::default()));
4408 let mut drv = Drv { base };
4409 // A real binary terminator (C caps an EOS at two bytes): ESC, then NUL —
4410 // neither of which the old two-case table escaped.
4411 drv.set_input_eos(&AsynUser::default(), b"\x1b\0").unwrap();
4412 // …and the named escapes beyond CR/LF: TAB and BEL.
4413 drv.set_output_eos(&AsynUser::default(), b"\t\x07").unwrap();
4414
4415 let mut out = String::new();
4416 drv.report(&mut out, 1);
4417 assert!(
4418 out.contains(" Input EOS[2]: \\x1b\\0\n"),
4419 "CBUG-D4 refused: C's epicsStrPrintEscaped lacked a `case 0` (epicsString.c:255-260) and printed \\x00; the port supplies it so NUL renders \\0, matching epicsStrnEscapedFromRaw: {out}"
4420 );
4421 assert!(
4422 out.contains(" Output EOS[2]: \\t\\a\n"),
4423 "BEL is `\\a` in C's table, not `\\x07` (epicsString.c:245): {out}"
4424 );
4425 }
4426
4427 /// R16-49: the report has no options block, at any level.
4428 ///
4429 /// C `asynPortDriver::report` (asynPortDriver.cpp:3677-3710) prints the port
4430 /// name, the timestamp, the EOS pair, the parameter lists and — at
4431 /// `details >= 3` — the interrupt clients. It never prints options, and it
4432 /// could not: `asynOption` is a `getOption`/`setOption` pair keyed by a
4433 /// driver-defined string, with no enumeration to walk.
4434 #[test]
4435 fn report_prints_no_options_block() {
4436 struct Drv {
4437 base: PortDriverBase,
4438 }
4439 impl PortDriver for Drv {
4440 fn base(&self) -> &PortDriverBase {
4441 &self.base
4442 }
4443 fn base_mut(&mut self) -> &mut PortDriverBase {
4444 &mut self.base
4445 }
4446 }
4447
4448 let mut drv = Drv {
4449 base: PortDriverBase::new("opt_rep", 1, PortFlags::default()),
4450 };
4451 drv.set_option(&mut AsynUser::default(), "baud", "9600")
4452 .unwrap();
4453
4454 for level in 0..=4 {
4455 let mut out = String::new();
4456 drv.report(&mut out, level);
4457 assert!(
4458 !out.contains("option") && !out.contains("baud"),
4459 "asynReport {level} must print no options block: {out}"
4460 );
4461 }
4462 }
4463}