Skip to main content

SerialManager

Struct SerialManager 

Source
pub struct SerialManager { /* private fields */ }
Expand description

Owns every open port (desktop serial, tcp://, ble://, Android USB, CMUX channels).

Cheap to clone (all clones share the same ports). Methods block: call them from a plain thread or tokio::task::spawn_blocking, not straight from an async task.

Lock order: serialports before virtual_ports; never hold a map lock across device I/O, thread spawn, or JoinHandle join.

Implementations§

Source§

impl SerialManager

Source

pub fn available_ports_detailed(&self) -> Result<Vec<PortDetails>, Error>

Every serial port with typed details (numeric vid/pid, USB interface number, location, Linux /dev/serial links), sorted by path. The 4.x Self::available_ports map is unchanged. On Android the fields come from the 4.x map (no interface / location).

Source§

impl SerialManager

Source

pub fn supports_modem_lines(&self, path: &str) -> bool

false when path has no real RTS/DTR/CTS/DSR/RI/DCD: tcp:// bridges and ble:// UARTs, where the modem-line setters still succeed (the value is stored locally) and the getters return fixed values, and CMUX channels (path#dlci=N), where line calls fail (the lines belong to the physical port). Check this before relying on hardware flow control or line signalling. Local serial ports return true. Needs no open port.

Source§

impl SerialManager

Source

pub fn new() -> Self

Examples found in repository?
examples/headless.rs (line 15)
10fn main() -> Result<(), serialplugin_core::Error> {
11    let mut args = std::env::args().skip(1);
12    let path = args.next().expect("usage: headless <path> [baud]");
13    let baud = args.next().map_or(115_200, |b| b.parse().expect("baud"));
14
15    let serial = SerialManager::new();
16    let path = serial.open(path, baud, None, None, None, None, None)?;
17    let sink: EventSink = Arc::new(|event| {
18        match event {
19            SerialEvent::Data { data, .. } => println!("{}", String::from_utf8_lossy(&data)),
20            SerialEvent::Disconnect { path, reason } => {
21                eprintln!("{path} disconnected: {reason}");
22                std::process::exit(1);
23            }
24            other => eprintln!("{other:?}"),
25        }
26        true
27    });
28    let parser =
29        serde_json::from_value(serde_json::json!({"type": "readline", "delimiter": "\r\n"}))
30            .expect("parser config");
31    serial.watch_framed(path, WatchOptions::default(), Some(parser), sink)?;
32    loop {
33        std::thread::park();
34    }
35}
Source

pub fn available_ports( &self, single_port_per_device: bool, ) -> Result<HashMap<String, HashMap<String, String>>, Error>

Get serial port list

Source

pub fn watch_ports( &self, options: WatchPortsOptions, sink: PortListSink, ) -> Result<u32, Error>

Subscribe to available-port attach/detach events. sink first gets a Snapshot, then added / removed. Returns the id for Self::unwatch_ports.

Source

pub fn watch_ports_with_id( &self, id: u32, options: WatchPortsOptions, sink: PortListSink, ) -> Result<u32, Error>

Self::watch_ports under a caller-chosen id (the plugin uses its IPC channel id).

Source

pub fn unwatch_ports(&self, channel_id: u32) -> Result<(), Error>

Stop a port-list watch session.

Source

pub fn managed_ports(&self) -> Result<Vec<String>, Error>

Get a list of managed serial ports.

Source

pub fn cancel_read(&self, path: String) -> Result<(), Error>

Cancel an in-flight poll Self::read (does not stop an active Self::watch).

Source

pub fn close(&self, path: String) -> Result<(), Error>

Close the specified serial port. What the hub still holds (the watch batch, a parser’s remainder) reaches the watches first, in order; no Disconnect is sent. Succeeds once on a port the core already released after a disconnect.

Source

pub fn close_core(&self, path: String) -> Result<(), CoreError>

Source

pub fn close_all(&self) -> Result<(), Error>

Close all open serial ports

Source

pub fn force_close(&self, path: String) -> Result<(), Error>

Force close a serial port

Source

pub fn open( &self, path: String, baud_rate: u32, data_bits: Option<DataBits>, flow_control: Option<FlowControl>, parity: Option<Parity>, stop_bits: Option<StopBits>, timeout: Option<u64>, ) -> Result<String, Error>

Examples found in repository?
examples/headless.rs (line 16)
10fn main() -> Result<(), serialplugin_core::Error> {
11    let mut args = std::env::args().skip(1);
12    let path = args.next().expect("usage: headless <path> [baud]");
13    let baud = args.next().map_or(115_200, |b| b.parse().expect("baud"));
14
15    let serial = SerialManager::new();
16    let path = serial.open(path, baud, None, None, None, None, None)?;
17    let sink: EventSink = Arc::new(|event| {
18        match event {
19            SerialEvent::Data { data, .. } => println!("{}", String::from_utf8_lossy(&data)),
20            SerialEvent::Disconnect { path, reason } => {
21                eprintln!("{path} disconnected: {reason}");
22                std::process::exit(1);
23            }
24            other => eprintln!("{other:?}"),
25        }
26        true
27    });
28    let parser =
29        serde_json::from_value(serde_json::json!({"type": "readline", "delimiter": "\r\n"}))
30            .expect("parser config");
31    serial.watch_framed(path, WatchOptions::default(), Some(parser), sink)?;
32    loop {
33        std::thread::park();
34    }
35}
Source

pub fn open_with_lines( &self, path: String, baud_rate: u32, data_bits: Option<DataBits>, flow_control: Option<FlowControl>, parity: Option<Parity>, stop_bits: Option<StopBits>, timeout: Option<u64>, lines: ModemLinesOnOpen, ) -> Result<String, Error>

Self::open with explicit DTR / RTS levels on open.

Source

pub fn open_core( &self, path: String, baud_rate: u32, data_bits: Option<DataBits>, flow_control: Option<FlowControl>, parity: Option<Parity>, stop_bits: Option<StopBits>, timeout: Option<u64>, lines: ModemLinesOnOpen, ) -> Result<String, CoreError>

Self::open_with_lines with a CoreError (kind NotFound, PermissionDenied, Busy, … and the platform error as its source). timeout (ms, default 1000) is the port’s read / write timeout; Self::set_timeout changes it later.

Opening a path that is already open (or disconnected and not yet closed) replaces that session, as open does in 4.x: it is closed first, with its watches, watch_core streams, CMUX channels and RX hub.

Source

pub fn open_watch_core( &self, path: String, baud_rate: u32, data_bits: Option<DataBits>, flow_control: Option<FlowControl>, parity: Option<Parity>, stop_bits: Option<StopBits>, timeout: Option<u64>, lines: ModemLinesOnOpen, options: WatchOptions, parser: Option<FramerConfig>, sink: CoreSink, ) -> Result<(String, SubscriptionId), CoreError>

Self::open_core plus a Self::watch_core stream that exists before the port’s first read: no byte and no event is lost (a RDY / URC sent right after open, or a Disconnect of a port that dies at once, which still returns Ok). Returns the session path and the stream’s id (for Self::unwatch_core). An invalid parser fails before the port is opened.

Source

pub fn insert_port_watch_core( &self, path: String, port: Box<dyn SerialPortTrait>, options: WatchOptions, parser: Option<FramerConfig>, sink: CoreSink, ) -> Result<SubscriptionId, CoreError>

Self::insert_port plus a Self::watch_core stream that exists before the port’s first read, as Self::open_watch_core.

Source

pub fn insert_port( &self, path: String, port: Box<dyn SerialPortTrait>, ) -> Result<(), CoreError>

Manage port under path as if Self::open had opened it (tests, custom transports, a fake device). An open port under path is closed first. Its current timeout() is the port timeout.

On Unix (not TCP / BLE) writes and control calls go to port.try_clone() when it succeeds, reads to port: a clone must share the device (like a dup’ed fd), or try_clone must return Err to keep one handle for everything.

Source

pub fn watch( &self, path: String, options: WatchOptions, sink: EventSink, ) -> Result<u32, Error>

Stream port events into sink (one watch per port and manager). Returns the id for Self::unwatch. As in 4.x, sink runs on the RX side: the port’s hub thread, or the caller of unwatch / close for the tail they deliver. It never runs under a manager lock, but a slow sink holds up RX (keep it short, e.g. forward into a channel), and calling at() / exchange on the same port from it waits for the RX it blocks. Nothing reaches it after close() returns. Self::watch_core has its own delivery thread instead.

Source

pub fn watch_with_id( &self, channel_id: u32, path: String, options: WatchOptions, sink: EventSink, ) -> Result<u32, Error>

Self::watch under a caller-chosen id (the plugin uses its IPC channel id).

Source

pub fn watch_framed( &self, path: String, options: WatchOptions, parser: Option<FramerConfig>, sink: EventSink, ) -> Result<u32, Error>

Self::watch with a native parser: each complete frame becomes exactly one SerialEvent::Data (the batch timer no longer applies). An invalid config fails before the watch starts. With WatchOptions::route_urc the URC split runs first and only non-URC lines reach the parser. On unwatch, close or disconnect the parser’s buffered remainder is sent as a final data event (before disconnect), like Node serialport emits on stream end.

Examples found in repository?
examples/headless.rs (line 31)
10fn main() -> Result<(), serialplugin_core::Error> {
11    let mut args = std::env::args().skip(1);
12    let path = args.next().expect("usage: headless <path> [baud]");
13    let baud = args.next().map_or(115_200, |b| b.parse().expect("baud"));
14
15    let serial = SerialManager::new();
16    let path = serial.open(path, baud, None, None, None, None, None)?;
17    let sink: EventSink = Arc::new(|event| {
18        match event {
19            SerialEvent::Data { data, .. } => println!("{}", String::from_utf8_lossy(&data)),
20            SerialEvent::Disconnect { path, reason } => {
21                eprintln!("{path} disconnected: {reason}");
22                std::process::exit(1);
23            }
24            other => eprintln!("{other:?}"),
25        }
26        true
27    });
28    let parser =
29        serde_json::from_value(serde_json::json!({"type": "readline", "delimiter": "\r\n"}))
30            .expect("parser config");
31    serial.watch_framed(path, WatchOptions::default(), Some(parser), sink)?;
32    loop {
33        std::thread::park();
34    }
35}
Source

pub fn watch_framed_with_id( &self, channel_id: u32, path: String, options: WatchOptions, parser: Option<FramerConfig>, channel: EventSink, ) -> Result<u32, Error>

Self::watch_framed under a caller-chosen id.

Source

pub fn unwatch(&self, channel_id: u32) -> Result<(), Error>

Source

pub fn read( &self, path: String, timeout: Option<u64>, size: Option<usize>, ) -> Result<String, Error>

Source

pub fn read_binary( &self, path: String, timeout: Option<u64>, size: Option<usize>, ) -> Result<Vec<u8>, Error>

Source

pub fn write(&self, path: String, value: String) -> Result<usize, Error>

Write data to the serial port (or a CMUX channel path#dlci=N).

Source

pub fn write_binary(&self, path: String, value: Vec<u8>) -> Result<usize, Error>

Write binary data to the serial port (or a CMUX channel path#dlci=N).

Source

pub fn write_core( &self, path: String, data: Vec<u8>, ) -> Result<usize, CoreError>

Self::write_binary with a CoreError (the I/O error as its source).

Source

pub fn set_baud_rate(&self, path: String, baud_rate: u32) -> Result<(), Error>

Set the baud rate

Source

pub fn set_data_bits( &self, path: String, data_bits: DataBits, ) -> Result<(), Error>

Set the data bits

Source

pub fn set_flow_control( &self, path: String, flow_control: FlowControl, ) -> Result<(), Error>

Set the flow control

Source

pub fn set_parity(&self, path: String, parity: Parity) -> Result<(), Error>

Set the parity

Source

pub fn set_stop_bits( &self, path: String, stop_bits: StopBits, ) -> Result<(), Error>

Set the stop bits

Source

pub fn set_timeout(&self, path: String, timeout: Duration) -> Result<(), Error>

Set the timeout

Source

pub fn write_request_to_send( &self, path: String, level: bool, ) -> Result<(), Error>

Set the RTS (Request To Send) control signal

Source

pub fn write_data_terminal_ready( &self, path: String, level: bool, ) -> Result<(), Error>

Set the DTR (Data Terminal Ready) control signal

Source

pub fn read_clear_to_send(&self, path: String) -> Result<bool, Error>

Read the CTS (Clear To Send) control signal state

Source

pub fn read_data_set_ready(&self, path: String) -> Result<bool, Error>

Read the DSR (Data Set Ready) control signal state

Source

pub fn read_ring_indicator(&self, path: String) -> Result<bool, Error>

Read the RI (Ring Indicator) control signal state

Source

pub fn read_carrier_detect(&self, path: String) -> Result<bool, Error>

Read the CD (Carrier Detect) control signal state

Source

pub fn bytes_to_read(&self, path: String) -> Result<u32, Error>

Get the number of bytes available to read

Source

pub fn bytes_to_write(&self, path: String) -> Result<u32, Error>

Get the number of bytes waiting to be written

Source

pub fn clear_buffer( &self, path: String, buffer_to_clear: ClearBuffer, ) -> Result<(), Error>

Clear input/output buffers Input / All also drop what the RX hub holds for no one yet.

Source

pub fn set_break(&self, path: String) -> Result<(), Error>

Start break signal transmission

Source

pub fn clear_break(&self, path: String) -> Result<(), Error>

Stop break signal transmission

Source

pub fn exchange( &self, path: String, value: String, options: ExchangeOptions, ) -> Result<ExchangeResponse, Error>

Write payload and read until terminators, idle silence, or timeout (AT-style exchange).

Source

pub fn exchange_binary( &self, path: String, value: Vec<u8>, options: ExchangeOptions, ) -> Result<ExchangeResponse, Error>

Binary variant of Self::exchange.

Source

pub fn exchange_core( &self, path: String, value: Vec<u8>, options: ExchangeOptions, ) -> Result<ExchangeResponse, CoreError>

Self::exchange_binary with a CoreError (Timeout, Cancelled, …).

Source

pub fn at( &self, path: String, command: String, options: Option<AtCommandOptions>, ) -> Result<AtCommandResult, Error>

Source

pub fn at_core( &self, path: String, command: String, options: Option<AtCommandOptions>, ) -> Result<AtCommandResult, CoreError>

Source

pub fn at_phases( &self, path: String, phases: Vec<AtPhase>, ) -> Result<Vec<AtCommandResult>, Error>

Multi-phase AT flow (e.g. CMGS) — phases run atomically without interleaving other jobs.

Source

pub fn send_sms_pdu( &self, path: String, length: u32, pdu: Vec<u8>, options: Option<SendSmsPduOptions>, ) -> Result<Vec<AtCommandResult>, Error>

Built-in CMGS recipe: AT+CMGS=n → > → PDU + Ctrl+Z → final line.

Source

pub fn configure_at_session( &self, path: String, session: AtSessionConfig, ) -> Result<(), Error>

Configure AT session defaults for native at jobs on this port.

Source

pub fn enable_mux( &self, path: String, command: String, timeout_ms: u64, ) -> Result<(), Error>

Enter GSM 07.10 CMUX mode (AT+CMUX=… then attach deframer to the RX hub).

Source

pub fn open_mux_channel( &self, physical_path: String, dlci: u8, ) -> Result<String, Error>

Register a virtual DLCI channel on an CMUX-enabled physical port.

Source

pub fn disable_mux(&self, path: String) -> Result<(), Error>

Tear down CMUX: close virtual channels and detach deframer. The CLD wait (up to T2) runs without the manager’s map lock.

Source

pub fn cancel_exchange(&self, path: String) -> Result<(), Error>

Cancel an in-flight exchange and reject queued waiters on path.

Source§

impl SerialManager

The 4.2 core API: CoreEvent streams, port-state subscriptions, queue limits.

Source

pub fn watch_core( &self, path: String, options: WatchOptions, parser: Option<FramerConfig>, sink: CoreSink, ) -> Result<SubscriptionId, CoreError>

Stream one port’s events into sink as CoreEvent::Event (the final Disconnect included). Any number of these may run on a port, beside the old Self::watch: each gets its own copy of the stream and its own parser / route_urc state, and URCs caught during at() / exchange reach every one with route_urc. See CoreSink for threading, the queue and overflow.

Source

pub fn unwatch_core(&self, id: SubscriptionId) -> Result<(), CoreError>

Stop a Self::watch_core stream; its batch and parser remainder arrive last. NotFound also for a stream that already ended (overflow, sink returned false, port gone).

Source

pub fn subscribe_core(&self, sink: CoreSink) -> SubscriptionId

Port states of every port of this manager (CoreEvent::PortState: opened, disconnected with its kind and reason, closed); needs no watch. Same queue and overflow rules as Self::watch_core.

Source

pub fn unsubscribe_core(&self, id: SubscriptionId) -> Result<(), CoreError>

Source

pub fn set_core_queue_capacity(&self, bytes: usize)

Queue limit (bytes of event data) of core receivers created from now on. Default crate::events::DEFAULT_CORE_QUEUE_BYTES.

Trait Implementations§

Source§

impl Clone for SerialManager

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for SerialManager

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl ExchangeRunner for SerialManager

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.