slowtec / tokio-modbus

A tokio-based modbus library
Apache License 2.0
398 stars 120 forks source link

Whats the purpose of the sync rtu client? #70

Open zzeroo opened 3 years ago

zzeroo commented 3 years ago

With the async rtu client under windows I had massive Permission denied issues (A separate issue follows).

Now I try to get the sync rtu part up and running and stumbled upon this one:

thread 'main' panicked at 'there is no reactor running, must be called from the context of Tokio runtime'

Here is my example

#[cfg(all(feature = "rtu", feature = "sync"))]
pub fn main() {
    use tokio_modbus::prelude::*;
    use tokio_serial::{Serial, SerialPortSettings};

    let tty_path = "/dev/ttyUSB0";
    let slave = Slave(247);
    let settings = SerialPortSettings::default();

    let mut ctx = sync::rtu::connect_slave(&tty_path, &settings, slave).unwrap();
    let buff = ctx.read_input_registers(0x1000, 7).unwrap();
    println!("Response is '{:?}'", buff);
}

#[cfg(not(all(feature = "rtu", feature = "sync")))]
pub fn main() {
    println!("features `rtu` and `sync` are required to run this example");
    std::process::exit(1);
}

Does the "sync" rtu part differ from the sync tcp one? The tcp example looks for me really sync without a runtime I mean.

bootrecords commented 3 years ago

After looking at it a bit more in-depth, I have to concur that the design is somewhat awkward. Both the TCP and RTU sync clients internally wrap around a tokio runtime that is always blocked on any call to the sync context, but under the hood everything in this crate uses the async Modbus engine.

From what I can tell your example should run just fine... all calls that require a runtime should be piped through one, though one thing I found peculiar is a call to Serial::from_path, which eventually resolves to a default tokio-net::util::PollEvented that has not been registered with a reactor. However, it may require one in order to handle the later read_input_registers call here.

We have a very similar sync RTU example in #72 (and #76), but I haven't run it against any device so far. The above issue may be alleviated in the newer version of tokio-serial that is being used alongside the tokio v1 upgrades - someone may want to check that sync example against an actual machine, though.