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