Expand description
One serial port, shared by a program and every driver on it.
A UART carries bytes one character at a time and knows nothing of messages: a framing such
as SLIP or COBS from pamoja-serial, or the silences of Modbus RTU, is what marks where one
ends. SerialPort is a handle to one port that clones cheaply, as
I2cBus is to one bus, so a program, a thread that reads, and a
protocol client can all hold the same port. Behind the handle is one of five things:
- The kernel’s serial device, opened raw with
SerialPort::open:/dev/serial0for a Raspberry Pi’s own UART,/dev/ttyUSB0or/dev/ttyACM0for a USB adapter. Only Linux has one here. - A line looped back on itself,
SerialPort::looped: every byte written is read back, as with TX wired to RX. - One end of a null-modem pair,
SerialPort::pair: what one end writes, the other reads. - A simulated device,
SerialPort::simulated, that takes every write and answers with bytes of its own: anything that implementsPeer, such as a Modbus server. - A script,
SerialPort::scripted, of the writes a driver is expected to make and the bytes the far end sends back.
A read waits for bytes up to a timeout. On the kernel’s device the process waits. On every
other port nothing waits, since nothing else is coming, and the time a read would have
waited is added to SerialPort::waited_micros, so a test of a device that never answers
runs at once and still says how long a real one would have taken.
§Examples
use std::time::Duration;
use pamoja_hal::port::{SerialPort, Settings};
// Two ends of one line: a gateway and the node it listens to.
let (gateway, node) = SerialPort::pair(Settings::new(115_200));
node.write(b"t=21.5")?;
let mut buffer = [0u8; 16];
let got = gateway.read(&mut buffer, Duration::from_millis(100))?;
assert_eq!(&buffer[..got], b"t=21.5");
// Nothing more is coming: the read gives up after its timeout, which is counted, not slept.
assert_eq!(gateway.read(&mut buffer, Duration::from_millis(100))?, 0);
assert_eq!(gateway.waited_micros(), 100_000);Structs§
- Serial
Port - One serial port, reached by every clone of this handle.
- Settings
- A port’s speed and character format: eight data bits, with the parity and stop bits given.
Enums§
- Open
Error - Why a serial device could not be opened.
- Parity
- The parity bit each character carries.
- Port
Error - Why a read or a write on a
SerialPortfailed. - Port
Kind - What is on the other end of a
SerialPort. - Port
Step - One step of a
SerialPort::scriptedport. - Stop
Bits - How many stop bits end each character.
Traits§
- Peer
- A device at the far end of a simulated serial line.