Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ModbusRequest::parse_slice() applied offset is wrong for write functions #26

Closed
Achtuur opened this issue Feb 29, 2024 · 1 comment · Fixed by #27
Closed

ModbusRequest::parse_slice() applied offset is wrong for write functions #26

Achtuur opened this issue Feb 29, 2024 · 1 comment · Fixed by #27

Comments

@Achtuur
Copy link
Contributor

Achtuur commented Feb 29, 2024

Problem

When calling client::MobusRequest::parse_slice() using a buffer of data from a write request (ie modbus functions 0x6 or 0x10), the returned slice skips the high byte of the read register. In parse_slice(), an offset of 3 is applied to the start of the frame, which assumes there is always 3 bytes before the actual data bytes. This is true for reads, as there is a byte that indicates the number of data bytes to follow, but write functions are missing this byte. While this is not per se a huge issue, since you usually don't care about the response to a write function, it's still incorrectly parsed.

Example

use rmodbus::client::ModbusRequest;
let mut request = ModbusRequest::new(11, ModbusProto::Rtu);
let mut buf = Vec::new();

// buf now contains [0xB, 0x6, 0x0, 0x1, 0x0, 0x3, 0x98, 0xA1]
request.generate_set_holding(1, 2, &mut buf)?;

let expected_response = buf; // write functions echo the request
// parsed should have the written to registers and written value
// which is [0x0, 0x1, 0x0, 03] in this case
let parsed = request.parse_slice(&expected_response)

// this fails, as parsed is equal to [0x1, 0x0, 0x3] (skips the first byte)
assert_eq!(parsed, [0x0, 0x1, 0x0, 0x3]);

Proposed solution

Instead of always adding 3 to the start of the frame, a check should be done on the function code. If the function code corresponds to a write function, the offset should be 2 instead.

@Achtuur
Copy link
Contributor Author

Achtuur commented Feb 29, 2024

created pr at #27

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant