Easy Modbus

MIT licensed Build Status

A Rust Modbus library.

Examples

A simple Modbus TCP Server:

```rust,no_run use std::error::Error;

use futures::SinkExt; use tokio::net::{TcpListener, TcpStream}; use tokiostream::StreamExt; use tokioutil::codec::Framed;

use easy_modbus::{Frame, codec::TcpServerCodec};

[tokio::main]

async fn main() -> Result<(), Box> { let addr = "127.0.0.1:502".to_string(); let server = TcpListener::bind(&addr).await?; println!("Listening on: {}", addr);

loop {
    let (stream, _) = server.accept().await?;
    tokio::spawn(async move {
        if let Err(e) = process(stream).await {
            println!("failed to  process connection; error = {}", e);
        }
    });
}

}

async fn process(stream: TcpStream) -> Result<(), Box> { let mut transport = Framed::new(stream, TcpServerCodec); let frame = Frame::tcp(); while let Some(request) = transport.next().await { match request { Ok(request) => { println!("load request --- {:?}", request); let response = frame.readcoilsresponse(0x01, vec![0x00, 0x01]); println!("send response --- {:?}", response); transport.send(response).await?; } Err(e) => return Err(e.into()), } } Ok(()) } ```

A simple Modbus TCP Client:

``` rust,no_run use std::error::Error;

use futures::SinkExt; use tokio::net::TcpStream; use tokiostream::StreamExt; use tokioutil::codec::Framed;

use easy_modbus::{Frame, codec::TcpClientCodec};

[tokio::main]

async fn main() -> Result<(), Box> { let addr = "127.0.0.1:502".tostring(); let stream = TcpStream::connect(&addr).await?; let mut transport = Framed::new(stream, TcpClientCodec); let frame = Frame::tcp(); let request = frame.readcoils_request(0x01, 0x02, 0x08);

transport.send(request).await?;
while let Some(response) = transport.next().await {
    match response {
        Ok(response) => {
            println!("{:?}", response);
        }
        Err(e) => {
            return Err(e.into());
        }
    }
}
Ok(())

} ```

Source Code Mirror

sourcehut

License

This project is licensed under the [MIT license].