Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,8 @@ pub fn catalog() -> Value {
{ "key": "function", "label": "Function", "type": "select",
"options": ["holding", "input", "coils", "discrete"], "default": "holding" },
{ "key": "address", "label": "Address", "type": "number", "default": 0 },
{ "key": "quantity", "label": "Quantity", "type": "number", "default": 1 }
{ "key": "quantity", "label": "Quantity", "type": "number", "default": 1 },
{ "key": "max_read", "label": "Max per request (0 = one)", "type": "number", "default": 0 }
]
},
{
Expand Down
74 changes: 58 additions & 16 deletions src/runtime/nodes/modbus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ pub struct ModbusReadNode {
address: u16,
#[serde(default = "default_quantity")]
quantity: u16,
/// Max items per Modbus request — `quantity` is read in chunks of this on
/// the same connection (some PLCs reject large reads). 0 = one request.
#[serde(default)]
max_read: u16,
}

impl ModbusReadNode {
Expand All @@ -59,6 +63,52 @@ enum ReadOutcome {
Io(String),
}

/// How long to wait for one Modbus read reply before treating it as an I/O
/// error (so an unresponsive device doesn't hang the node forever).
const READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);

/// Read `quantity` items starting at `address`, in chunks of `chunk` (0 = one
/// request) on the same connection. Concatenates the chunks into one array so a
/// PLC that rejects large reads still returns the whole block. Each chunk is
/// time-bounded.
async fn read_chunked(
c: &mut ModbusCtx,
function: &str,
address: u16,
quantity: u16,
chunk: u16,
) -> ReadOutcome {
let step = if chunk == 0 { quantity.max(1) } else { chunk };
let bits = matches!(function, "coils" | "discrete");
let mut words: Vec<u16> = Vec::new();
let mut flags: Vec<bool> = Vec::new();
let mut addr = address;
let mut left = quantity;
// timeout(Elapsed) wraps Result(transport error) wraps Result(exception).
macro_rules! do_read {
($call:expr, $sink:expr) => {
match tokio::time::timeout(READ_TIMEOUT, $call).await {
Err(_) => return ReadOutcome::Io("read timeout".to_string()),
Ok(Err(e)) => return ReadOutcome::Io(format!("{e}")),
Ok(Ok(Err(ex))) => return ReadOutcome::Exception(format!("{ex:?}")),
Ok(Ok(Ok(v))) => $sink.extend(v),
}
};
}
while left > 0 {
let n = left.min(step);
match function {
"input" => do_read!(c.read_input_registers(addr, n), words),
"coils" => do_read!(c.read_coils(addr, n), flags),
"discrete" => do_read!(c.read_discrete_inputs(addr, n), flags),
_ => do_read!(c.read_holding_registers(addr, n), words),
}
addr = addr.wrapping_add(n);
left -= n;
}
ReadOutcome::Ok(if bits { json!(flags) } else { json!(words) })
}

#[async_trait]
impl Node for ModbusReadNode {
async fn run(self: Box<Self>, mut ctx: NodeCtx) -> anyhow::Result<()> {
Expand All @@ -83,22 +133,14 @@ impl Node for ModbusReadNode {
}
let c = conn.as_mut().expect("just connected");

// Outer Result = transport error, inner = protocol exception.
macro_rules! decode {
($call:expr) => {
match $call.await {
Ok(Ok(v)) => ReadOutcome::Ok(json!(v)),
Ok(Err(ex)) => ReadOutcome::Exception(format!("{ex:?}")),
Err(e) => ReadOutcome::Io(format!("{e}")),
}
};
}
let outcome = match self.function.as_str() {
"input" => decode!(c.read_input_registers(self.address, self.quantity)),
"coils" => decode!(c.read_coils(self.address, self.quantity)),
"discrete" => decode!(c.read_discrete_inputs(self.address, self.quantity)),
_ => decode!(c.read_holding_registers(self.address, self.quantity)),
};
let outcome = read_chunked(
c,
&self.function,
self.address,
self.quantity,
self.max_read,
)
.await;
match outcome {
ReadOutcome::Ok(v) => ctx.emit(Msg::new(v)).await,
ReadOutcome::Exception(ex) => {
Expand Down