Skip to main content

serialplugin_core/
events.rs

1//! Streaming event types, event sinks and watch / exchange options.
2
3use serde::{Deserialize, Serialize};
4use std::sync::Arc;
5
6/// Receives the events of one [`SerialManager::watch`](crate::SerialManager::watch).
7///
8/// Called on the port's RX thread, so keep it short (push into a channel for heavy
9/// work); the last events of a watch (parser remainder on unwatch / close / re-watch)
10/// may run on the caller's thread instead. Events arrive in order, one call at a time
11/// per port, never under a manager lock: the sink may call back into the manager.
12/// Return `false` once the receiver is gone; the failure is logged.
13pub type EventSink = Arc<dyn Fn(SerialEvent) -> bool + Send + Sync>;
14
15/// Receives [`PortListEvent`]s of one [`SerialManager::watch_ports`](crate::SerialManager::watch_ports).
16/// Returning `false` ends the subscription.
17pub type PortListSink = Arc<dyn Fn(PortListEvent) -> bool + Send + Sync>;
18
19/// Forward events to a Tauri IPC channel (serialized to JSON per event); the sink
20/// reports `false` once the webview side of the channel is gone. Feature `tauri`.
21#[cfg(feature = "tauri")]
22pub fn channel_sink<E>(channel: tauri::ipc::Channel<E>) -> Arc<dyn Fn(E) -> bool + Send + Sync>
23where
24    E: tauri::ipc::IpcResponse + Send + Sync + 'static,
25{
26    Arc::new(move |event| channel.send(event).is_ok())
27}
28
29/// Options for [`SerialManager::watch_ports`](crate::SerialManager::watch_ports).
30#[derive(Debug, Clone, Default, Serialize, Deserialize)]
31#[serde(rename_all = "camelCase")]
32pub struct WatchPortsOptions {
33    /// Same as [`SerialManager::available_ports`](crate::SerialManager::available_ports) `single_port_per_device`.
34    #[serde(default)]
35    pub single_port_per_device: Option<bool>,
36    /// Poll interval on desktop (ms). Default: 2000. Android also polls as fallback.
37    #[serde(default)]
38    pub poll_interval_ms: Option<u64>,
39}
40
41/// Port list change events delivered to a [`PortListSink`].
42#[derive(Debug, Clone, Serialize, Deserialize)]
43#[serde(tag = "kind", rename_all = "camelCase")]
44pub enum PortListEvent {
45    /// Initial/full list when subscribing or after reconnect.
46    Snapshot {
47        ports: std::collections::HashMap<String, std::collections::HashMap<String, String>>,
48    },
49    /// A serial device appeared in the system enumeration.
50    Added {
51        path: String,
52        info: std::collections::HashMap<String, String>,
53    },
54    /// A serial device disappeared from the system enumeration.
55    Removed { path: String },
56}
57
58/// Event delivered to an [`EventSink`] (in the Tauri plugin: to the webview channel, as JSON).
59#[derive(Debug, Clone, Serialize, Deserialize)]
60#[serde(tag = "kind", rename_all = "camelCase")]
61pub enum SerialEvent {
62    Data {
63        path: String,
64        data: Vec<u8>,
65        size: usize,
66    },
67    Disconnect {
68        path: String,
69        reason: String,
70    },
71    Urc {
72        path: String,
73        line: String,
74    },
75    Error {
76        path: String,
77        message: String,
78    },
79}
80
81/// Options for [`SerialManager::watch`](crate::SerialManager::watch). Unknown keys are
82/// ignored (as in 4.0.0). A native parser is passed separately, see
83/// [`SerialManager::watch_framed`](crate::SerialManager::watch_framed).
84#[derive(Debug, Clone, Default, Serialize, Deserialize)]
85#[serde(rename_all = "camelCase")]
86pub struct WatchOptions {
87    #[serde(default)]
88    pub timeout: Option<u64>,
89    #[serde(default)]
90    pub size: Option<usize>,
91    #[serde(default)]
92    pub serial_data_flush_interval_ms: Option<u64>,
93    /// When `true`, idle watch RX is line-routed so AT URC lines become
94    /// [`SerialEvent::Urc`] instead of raw `data`. Default `false`: bytes are
95    /// forwarded unchanged (binary / NMEA / non-AT streams).
96    ///
97    /// The JS guest sets this automatically when `onUrc` is provided.
98    #[serde(default)]
99    pub route_urc: bool,
100}
101
102/// Receives the events of the core's new API: one
103/// [`SerialManager::watch_core`](crate::SerialManager::watch_core) stream or the port
104/// states of [`SerialManager::subscribe_core`](crate::SerialManager::subscribe_core).
105///
106/// Runs on a delivery thread of its own (one per subscription), never on the RX
107/// thread and never under a manager lock: it may block for a while, and it may call
108/// back into the manager, `at()` on the same port included. Events wait in a bounded
109/// queue ([`SerialManager::set_core_queue_capacity`](crate::SerialManager::set_core_queue_capacity),
110/// default [`DEFAULT_CORE_QUEUE_BYTES`]); when it is full the sink gets one
111/// [`CoreEvent::Overflow`] and is unsubscribed. Returning `false` unsubscribes too.
112pub type CoreSink = Arc<dyn Fn(CoreEvent) -> bool + Send + Sync>;
113
114/// Default per-subscription queue of the core's Rust receivers (4 MiB of event data).
115pub const DEFAULT_CORE_QUEUE_BYTES: usize = 4 << 20;
116
117/// Id of a [`SerialManager::watch_core`](crate::SerialManager::watch_core) stream or a
118/// [`SerialManager::subscribe_core`](crate::SerialManager::subscribe_core) subscription.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
120pub struct SubscriptionId(pub u64);
121
122/// Event of the core's new API (see [`CoreSink`]).
123#[derive(Debug, Clone)]
124#[non_exhaustive]
125pub enum CoreEvent {
126    /// A watch event, exactly as the old watch sends it (the final `Disconnect` included).
127    Event(SerialEvent),
128    /// The queue overflowed: data from byte `dropped_from` of this stream on (counting
129    /// `Data` bytes delivered before it) is gone, and the sink is unsubscribed.
130    Overflow { dropped_from: u64 },
131    /// A port changed state ([`SerialManager::subscribe_core`](crate::SerialManager::subscribe_core) only).
132    PortState { path: String, state: PortStatus },
133}
134
135/// A port's state change in [`CoreEvent::PortState`].
136#[derive(Debug, Clone, PartialEq, Eq)]
137#[non_exhaustive]
138pub enum PortStatus {
139    Opened,
140    /// Lost without `close()` (unplug, EOF, I/O error); the core has released the port.
141    Disconnected {
142        kind: crate::error::ErrorKind,
143        reason: String,
144    },
145    /// Closed by `close()` / `force_close()` / `close_all()`.
146    Closed,
147}
148
149/// How RX is prepared before sending an exchange payload.
150#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
151#[serde(rename_all = "camelCase")]
152pub enum RxPrepareMode {
153    /// Read until idle (default) — soft drain, preserves URC for parsing.
154    #[default]
155    Drain,
156    /// Hardware/driver input buffer purge.
157    Purge,
158    /// Do not touch RX before write.
159    None,
160}
161
162pub use serial_codec::at::AtResultFormat;
163
164/// When an exchange read is considered complete.
165#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
166#[serde(rename_all = "camelCase")]
167pub enum ExchangeCompletionMode {
168    /// Complete when the last non-empty line is OK / ERROR / +CME|CMS ERROR (default for AT).
169    #[default]
170    AtFinalLine,
171    /// Complete when the last line is an intermediate result (`>`, `CONNECT`, numeric `1`).
172    AtIntermediate,
173    /// Legacy substring terminators anywhere in the buffer.
174    Substring,
175}
176
177/// Options for [`SerialManager::exchange`](crate::SerialManager::exchange) (write + read-until-response).
178#[derive(Debug, Clone, Default, Serialize, Deserialize)]
179#[serde(rename_all = "camelCase")]
180pub struct ExchangeOptions {
181    /// Wall-clock limit for the whole exchange (ms). Default: 5000.
182    #[serde(default)]
183    pub timeout_ms: Option<u64>,
184    /// Maximum response size in bytes. Default: 4096.
185    #[serde(default)]
186    pub max_bytes: Option<usize>,
187    /// Substring terminators (used when `completion_mode` is `substring`).
188    #[serde(default)]
189    pub terminators: Option<Vec<String>>,
190    /// Complete after this many ms of RX silence once data has arrived.
191    #[serde(default)]
192    pub idle_ms: Option<u64>,
193    /// How to prepare RX before write. Default: drain.
194    #[serde(default)]
195    pub rx_prepare: Option<RxPrepareMode>,
196    /// Idle ms during soft drain. Default: 50.
197    #[serde(default)]
198    pub drain_idle_ms: Option<u64>,
199    /// Max ms for soft drain. Default: 200.
200    #[serde(default)]
201    pub drain_max_ms: Option<u64>,
202    /// Completion strategy. Default: atFinalLine.
203    #[serde(default)]
204    pub completion_mode: Option<ExchangeCompletionMode>,
205    /// Command string for AT parse (echo / solicited classification).
206    #[serde(default)]
207    pub command: Option<String>,
208    /// Prefixes treated as solicited `+` lines (not URC), e.g. `+CSQ:`.
209    #[serde(default)]
210    pub solicited_prefixes: Option<Vec<String>>,
211    /// Verbose (`ATV1`) vs numeric (`ATV0`) final/intermediate lines. Default: verbose.
212    #[serde(default)]
213    pub result_format: Option<AtResultFormat>,
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn serial_event_data_roundtrip() {
222        let event = SerialEvent::Data {
223            path: "/dev/ttyUSB0".into(),
224            data: vec![1, 2, 255],
225            size: 3,
226        };
227        let json = serde_json::to_value(&event).unwrap();
228        assert_eq!(json["kind"], "data");
229        assert_eq!(json["path"], "/dev/ttyUSB0");
230        let back: SerialEvent = serde_json::from_value(json).unwrap();
231        match back {
232            SerialEvent::Data { size, .. } => assert_eq!(size, 3),
233            _ => panic!("expected data"),
234        }
235    }
236
237    #[test]
238    fn serial_event_error_roundtrip() {
239        let event = SerialEvent::Error {
240            path: "/dev/ttyUSB0".into(),
241            message: "read glitch".into(),
242        };
243        let json = serde_json::to_value(&event).unwrap();
244        assert_eq!(json["kind"], "error");
245        assert_eq!(json["message"], "read glitch");
246        let back: SerialEvent = serde_json::from_value(json).unwrap();
247        match back {
248            SerialEvent::Error { message, .. } => assert_eq!(message, "read glitch"),
249            _ => panic!("expected error"),
250        }
251    }
252
253    #[test]
254    fn serial_event_disconnect_roundtrip() {
255        let event = SerialEvent::Disconnect {
256            path: "/dev/ttyUSB0".into(),
257            reason: "USB unplugged".into(),
258        };
259        let json = serde_json::to_value(&event).unwrap();
260        assert_eq!(json["kind"], "disconnect");
261        assert_eq!(json["reason"], "USB unplugged");
262        let back: SerialEvent = serde_json::from_value(json).unwrap();
263        match back {
264            SerialEvent::Disconnect { reason, .. } => assert_eq!(reason, "USB unplugged"),
265            _ => panic!("expected disconnect"),
266        }
267    }
268}