Skip to main content

r413d08_lib/
tokio_common.rs

1//! This module provides common data structures and error types for the `tokio`
2//! based clients.
3//!
4//! It defines the `Error` enum, which encapsulates all possible communication errors.
5
6use crate::protocol as proto;
7
8/// Represents all possible errors that can occur during Modbus communication.
9#[derive(thiserror::Error, Debug)]
10pub enum Error {
11    /// An error originating from the protocol logic, such as invalid data.
12    #[error(transparent)]
13    Protocol(#[from] proto::Error),
14
15    /// A Modbus exception response from the device (e.g., "Illegal Function").
16    #[error(transparent)]
17    ModbusException(#[from] tokio_modbus::ExceptionCode),
18
19    /// A transport or communication error from the underlying `tokio-modbus` client.
20    #[error(transparent)]
21    Modbus(#[from] tokio_modbus::Error),
22}
23
24/// The result type for tokio operations.
25pub(crate) type Result<T> = std::result::Result<T, Error>;
26
27/// The parity used for serial communication.
28pub const PARITY: &tokio_serial::Parity = &tokio_serial::Parity::None;
29/// The number of stop bits used for serial communication.
30pub const STOP_BITS: &tokio_serial::StopBits = &tokio_serial::StopBits::One;
31/// The number of data bits used for serial communication.
32pub const DATA_BITS: &tokio_serial::DataBits = &tokio_serial::DataBits::Eight;
33/// The baud rate used for serial communication.
34pub const BAUD_RATE: u32 = 9600;
35
36/// Creates and configures a `tokio_serial::SerialPortBuilder` for RTU communication.
37///
38/// This function sets up the standard communication parameters required by the
39/// R413D08 device: 9600 baud, no parity, 8 data bits, and 1 stop bit.
40///
41/// Note that this function only creates and configures the builder. It does not
42/// open the serial port, and therefore does not perform any I/O and cannot fail.
43/// The actual connection is established when this builder is used by a `tokio-modbus`
44/// client constructor.
45///
46/// # Arguments
47///
48/// * `device` - The path to the serial port device (e.g., `/dev/ttyUSB0` on Linux
49///   or `COM3` on Windows).
50pub fn serial_port_builder(device: &str) -> tokio_serial::SerialPortBuilder {
51    tokio_serial::new(device, BAUD_RATE)
52        .parity(*PARITY)
53        .stop_bits(*STOP_BITS)
54        .data_bits(*DATA_BITS)
55        .flow_control(tokio_serial::FlowControl::None)
56}