Skip to content

Conversation

@Abestanis
Copy link
Contributor

@Abestanis Abestanis commented Sep 19, 2025

Sometimes a multi byte value is stored over a span of registers, e.g a 64bit value could be stored over 4 consecutive registers. When sending a request to write to such a register, one has to use WriteMultipleRegisters(Address, Data<'r>), which requires a data.

If the rust code is using the value as a 64 bit integer, it is quite cumbersome to convert it to &[u16] that is required by Data::from_words, the only way to construct a Data.

This PR proposes some TryFrom and From implementations to help with these situations. You can now write

Data::from(&0x12345678_u64.to_be_bytes())

Since From can only be implemented for even number of bytes, a helper macro is used to declare implementations up to [u8; 32] (similar how Default is implemented for arrays in the standard library).

One question: Why is constructing a zero length Data forbidden? I don't have a usecase, but should it be allowed?

@flosse
Copy link
Member

flosse commented Sep 20, 2025

I think that such auxiliary functions have nothing directly to do with Modbus and should rather be kept separate.

@Abestanis
Copy link
Contributor Author

Abestanis commented Sep 20, 2025

I think that such auxiliary functions have nothing directly to do with Modbus and should rather be kept separate.

What do you mean by that? modbus-core enforces the use of Data in WriteMultipleRegisters(Address, Data<'r>), and the data member of Data is crate private. There is no way of adding this functionality from outside of the crate, except for jumping trough a bunch of hoops and u16 conversions with Data::from_words.

@flosse
Copy link
Member

flosse commented Sep 20, 2025

Sorry, that was my bad, I had forgotten that the fields of Data are not public.
So yes, your suggestion could make sense 🤔
Give me another chance to think about it before I merge this PR.

@flosse
Copy link
Member

flosse commented Sep 21, 2025

Okay, so I don't have a better suggestion at the moment, and I don't see any other difficulties for now.

@flosse flosse merged commit 2d86d92 into slowtec:master Sep 21, 2025
4 checks passed
@Abestanis Abestanis deleted the feature/data_from branch September 21, 2025 13:15
AsgerWenneb pushed a commit to AsgerWenneb/modbus-core that referenced this pull request Dec 16, 2025
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 this pull request may close these issues.

2 participants