fix request
This commit is contained in:
parent
724bedebf5
commit
1f747f2655
@ -34,7 +34,6 @@ async fn main() {
|
|||||||
|
|
||||||
println!("port: {:?}", c.port);
|
println!("port: {:?}", c.port);
|
||||||
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
// 1. 读取4字节长度前缀 (big-endian)
|
// 1. 读取4字节长度前缀 (big-endian)
|
||||||
let mut len_bytes = [0u8; 2];
|
let mut len_bytes = [0u8; 2];
|
||||||
|
|||||||
@ -9,7 +9,7 @@ use tokio_modbus::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
pub (crate) struct ModbusClient {
|
pub (crate) struct ModbusClient {
|
||||||
ctx: Context
|
stream: SerialStream
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ModbusClient {
|
impl ModbusClient {
|
||||||
@ -36,14 +36,51 @@ impl ModbusClient {
|
|||||||
.timeout(std::time::Duration::from_millis(serial_config.timeout as u64));
|
.timeout(std::time::Duration::from_millis(serial_config.timeout as u64));
|
||||||
|
|
||||||
// 2. 建立串口连接
|
// 2. 建立串口连接
|
||||||
let port = builder.open_native_async().unwrap();
|
let stream = builder.open_native_async().unwrap();
|
||||||
|
|
||||||
// 3. 创建Modbus RTU客户端 (0.16.1新API)
|
|
||||||
let slave_id = Slave(0x01); // 从站地址
|
|
||||||
let ctx = rtu::attach_slave(port, slave_id);
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
ctx
|
stream
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn request(&mut self, slave_id: u8, address: u16) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let slave = Slave(slave_id);
|
||||||
|
let mut ctx = rtu::attach_slave(&mut self.stream, slave);
|
||||||
|
|
||||||
|
// 根据 address 范围执行不同操作
|
||||||
|
match address {
|
||||||
|
// 保持寄存器(Holding Registers): 40000-49999
|
||||||
|
40000..=49999 => {
|
||||||
|
let modbus_addr = address - 40000; // 转换为 Modbus 协议地址(0-9999)
|
||||||
|
let response = ctx.read_holding_registers(modbus_addr, 1).await?;
|
||||||
|
println!("Holding Register {}: {:?}", modbus_addr, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 输入寄存器(Input Registers): 30000-39999
|
||||||
|
30000..=39999 => {
|
||||||
|
let modbus_addr = address - 30000;
|
||||||
|
let response = ctx.read_input_registers(modbus_addr, 1).await?;
|
||||||
|
println!("Input Register {}: {:?}", modbus_addr, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 离散输入(Discrete Inputs): 10000-19999
|
||||||
|
10000..=19999 => {
|
||||||
|
let modbus_addr = address - 10000;
|
||||||
|
let response = ctx.read_discrete_inputs(modbus_addr, 1).await?;
|
||||||
|
println!("Discrete Input {}: {:?}", modbus_addr, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 线圈(Coils): 0-9999
|
||||||
|
0..=9999 => {
|
||||||
|
let response = ctx.read_coils(address, 1).await?;
|
||||||
|
println!("Coil {}: {:?}", address, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => {
|
||||||
|
return Err("Invalid Modbus address".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user