Module tokio_async

Module tokio_async 

Source
Available on crate features tokio-rtu or tokio-tcp only.
Expand description

Asynchronous tokio-modbus client for the R4DCB08 temperature module.

This module provides a high-level API (R4DCB08 struct) to interact with the R4DCB08 8-channel temperature module using Modbus RTU or TCP. It handles the conversion between Rust types defined in the crate::protocol module and the raw Modbus register values.

All client methods are async and must be .awaited.

§Examples

§TCP Client Example

use r4dcb08_lib::tokio_async::R4DCB08;
use std::net::SocketAddr;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let socket_addr: SocketAddr = "127.0.0.1:502".parse()?;

    // Connect to the Modbus TCP device
    let mut modbus_ctx = tokio_modbus::client::tcp::connect(socket_addr).await?;

    // Read temperatures from all 8 channels with a timeout
    let result = tokio::time::timeout(
        Duration::from_secs(1),
        R4DCB08::read_temperatures(&mut modbus_ctx),
    )
    .await;

    match result {
        Ok(Ok(temperatures)) => println!("Temperatures: {}", temperatures),
        Ok(Err(e)) => eprintln!("Modbus error: {}", e),
        Err(e) => eprintln!("Timeout error: {}", e),
    }

    Ok(())
}

§RTU Client Example

use r4dcb08_lib::tokio_async::R4DCB08;
use r4dcb08_lib::protocol::{Address, BaudRate};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let builder = r4dcb08_lib::tokio_common::serial_port_builder(
        "/dev/ttyUSB0", // Or "COM3" on Windows, etc.
        &BaudRate::B9600,
    );
    let port = tokio_serial::SerialStream::open(&builder)?;
    let slave = tokio_modbus::Slave(1);
    let mut modbus_ctx = tokio_modbus::client::rtu::attach_slave(port, slave);

    // Read the device's configured baud rate with a timeout
    let result = tokio::time::timeout(
        Duration::from_secs(1),
        R4DCB08::read_baud_rate(&mut modbus_ctx),
    )
    .await;

    match result {
        Ok(Ok(remote_baud_rate)) => println!("Device baud rate: {}", remote_baud_rate),
        Ok(Err(e)) => eprintln!("Modbus error: {}", e),
        Err(e) => eprintln!("Timeout error: {}", e),
    }

    Ok(())
}

Structs§

R4DCB08
Asynchronous client for interacting with the R4DCB08 temperature module over Modbus.