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/// How RX is prepared before sending an exchange payload.
103#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
104#[serde(rename_all = "camelCase")]
105pub enum RxPrepareMode {
106    /// Read until idle (default) — soft drain, preserves URC for parsing.
107    #[default]
108    Drain,
109    /// Hardware/driver input buffer purge.
110    Purge,
111    /// Do not touch RX before write.
112    None,
113}
114
115pub use serial_codec::at::AtResultFormat;
116
117/// When an exchange read is considered complete.
118#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
119#[serde(rename_all = "camelCase")]
120pub enum ExchangeCompletionMode {
121    /// Complete when the last non-empty line is OK / ERROR / +CME|CMS ERROR (default for AT).
122    #[default]
123    AtFinalLine,
124    /// Complete when the last line is an intermediate result (`>`, `CONNECT`, numeric `1`).
125    AtIntermediate,
126    /// Legacy substring terminators anywhere in the buffer.
127    Substring,
128}
129
130/// Options for [`SerialManager::exchange`](crate::SerialManager::exchange) (write + read-until-response).
131#[derive(Debug, Clone, Default, Serialize, Deserialize)]
132#[serde(rename_all = "camelCase")]
133pub struct ExchangeOptions {
134    /// Wall-clock limit for the whole exchange (ms). Default: 5000.
135    #[serde(default)]
136    pub timeout_ms: Option<u64>,
137    /// Maximum response size in bytes. Default: 4096.
138    #[serde(default)]
139    pub max_bytes: Option<usize>,
140    /// Substring terminators (used when `completion_mode` is `substring`).
141    #[serde(default)]
142    pub terminators: Option<Vec<String>>,
143    /// Complete after this many ms of RX silence once data has arrived.
144    #[serde(default)]
145    pub idle_ms: Option<u64>,
146    /// How to prepare RX before write. Default: drain.
147    #[serde(default)]
148    pub rx_prepare: Option<RxPrepareMode>,
149    /// Idle ms during soft drain. Default: 50.
150    #[serde(default)]
151    pub drain_idle_ms: Option<u64>,
152    /// Max ms for soft drain. Default: 200.
153    #[serde(default)]
154    pub drain_max_ms: Option<u64>,
155    /// Completion strategy. Default: atFinalLine.
156    #[serde(default)]
157    pub completion_mode: Option<ExchangeCompletionMode>,
158    /// Command string for AT parse (echo / solicited classification).
159    #[serde(default)]
160    pub command: Option<String>,
161    /// Prefixes treated as solicited `+` lines (not URC), e.g. `+CSQ:`.
162    #[serde(default)]
163    pub solicited_prefixes: Option<Vec<String>>,
164    /// Verbose (`ATV1`) vs numeric (`ATV0`) final/intermediate lines. Default: verbose.
165    #[serde(default)]
166    pub result_format: Option<AtResultFormat>,
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn serial_event_data_roundtrip() {
175        let event = SerialEvent::Data {
176            path: "/dev/ttyUSB0".into(),
177            data: vec![1, 2, 255],
178            size: 3,
179        };
180        let json = serde_json::to_value(&event).unwrap();
181        assert_eq!(json["kind"], "data");
182        assert_eq!(json["path"], "/dev/ttyUSB0");
183        let back: SerialEvent = serde_json::from_value(json).unwrap();
184        match back {
185            SerialEvent::Data { size, .. } => assert_eq!(size, 3),
186            _ => panic!("expected data"),
187        }
188    }
189
190    #[test]
191    fn serial_event_error_roundtrip() {
192        let event = SerialEvent::Error {
193            path: "/dev/ttyUSB0".into(),
194            message: "read glitch".into(),
195        };
196        let json = serde_json::to_value(&event).unwrap();
197        assert_eq!(json["kind"], "error");
198        assert_eq!(json["message"], "read glitch");
199        let back: SerialEvent = serde_json::from_value(json).unwrap();
200        match back {
201            SerialEvent::Error { message, .. } => assert_eq!(message, "read glitch"),
202            _ => panic!("expected error"),
203        }
204    }
205
206    #[test]
207    fn serial_event_disconnect_roundtrip() {
208        let event = SerialEvent::Disconnect {
209            path: "/dev/ttyUSB0".into(),
210            reason: "USB unplugged".into(),
211        };
212        let json = serde_json::to_value(&event).unwrap();
213        assert_eq!(json["kind"], "disconnect");
214        assert_eq!(json["reason"], "USB unplugged");
215        let back: SerialEvent = serde_json::from_value(json).unwrap();
216        match back {
217            SerialEvent::Disconnect { reason, .. } => assert_eq!(reason, "USB unplugged"),
218            _ => panic!("expected disconnect"),
219        }
220    }
221}