mbus-core 0.14.0

Protocol types, errors, function codes, and transport traits for the modbus-rs workspace
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Modbus Device Identification Models
//!
//! This module provides the data structures and types required for Function Code 43 (0x2B),
//! specifically the Encapsulated Interface Transport for Read Device Identification (MEI Type 0x0E).
//!
//! It includes:
//! - `DeviceIdentificationResponse`: The top-level response structure.
//! - `DeviceIdObject`: Individual identification objects (e.g., Vendor Name, Product Code).
//! - `ObjectId`: Strongly typed identifiers for basic, regular, and extended objects.
//! - `DeviceIdObjectIterator`: A memory-efficient iterator for parsing objects from raw buffers.
//!
//! # Example
//! ```
//! # use mbus_core::models::diagnostic::{DeviceIdentificationResponse, ReadDeviceIdCode, ConformityLevel, ObjectId};
//! # let resp = DeviceIdentificationResponse {
//! #     read_device_id_code: ReadDeviceIdCode::Basic,
//! #     conformity_level: ConformityLevel::BasicStreamAndIndividual,
//! #     more_follows: false,
//! #     next_object_id: ObjectId::from(0x00),
//! #     objects_data: [0; 252],
//! #     number_of_objects: 0,
//! # };
//! // Assuming a response has been received and parsed into `resp`
//! for obj_result in resp.objects() {
//!     let obj = obj_result.expect("Valid object");
//!     println!("Object ID: {}, Value: {:?}", obj.object_id, obj.value);
//! }
//! ```

use crate::{data_unit::common::MAX_PDU_DATA_LEN, errors::MbusError};
#[cfg(all(feature = "defmt-format", target_os = "none"))]
use defmt;
use heapless::Vec;

/// Represents an object ID.
#[derive(Debug, Clone, PartialEq)]
pub struct DeviceIdObject {
    /// The ID of the object.
    pub object_id: ObjectId,
    /// The value of the object.
    pub value: Vec<u8, MAX_PDU_DATA_LEN>,
}

/// An iterator over the device identification objects.
///
/// This iterator performs lazy parsing of the `objects_data` buffer, ensuring
/// that memory is only allocated for one object at a time during iteration.
pub struct DeviceIdObjectIterator<'a> {
    /// Reference to the raw byte buffer containing the objects.
    pub(crate) data: &'a [u8],
    /// Current byte offset within the data buffer.
    offset: usize,
    /// Current object count.
    count: u8,
    /// Total number of objects.
    total: u8,
}

impl<'a> Iterator for DeviceIdObjectIterator<'a> {
    type Item = Result<DeviceIdObject, MbusError>;

    /// Advances the iterator and returns the next device ID object.
    fn next(&mut self) -> Option<Self::Item> {
        if self.count >= self.total {
            return None;
        }

        // Parsing logic is handled internally in the iterator step
        // We reuse the parsing logic from the original implementation but applied incrementally
        self.parse_next()
    }
}

impl<'a> DeviceIdObjectIterator<'a> {
    /// Parses the next `DeviceIdObject` from the raw objects data buffer.
    ///
    /// Each object in the stream consists of:
    /// - Object Id (1 byte)
    /// - Object Length (1 byte)
    /// - Object Value (N bytes)
    fn parse_next(&mut self) -> Option<Result<DeviceIdObject, MbusError>> {
        // Check if there is enough data for the 2-byte header (Id + Length)
        if self.offset + 2 > self.data.len() {
            return Some(Err(MbusError::InvalidPduLength));
        }
        let obj_id = ObjectId::from(self.data[self.offset]);
        let obj_len = self.data[self.offset + 1] as usize;
        self.offset += 2; // Move past the header

        // Ensure the remaining data contains the full object value
        if self.offset + obj_len > self.data.len() {
            return Some(Err(MbusError::InvalidPduLength));
        }

        let mut value = Vec::new();
        // Copy the object value into the heapless::Vec
        if value
            .extend_from_slice(&self.data[self.offset..self.offset + obj_len])
            .is_err()
        {
            return Some(Err(MbusError::BufferTooSmall));
        }

        self.offset += obj_len;
        self.count += 1;

        Some(Ok(DeviceIdObject {
            object_id: obj_id,
            value,
        }))
    }
}

/// Represents a response to a Read Device Identification request (FC 43 / MEI 0E).
#[derive(Debug, Clone, PartialEq)]
pub struct DeviceIdentificationResponse {
    /// The code defining the type of access.
    pub read_device_id_code: ReadDeviceIdCode,
    /// The conformity level of the response.
    pub conformity_level: ConformityLevel,
    /// Indicates if there are more objects to follow.
    pub more_follows: bool,
    /// The ID of the next object in the response.
    pub next_object_id: ObjectId,
    /// The raw data of the objects.
    pub objects_data: [u8; MAX_PDU_DATA_LEN],
    /// The number of objects returned in the response.
    pub number_of_objects: u8,
}

impl DeviceIdentificationResponse {
    /// Returns an iterator over the device identification objects.
    pub fn objects(&self) -> DeviceIdObjectIterator<'_> {
        DeviceIdObjectIterator {
            data: &self.objects_data,
            offset: 0,
            count: 0,
            total: self.number_of_objects,
        }
    }
}

/// Object IDs for Basic Device Identification.
///
/// These objects are mandatory for the Basic conformity level.
/// Access type: Stream (ReadDeviceIdCode 0x01, 0x02, 0x03) or Individual (ReadDeviceIdCode 0x04).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum BasicObjectId {
    /// Vendor Name (Mandatory). Object ID 0x00.
    VendorName = 0x00,
    /// Product Code (Mandatory). Object ID 0x01.
    ProductCode = 0x01,
    /// Major Minor Revision (Mandatory). Object ID 0x02.
    MajorMinorRevision = 0x02,
}

impl TryFrom<u8> for BasicObjectId {
    type Error = MbusError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0x00 => Ok(BasicObjectId::VendorName),
            0x01 => Ok(BasicObjectId::ProductCode),
            0x02 => Ok(BasicObjectId::MajorMinorRevision),
            _ => Err(MbusError::InvalidAddress),
        }
    }
}

#[cfg(all(feature = "defmt-format", target_os = "none"))]
impl defmt::Format for BasicObjectId {
    fn format(&self, f: defmt::Formatter) {
        match self {
            BasicObjectId::VendorName => defmt::write!(f, "VendorName"),
            BasicObjectId::ProductCode => defmt::write!(f, "ProductCode"),
            BasicObjectId::MajorMinorRevision => defmt::write!(f, "MajorMinorRevision"),
        }
    }
}

#[cfg(feature = "error-trait")]
impl core::fmt::Display for BasicObjectId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            BasicObjectId::VendorName => write!(f, "VendorName"),
            BasicObjectId::ProductCode => write!(f, "ProductCode"),
            BasicObjectId::MajorMinorRevision => write!(f, "MajorMinorRevision"),
        }
    }
}

/// Object IDs for Regular Device Identification.
///
/// These objects are optional but defined in the standard.
/// Access type: Stream (ReadDeviceIdCode 0x02, 0x03) or Individual (ReadDeviceIdCode 0x04).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum RegularObjectId {
    /// Vendor URL (Optional). Object ID 0x03.
    VendorUrl = 0x03,
    /// Product Name (Optional). Object ID 0x04.
    ProductName = 0x04,
    /// Model Name (Optional). Object ID 0x05.
    ModelName = 0x05,
    /// User Application Name (Optional). Object ID 0x06.
    UserApplicationName = 0x06,
}

impl TryFrom<u8> for RegularObjectId {
    type Error = MbusError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0x03 => Ok(RegularObjectId::VendorUrl),
            0x04 => Ok(RegularObjectId::ProductName),
            0x05 => Ok(RegularObjectId::ModelName),
            0x06 => Ok(RegularObjectId::UserApplicationName),
            _ => Err(MbusError::InvalidAddress),
        }
    }
}

#[cfg(all(feature = "defmt-format", target_os = "none"))]
impl defmt::Format for RegularObjectId {
    fn format(&self, f: defmt::Formatter) {
        match self {
            RegularObjectId::VendorUrl => defmt::write!(f, "VendorUrl"),
            RegularObjectId::ProductName => defmt::write!(f, "ProductName"),
            RegularObjectId::ModelName => defmt::write!(f, "ModelName"),
            RegularObjectId::UserApplicationName => defmt::write!(f, "UserApplicationName"),
        }
    }
}

#[cfg(feature = "error-trait")]
impl core::fmt::Display for RegularObjectId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            RegularObjectId::VendorUrl => write!(f, "VendorUrl"),
            RegularObjectId::ProductName => write!(f, "ProductName"),
            RegularObjectId::ModelName => write!(f, "ModelName"),
            RegularObjectId::UserApplicationName => write!(f, "UserApplicationName"),
        }
    }
}

/// Extended Object IDs.
///
/// Range 0x80 - 0xFF. These are private/vendor-specific.
/// Access type: Stream (ReadDeviceIdCode 0x03) or Individual (ReadDeviceIdCode 0x04).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExtendedObjectId(u8);

impl ExtendedObjectId {
    /// Creates a new `ExtendedObjectId`.
    ///
    /// Returns `None` if the id is not in the range 0x80..=0xFF.
    pub fn new(id: u8) -> Option<Self> {
        if (0x80..=0xFF).contains(&id) {
            Some(Self(id))
        } else {
            None
        }
    }

    /// Returns the raw object ID.
    pub fn value(&self) -> u8 {
        self.0
    }
}

/// Read Device ID Code (Function Code 43 / 14).
///
/// Defines the type of access requested.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum ReadDeviceIdCode {
    /// Sentinel default used before parsing a concrete code.
    /// This value should not appear in a valid decoded request.
    #[default]
    Err,
    /// Request to get the basic device identification (stream access).
    Basic = 0x01,
    /// Request to get the regular device identification (stream access).
    Regular = 0x02,
    /// Request to get the extended device identification (stream access).
    Extended = 0x03,
    /// Request to get one specific identification object (individual access).
    Specific = 0x04,
}

impl TryFrom<u8> for ReadDeviceIdCode {
    type Error = MbusError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0x01 => Ok(ReadDeviceIdCode::Basic),
            0x02 => Ok(ReadDeviceIdCode::Regular),
            0x03 => Ok(ReadDeviceIdCode::Extended),
            0x04 => Ok(ReadDeviceIdCode::Specific),
            _ => Err(MbusError::InvalidDeviceIdCode),
        }
    }
}

/// Conformity Level returned in the response.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ConformityLevel {
    /// Basic identification (stream access only).
    BasicStreamOnly = 0x01,
    /// Regular identification (stream access only).
    RegularStreamOnly = 0x02,
    /// Extended identification (stream access only).
    ExtendedStreamOnly = 0x03,
    /// Basic identification (stream access and individual access).
    BasicStreamAndIndividual = 0x81,
    /// Regular identification (stream access and individual access).
    RegularStreamAndIndividual = 0x82,
    /// Extended identification (stream access and individual access).
    ExtendedStreamAndIndividual = 0x83,
}

impl TryFrom<u8> for ConformityLevel {
    type Error = MbusError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0x01 => Ok(ConformityLevel::BasicStreamOnly),
            0x02 => Ok(ConformityLevel::RegularStreamOnly),
            0x03 => Ok(ConformityLevel::ExtendedStreamOnly),
            0x81 => Ok(ConformityLevel::BasicStreamAndIndividual),
            0x82 => Ok(ConformityLevel::RegularStreamAndIndividual),
            0x83 => Ok(ConformityLevel::ExtendedStreamAndIndividual),
            _ => Err(MbusError::ParseError),
        }
    }
}

/// Represents any valid Modbus Device Identification Object ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ObjectId {
    /// Sentinel default used before parsing a concrete object identifier.
    /// This value should not appear in a valid decoded response.
    #[default]
    Err,
    /// Basic Device Identification Object IDs (0x00 - 0x02).
    Basic(BasicObjectId),
    /// Regular Device Identification Object IDs (0x03 - 0x06).
    Regular(RegularObjectId),
    /// Extended Device Identification Object IDs (0x80 - 0xFF).
    Extended(ExtendedObjectId),
    /// Reserved range (0x07 - 0x7F).
    Reserved(u8),
}

impl From<u8> for ObjectId {
    fn from(id: u8) -> Self {
        if let Ok(basic) = BasicObjectId::try_from(id) {
            ObjectId::Basic(basic)
        } else if let Ok(regular) = RegularObjectId::try_from(id) {
            ObjectId::Regular(regular)
        } else if let Some(extended) = ExtendedObjectId::new(id) {
            ObjectId::Extended(extended)
        } else {
            ObjectId::Reserved(id)
        }
    }
}

#[cfg(all(feature = "defmt-format", target_os = "none"))]
impl defmt::Format for ObjectId {
    fn format(&self, f: defmt::Formatter) {
        match self {
            ObjectId::Basic(id) => defmt::write!(f, "Basic({})", id),
            ObjectId::Regular(id) => defmt::write!(f, "Regular({})", id),
            ObjectId::Extended(id) => defmt::write!(f, "Extended({:#04X})", id.value()),
            ObjectId::Reserved(id) => defmt::write!(f, "Reserved({:#04X})", id),
            ObjectId::Err => defmt::write!(f, "Err (sentinel default)"),
        }
    }
}

#[cfg(feature = "error-trait")]
impl core::fmt::Display for ObjectId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            ObjectId::Basic(id) => write!(f, "Basic({})", id),
            ObjectId::Regular(id) => write!(f, "Regular({})", id),
            ObjectId::Extended(id) => write!(f, "Extended({:#04X})", id.value()),
            ObjectId::Reserved(id) => write!(f, "Reserved({:#04X})", id),
            ObjectId::Err => write!(f, "Err (sentinel default)"),
        }
    }
}

impl From<ObjectId> for u8 {
    fn from(oid: ObjectId) -> u8 {
        match oid {
            ObjectId::Basic(id) => id as u8,
            ObjectId::Regular(id) => id as u8,
            ObjectId::Extended(id) => id.value(),
            ObjectId::Reserved(id) => id,
            ObjectId::Err => 0, // Sentinel default path.
        }
    }
}