Devices
Also known as: serial port com usb rs-232 uart arduino board sensor modem baud hardware device tty
● Intermediate3 minBefore this: BytesSpec 14.18
std.devices talks to devices on a cable. Serial ports come first: boards, sensors and modems on USB or RS-232. They need the capability Serial.
use std.devices
fn main() ! Error uses Serial, Console {
for path in devices.serial_ports() {
print(path)
}
const board = try devices.open_serial("/dev/ttyUSB0", 115_200)
try board.write("ping\n".bytes())
const answer = try board.read(64)
print(answer.text() ?? "?")
}It lists the ports, opens one at 115,200 bits a second, sends ping and prints the answer. A port is named as the system names it: COM3 on Windows, /dev/ttyUSB0 on Linux.
| Function or method | Gives |
|---|---|
devices.serial_ports() -> [String] | The serial ports there are: COM3 on Windows, /dev/ttyUSB0 on Linux |
devices.open_serial(path, baud) -> SerialPort ! DeviceError | Opens the port at path at baud bits a second (8 data bits, no parity, 1 stop bit) |
port.write(data) ! DeviceError | Sends the Bytes data |
port.read(max) -> Bytes ! DeviceError | Up to max bytes: what has arrived, waiting at most a second for the first; empty Bytes when none came |
port.close() | Closes the port; a port is closed anyway when its last holder ends |
- A port runs with 8 data bits, no parity and 1 stop bit, the setting most devices use.
readwaits at most a second for the first byte, and gives emptyByteswhen none came. While it waits, the task keeps its turn.- Each kind of device has a capability of its own, so a function's signature shows what it can reach, and an agent gets one only when a person approves it.
When a port isn't there
DeviceError is NotFound(path), Denied(path) (another program has the port, or the user may not open it) or Failed(path, reason):
use std.devices
fn main() uses Serial, Console {
const board = devices.open_serial("COM250", 115_200) catch e => {
print("can't open it: {e}")
return
}
board.close()
}The program ran and printed:
kavach run not-found.kav
can't open it: NotFound(path: "COM250")It needs Serial
A function that reaches a port says so in its uses, or it doesn't compile:
use std.devices
pub fn ports() -> [String] uses Console {
devices.serial_ports()
}
fn main() uses Console {
print(ports())
}The compiler refused the program:
kavach run needs.kav
error: `ports` uses Serial, but its `uses` clause doesn't list it: add `Serial` to `uses` (spec 8.1)kavach test has no fake serial port yet, so a function that uses Serial gets no generated tests.