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 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

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 watch( &self, path: String, options: WatchOptions, sink: EventSink, ) -> Result<u32, Error>

Stream port events into sink (one watch per port). Returns the id for Self::unwatch. sink runs on the port’s RX thread, keep it short; the last events (parser remainder on unwatch / close) may run on the caller’s thread. It never runs under a manager lock, so it may call back into the manager.

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

Source

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

Write binary data to the serial port

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

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 at( &self, path: String, command: String, options: Option<AtCommandOptions>, ) -> Result<AtCommandResult, Error>

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.

Source

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

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

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.