Skip to main content

modbus_read/
decode.rs

1//! Register words into numbers.
2//!
3//! A device answers with 16-bit words. Whether two of them are 100 000 or
4//! 50.0 comes from its manual. [`RegisterKind`] is that choice.
5//! [`Scale`] is the factor the map applies afterwards.
6
7use crate::frame::{ModbusError, RegisterCount};
8
9/// How a device's register map spells one quantity.
10///
11/// Registers are 16-bit words and mean nothing by themselves: the same two
12/// words are 100 000 to one meter and 50.0 to the next. Which it is comes from
13/// the device's manual and is decided here — once, as a calculation over the
14/// words, so no caller reassembles bytes.
15///
16/// Four kinds, because four are what common meter manuals print. A fifth
17/// arrives with the device that needs it, as a variant the compiler makes
18/// every `match` account for.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub enum RegisterKind {
21    /// One register as an unsigned 16-bit integer.
22    U16,
23    /// One register as a signed 16-bit integer.
24    I16,
25    /// Two registers as an unsigned 32-bit integer, most significant word first.
26    U32Be,
27    /// Two registers as an IEEE 754 binary32, most significant word first.
28    F32Be,
29}
30
31/// The factor a register map applies to a decoded word.
32///
33/// A meter that reports tenths of a unit is read with a scale of 0.1. The
34/// constructor is the check: zero would read every register as nothing and no
35/// map means that, and a non-finite factor would put a NaN in a reading. A
36/// *negative* scale is accepted — a device whose export register counts down
37/// from zero is a map, not a mistake.
38#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
39pub struct Scale(f64);
40
41impl RegisterKind {
42    /// How many registers this kind occupies.
43    ///
44    /// Exhaustive by construction, like [`crate::FunctionCode::code`]: a
45    /// fifth kind does not compile until someone writes here how wide it is.
46    #[must_use]
47    pub const fn registers(self) -> u16 {
48        match self {
49            Self::U16 | Self::I16 => 1,
50            Self::U32Be | Self::F32Be => 2,
51        }
52    }
53
54    /// Whether a read of `count` registers is the width this kind needs.
55    ///
56    /// The one spelling of that rule, so every register map asks the same
57    /// question instead of writing the comparison again: a `U32Be` read as one
58    /// register is half a number.
59    #[must_use]
60    pub const fn fits(self, count: RegisterCount) -> bool {
61        count.get() == self.registers()
62    }
63
64    /// The kind's name, for an error an operator reads beside a manual.
65    #[must_use]
66    pub const fn name(self) -> &'static str {
67        match self {
68            Self::U16 => "u16",
69            Self::I16 => "i16",
70            Self::U32Be => "u32be",
71            Self::F32Be => "f32be",
72        }
73    }
74
75    /// The number these words carry, unscaled.
76    ///
77    /// Big-endian throughout, first word most significant, which is the
78    /// protocol's order and the order most device manuals print.
79    ///
80    /// # Errors
81    ///
82    /// Returns [`ModbusError::WordCount`] when the slice is not exactly
83    /// [`Self::registers`] words long. A `U32Be` decoded from one word would
84    /// be half a number.
85    pub fn decode(self, words: &[u16]) -> Result<f64, ModbusError> {
86        match (self, words) {
87            (Self::U16, [word]) => Ok(f64::from(*word)),
88            (Self::I16, [word]) => Ok(f64::from(i16::from_be_bytes(word.to_be_bytes()))),
89            (Self::U32Be, [high, low]) => Ok(f64::from(wide(*high, *low))),
90            // IEEE 754 single precision, the two words in the order the device
91            // sent them. Every bit pattern is an `f32`.
92            (Self::F32Be, [high, low]) => Ok(f64::from(f32::from_bits(wide(*high, *low)))),
93            // Every kind is named again rather than swept into a `_`, so a
94            // fifth one does not compile until someone says how wide it is.
95            // The only case left here is a slice of the wrong length.
96            (Self::U16 | Self::I16 | Self::U32Be | Self::F32Be, _) => Err(ModbusError::WordCount {
97                kind: self.name(),
98                expected: self.registers(),
99                found: words.len(),
100            }),
101        }
102    }
103}
104
105/// Two registers as one 32-bit value, the first register most significant.
106fn wide(high: u16, low: u16) -> u32 {
107    (u32::from(high) << u16::BITS) | u32::from(low)
108}
109
110impl Scale {
111    /// A finite, non-zero factor.
112    ///
113    /// # Errors
114    ///
115    /// Returns [`ModbusError::NonFiniteScale`] for NaN or an infinity and
116    /// [`ModbusError::ZeroScale`] for zero.
117    pub fn new(factor: f64) -> Result<Self, ModbusError> {
118        if !factor.is_finite() {
119            return Err(ModbusError::NonFiniteScale);
120        }
121        if factor == 0.0 {
122            return Err(ModbusError::ZeroScale);
123        }
124        Ok(Self(factor))
125    }
126
127    /// A map that changes nothing: the register is already in the unit
128    /// the caller wants.
129    #[must_use]
130    pub const fn one() -> Self {
131        Self(1.0)
132    }
133
134    /// The factor itself.
135    #[must_use]
136    pub const fn get(self) -> f64 {
137        self.0
138    }
139
140    /// This scale applied to a decoded register.
141    #[must_use]
142    pub fn apply(self, value: f64) -> f64 {
143        value * self.0
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::{RegisterKind, Scale};
150    use crate::frame::{ModbusError, RegisterCount};
151
152    /// Every kind decoded here is compared exactly. These are integers and
153    /// powers of two in `f64`, so an exact comparison is the right one and a
154    /// tolerance would only hide a decoder that drifted.
155    ///
156    /// The bit patterns are synthetic. They are not readings from a device.
157    #[test]
158    fn a_float_register_pair_decodes_to_the_number_its_manual_prints() {
159        let decoded = RegisterKind::F32Be.decode(&[0x4248, 0x0000]);
160
161        assert_eq!(decoded, Ok(50.0));
162    }
163
164    #[test]
165    fn a_signed_register_decodes_below_zero() {
166        let decoded = RegisterKind::I16.decode(&[0xFF38]);
167
168        assert_eq!(decoded, Ok(-200.0));
169    }
170
171    #[test]
172    fn the_same_word_is_two_numbers_depending_on_the_kind() {
173        assert_eq!(RegisterKind::U16.decode(&[0xFFFF]), Ok(65_535.0));
174        assert_eq!(RegisterKind::I16.decode(&[0xFFFF]), Ok(-1.0));
175    }
176
177    #[test]
178    fn a_wide_register_pair_decodes_most_significant_word_first() {
179        let decoded = RegisterKind::U32Be.decode(&[0x0001, 0x86A0]);
180
181        assert_eq!(decoded, Ok(100_000.0));
182    }
183
184    #[test]
185    fn each_kind_knows_how_many_registers_it_occupies() {
186        assert_eq!(RegisterKind::U16.registers(), 1);
187        assert_eq!(RegisterKind::I16.registers(), 1);
188        assert_eq!(RegisterKind::U32Be.registers(), 2);
189        assert_eq!(RegisterKind::F32Be.registers(), 2);
190    }
191
192    #[test]
193    fn each_kind_names_itself() {
194        assert_eq!(RegisterKind::U16.name(), "u16");
195        assert_eq!(RegisterKind::I16.name(), "i16");
196        assert_eq!(RegisterKind::U32Be.name(), "u32be");
197        assert_eq!(RegisterKind::F32Be.name(), "f32be");
198    }
199
200    /// Every register map asks this one question, so it is proved once here
201    /// rather than in each of them.
202    #[test]
203    fn a_count_fits_only_the_kind_that_is_that_wide() {
204        let one = RegisterCount::new(1).expect("one register is a count");
205        let two = RegisterCount::new(2).expect("two registers is a count");
206
207        assert!(RegisterKind::I16.fits(one));
208        assert!(!RegisterKind::I16.fits(two));
209        assert!(RegisterKind::F32Be.fits(two));
210        assert!(!RegisterKind::F32Be.fits(one));
211    }
212
213    /// Half of a 32-bit quantity is not a smaller reading, it is a wrong one.
214    #[test]
215    fn a_wide_kind_handed_one_word_is_refused() {
216        let refused = RegisterKind::U32Be.decode(&[0x0001]);
217
218        assert_eq!(
219            refused,
220            Err(ModbusError::WordCount {
221                kind: "u32be",
222                expected: 2,
223                found: 1,
224            })
225        );
226    }
227
228    #[test]
229    fn a_narrow_kind_handed_two_words_is_refused() {
230        let refused = RegisterKind::U16.decode(&[1, 2]);
231
232        assert_eq!(
233            refused,
234            Err(ModbusError::WordCount {
235                kind: "u16",
236                expected: 1,
237                found: 2,
238            })
239        );
240    }
241
242    #[test]
243    fn a_kind_handed_no_words_is_refused() {
244        let refused = RegisterKind::F32Be.decode(&[]);
245
246        assert_eq!(
247            refused,
248            Err(ModbusError::WordCount {
249                kind: "f32be",
250                expected: 2,
251                found: 0,
252            })
253        );
254    }
255
256    /// Scaled readings are compared with a tolerance rather than for
257    /// equality: 0.1 is not exact in binary, and a test that depended on the
258    /// last bit would be asserting the rounding mode rather than the decoder.
259    fn near(found: f64, expected: f64) -> bool {
260        (found - expected).abs() < 1e-9
261    }
262
263    #[test]
264    fn a_scale_turns_tenths_into_the_unit() {
265        let scale = Scale::new(0.1).expect("a tenth is a scale");
266
267        let scaled = scale.apply(2500.0);
268
269        assert!(near(scaled, 250.0), "2500 tenths is 250, found {scaled}");
270        assert!(near(scale.get(), 0.1));
271    }
272
273    #[test]
274    fn a_scale_of_one_changes_nothing() {
275        assert!(near(Scale::one().apply(412.0), 412.0));
276    }
277
278    /// A device whose export register counts down from zero is a map, not a
279    /// mistake.
280    #[test]
281    fn a_negative_scale_is_a_map_and_is_accepted() {
282        let scale = Scale::new(-1.0).expect("a sign flip is a scale");
283
284        assert!(near(scale.apply(250.0), -250.0));
285    }
286
287    #[test]
288    fn a_scale_of_zero_is_refused() {
289        assert_eq!(Scale::new(0.0), Err(ModbusError::ZeroScale));
290    }
291
292    #[test]
293    fn a_scale_that_is_not_a_number_is_refused() {
294        assert_eq!(Scale::new(f64::NAN), Err(ModbusError::NonFiniteScale));
295        assert_eq!(Scale::new(f64::INFINITY), Err(ModbusError::NonFiniteScale));
296        assert_eq!(
297            Scale::new(f64::NEG_INFINITY),
298            Err(ModbusError::NonFiniteScale)
299        );
300    }
301}