r4dcb08_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
34/// Creates and configures a `tokio_serial::SerialPortBuilder` for RTU communication.
35///
36/// This function sets up the standard communication parameters required by the
37/// R4DCB08 device: no parity, 8 data bits, and 1 stop bit.
38///
39/// Note that this function only creates and configures the builder. It does not
40/// open the serial port, and therefore does not perform any I/O and cannot fail.
41/// The actual connection is established when this builder is used by a `tokio-modbus`
42/// client constructor.
43///
44/// # Arguments
45///
46/// * `device` - The path to the serial port device (e.g., `/dev/ttyUSB0` on Linux
47///   or `COM3` on Windows).
48/// * `baud_rate` - The baud rate for the serial communication.
49pub fn serial_port_builder(
50    device: &str,
51    baud_rate: &proto::BaudRate,
52) -> tokio_serial::SerialPortBuilder {
53    tokio_serial::new(device, *baud_rate as u32)
54        .parity(*PARITY)
55        .stop_bits(*STOP_BITS)
56        .data_bits(*DATA_BITS)
57        .flow_control(tokio_serial::FlowControl::None)
58}