Skip to main content

spodes_rs/types/
attrs.rs

1//! Typed attributes for COSEM interface classes (IEC 62056-6-2).
2//!
3//! Each IC has specific attribute types defined in the standard. This module
4//! provides strongly-typed structs for these attributes, replacing the generic
5//! `CosemDataType` where possible while maintaining BER compatibility.
6
7use crate::obis::ObisCode;
8use crate::types::CosemDataType;
9use serde::{Deserialize, Serialize};
10
11/// Logical name (OBIS code) — attribute 1 of all ICs.
12pub type LogicalName = ObisCode;
13
14/// CHOICE type — any COSEM data type (for value, status, etc.).
15/// This maintains backward compatibility with the generic CosemDataType.
16pub type Choice = CosemDataType;
17
18/// Date-time value (12 octets) per IEC 62056-6-2, 4.1.6.1.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct DateTime(pub [u8; 12]);
21
22impl DateTime {
23    /// Creates a new DateTime from raw bytes.
24    pub fn new(bytes: [u8; 12]) -> Self {
25        Self(bytes)
26    }
27
28    /// Returns the raw bytes.
29    pub fn as_bytes(&self) -> &[u8; 12] {
30        &self.0
31    }
32
33    /// Creates a DateTime from year, month, day, hour, minute, second.
34    pub fn from_ymdhms(year: u16, month: u8, day: u8, hour: u8, min: u8, sec: u8) -> Self {
35        let mut buf = [0u8; 12];
36        buf[0..2].copy_from_slice(&year.to_be_bytes());
37        buf[2] = month;
38        buf[3] = day;
39        buf[4] = 0xFF; // day of week (any)
40        buf[5] = hour;
41        buf[6] = min;
42        buf[7] = sec;
43        buf[8] = 0; // hundredths
44        buf[9..12].copy_from_slice(&[0, 0, 0]); // deviation, clocks, reserved
45        Self(buf)
46    }
47}
48
49impl From<DateTime> for CosemDataType {
50    fn from(dt: DateTime) -> Self {
51        // COSEM date-time on the wire is octet-string SIZE(12), not A-XDR tag 25.
52        CosemDataType::OctetString(dt.0.to_vec())
53    }
54}
55
56impl TryFrom<&CosemDataType> for DateTime {
57    type Error = String;
58
59    fn try_from(value: &CosemDataType) -> Result<Self, String> {
60        match value {
61            CosemDataType::DateTime(bytes) | CosemDataType::OctetString(bytes) if bytes.len() == 12 => {
62                let mut buf = [0u8; 12];
63                buf.copy_from_slice(bytes);
64                Ok(DateTime(buf))
65            }
66            _ => Err("expected 12-byte date-time or octet-string".to_string()),
67        }
68    }
69}
70
71/// Bit-string value (held as raw octets).
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct BitString(pub Vec<u8>);
74
75impl BitString {
76    /// Creates a new BitString from raw bytes.
77    pub fn new(bytes: Vec<u8>) -> Self {
78        Self(bytes)
79    }
80
81    /// Returns the raw bytes.
82    pub fn as_bytes(&self) -> &[u8] {
83        &self.0
84    }
85
86    /// Checks if bit `n` is set.
87    pub fn get(&self, n: usize) -> bool {
88        let byte = n / 8;
89        let bit = n % 8;
90        byte < self.0.len() && (self.0[byte] & (1 << (7 - bit))) != 0
91    }
92}
93
94impl From<BitString> for CosemDataType {
95    fn from(bs: BitString) -> Self {
96        CosemDataType::BitString(bs.0)
97    }
98}
99
100/// ScalerUnit: structure { scaler: integer, unit: enum }
101/// per IEC 62056-6-2, Table 41.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103pub struct ScalerUnit {
104    /// The scaler (power of 10): value = raw × 10^scaler.
105    pub scaler: i8,
106    /// The unit code per IEC 62056-6-2, Table 42.
107    pub unit: u8,
108}
109
110impl ScalerUnit {
111    /// Creates a new ScalerUnit.
112    pub fn new(scaler: i8, unit: u8) -> Self {
113        Self { scaler, unit }
114    }
115
116    /// Converts a raw value to the scaled value.
117    #[allow(clippy::cast_precision_loss)] // COSEM register readings stay far below 2^53
118    pub fn apply(&self, raw: i64) -> f64 {
119        raw as f64 * 10f64.powi(i32::from(self.scaler))
120    }
121}
122
123impl From<ScalerUnit> for CosemDataType {
124    fn from(su: ScalerUnit) -> Self {
125        CosemDataType::Structure(vec![CosemDataType::Integer(su.scaler), CosemDataType::Enum(su.unit)])
126    }
127}
128
129impl TryFrom<&CosemDataType> for ScalerUnit {
130    type Error = String;
131
132    fn try_from(value: &CosemDataType) -> Result<Self, String> {
133        match value {
134            CosemDataType::Structure(fields) if fields.len() >= 2 => {
135                let scaler = match &fields[0] {
136                    CosemDataType::Integer(v) => *v,
137                    CosemDataType::Long(v) => i8::try_from(*v).map_err(|_| "scaler must be integer".to_string())?,
138                    _ => return Err("scaler must be integer".to_string()),
139                };
140                let unit = match &fields[1] {
141                    CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
142                    _ => return Err("unit must be enum".to_string()),
143                };
144                Ok(ScalerUnit { scaler, unit })
145            }
146            _ => Err("expected structure {scaler, unit}".to_string()),
147        }
148    }
149}
150
151/// Capture object definition: structure { class_id, logical_name, attribute_index, data_index }
152/// per IEC 62056-6-2, 4.3.6.2.
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154pub struct CaptureObjectDefinition {
155    /// The class id of the captured object.
156    pub class_id: u16,
157    /// The logical name (OBIS code) of the captured object.
158    pub logical_name: ObisCode,
159    /// The attribute index to capture.
160    pub attribute_index: u8,
161    /// The data index (0 for the whole attribute).
162    pub data_index: u8,
163}
164
165impl CaptureObjectDefinition {
166    /// Creates a new CaptureObjectDefinition.
167    pub fn new(class_id: u16, logical_name: ObisCode, attribute_index: u8, data_index: u8) -> Self {
168        Self { class_id, logical_name, attribute_index, data_index }
169    }
170}
171
172impl From<CaptureObjectDefinition> for CosemDataType {
173    fn from(cod: CaptureObjectDefinition) -> Self {
174        CosemDataType::Structure(vec![
175            CosemDataType::LongUnsigned(cod.class_id),
176            CosemDataType::OctetString(cod.logical_name.to_bytes()),
177            CosemDataType::Unsigned(cod.attribute_index),
178            CosemDataType::Unsigned(cod.data_index),
179        ])
180    }
181}
182
183impl TryFrom<&CosemDataType> for CaptureObjectDefinition {
184    type Error = String;
185
186    fn try_from(value: &CosemDataType) -> Result<Self, String> {
187        match value {
188            CosemDataType::Structure(fields) if fields.len() >= 4 => {
189                let class_id = match &fields[0] {
190                    CosemDataType::LongUnsigned(v) => *v,
191                    _ => return Err("class_id must be long-unsigned".to_string()),
192                };
193                let logical_name = match &fields[1] {
194                    CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
195                        ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
196                    }
197                    _ => return Err("logical_name must be 6-byte octet-string".to_string()),
198                };
199                let attribute_index = match &fields[2] {
200                    CosemDataType::Unsigned(v) => *v,
201                    CosemDataType::Integer(v) => {
202                        u8::try_from(*v).map_err(|_| "attribute_index must be unsigned".to_string())?
203                    }
204                    _ => return Err("attribute_index must be unsigned".to_string()),
205                };
206                let data_index = match &fields[3] {
207                    CosemDataType::Unsigned(v) => *v,
208                    CosemDataType::LongUnsigned(v) => {
209                        u8::try_from(*v).map_err(|_| "data_index must be unsigned".to_string())?
210                    }
211                    _ => return Err("data_index must be unsigned".to_string()),
212                };
213                Ok(CaptureObjectDefinition { class_id, logical_name, attribute_index, data_index })
214            }
215            _ => Err("expected structure {class_id, logical_name, attribute_index, data_index}".to_string()),
216        }
217    }
218}
219
220/// Sort method for Profile generic (IEC 62056-6-2, 4.3.6.2).
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
222pub enum SortMethod {
223    /// FIFO (first in, first out).
224    Fifo = 1,
225    /// LIFO (last in, first out).
226    Lifo = 2,
227    /// Largest value first.
228    Largest = 3,
229    /// Smallest value first.
230    Smallest = 4,
231    /// Nearest to zero.
232    NearestToZero = 5,
233    /// Farthest from zero.
234    FarthestFromZero = 6,
235}
236
237impl SortMethod {
238    /// Parses a sort method from its numeric value.
239    pub fn from_u8(v: u8) -> Option<Self> {
240        match v {
241            1 => Some(Self::Fifo),
242            2 => Some(Self::Lifo),
243            3 => Some(Self::Largest),
244            4 => Some(Self::Smallest),
245            5 => Some(Self::NearestToZero),
246            6 => Some(Self::FarthestFromZero),
247            _ => None,
248        }
249    }
250}
251
252/// Association status (IEC 62056-6-2, 4.4.3.2).
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
254pub enum AssociationStatus {
255    /// Non-associated.
256    NonAssociated = 0,
257    /// Association pending.
258    AssociationPending = 1,
259    /// Associated.
260    Associated = 2,
261}
262
263// ============================================================================
264// Typed attribute structs for each IC (IEC 62056-6-2)
265// ============================================================================
266
267/// Data class (class_id = 1) attributes.
268/// - attr 1: logical_name (octet-string)
269/// - attr 2: value (CHOICE)
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct DataAttrs {
272    /// OBIS logical name (attribute 1).
273    pub logical_name: LogicalName,
274    /// Attribute value (CHOICE type, attribute 2).
275    pub value: Choice,
276}
277
278/// Register class (class_id = 3) attributes.
279/// - attr 1: logical_name (octet-string)
280/// - attr 2: value (CHOICE)
281/// - attr 3: scaler_unit (scal_unit_type)
282#[derive(Debug, Clone, Serialize, Deserialize)]
283pub struct RegisterAttrs {
284    /// OBIS logical name (attribute 1).
285    pub logical_name: LogicalName,
286    /// Attribute value (CHOICE type, attribute 2).
287    pub value: Choice,
288    /// Scaler and unit (attribute 3).
289    pub scaler_unit: ScalerUnit,
290}
291
292/// Extended register class (class_id = 4) attributes.
293/// - attr 1: logical_name (octet-string)
294/// - attr 2: value (CHOICE)
295/// - attr 3: scaler_unit (scal_unit_type)
296/// - attr 4: status (CHOICE)
297/// - attr 5: capture_time (octet-string)
298#[derive(Debug, Clone, Serialize, Deserialize)]
299pub struct ExtendedRegisterAttrs {
300    /// OBIS logical name (attribute 1).
301    pub logical_name: LogicalName,
302    /// Attribute value (CHOICE type, attribute 2).
303    pub value: Choice,
304    /// Scaler and unit (attribute 3).
305    pub scaler_unit: ScalerUnit,
306    /// Status value (CHOICE type, attribute 4).
307    pub status: Choice,
308    /// Capture time (attribute 5).
309    pub capture_time: Choice,
310}
311
312/// Demand register class (class_id = 5) attributes.
313/// - attr 1: logical_name (octet-string)
314/// - attr 2: current_average_value (CHOICE)
315/// - attr 3: last_average_value (CHOICE)
316/// - attr 4: scaler_unit (scal_unit_type)
317/// - attr 5: status (CHOICE)
318/// - attr 6: capture_time (octet-string)
319/// - attr 7: start_time_current (octet-string)
320/// - attr 8: period (double-long-unsigned)
321/// - attr 9: number_of_periods (long-unsigned)
322#[derive(Debug, Clone, Serialize, Deserialize)]
323pub struct DemandRegisterAttrs {
324    /// OBIS logical name (attribute 1).
325    pub logical_name: LogicalName,
326    /// Current average value (CHOICE type, attribute 2).
327    pub current_average_value: Choice,
328    /// Last average value (CHOICE type, attribute 3).
329    pub last_average_value: Choice,
330    /// Scaler and unit (attribute 4).
331    pub scaler_unit: ScalerUnit,
332    /// Status value (CHOICE type, attribute 5).
333    pub status: Choice,
334    /// Capture time (attribute 6).
335    pub capture_time: Choice,
336    /// Start time for current period (attribute 7).
337    pub start_time_current: Choice,
338    /// Period in seconds (attribute 8).
339    pub period: u32,
340    /// Number of periods (attribute 9).
341    pub number_of_periods: u16,
342}
343
344/// Profile generic class (class_id = 7) attributes.
345/// - attr 1: logical_name (octet-string)
346/// - attr 2: buffer (array)
347/// - attr 3: capture_objects (array)
348/// - attr 4: capture_period (double-long-unsigned)
349/// - attr 5: sort_method (enum)
350/// - attr 6: sort_object (capture_object_definition)
351/// - attr 7: entries_in_use (double-long-unsigned)
352/// - attr 8: profile_entries (double-long-unsigned)
353#[derive(Debug, Clone, Serialize, Deserialize)]
354pub struct ProfileGenericAttrs {
355    /// OBIS logical name (attribute 1).
356    pub logical_name: LogicalName,
357    /// Buffer of captured data records (attribute 2).
358    pub buffer: Vec<Choice>,
359    /// Capture objects definition (attribute 3).
360    pub capture_objects: Vec<CaptureObjectDefinition>,
361    /// Capture period in seconds (attribute 4).
362    pub capture_period: u32,
363    /// Sort method (attribute 5).
364    pub sort_method: SortMethod,
365    /// Sort object (attribute 6).
366    pub sort_object: Option<CaptureObjectDefinition>,
367    /// Number of entries currently in buffer (attribute 7).
368    pub entries_in_use: u32,
369    /// Maximum number of profile entries (attribute 8).
370    pub profile_entries: u32,
371}
372
373/// Clock class (class_id = 8) attributes.
374/// - attr 1: logical_name (octet-string)
375/// - attr 2: time (date-time)
376/// - attr 3: time_zone (long)
377/// - attr 4: status (bit-string)
378/// - attr 5: daylight_savings_begin (date-time)
379/// - attr 6: daylight_savings_end (date-time)
380/// - attr 7: daylight_savings_deviation (integer)
381/// - attr 8: daylight_savings_enabled (boolean)
382/// - attr 9: clock_base (enum)
383#[derive(Debug, Clone, Serialize, Deserialize)]
384pub struct ClockAttrs {
385    /// OBIS logical name (attribute 1).
386    pub logical_name: LogicalName,
387    /// Current date and time (attribute 2).
388    pub time: DateTime,
389    /// Time zone deviation from UTC in minutes (attribute 3).
390    pub time_zone: i16,
391    /// Clock status bit-string (attribute 4).
392    pub status: u8,
393    /// Daylight savings begin time (attribute 5).
394    pub daylight_savings_begin: DateTime,
395    /// Daylight savings end time (attribute 6).
396    pub daylight_savings_end: DateTime,
397    /// Daylight savings deviation in minutes (attribute 7).
398    pub daylight_savings_deviation: i8,
399    /// Daylight savings enabled flag (attribute 8).
400    pub daylight_savings_enabled: bool,
401    /// Clock base source (attribute 9).
402    pub clock_base: u8,
403}
404
405/// Script table class (class_id = 9) attributes.
406/// - attr 1: logical_name (octet-string)
407/// - attr 2: scripts (array of {script_id, actions})
408#[derive(Debug, Clone, Serialize, Deserialize)]
409pub struct ScriptTableAttrs {
410    /// OBIS logical name (attribute 1).
411    pub logical_name: LogicalName,
412    /// Array of script entries (attribute 2).
413    pub scripts: Vec<Choice>,
414}
415
416/// Schedule class (class_id = 10) attributes.
417/// - attr 1: logical_name (octet-string)
418/// - attr 2: entries (array of {switch_time, day_profile_table, week_profile_table, month_profile_table})
419#[derive(Debug, Clone, Serialize, Deserialize)]
420pub struct ScheduleAttrs {
421    /// OBIS logical name (attribute 1).
422    pub logical_name: LogicalName,
423    /// Array of schedule entries (attribute 2).
424    pub entries: Vec<Choice>,
425}
426
427/// Special days table class (class_id = 11) attributes.
428/// - attr 1: logical_name (octet-string)
429/// - attr 2: entries (array of {date, day_id})
430#[derive(Debug, Clone, Serialize, Deserialize)]
431pub struct SpecialDaysTableAttrs {
432    /// OBIS logical name (attribute 1).
433    pub logical_name: LogicalName,
434    /// Array of special day entries (attribute 2).
435    pub entries: Vec<Choice>,
436}
437
438/// Association LN class (class_id = 15) attributes.
439/// - attr 1: logical_name (octet-string)
440/// - attr 2: object_list (object_list_type)
441/// - attr 3: associated_partners_id (associated_partners_type)
442/// - attr 4: application_context_name (context_name_type)
443/// - attr 5: xDLMS_context_info (xDLMS_context_type)
444/// - attr 6: authentication_mechanism_name (mechanism_name_type)
445/// - attr 7: secret (octet-string)
446/// - attr 8: association_status (enum)
447/// - attr 9: security_setup_reference (octet-string) [v1+]
448/// - attr 10: user_list (array) \[v2\]
449/// - attr 11: current_user (structure) \[v2\]
450#[derive(Debug, Clone, Serialize, Deserialize)]
451pub struct AssociationLnAttrs {
452    /// OBIS logical name (attribute 1).
453    pub logical_name: LogicalName,
454    /// Object list (attribute 2).
455    pub object_list: Vec<Choice>,
456    /// Associated partners identifier (attribute 3).
457    pub associated_partners_id: Choice,
458    /// Application context name (attribute 4).
459    pub application_context_name: Choice,
460    /// xDLMS context info (attribute 5).
461    pub xdlms_context_info: Choice,
462    /// Authentication mechanism name (attribute 6).
463    pub authentication_mechanism_name: u8,
464    /// Secret / password (attribute 7).
465    pub secret: Vec<u8>,
466    /// Association status (attribute 8).
467    pub association_status: AssociationStatus,
468    /// Security setup reference (attribute 9, v1+).
469    pub security_setup_reference: Option<ObisCode>,
470    /// User list (attribute 10, v2).
471    pub user_list: Vec<Choice>,
472    /// Current user (attribute 11, v2).
473    pub current_user: Option<Choice>,
474}
475
476/// SAP assignment class (class_id = 17) attributes.
477/// - attr 1: logical_name (octet-string)
478/// - attr 2: sap_assignment_list (array of {sap_name, sap_address})
479#[derive(Debug, Clone, Serialize, Deserialize)]
480pub struct SapAssignmentAttrs {
481    /// OBIS logical name (attribute 1).
482    pub logical_name: LogicalName,
483    /// SAP assignment list (attribute 2).
484    pub sap_assignment_list: Vec<Choice>,
485}
486
487/// Activity calendar class (class_id = 20) attributes.
488/// - attr 1: logical_name (octet-string)
489/// - attr 2: calendar_name (octet-string)
490/// - attr 3: week_profile_table (array)
491/// - attr 4: day_profile_table (array)
492/// - attr 5: month_profile_table (array)
493/// - attr 6: active_calendar (octet-string)
494#[derive(Debug, Clone, Serialize, Deserialize)]
495pub struct ActivityCalendarAttrs {
496    /// OBIS logical name (attribute 1).
497    pub logical_name: LogicalName,
498    /// Calendar name (attribute 2).
499    pub calendar_name: Vec<u8>,
500    /// Week profile table (attribute 3).
501    pub week_profile_table: Vec<Choice>,
502    /// Day profile table (attribute 4).
503    pub day_profile_table: Vec<Choice>,
504    /// Month profile table (attribute 5).
505    pub month_profile_table: Vec<Choice>,
506    /// Active calendar name (attribute 6).
507    pub active_calendar: Vec<u8>,
508}
509
510/// Register monitor class (class_id = 21) attributes.
511/// - attr 1: logical_name (octet-string)
512/// - attr 2: thresholds (array of {value, script})
513#[derive(Debug, Clone, Serialize, Deserialize)]
514pub struct RegisterMonitorAttrs {
515    /// OBIS logical name (attribute 1).
516    pub logical_name: LogicalName,
517    /// Threshold definitions (attribute 2).
518    pub thresholds: Vec<Choice>,
519}
520
521/// Single action schedule class (class_id = 22) attributes.
522/// - attr 1: logical_name (octet-string)
523/// - attr 2: executed_script (capture_object_definition)
524/// - attr 3: execution_time (array of octet-string)
525#[derive(Debug, Clone, Serialize, Deserialize)]
526pub struct SingleActionScheduleAttrs {
527    /// OBIS logical name (attribute 1).
528    pub logical_name: LogicalName,
529    /// Executed script reference (attribute 2).
530    pub executed_script: CaptureObjectDefinition,
531    /// Execution time array (attribute 3).
532    pub execution_time: Vec<Choice>,
533}
534
535/// Image transfer class (class_id = 18) attributes.
536/// - attr 1: logical_name (octet-string)
537/// - attr 2: block_size (long-unsigned)
538/// - attr 3: transferred_blocks (double-long-unsigned)
539/// - attr 4: last_block_number (double-long-unsigned)
540/// - attr 5: transfer_status (enum)
541/// - attr 6: image_transfer_enabled (boolean)
542/// - attr 7: image_transferred_block_status (bit-string)
543/// - attr 8: image_first_not_transferred_block_number (double-long-unsigned)
544/// - attr 9: image_block_transfer_trigger (enum)
545/// - attr 10: image_transfer_service_enable (boolean)
546/// - attr 11: image_activation_info (array)
547#[derive(Debug, Clone, Serialize, Deserialize)]
548pub struct ImageTransferAttrs {
549    /// OBIS logical name (attribute 1).
550    pub logical_name: LogicalName,
551    /// Block size for transfer (attribute 2).
552    pub block_size: u16,
553    /// Number of transferred blocks (attribute 3).
554    pub transferred_blocks: u32,
555    /// Last block number transferred (attribute 4).
556    pub last_block_number: u32,
557    /// Transfer status (attribute 5).
558    pub transfer_status: u8,
559    /// Image transfer enabled flag (attribute 6).
560    pub image_transfer_enabled: bool,
561    /// Block transfer status bit-string (attribute 7).
562    pub image_transferred_block_status: Vec<u8>,
563    /// First not transferred block number (attribute 8).
564    pub image_first_not_transferred_block_number: u32,
565    /// Block transfer trigger (attribute 9).
566    pub image_block_transfer_trigger: u8,
567    /// Transfer service enable flag (attribute 10).
568    pub image_transfer_service_enable: bool,
569    /// Activation info array (attribute 11).
570    pub image_activation_info: Vec<Choice>,
571}
572
573/// Disconnect control class (class_id = 70) attributes.
574/// - attr 1: logical_name (octet-string)
575/// - attr 2: output_state (boolean)
576/// - attr 3: control_mode (enum)
577/// - attr 4: physical_output_name (octet-string)
578#[derive(Debug, Clone, Serialize, Deserialize)]
579pub struct DisconnectControlAttrs {
580    /// OBIS logical name (attribute 1).
581    pub logical_name: LogicalName,
582    /// Output state (attribute 2).
583    pub output_state: bool,
584    /// Control mode (attribute 3).
585    pub control_mode: u8,
586    /// Physical output name (attribute 4).
587    pub physical_output_name: Vec<u8>,
588}
589
590/// Limiter class (class_id = 71) attributes.
591/// - attr 1: logical_name (octet-string)
592/// - attr 2: monitored_value (CHOICE)
593/// - attr 3: threshold_normal (CHOICE)
594/// - attr 4: threshold_min_operation (CHOICE)
595/// - attr 5: threshold_max_operation (CHOICE)
596/// - attr 6: min_over_threshold_duration (long-unsigned)
597/// - attr 7: min_under_threshold_duration (long-unsigned)
598/// - attr 8: emergency_profile (capture_object_definition)
599/// - attr 9: emergency_profile_action (enum)
600/// - attr 10: active_calendar_name (octet-string)
601/// - attr 11: emergency_profile_group_id (long-unsigned)
602#[derive(Debug, Clone, Serialize, Deserialize)]
603pub struct LimiterAttrs {
604    /// OBIS logical name (attribute 1).
605    pub logical_name: LogicalName,
606    /// Monitored value (attribute 2).
607    pub monitored_value: Choice,
608    /// Normal threshold (attribute 3).
609    pub threshold_normal: Choice,
610    /// Minimum operation threshold (attribute 4).
611    pub threshold_min_operation: Choice,
612    /// Maximum operation threshold (attribute 5).
613    pub threshold_max_operation: Choice,
614    /// Minimum over-threshold duration (attribute 6).
615    pub min_over_threshold_duration: u16,
616    /// Minimum under-threshold duration (attribute 7).
617    pub min_under_threshold_duration: u16,
618    /// Emergency profile (attribute 8).
619    pub emergency_profile: CaptureObjectDefinition,
620    /// Emergency profile action (attribute 9).
621    pub emergency_profile_action: u8,
622    /// Active calendar name (attribute 10).
623    pub active_calendar_name: Vec<u8>,
624    /// Emergency profile group ID (attribute 11).
625    pub emergency_profile_group_id: u16,
626}
627
628/// TCP-UDP setup class (class_id = 41) attributes.
629/// - attr 1: logical_name (octet-string)
630/// - attr 2: port (long-unsigned)
631/// - attr 3: tcp-udp_protocol (octet-string)
632/// - attr 4: ip_reference (octet-string)
633/// - attr 5: maximum_simultaneous_connections (long-unsigned)
634/// - attr 6: maximum_segment_size (long-unsigned)
635/// - attr 7: inactivity_timeout (long-unsigned)
636/// - attr 8: transport_security (enum)
637/// - attr 9: password_setup (octet-string)
638/// - attr 10: password (visible-string)
639/// - attr 11: default_password_status (enum)
640#[derive(Debug, Clone, Serialize, Deserialize)]
641pub struct TcpUdpSetupAttrs {
642    /// OBIS logical name (attribute 1).
643    pub logical_name: LogicalName,
644    /// Port number (attribute 2).
645    pub port: u16,
646    /// TCP/UDP protocol type (attribute 3).
647    pub tcp_udp_protocol: Vec<u8>,
648    /// IP reference logical name (attribute 4).
649    pub ip_reference: Vec<u8>,
650    /// Maximum simultaneous connections (attribute 5).
651    pub maximum_simultaneous_connections: u16,
652    /// Maximum segment size (attribute 6).
653    pub maximum_segment_size: u16,
654    /// Inactivity timeout in seconds (attribute 7).
655    pub inactivity_timeout: u16,
656    /// Transport security mode (attribute 8).
657    pub transport_security: u8,
658    /// Password setup reference (attribute 9).
659    pub password_setup: Vec<u8>,
660    /// Password (attribute 10).
661    pub password: Vec<u8>,
662    /// Default password status (attribute 11).
663    pub default_password_status: u8,
664}
665
666/// IPv4 setup class (class_id = 42) attributes.
667/// - attr 1: logical_name (octet-string)
668/// - attr 2: ip_address (octet-string, 4 bytes)
669/// - attr 3: subnet_mask (octet-string, 4 bytes)
670/// - attr 4: gateway_ip_address (octet-string, 4 bytes)
671/// - attr 5: use_dhcp (boolean)
672#[derive(Debug, Clone, Serialize, Deserialize)]
673pub struct Ipv4SetupAttrs {
674    /// OBIS logical name (attribute 1).
675    pub logical_name: LogicalName,
676    /// IP address, 4 bytes (attribute 2).
677    pub ip_address: [u8; 4],
678    /// Subnet mask, 4 bytes (attribute 3).
679    pub subnet_mask: [u8; 4],
680    /// Gateway IP address, 4 bytes (attribute 4).
681    pub gateway_ip_address: [u8; 4],
682    /// Use DHCP flag (attribute 5).
683    pub use_dhcp: bool,
684}
685
686/// IPv6 setup class (class_id = 48) attributes.
687/// - attr 1: logical_name (octet-string)
688/// - attr 2: ip_address (octet-string, 16 bytes)
689/// - attr 3: prefix_length (octet-string)
690/// - attr 4: gateway_ip_address (octet-string, 16 bytes)
691/// - attr 5: use_dhcp (boolean)
692/// - attr 6: multicast_address (octet-string, 16 bytes)
693#[derive(Debug, Clone, Serialize, Deserialize)]
694pub struct Ipv6SetupAttrs {
695    /// OBIS logical name (attribute 1).
696    pub logical_name: LogicalName,
697    /// IP address, 16 bytes (attribute 2).
698    pub ip_address: [u8; 16],
699    /// Prefix length (attribute 3).
700    pub prefix_length: u8,
701    /// Gateway IP address, 16 bytes (attribute 4).
702    pub gateway_ip_address: [u8; 16],
703    /// Use DHCP flag (attribute 5).
704    pub use_dhcp: bool,
705    /// Multicast address, 16 bytes (attribute 6).
706    pub multicast_address: [u8; 16],
707}
708
709/// MAC address setup class (class_id = 43) attributes.
710/// - attr 1: logical_name (octet-string)
711/// - attr 2: unicast_mac_address (octet-string, 6 bytes)
712/// - attr 3: broadcast_mac_address (octet-string, 6 bytes)
713/// - attr 4: multicast_mac_address (octet-string, 6 bytes)
714#[derive(Debug, Clone, Serialize, Deserialize)]
715pub struct MacAddressSetupAttrs {
716    /// OBIS logical name (attribute 1).
717    pub logical_name: LogicalName,
718    /// Unicast MAC address, 6 bytes (attribute 2).
719    pub unicast_mac_address: [u8; 6],
720    /// Broadcast MAC address, 6 bytes (attribute 3).
721    pub broadcast_mac_address: [u8; 6],
722    /// Multicast MAC address, 6 bytes (attribute 4).
723    pub multicast_mac_address: [u8; 6],
724}
725
726/// GPRS modem setup class (class_id = 45) attributes.
727/// - attr 1: logical_name (octet-string)
728/// - attr 2: apn (visible-string)
729/// - attr 3: pin_code (visible-string)
730/// - attr 4: username (visible-string)
731/// - attr 5: password (visible-string)
732/// - attr 6: ask_for_password (boolean)
733/// - attr 7: ip_address (octet-string, 4 bytes)
734/// - attr 8: ip_port (long-unsigned)
735/// - attr 9: transfer_services (bit-string)
736/// - attr 10: default_transfers (octet-string)
737/// - attr 11: gprs_timeout (long-unsigned)
738#[derive(Debug, Clone, Serialize, Deserialize)]
739pub struct GprsModemSetupAttrs {
740    /// OBIS logical name (attribute 1).
741    pub logical_name: LogicalName,
742    /// Access point name (attribute 2).
743    pub apn: Vec<u8>,
744    /// PIN code (attribute 3).
745    pub pin_code: Vec<u8>,
746    /// Username (attribute 4).
747    pub username: Vec<u8>,
748    /// Password (attribute 5).
749    pub password: Vec<u8>,
750    /// Ask for password flag (attribute 6).
751    pub ask_for_password: bool,
752    /// IP address, 4 bytes (attribute 7).
753    pub ip_address: [u8; 4],
754    /// IP port number (attribute 8).
755    pub ip_port: u16,
756    /// Transfer services (attribute 9).
757    pub transfer_services: Vec<u8>,
758    /// Default transfers (attribute 10).
759    pub default_transfers: Vec<u8>,
760    /// GPRS timeout in seconds (attribute 11).
761    pub gprs_timeout: u16,
762}
763
764/// GSM diagnostic class (class_id = 47) attributes.
765/// - attr 1: logical_name (octet-string)
766/// - attr 2: cell_id (octet-string)
767/// - attr 3: location_id (octet-string)
768/// - attr 4: imsi (octet-string)
769/// - attr 5: imei (octet-string)
770/// - attr 6: rn (octet-string)
771/// - attr 7: cn (octet-string)
772/// - attr 8: signal_quality (octet-string)
773/// - attr 9: signal_strength (octet-string)
774/// - attr 10: channel_number (octet-string)
775/// - attr 11: cell_parameter_id (octet-string)
776/// - attr 12: bsic (octet-string)
777/// - attr 13: iccid (octet-string)
778/// - attr 14: lac (octet-string)
779/// - attr 15: mcc (octet-string)
780/// - attr 16: mnc (octet-string)
781/// - attr 17: tmsi (octet-string)
782/// - attr 18: tmgi (octet-string)
783/// - attr 19: gprs_status (octet-string)
784/// - attr 20: routing_area_code (octet-string)
785/// - attr 21: geographic_address (octet-string)
786/// - attr 22: access_point_name (visible-string)
787/// - attr 23: data_transport_state (octet-string)
788/// - attr 24: nma_message (octet-string)
789#[derive(Debug, Clone, Serialize, Deserialize)]
790pub struct GsmDiagnosticAttrs {
791    /// OBIS logical name (attribute 1).
792    pub logical_name: LogicalName,
793    /// Cell ID (attribute 2).
794    pub cell_id: Vec<u8>,
795    /// Location area ID (attribute 3).
796    pub location_id: Vec<u8>,
797    /// IMSI (attribute 4).
798    pub imsi: Vec<u8>,
799    /// IMEI (attribute 5).
800    pub imei: Vec<u8>,
801    /// Routing area code (attribute 6).
802    pub rn: Vec<u8>,
803    /// Cell ID (attribute 7).
804    pub cn: Vec<u8>,
805    /// Signal quality (attribute 8).
806    pub signal_quality: Vec<u8>,
807    /// Signal strength (attribute 9).
808    pub signal_strength: Vec<u8>,
809    /// Channel number (attribute 10).
810    pub channel_number: Vec<u8>,
811    /// Cell parameter ID (attribute 11).
812    pub cell_parameter_id: Vec<u8>,
813    /// Base station ID code (attribute 12).
814    pub bsic: Vec<u8>,
815    /// SIM card ICCID (attribute 13).
816    pub iccid: Vec<u8>,
817    /// Location area code (attribute 14).
818    pub lac: Vec<u8>,
819    /// Mobile country code (attribute 15).
820    pub mcc: Vec<u8>,
821    /// Mobile network code (attribute 16).
822    pub mnc: Vec<u8>,
823    /// Temporary mobile subscriber ID (attribute 17).
824    pub tmsi: Vec<u8>,
825    /// Temporary mobile group ID (attribute 18).
826    pub tmgi: Vec<u8>,
827    /// GPRS status (attribute 19).
828    pub gprs_status: Vec<u8>,
829    /// Routing area code (attribute 20).
830    pub routing_area_code: Vec<u8>,
831    /// Geographic address (attribute 21).
832    pub geographic_address: Vec<u8>,
833    /// Access point name (attribute 22).
834    pub access_point_name: Vec<u8>,
835    /// Data transport state (attribute 23).
836    pub data_transport_state: Vec<u8>,
837    /// NMA message (attribute 24).
838    pub nma_message: Vec<u8>,
839}
840
841/// Arbitrator class (class_id = 68) attributes.
842/// - attr 1: logical_name (octet-string)
843/// - attr 2: capture_groups (array of capture_object_definition)
844/// - attr 3: action_groups (array of array)
845#[derive(Debug, Clone, Serialize, Deserialize)]
846pub struct ArbitratorAttrs {
847    /// OBIS logical name (attribute 1).
848    pub logical_name: LogicalName,
849    /// Capture groups (attribute 2).
850    pub capture_groups: Vec<CaptureObjectDefinition>,
851    /// Action groups (attribute 3).
852    pub action_groups: Vec<Choice>,
853}
854
855/// IEC HDLC setup class (class_id = 23) attributes.
856/// - attr 1: logical_name (octet-string)
857/// - attr 2: channel (unsigned)
858/// - attr 3: wait (array)
859/// - attr 4: client_address (long-unsigned)
860/// - attr 5: server_address (long-unsigned)
861/// - attr 6: window_size_tx (unsigned)
862/// - attr 7: window_size_rx (unsigned)
863/// - attr 8: max_info_tx (long-unsigned)
864/// - attr 9: max_info_rx (long-unsigned)
865/// - attr 10: max_timeout_tx (long-unsigned)
866/// - attr 11: max_retries_tx (long-unsigned)
867/// - attr 12: max_timeout_respond (long-unsigned)
868/// - attr 13: max_retries_respond (long-unsigned)
869#[derive(Debug, Clone, Serialize, Deserialize)]
870pub struct IecHdlcSetupAttrs {
871    /// OBIS logical name (attribute 1).
872    pub logical_name: LogicalName,
873    /// Communication channel (attribute 2).
874    pub channel: u8,
875    /// Wait time array (attribute 3).
876    pub wait: Vec<Choice>,
877    /// Client HDLC address (attribute 4).
878    pub client_address: u16,
879    /// Server HDLC address (attribute 5).
880    pub server_address: u16,
881    /// TX window size (attribute 6).
882    pub window_size_tx: u8,
883    /// RX window size (attribute 7).
884    pub window_size_rx: u8,
885    /// Max info field TX (attribute 8).
886    pub max_info_tx: u16,
887    /// Max info field RX (attribute 9).
888    pub max_info_rx: u16,
889    /// Max timeout TX in ms (attribute 10).
890    pub max_timeout_tx: u16,
891    /// Max retries TX (attribute 11).
892    pub max_retries_tx: u8,
893    /// Max timeout for respond in ms (attribute 12).
894    pub max_timeout_respond: u16,
895    /// Max retries for respond (attribute 13).
896    pub max_retries_respond: u8,
897}
898
899/// IEC local port setup class (class_id = 19) attributes.
900/// - attr 1: logical_name (octet-string)
901/// - attr 2: mode (enum)
902/// - attr 3: communication_speed (unsigned)
903/// - attr 4: max_size_info_field (long-unsigned)
904/// - attr 5: device_address (octet-string)
905/// - attr 6: password1 (octet-string)
906/// - attr 7: password2 (octet-string)
907/// - attr 8: password3 (octet-string)
908/// - attr 9: client_address (octet-string)
909/// - attr 10: point_to_point_address (octet-string)
910#[derive(Debug, Clone, Serialize, Deserialize)]
911pub struct IecLocalPortSetupAttrs {
912    /// OBIS logical name (attribute 1).
913    pub logical_name: LogicalName,
914    /// Communication mode (attribute 2).
915    pub mode: u8,
916    /// Communication speed (attribute 3).
917    pub communication_speed: u8,
918    /// Maximum info field size (attribute 4).
919    pub max_size_info_field: u16,
920    /// Device address (attribute 5).
921    pub device_address: Vec<u8>,
922    /// Password 1 (attribute 6).
923    pub password1: Vec<u8>,
924    /// Password 2 (attribute 7).
925    pub password2: Vec<u8>,
926    /// Password 3 (attribute 8).
927    pub password3: Vec<u8>,
928    /// Client address (attribute 9).
929    pub client_address: Vec<u8>,
930    /// Point-to-point address (attribute 10).
931    pub point_to_point_address: Vec<u8>,
932}
933
934/// M-Bus slave port setup class (class_id = 25) attributes.
935/// - attr 1: logical_name (octet-string)
936/// - attr 2: mbus_address (octet-string)
937/// - attr 3: identification_number (octet-string)
938/// - attr 4: manufacturer_id (octet-string)
939/// - attr 5: data_type (octet-string)
940/// - attr 6: max_slave_pifs (long-unsigned)
941/// - attr 7: max_master_pifs (long-unsigned)
942/// - attr 8: character_encoding (octet-string)
943/// - attr 9: m_bus_mode (enum)
944#[derive(Debug, Clone, Serialize, Deserialize)]
945pub struct MbusSlavePortSetupAttrs {
946    /// OBIS logical name (attribute 1).
947    pub logical_name: LogicalName,
948    /// M-Bus slave address (attribute 2).
949    pub mbus_address: Vec<u8>,
950    /// Identification number (attribute 3).
951    pub identification_number: Vec<u8>,
952    /// Manufacturer ID (attribute 4).
953    pub manufacturer_id: Vec<u8>,
954    /// Data type (attribute 5).
955    pub data_type: Vec<u8>,
956    /// Max slave PI frames (attribute 6).
957    pub max_slave_pifs: u16,
958    /// Max master PI frames (attribute 7).
959    pub max_master_pifs: u16,
960    /// Character encoding (attribute 8).
961    pub character_encoding: Vec<u8>,
962    /// M-Bus mode (attribute 9).
963    pub m_bus_mode: u8,
964}
965
966/// Data protection class (class_id = 30) attributes.
967/// - attr 1: logical_name (octet-string)
968/// - attr 2: protection_method (enum)
969/// - attr 3: protection_key (octet-string)
970/// - attr 4: key_translation_table_1 (array)
971/// - attr 5: key_translation_table_2 (array)
972/// - attr 6: key_translation_table_3 (array)
973#[derive(Debug, Clone, Serialize, Deserialize)]
974pub struct DataProtectionAttrs {
975    /// OBIS logical name (attribute 1).
976    pub logical_name: LogicalName,
977    /// Protection method (attribute 2).
978    pub protection_method: u8,
979    /// Protection key (attribute 3).
980    pub protection_key: Vec<u8>,
981    /// Key translation table 1 (attribute 4).
982    pub key_translation_table_1: Vec<Choice>,
983    /// Key translation table 2 (attribute 5).
984    pub key_translation_table_2: Vec<Choice>,
985    /// Key translation table 3 (attribute 6).
986    pub key_translation_table_3: Vec<Choice>,
987}
988
989/// Security setup class (class_id = 64) attributes.
990/// - attr 1: logical_name (octet-string)
991/// - attr 2: security_policy (enum)
992/// - attr 3: security_suite (enum)
993/// - attr 4: client_system_title (octet-string)
994/// - attr 5: server_system_title (octet-string)
995/// - attr 6: certificates (array)
996#[derive(Debug, Clone, Serialize, Deserialize)]
997pub struct SecuritySetupAttrs {
998    /// OBIS logical name (attribute 1).
999    pub logical_name: LogicalName,
1000    /// Security policy (attribute 2).
1001    pub security_policy: u8,
1002    /// Security suite (attribute 3).
1003    pub security_suite: u8,
1004    /// Client system title (attribute 4).
1005    pub client_system_title: Vec<u8>,
1006    /// Server system title (attribute 5).
1007    pub server_system_title: Vec<u8>,
1008    /// Certificates array (attribute 6).
1009    pub certificates: Vec<Choice>,
1010}
1011
1012impl AssociationStatus {
1013    /// Parses an association status from its numeric value.
1014    pub fn from_u8(v: u8) -> Option<Self> {
1015        match v {
1016            0 => Some(Self::NonAssociated),
1017            1 => Some(Self::AssociationPending),
1018            2 => Some(Self::Associated),
1019            _ => None,
1020        }
1021    }
1022}
1023
1024/// Clock base (IEC 62056-6-2, 4.3.7).
1025#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1026pub enum ClockBase {
1027    /// No clock base.
1028    None = 0,
1029    /// Internal crystal.
1030    InternalCrystal = 1,
1031    /// Mains frequency.
1032    MainsFrequency = 2,
1033    /// GPS.
1034    Gps = 3,
1035    /// Radio clock.
1036    RadioClock = 4,
1037}
1038
1039impl ClockBase {
1040    /// Parses a clock base from its numeric value.
1041    pub fn from_u8(v: u8) -> Option<Self> {
1042        match v {
1043            0 => Some(Self::None),
1044            1 => Some(Self::InternalCrystal),
1045            2 => Some(Self::MainsFrequency),
1046            3 => Some(Self::Gps),
1047            4 => Some(Self::RadioClock),
1048            _ => None,
1049        }
1050    }
1051}
1052
1053// ============================================================================
1054// Shared COSEM typed structures (Blue Book / IEC 62056-6-2)
1055// ============================================================================
1056
1057/// `access_right` — structure { attribute_access, method_access }
1058/// Used by Association LN (attr 2) and Association SN.
1059#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1060pub struct AccessRight {
1061    /// Attribute access permissions.
1062    pub attribute_access: Vec<AttributeAccessItem>,
1063    /// Method access permissions.
1064    pub method_access: Vec<MethodAccessItem>,
1065}
1066
1067impl From<AccessRight> for CosemDataType {
1068    fn from(ar: AccessRight) -> Self {
1069        CosemDataType::Structure(vec![
1070            CosemDataType::Array(ar.attribute_access.into_iter().map(CosemDataType::from).collect()),
1071            CosemDataType::Array(ar.method_access.into_iter().map(CosemDataType::from).collect()),
1072        ])
1073    }
1074}
1075
1076impl TryFrom<&CosemDataType> for AccessRight {
1077    type Error = String;
1078    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1079        match value {
1080            CosemDataType::Structure(fields) if fields.len() >= 2 => {
1081                let attribute_access = match &fields[0] {
1082                    CosemDataType::Array(items) => {
1083                        items.iter().map(AttributeAccessItem::try_from).collect::<Result<Vec<_>, _>>()?
1084                    }
1085                    _ => return Err("attribute_access must be array".to_string()),
1086                };
1087                let method_access = match &fields[1] {
1088                    CosemDataType::Array(items) => {
1089                        items.iter().map(MethodAccessItem::try_from).collect::<Result<Vec<_>, _>>()?
1090                    }
1091                    _ => return Err("method_access must be array".to_string()),
1092                };
1093                Ok(AccessRight { attribute_access, method_access })
1094            }
1095            _ => Err("expected structure {attribute_access, method_access}".to_string()),
1096        }
1097    }
1098}
1099
1100/// `attribute_access_item` — structure { attribute_id, access_mode, access_selectors }
1101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1102pub struct AttributeAccessItem {
1103    /// Attribute identifier.
1104    pub attribute_id: i8,
1105    /// Access mode for the attribute.
1106    pub access_mode: u8,
1107    /// Optional access selectors.
1108    pub access_selectors: Option<Vec<i8>>,
1109}
1110
1111impl From<AttributeAccessItem> for CosemDataType {
1112    fn from(item: AttributeAccessItem) -> Self {
1113        let access_selectors = item.access_selectors.map_or(CosemDataType::Null, |ids| {
1114            CosemDataType::Array(ids.into_iter().map(CosemDataType::Integer).collect())
1115        });
1116        CosemDataType::Structure(vec![
1117            CosemDataType::Integer(item.attribute_id),
1118            CosemDataType::Enum(item.access_mode),
1119            access_selectors,
1120        ])
1121    }
1122}
1123
1124impl TryFrom<&CosemDataType> for AttributeAccessItem {
1125    type Error = String;
1126    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1127        match value {
1128            CosemDataType::Structure(fields) if fields.len() >= 3 => {
1129                let attribute_id = match &fields[0] {
1130                    CosemDataType::Integer(v) => *v,
1131                    CosemDataType::Long(v) => {
1132                        i8::try_from(*v).map_err(|_| "attribute_id must be integer".to_string())?
1133                    }
1134                    _ => return Err("attribute_id must be integer".to_string()),
1135                };
1136                let access_mode = match &fields[1] {
1137                    CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
1138                    _ => return Err("access_mode must be enum".to_string()),
1139                };
1140                let access_selectors = match &fields[2] {
1141                    CosemDataType::Array(items) => {
1142                        let ids = items
1143                            .iter()
1144                            .map(|item| match item {
1145                                CosemDataType::Integer(v) => Ok(*v),
1146                                CosemDataType::Long(v) => {
1147                                    i8::try_from(*v).map_err(|_| "selector must be integer".to_string())
1148                                }
1149                                _ => Err("selector must be integer".to_string()),
1150                            })
1151                            .collect::<Result<Vec<_>, _>>()?;
1152                        Some(ids)
1153                    }
1154                    _ => None,
1155                };
1156                Ok(AttributeAccessItem { attribute_id, access_mode, access_selectors })
1157            }
1158            _ => Err("expected structure {attribute_id, access_mode, access_selectors}".to_string()),
1159        }
1160    }
1161}
1162
1163/// `method_access_item` — structure { method_id, access_mode }
1164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1165pub struct MethodAccessItem {
1166    /// Method identifier.
1167    pub method_id: i8,
1168    /// Access mode for the method.
1169    pub access_mode: u8,
1170}
1171
1172impl From<MethodAccessItem> for CosemDataType {
1173    fn from(item: MethodAccessItem) -> Self {
1174        CosemDataType::Structure(vec![CosemDataType::Integer(item.method_id), CosemDataType::Enum(item.access_mode)])
1175    }
1176}
1177
1178impl TryFrom<&CosemDataType> for MethodAccessItem {
1179    type Error = String;
1180    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1181        match value {
1182            CosemDataType::Structure(fields) if fields.len() >= 2 => {
1183                let method_id = match &fields[0] {
1184                    CosemDataType::Integer(v) => *v,
1185                    CosemDataType::Long(v) => i8::try_from(*v).map_err(|_| "method_id must be integer".to_string())?,
1186                    _ => return Err("method_id must be integer".to_string()),
1187                };
1188                let access_mode = match &fields[1] {
1189                    CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
1190                    _ => return Err("access_mode must be enum".to_string()),
1191                };
1192                Ok(MethodAccessItem { method_id, access_mode })
1193            }
1194            _ => Err("expected structure {method_id, access_mode}".to_string()),
1195        }
1196    }
1197}
1198
1199/// `object_list_element` — structure { class_id, version, logical_name, access_rights }
1200/// Used in Association LN attr 2 (object_list).
1201#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1202pub struct ObjectListElement {
1203    /// COSEM class identifier.
1204    pub class_id: u16,
1205    /// Class version number.
1206    pub version: u8,
1207    /// OBIS logical name.
1208    pub logical_name: ObisCode,
1209    /// Access rights for this object.
1210    pub access_rights: AccessRight,
1211}
1212
1213impl From<ObjectListElement> for CosemDataType {
1214    fn from(e: ObjectListElement) -> Self {
1215        CosemDataType::Structure(vec![
1216            CosemDataType::LongUnsigned(e.class_id),
1217            CosemDataType::Unsigned(e.version),
1218            CosemDataType::OctetString(e.logical_name.to_bytes()),
1219            CosemDataType::from(e.access_rights),
1220        ])
1221    }
1222}
1223
1224impl TryFrom<&CosemDataType> for ObjectListElement {
1225    type Error = String;
1226    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1227        match value {
1228            CosemDataType::Structure(fields) if fields.len() >= 4 => {
1229                let class_id = match &fields[0] {
1230                    CosemDataType::LongUnsigned(v) => *v,
1231                    _ => return Err("class_id must be long-unsigned".to_string()),
1232                };
1233                let version = match &fields[1] {
1234                    CosemDataType::Unsigned(v) => *v,
1235                    CosemDataType::LongUnsigned(v) => {
1236                        u8::try_from(*v).map_err(|_| "version must be unsigned".to_string())?
1237                    }
1238                    _ => return Err("version must be unsigned".to_string()),
1239                };
1240                let logical_name = match &fields[2] {
1241                    CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
1242                        ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
1243                    }
1244                    _ => return Err("logical_name must be 6-byte octet-string".to_string()),
1245                };
1246                let access_rights = AccessRight::try_from(&fields[3])?;
1247                Ok(ObjectListElement { class_id, version, logical_name, access_rights })
1248            }
1249            _ => Err("expected structure {class_id, version, logical_name, access_rights}".to_string()),
1250        }
1251    }
1252}
1253
1254/// `associated_partners_type` — structure { client_SAP, server_SAP }
1255/// Used in Association LN attr 3.
1256#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1257pub struct AssociatedPartnersId {
1258    /// Client SAP address.
1259    pub client_sap: i8,
1260    /// Server SAP address.
1261    pub server_sap: u16,
1262}
1263
1264impl From<AssociatedPartnersId> for CosemDataType {
1265    fn from(ap: AssociatedPartnersId) -> Self {
1266        CosemDataType::Structure(vec![
1267            CosemDataType::Integer(ap.client_sap),
1268            CosemDataType::LongUnsigned(ap.server_sap),
1269        ])
1270    }
1271}
1272
1273impl TryFrom<&CosemDataType> for AssociatedPartnersId {
1274    type Error = String;
1275    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1276        match value {
1277            CosemDataType::Structure(fields) if fields.len() >= 2 => {
1278                let client_sap = match &fields[0] {
1279                    CosemDataType::Integer(v) => *v,
1280                    CosemDataType::Long(v) => i8::try_from(*v).map_err(|_| "client_SAP must be integer".to_string())?,
1281                    _ => return Err("client_SAP must be integer".to_string()),
1282                };
1283                let server_sap = match &fields[1] {
1284                    CosemDataType::LongUnsigned(v) => *v,
1285                    CosemDataType::Unsigned(v) => u16::from(*v),
1286                    _ => return Err("server_SAP must be long-unsigned".to_string()),
1287                };
1288                Ok(AssociatedPartnersId { client_sap, server_sap })
1289            }
1290            _ => Err("expected structure {client_SAP, server_SAP}".to_string()),
1291        }
1292    }
1293}
1294
1295/// `context_name_type` — CHOICE of structure or octet-string.
1296/// Used in Association LN attr 4.
1297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1298pub enum ContextName {
1299    /// Encoded as a 7-element structure of OID arc components.
1300    Structure {
1301        /// Joint-iso-ccitt arc (2).
1302        joint_iso_ctt: u8,
1303        /// Country arc.
1304        country: u8,
1305        /// Country name arc.
1306        country_name: u16,
1307        /// Identified organization arc.
1308        identified_organization: u8,
1309        /// DLMS UA arc.
1310        dlms_ua: u8,
1311        /// Application context arc.
1312        application_context: u8,
1313        /// Context identifier arc.
1314        context_id: u8,
1315    },
1316    /// Encoded as raw octet-string (OBJECT IDENTIFIER).
1317    OctetString(Vec<u8>),
1318}
1319
1320impl From<ContextName> for CosemDataType {
1321    fn from(cn: ContextName) -> Self {
1322        match cn {
1323            ContextName::Structure {
1324                joint_iso_ctt,
1325                country,
1326                country_name,
1327                identified_organization,
1328                dlms_ua,
1329                application_context,
1330                context_id,
1331            } => CosemDataType::Structure(vec![
1332                CosemDataType::Unsigned(joint_iso_ctt),
1333                CosemDataType::Unsigned(country),
1334                CosemDataType::LongUnsigned(country_name),
1335                CosemDataType::Unsigned(identified_organization),
1336                CosemDataType::Unsigned(dlms_ua),
1337                CosemDataType::Unsigned(application_context),
1338                CosemDataType::Unsigned(context_id),
1339            ]),
1340            ContextName::OctetString(bytes) => CosemDataType::OctetString(bytes),
1341        }
1342    }
1343}
1344
1345impl TryFrom<&CosemDataType> for ContextName {
1346    type Error = String;
1347    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1348        match value {
1349            CosemDataType::Structure(fields) if fields.len() >= 7 => {
1350                let joint_iso_ctt = match &fields[0] {
1351                    CosemDataType::Unsigned(v) => *v,
1352                    _ => return Err("joint_iso_ctt must be unsigned".to_string()),
1353                };
1354                let country = match &fields[1] {
1355                    CosemDataType::Unsigned(v) => *v,
1356                    _ => return Err("country must be unsigned".to_string()),
1357                };
1358                let country_name = match &fields[2] {
1359                    CosemDataType::LongUnsigned(v) => *v,
1360                    _ => return Err("country_name must be long-unsigned".to_string()),
1361                };
1362                let identified_organization = match &fields[3] {
1363                    CosemDataType::Unsigned(v) => *v,
1364                    _ => return Err("identified_organization must be unsigned".to_string()),
1365                };
1366                let dlms_ua = match &fields[4] {
1367                    CosemDataType::Unsigned(v) => *v,
1368                    _ => return Err("DLMS_UA must be unsigned".to_string()),
1369                };
1370                let application_context = match &fields[5] {
1371                    CosemDataType::Unsigned(v) => *v,
1372                    _ => return Err("application_context must be unsigned".to_string()),
1373                };
1374                let context_id = match &fields[6] {
1375                    CosemDataType::Unsigned(v) => *v,
1376                    _ => return Err("context_id must be unsigned".to_string()),
1377                };
1378                Ok(ContextName::Structure {
1379                    joint_iso_ctt,
1380                    country,
1381                    country_name,
1382                    identified_organization,
1383                    dlms_ua,
1384                    application_context,
1385                    context_id,
1386                })
1387            }
1388            CosemDataType::OctetString(bytes) => Ok(ContextName::OctetString(bytes.clone())),
1389            _ => Err("expected structure or octet-string for context_name".to_string()),
1390        }
1391    }
1392}
1393
1394/// `xDLMS-context-type` — structure { conformance, max_receive_pdu_size, ... }
1395/// Used in Association LN attr 5.
1396#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1397pub struct XDLMSContextInfo {
1398    /// Conformance block (bit-string).
1399    pub conformance: Vec<u8>,
1400    /// Maximum receive PDU size in bytes.
1401    pub max_receive_pdu_size: u16,
1402    /// Maximum send PDU size in bytes.
1403    pub max_send_pdu_size: u16,
1404    /// DLMS version number.
1405    pub dlms_version_number: u8,
1406    /// Quality of service (-1 = default).
1407    pub quality_of_service: i8,
1408    /// Cyphering info (octet-string).
1409    pub cyphering_info: Vec<u8>,
1410}
1411
1412impl From<XDLMSContextInfo> for CosemDataType {
1413    fn from(ctx: XDLMSContextInfo) -> Self {
1414        CosemDataType::Structure(vec![
1415            CosemDataType::BitString(ctx.conformance),
1416            CosemDataType::LongUnsigned(ctx.max_receive_pdu_size),
1417            CosemDataType::LongUnsigned(ctx.max_send_pdu_size),
1418            CosemDataType::Unsigned(ctx.dlms_version_number),
1419            CosemDataType::Integer(ctx.quality_of_service),
1420            CosemDataType::OctetString(ctx.cyphering_info),
1421        ])
1422    }
1423}
1424
1425impl TryFrom<&CosemDataType> for XDLMSContextInfo {
1426    type Error = String;
1427    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1428        match value {
1429            CosemDataType::Structure(fields) if fields.len() >= 6 => {
1430                let conformance = match &fields[0] {
1431                    CosemDataType::BitString(v) => v.clone(),
1432                    _ => return Err("conformance must be bit-string".to_string()),
1433                };
1434                let max_receive_pdu_size = match &fields[1] {
1435                    CosemDataType::LongUnsigned(v) => *v,
1436                    _ => return Err("max_receive_pdu_size must be long-unsigned".to_string()),
1437                };
1438                let max_send_pdu_size = match &fields[2] {
1439                    CosemDataType::LongUnsigned(v) => *v,
1440                    _ => return Err("max_send_pdu_size must be long-unsigned".to_string()),
1441                };
1442                let dlms_version_number = match &fields[3] {
1443                    CosemDataType::Unsigned(v) => *v,
1444                    _ => return Err("dlms_version_number must be unsigned".to_string()),
1445                };
1446                let quality_of_service = match &fields[4] {
1447                    CosemDataType::Integer(v) => *v,
1448                    CosemDataType::Long(v) => {
1449                        i8::try_from(*v).map_err(|_| "quality_of_service must be integer".to_string())?
1450                    }
1451                    _ => return Err("quality_of_service must be integer".to_string()),
1452                };
1453                let cyphering_info = match &fields[5] {
1454                    CosemDataType::OctetString(v) => v.clone(),
1455                    _ => return Err("cyphering_info must be octet-string".to_string()),
1456                };
1457                Ok(XDLMSContextInfo {
1458                    conformance,
1459                    max_receive_pdu_size,
1460                    max_send_pdu_size,
1461                    dlms_version_number,
1462                    quality_of_service,
1463                    cyphering_info,
1464                })
1465            }
1466            _ => Err("expected structure for xDLMS_context_info".to_string()),
1467        }
1468    }
1469}
1470
1471/// `value_definition` — structure { class_id, logical_name, attribute_index }
1472/// Used in Register Monitor (attr 3) and Limiter (attr 2).
1473#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1474pub struct ValueDefinition {
1475    /// COSEM class identifier.
1476    pub class_id: u16,
1477    /// OBIS logical name of the target object.
1478    pub logical_name: ObisCode,
1479    /// Attribute index to read.
1480    pub attribute_index: i8,
1481}
1482
1483impl From<ValueDefinition> for CosemDataType {
1484    fn from(vd: ValueDefinition) -> Self {
1485        CosemDataType::Structure(vec![
1486            CosemDataType::LongUnsigned(vd.class_id),
1487            CosemDataType::OctetString(vd.logical_name.to_bytes()),
1488            CosemDataType::Integer(vd.attribute_index),
1489        ])
1490    }
1491}
1492
1493impl TryFrom<&CosemDataType> for ValueDefinition {
1494    type Error = String;
1495    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1496        match value {
1497            CosemDataType::Structure(fields) if fields.len() >= 3 => {
1498                let class_id = match &fields[0] {
1499                    CosemDataType::LongUnsigned(v) => *v,
1500                    _ => return Err("class_id must be long-unsigned".to_string()),
1501                };
1502                let logical_name = match &fields[1] {
1503                    CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
1504                        ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
1505                    }
1506                    _ => return Err("logical_name must be 6-byte octet-string".to_string()),
1507                };
1508                let attribute_index = match &fields[2] {
1509                    CosemDataType::Integer(v) => *v,
1510                    CosemDataType::Long(v) => {
1511                        i8::try_from(*v).map_err(|_| "attribute_index must be integer".to_string())?
1512                    }
1513                    _ => return Err("attribute_index must be integer".to_string()),
1514                };
1515                Ok(ValueDefinition { class_id, logical_name, attribute_index })
1516            }
1517            _ => Err("expected structure {class_id, logical_name, attribute_index}".to_string()),
1518        }
1519    }
1520}
1521
1522/// `action_item` — structure { script_logical_name, script_selector }
1523/// Used in Register Monitor, Limiter, and other ICs.
1524#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1525pub struct ActionItem {
1526    /// Logical name of the Script Table object.
1527    pub script_logical_name: ObisCode,
1528    /// Script identifier to execute.
1529    pub script_selector: u16,
1530}
1531
1532impl From<ActionItem> for CosemDataType {
1533    fn from(ai: ActionItem) -> Self {
1534        CosemDataType::Structure(vec![
1535            CosemDataType::OctetString(ai.script_logical_name.to_bytes()),
1536            CosemDataType::LongUnsigned(ai.script_selector),
1537        ])
1538    }
1539}
1540
1541impl TryFrom<&CosemDataType> for ActionItem {
1542    type Error = String;
1543    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1544        match value {
1545            CosemDataType::Structure(fields) if fields.len() >= 2 => {
1546                let script_logical_name = match &fields[0] {
1547                    CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
1548                        ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
1549                    }
1550                    _ => return Err("script_logical_name must be 6-byte octet-string".to_string()),
1551                };
1552                let script_selector = match &fields[1] {
1553                    CosemDataType::LongUnsigned(v) => *v,
1554                    CosemDataType::Unsigned(v) => u16::from(*v),
1555                    _ => return Err("script_selector must be long-unsigned".to_string()),
1556                };
1557                Ok(ActionItem { script_logical_name, script_selector })
1558            }
1559            _ => Err("expected structure {script_logical_name, script_selector}".to_string()),
1560        }
1561    }
1562}
1563
1564/// `action_set` — structure { action_up, action_down }
1565/// Used in Register Monitor (attr 4).
1566#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1567pub struct ActionSet {
1568    /// Action to execute on threshold increase.
1569    pub action_up: ActionItem,
1570    /// Action to execute on threshold decrease.
1571    pub action_down: ActionItem,
1572}
1573
1574impl From<ActionSet> for CosemDataType {
1575    fn from(a: ActionSet) -> Self {
1576        CosemDataType::Structure(vec![CosemDataType::from(a.action_up), CosemDataType::from(a.action_down)])
1577    }
1578}
1579
1580impl TryFrom<&CosemDataType> for ActionSet {
1581    type Error = String;
1582    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1583        match value {
1584            CosemDataType::Structure(fields) if fields.len() >= 2 => {
1585                let action_up = ActionItem::try_from(&fields[0])?;
1586                let action_down = ActionItem::try_from(&fields[1])?;
1587                Ok(ActionSet { action_up, action_down })
1588            }
1589            _ => Err("expected structure {action_up, action_down}".to_string()),
1590        }
1591    }
1592}
1593
1594/// `action_specification` — structure { service_id, class_id, logical_name, index, parameter }
1595/// Used in Script Table (attr 2).
1596#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1597pub struct ActionSpecification {
1598    /// Service ID (method number).
1599    pub service_id: u8,
1600    /// Target class identifier.
1601    pub class_id: u16,
1602    /// OBIS logical name of the target object.
1603    pub logical_name: ObisCode,
1604    /// Attribute index (0 for methods).
1605    pub index: i8,
1606    /// Parameter value for the service.
1607    pub parameter: Choice,
1608}
1609
1610impl From<ActionSpecification> for CosemDataType {
1611    fn from(aspec: ActionSpecification) -> Self {
1612        CosemDataType::Structure(vec![
1613            CosemDataType::Enum(aspec.service_id),
1614            CosemDataType::LongUnsigned(aspec.class_id),
1615            CosemDataType::OctetString(aspec.logical_name.to_bytes()),
1616            CosemDataType::Integer(aspec.index),
1617            aspec.parameter,
1618        ])
1619    }
1620}
1621
1622impl TryFrom<&CosemDataType> for ActionSpecification {
1623    type Error = String;
1624    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1625        match value {
1626            CosemDataType::Structure(fields) if fields.len() >= 5 => {
1627                let service_id = match &fields[0] {
1628                    CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
1629                    _ => return Err("service_id must be enum".to_string()),
1630                };
1631                let class_id = match &fields[1] {
1632                    CosemDataType::LongUnsigned(v) => *v,
1633                    _ => return Err("class_id must be long-unsigned".to_string()),
1634                };
1635                let logical_name = match &fields[2] {
1636                    CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
1637                        ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
1638                    }
1639                    _ => return Err("logical_name must be 6-byte octet-string".to_string()),
1640                };
1641                let index = match &fields[3] {
1642                    CosemDataType::Integer(v) => *v,
1643                    CosemDataType::Long(v) => i8::try_from(*v).map_err(|_| "index must be integer".to_string())?,
1644                    _ => return Err("index must be integer".to_string()),
1645                };
1646                let parameter = fields[4].clone();
1647                Ok(ActionSpecification { service_id, class_id, logical_name, index, parameter })
1648            }
1649            _ => Err("expected structure {service_id, class_id, logical_name, index, parameter}".to_string()),
1650        }
1651    }
1652}
1653
1654/// `script` — structure { script_identifier, actions }
1655/// Used in Script Table (attr 2).
1656#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1657pub struct Script {
1658    /// Script identifier (unique within the Script Table).
1659    pub script_identifier: u16,
1660    /// Ordered list of actions to execute.
1661    pub actions: Vec<ActionSpecification>,
1662}
1663
1664impl From<Script> for CosemDataType {
1665    fn from(s: Script) -> Self {
1666        CosemDataType::Structure(vec![
1667            CosemDataType::LongUnsigned(s.script_identifier),
1668            CosemDataType::Array(s.actions.into_iter().map(CosemDataType::from).collect()),
1669        ])
1670    }
1671}
1672
1673impl TryFrom<&CosemDataType> for Script {
1674    type Error = String;
1675    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1676        match value {
1677            CosemDataType::Structure(fields) if fields.len() >= 2 => {
1678                let script_identifier = match &fields[0] {
1679                    CosemDataType::LongUnsigned(v) => *v,
1680                    _ => return Err("script_identifier must be long-unsigned".to_string()),
1681                };
1682                let actions = match &fields[1] {
1683                    CosemDataType::Array(items) => {
1684                        items.iter().map(ActionSpecification::try_from).collect::<Result<Vec<_>, _>>()?
1685                    }
1686                    _ => return Err("actions must be array".to_string()),
1687                };
1688                Ok(Script { script_identifier, actions })
1689            }
1690            _ => Err("expected structure {script_identifier, actions}".to_string()),
1691        }
1692    }
1693}
1694
1695/// `schedule_table_entry` — structure { index, enable, script_logical_name, ... }
1696/// Used in Schedule (attr 2).
1697#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1698pub struct ScheduleTableEntry {
1699    /// Entry index.
1700    pub index: u16,
1701    /// Enable flag.
1702    pub enable: bool,
1703    /// Logical name of the Script Table.
1704    pub script_logical_name: ObisCode,
1705    /// Script selector.
1706    pub script_selector: u16,
1707    /// Switch time.
1708    pub switch_time: Vec<u8>,
1709    /// Validity window in seconds.
1710    pub validity_window: u16,
1711    /// Execution weekdays bit-string.
1712    pub exec_weekdays: Vec<u8>,
1713    /// Execution special days bit-string.
1714    pub exec_specdays: Vec<u8>,
1715    /// Begin date.
1716    pub begin_date: Vec<u8>,
1717    /// End date.
1718    pub end_date: Vec<u8>,
1719}
1720
1721impl From<ScheduleTableEntry> for CosemDataType {
1722    fn from(e: ScheduleTableEntry) -> Self {
1723        CosemDataType::Structure(vec![
1724            CosemDataType::LongUnsigned(e.index),
1725            CosemDataType::Boolean(e.enable),
1726            CosemDataType::OctetString(e.script_logical_name.to_bytes()),
1727            CosemDataType::LongUnsigned(e.script_selector),
1728            CosemDataType::OctetString(e.switch_time),
1729            CosemDataType::LongUnsigned(e.validity_window),
1730            CosemDataType::BitString(e.exec_weekdays),
1731            CosemDataType::BitString(e.exec_specdays),
1732            CosemDataType::OctetString(e.begin_date),
1733            CosemDataType::OctetString(e.end_date),
1734        ])
1735    }
1736}
1737
1738impl TryFrom<&CosemDataType> for ScheduleTableEntry {
1739    type Error = String;
1740    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1741        match value {
1742            CosemDataType::Structure(fields) if fields.len() >= 10 => {
1743                let index = match &fields[0] {
1744                    CosemDataType::LongUnsigned(v) => *v,
1745                    _ => return Err("index must be long-unsigned".to_string()),
1746                };
1747                let enable = match &fields[1] {
1748                    CosemDataType::Boolean(v) => *v,
1749                    _ => return Err("enable must be boolean".to_string()),
1750                };
1751                let script_logical_name = match &fields[2] {
1752                    CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
1753                        ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
1754                    }
1755                    _ => return Err("script_logical_name must be 6-byte octet-string".to_string()),
1756                };
1757                let script_selector = match &fields[3] {
1758                    CosemDataType::LongUnsigned(v) => *v,
1759                    _ => return Err("script_selector must be long-unsigned".to_string()),
1760                };
1761                let switch_time = match &fields[4] {
1762                    CosemDataType::OctetString(v) => v.clone(),
1763                    _ => return Err("switch_time must be octet-string".to_string()),
1764                };
1765                let validity_window = match &fields[5] {
1766                    CosemDataType::LongUnsigned(v) => *v,
1767                    _ => return Err("validity_window must be long-unsigned".to_string()),
1768                };
1769                let exec_weekdays = match &fields[6] {
1770                    CosemDataType::BitString(v) => v.clone(),
1771                    _ => return Err("exec_weekdays must be bit-string".to_string()),
1772                };
1773                let exec_specdays = match &fields[7] {
1774                    CosemDataType::BitString(v) => v.clone(),
1775                    _ => return Err("exec_specdays must be bit-string".to_string()),
1776                };
1777                let begin_date = match &fields[8] {
1778                    CosemDataType::OctetString(v) => v.clone(),
1779                    _ => return Err("begin_date must be octet-string".to_string()),
1780                };
1781                let end_date = match &fields[9] {
1782                    CosemDataType::OctetString(v) => v.clone(),
1783                    _ => return Err("end_date must be octet-string".to_string()),
1784                };
1785                Ok(ScheduleTableEntry {
1786                    index,
1787                    enable,
1788                    script_logical_name,
1789                    script_selector,
1790                    switch_time,
1791                    validity_window,
1792                    exec_weekdays,
1793                    exec_specdays,
1794                    begin_date,
1795                    end_date,
1796                })
1797            }
1798            _ => Err("expected 10-element structure for schedule_table_entry".to_string()),
1799        }
1800    }
1801}
1802
1803/// `spec_day_entry` — structure { index, specialday_date, day_id }
1804/// Used in Special Days Table (attr 2).
1805#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1806pub struct SpecialDayEntry {
1807    /// Entry index.
1808    pub index: u16,
1809    /// Special day date.
1810    pub specialday_date: Vec<u8>,
1811    /// Day profile ID to use.
1812    pub day_id: u8,
1813}
1814
1815impl From<SpecialDayEntry> for CosemDataType {
1816    fn from(e: SpecialDayEntry) -> Self {
1817        CosemDataType::Structure(vec![
1818            CosemDataType::LongUnsigned(e.index),
1819            CosemDataType::OctetString(e.specialday_date),
1820            CosemDataType::Unsigned(e.day_id),
1821        ])
1822    }
1823}
1824
1825impl TryFrom<&CosemDataType> for SpecialDayEntry {
1826    type Error = String;
1827    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1828        match value {
1829            CosemDataType::Structure(fields) if fields.len() >= 3 => {
1830                let index = match &fields[0] {
1831                    CosemDataType::LongUnsigned(v) => *v,
1832                    _ => return Err("index must be long-unsigned".to_string()),
1833                };
1834                let specialday_date = match &fields[1] {
1835                    CosemDataType::OctetString(v) => v.clone(),
1836                    _ => return Err("specialday_date must be octet-string".to_string()),
1837                };
1838                let day_id = match &fields[2] {
1839                    CosemDataType::Unsigned(v) => *v,
1840                    _ => return Err("day_id must be unsigned".to_string()),
1841                };
1842                Ok(SpecialDayEntry { index, specialday_date, day_id })
1843            }
1844            _ => Err("expected structure {index, specialday_date, day_id}".to_string()),
1845        }
1846    }
1847}
1848
1849/// `season_profile` — structure { season_profile_name, season_start, week_name }
1850/// Used in Activity Calendar (attr 3/7).
1851#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1852pub struct SeasonProfile {
1853    /// Season profile name.
1854    pub season_profile_name: Vec<u8>,
1855    /// Season start date-time.
1856    pub season_start: Vec<u8>,
1857    /// Week profile name to use.
1858    pub week_name: Vec<u8>,
1859}
1860
1861impl From<SeasonProfile> for CosemDataType {
1862    fn from(sp: SeasonProfile) -> Self {
1863        CosemDataType::Structure(vec![
1864            CosemDataType::OctetString(sp.season_profile_name),
1865            CosemDataType::OctetString(sp.season_start),
1866            CosemDataType::OctetString(sp.week_name),
1867        ])
1868    }
1869}
1870
1871impl TryFrom<&CosemDataType> for SeasonProfile {
1872    type Error = String;
1873    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1874        match value {
1875            CosemDataType::Structure(fields) if fields.len() >= 3 => {
1876                let season_profile_name = match &fields[0] {
1877                    CosemDataType::OctetString(v) => v.clone(),
1878                    _ => return Err("season_profile_name must be octet-string".to_string()),
1879                };
1880                let season_start = match &fields[1] {
1881                    CosemDataType::OctetString(v) => v.clone(),
1882                    _ => return Err("season_start must be octet-string".to_string()),
1883                };
1884                let week_name = match &fields[2] {
1885                    CosemDataType::OctetString(v) => v.clone(),
1886                    _ => return Err("week_name must be octet-string".to_string()),
1887                };
1888                Ok(SeasonProfile { season_profile_name, season_start, week_name })
1889            }
1890            _ => Err("expected structure for season_profile".to_string()),
1891        }
1892    }
1893}
1894
1895/// `week_profile` — structure { week_profile_name, monday..sunday: day_id }
1896/// Used in Activity Calendar (attr 4/8).
1897#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1898pub struct WeekProfile {
1899    /// Week profile name.
1900    pub week_profile_name: Vec<u8>,
1901    /// Day profile ID for Monday.
1902    pub monday: u8,
1903    /// Day profile ID for Tuesday.
1904    pub tuesday: u8,
1905    /// Day profile ID for Wednesday.
1906    pub wednesday: u8,
1907    /// Day profile ID for Thursday.
1908    pub thursday: u8,
1909    /// Day profile ID for Friday.
1910    pub friday: u8,
1911    /// Day profile ID for Saturday.
1912    pub saturday: u8,
1913    /// Day profile ID for Sunday.
1914    pub sunday: u8,
1915}
1916
1917impl From<WeekProfile> for CosemDataType {
1918    fn from(wp: WeekProfile) -> Self {
1919        CosemDataType::Structure(vec![
1920            CosemDataType::OctetString(wp.week_profile_name),
1921            CosemDataType::Unsigned(wp.monday),
1922            CosemDataType::Unsigned(wp.tuesday),
1923            CosemDataType::Unsigned(wp.wednesday),
1924            CosemDataType::Unsigned(wp.thursday),
1925            CosemDataType::Unsigned(wp.friday),
1926            CosemDataType::Unsigned(wp.saturday),
1927            CosemDataType::Unsigned(wp.sunday),
1928        ])
1929    }
1930}
1931
1932impl TryFrom<&CosemDataType> for WeekProfile {
1933    type Error = String;
1934    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1935        match value {
1936            CosemDataType::Structure(fields) if fields.len() >= 8 => {
1937                let week_profile_name = match &fields[0] {
1938                    CosemDataType::OctetString(v) => v.clone(),
1939                    _ => return Err("week_profile_name must be octet-string".to_string()),
1940                };
1941                let get_u8 = |f: &CosemDataType| -> Result<u8, String> {
1942                    match f {
1943                        CosemDataType::Unsigned(v) => Ok(*v),
1944                        _ => Err("day_id must be unsigned".to_string()),
1945                    }
1946                };
1947                Ok(WeekProfile {
1948                    week_profile_name,
1949                    monday: get_u8(&fields[1])?,
1950                    tuesday: get_u8(&fields[2])?,
1951                    wednesday: get_u8(&fields[3])?,
1952                    thursday: get_u8(&fields[4])?,
1953                    friday: get_u8(&fields[5])?,
1954                    saturday: get_u8(&fields[6])?,
1955                    sunday: get_u8(&fields[7])?,
1956                })
1957            }
1958            _ => Err("expected 8-element structure for week_profile".to_string()),
1959        }
1960    }
1961}
1962
1963/// `day_profile_action` — structure { start_time, script_logical_name, script_selector }
1964/// Used inside `day_profile`.
1965#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1966pub struct DayProfileAction {
1967    /// Start time of the action.
1968    pub start_time: Vec<u8>,
1969    /// Logical name of the Script Table.
1970    pub script_logical_name: ObisCode,
1971    /// Script selector.
1972    pub script_selector: u16,
1973}
1974
1975impl From<DayProfileAction> for CosemDataType {
1976    fn from(a: DayProfileAction) -> Self {
1977        CosemDataType::Structure(vec![
1978            CosemDataType::OctetString(a.start_time),
1979            CosemDataType::OctetString(a.script_logical_name.to_bytes()),
1980            CosemDataType::LongUnsigned(a.script_selector),
1981        ])
1982    }
1983}
1984
1985impl TryFrom<&CosemDataType> for DayProfileAction {
1986    type Error = String;
1987    fn try_from(value: &CosemDataType) -> Result<Self, String> {
1988        match value {
1989            CosemDataType::Structure(fields) if fields.len() >= 3 => {
1990                let start_time = match &fields[0] {
1991                    CosemDataType::OctetString(v) => v.clone(),
1992                    _ => return Err("start_time must be octet-string".to_string()),
1993                };
1994                let script_logical_name = match &fields[1] {
1995                    CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
1996                        ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
1997                    }
1998                    _ => return Err("script_logical_name must be 6-byte octet-string".to_string()),
1999                };
2000                let script_selector = match &fields[2] {
2001                    CosemDataType::LongUnsigned(v) => *v,
2002                    _ => return Err("script_selector must be long-unsigned".to_string()),
2003                };
2004                Ok(DayProfileAction { start_time, script_logical_name, script_selector })
2005            }
2006            _ => Err("expected structure for day_profile_action".to_string()),
2007        }
2008    }
2009}
2010
2011/// `day_profile` — structure { day_id, day_schedule: array day_profile_action }
2012/// Used in Activity Calendar (attr 5/9).
2013#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2014pub struct DayProfile {
2015    /// Day profile identifier.
2016    pub day_id: u8,
2017    /// Ordered list of day schedule actions.
2018    pub day_schedule: Vec<DayProfileAction>,
2019}
2020
2021impl From<DayProfile> for CosemDataType {
2022    fn from(dp: DayProfile) -> Self {
2023        CosemDataType::Structure(vec![
2024            CosemDataType::Unsigned(dp.day_id),
2025            CosemDataType::Array(dp.day_schedule.into_iter().map(CosemDataType::from).collect()),
2026        ])
2027    }
2028}
2029
2030impl TryFrom<&CosemDataType> for DayProfile {
2031    type Error = String;
2032    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2033        match value {
2034            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2035                let day_id = match &fields[0] {
2036                    CosemDataType::Unsigned(v) => *v,
2037                    _ => return Err("day_id must be unsigned".to_string()),
2038                };
2039                let day_schedule = match &fields[1] {
2040                    CosemDataType::Array(items) => {
2041                        items.iter().map(DayProfileAction::try_from).collect::<Result<Vec<_>, _>>()?
2042                    }
2043                    _ => return Err("day_schedule must be array".to_string()),
2044                };
2045                Ok(DayProfile { day_id, day_schedule })
2046            }
2047            _ => Err("expected structure {day_id, day_schedule}".to_string()),
2048        }
2049    }
2050}
2051
2052/// `send_destination_and_method` — structure { transport_service, destination, message }
2053/// Used in Push Setup (attr 3).
2054#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2055pub struct SendDestinationAndMethod {
2056    /// Transport service identifier.
2057    pub transport_service: u8,
2058    /// Destination address or identifier.
2059    pub destination: Vec<u8>,
2060    /// Message type.
2061    pub message: u8,
2062}
2063
2064impl From<SendDestinationAndMethod> for CosemDataType {
2065    fn from(s: SendDestinationAndMethod) -> Self {
2066        CosemDataType::Structure(vec![
2067            CosemDataType::Enum(s.transport_service),
2068            CosemDataType::OctetString(s.destination),
2069            CosemDataType::Enum(s.message),
2070        ])
2071    }
2072}
2073
2074impl TryFrom<&CosemDataType> for SendDestinationAndMethod {
2075    type Error = String;
2076    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2077        match value {
2078            CosemDataType::Structure(fields) if fields.len() >= 3 => {
2079                let transport_service = match &fields[0] {
2080                    CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
2081                    _ => return Err("transport_service must be enum".to_string()),
2082                };
2083                let destination = match &fields[1] {
2084                    CosemDataType::OctetString(v) => v.clone(),
2085                    _ => return Err("destination must be octet-string".to_string()),
2086                };
2087                let message = match &fields[2] {
2088                    CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
2089                    _ => return Err("message must be enum".to_string()),
2090                };
2091                Ok(SendDestinationAndMethod { transport_service, destination, message })
2092            }
2093            _ => Err("expected structure for send_destination_and_method".to_string()),
2094        }
2095    }
2096}
2097
2098/// `communication_window` entry — structure { begin, end: date-time }
2099/// Used in Push Setup (attr 4).
2100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2101pub struct CommunicationWindow {
2102    /// Begin date-time of the communication window.
2103    pub begin: DateTime,
2104    /// End date-time of the communication window.
2105    pub end: DateTime,
2106}
2107
2108impl From<CommunicationWindow> for CosemDataType {
2109    fn from(cw: CommunicationWindow) -> Self {
2110        // Blue Book / openspodes: window bounds are octet-string SIZE(12).
2111        CosemDataType::Structure(vec![
2112            CosemDataType::OctetString(cw.begin.0.to_vec()),
2113            CosemDataType::OctetString(cw.end.0.to_vec()),
2114        ])
2115    }
2116}
2117
2118impl TryFrom<&CosemDataType> for CommunicationWindow {
2119    type Error = String;
2120    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2121        match value {
2122            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2123                let begin = DateTime::try_from(&fields[0])?;
2124                let end = DateTime::try_from(&fields[1])?;
2125                Ok(CommunicationWindow { begin, end })
2126            }
2127            _ => Err("expected structure {begin, end}".to_string()),
2128        }
2129    }
2130}
2131
2132/// `emergency_profile` — structure { emergency_profile_id, emergency_activation_time, emergency_duration }
2133/// Used in Limiter (attr 8).
2134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2135pub struct EmergencyProfile {
2136    /// Emergency profile group ID.
2137    pub emergency_profile_id: u16,
2138    /// Emergency activation time.
2139    pub emergency_activation_time: Vec<u8>,
2140    /// Emergency duration in seconds.
2141    pub emergency_duration: u32,
2142}
2143
2144impl From<EmergencyProfile> for CosemDataType {
2145    fn from(ep: EmergencyProfile) -> Self {
2146        CosemDataType::Structure(vec![
2147            CosemDataType::LongUnsigned(ep.emergency_profile_id),
2148            CosemDataType::OctetString(ep.emergency_activation_time),
2149            CosemDataType::DoubleLongUnsigned(ep.emergency_duration),
2150        ])
2151    }
2152}
2153
2154impl TryFrom<&CosemDataType> for EmergencyProfile {
2155    type Error = String;
2156    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2157        match value {
2158            CosemDataType::Structure(fields) if fields.len() >= 3 => {
2159                let emergency_profile_id = match &fields[0] {
2160                    CosemDataType::LongUnsigned(v) => *v,
2161                    _ => return Err("emergency_profile_id must be long-unsigned".to_string()),
2162                };
2163                let emergency_activation_time = match &fields[1] {
2164                    CosemDataType::OctetString(v) => v.clone(),
2165                    _ => return Err("emergency_activation_time must be octet-string".to_string()),
2166                };
2167                let emergency_duration = match &fields[2] {
2168                    CosemDataType::DoubleLongUnsigned(v) => *v,
2169                    _ => return Err("emergency_duration must be double-long-unsigned".to_string()),
2170                };
2171                Ok(EmergencyProfile { emergency_profile_id, emergency_activation_time, emergency_duration })
2172            }
2173            _ => Err("expected structure for emergency_profile".to_string()),
2174        }
2175    }
2176}
2177
2178/// `limiter_action` — structure { action_over_threshold, action_under_threshold }
2179/// Used in Limiter (attr 11).
2180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2181pub struct LimiterAction {
2182    /// Action to execute when threshold is exceeded.
2183    pub action_over_threshold: ActionItem,
2184    /// Action to execute when value returns below threshold.
2185    pub action_under_threshold: ActionItem,
2186}
2187
2188impl From<LimiterAction> for CosemDataType {
2189    fn from(a: LimiterAction) -> Self {
2190        CosemDataType::Structure(vec![
2191            CosemDataType::from(a.action_over_threshold),
2192            CosemDataType::from(a.action_under_threshold),
2193        ])
2194    }
2195}
2196
2197impl TryFrom<&CosemDataType> for LimiterAction {
2198    type Error = String;
2199    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2200        match value {
2201            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2202                let action_over_threshold = ActionItem::try_from(&fields[0])?;
2203                let action_under_threshold = ActionItem::try_from(&fields[1])?;
2204                Ok(LimiterAction { action_over_threshold, action_under_threshold })
2205            }
2206            _ => Err("expected structure {action_over_threshold, action_under_threshold}".to_string()),
2207        }
2208    }
2209}
2210
2211/// `object_definition` — structure { class_id, logical_name }
2212/// Used in Register Activation (attr 2).
2213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2214pub struct ObjectDefinition {
2215    /// COSEM class identifier.
2216    pub class_id: u16,
2217    /// OBIS logical name.
2218    pub logical_name: ObisCode,
2219}
2220
2221impl From<ObjectDefinition> for CosemDataType {
2222    fn from(od: ObjectDefinition) -> Self {
2223        CosemDataType::Structure(vec![
2224            CosemDataType::LongUnsigned(od.class_id),
2225            CosemDataType::OctetString(od.logical_name.to_bytes()),
2226        ])
2227    }
2228}
2229
2230impl TryFrom<&CosemDataType> for ObjectDefinition {
2231    type Error = String;
2232    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2233        match value {
2234            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2235                let class_id = match &fields[0] {
2236                    CosemDataType::LongUnsigned(v) => *v,
2237                    _ => return Err("class_id must be long-unsigned".to_string()),
2238                };
2239                let logical_name = match &fields[1] {
2240                    CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
2241                        ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
2242                    }
2243                    _ => return Err("logical_name must be 6-byte octet-string".to_string()),
2244                };
2245                Ok(ObjectDefinition { class_id, logical_name })
2246            }
2247            _ => Err("expected structure {class_id, logical_name}".to_string()),
2248        }
2249    }
2250}
2251
2252/// `register_act_mask` — structure { mask_name, index_list: array unsigned }
2253/// Used in Register Activation (attr 3).
2254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2255pub struct RegisterActMask {
2256    /// Mask name (visible string).
2257    pub mask_name: Vec<u8>,
2258    /// List of attribute indexes for the mask.
2259    pub index_list: Vec<u8>,
2260}
2261
2262impl From<RegisterActMask> for CosemDataType {
2263    fn from(m: RegisterActMask) -> Self {
2264        CosemDataType::Structure(vec![
2265            CosemDataType::OctetString(m.mask_name),
2266            CosemDataType::Array(m.index_list.into_iter().map(CosemDataType::Unsigned).collect()),
2267        ])
2268    }
2269}
2270
2271impl TryFrom<&CosemDataType> for RegisterActMask {
2272    type Error = String;
2273    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2274        match value {
2275            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2276                let mask_name = match &fields[0] {
2277                    CosemDataType::OctetString(v) => v.clone(),
2278                    _ => return Err("mask_name must be octet-string".to_string()),
2279                };
2280                let index_list = match &fields[1] {
2281                    CosemDataType::Array(items) => items
2282                        .iter()
2283                        .map(|item| match item {
2284                            CosemDataType::Unsigned(v) => Ok(*v),
2285                            _ => Err("index must be unsigned".to_string()),
2286                        })
2287                        .collect::<Result<Vec<_>, _>>()?,
2288                    _ => return Err("index_list must be array".to_string()),
2289                };
2290                Ok(RegisterActMask { mask_name, index_list })
2291            }
2292            _ => Err("expected structure {mask_name, index_list}".to_string()),
2293        }
2294    }
2295}
2296
2297/// `image_to_activate_info` entry — structure { image_block_number, image_block_value }
2298/// Used in Image Transfer (attr 7).
2299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2300pub struct ImageToActivateInfo {
2301    /// Image block number.
2302    pub image_block_number: u32,
2303    /// Image block data.
2304    pub image_block_value: Vec<u8>,
2305}
2306
2307impl From<ImageToActivateInfo> for CosemDataType {
2308    fn from(info: ImageToActivateInfo) -> Self {
2309        CosemDataType::Structure(vec![
2310            CosemDataType::DoubleLongUnsigned(info.image_block_number),
2311            CosemDataType::OctetString(info.image_block_value),
2312        ])
2313    }
2314}
2315
2316impl TryFrom<&CosemDataType> for ImageToActivateInfo {
2317    type Error = String;
2318    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2319        match value {
2320            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2321                let image_block_number = match &fields[0] {
2322                    CosemDataType::DoubleLongUnsigned(v) => *v,
2323                    _ => return Err("image_block_number must be double-long-unsigned".to_string()),
2324                };
2325                let image_block_value = match &fields[1] {
2326                    CosemDataType::OctetString(v) => v.clone(),
2327                    _ => return Err("image_block_value must be octet-string".to_string()),
2328                };
2329                Ok(ImageToActivateInfo { image_block_number, image_block_value })
2330            }
2331            _ => Err("expected structure for image_to_activate_info".to_string()),
2332        }
2333    }
2334}
2335
2336/// `single_action_schedule_executed_script` — structure { script_logical_name, script_selector }
2337/// Used in Single Action Schedule (attr 2).
2338#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2339pub struct ExecutedScript {
2340    /// Logical name of the Script Table.
2341    pub script_logical_name: ObisCode,
2342    /// Script selector.
2343    pub script_selector: u16,
2344}
2345
2346impl From<ExecutedScript> for CosemDataType {
2347    fn from(es: ExecutedScript) -> Self {
2348        CosemDataType::Structure(vec![
2349            CosemDataType::OctetString(es.script_logical_name.to_bytes()),
2350            CosemDataType::LongUnsigned(es.script_selector),
2351        ])
2352    }
2353}
2354
2355impl TryFrom<&CosemDataType> for ExecutedScript {
2356    type Error = String;
2357    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2358        match value {
2359            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2360                let script_logical_name = match &fields[0] {
2361                    CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
2362                        ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
2363                    }
2364                    _ => return Err("script_logical_name must be 6-byte octet-string".to_string()),
2365                };
2366                let script_selector = match &fields[1] {
2367                    CosemDataType::LongUnsigned(v) => *v,
2368                    _ => return Err("script_selector must be long-unsigned".to_string()),
2369                };
2370                Ok(ExecutedScript { script_logical_name, script_selector })
2371            }
2372            _ => Err("expected structure {script_logical_name, script_selector}".to_string()),
2373        }
2374    }
2375}
2376
2377/// `sap_assignment_entry` — structure { SAP: long-unsigned, logical_device_name: octet-string }
2378/// Used in SAP Assignment (attr 2).
2379#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2380pub struct SapAssignmentEntry {
2381    /// SAP address.
2382    pub sap: u16,
2383    /// Logical device name.
2384    pub logical_device_name: Vec<u8>,
2385}
2386
2387impl From<SapAssignmentEntry> for CosemDataType {
2388    fn from(entry: SapAssignmentEntry) -> Self {
2389        CosemDataType::Structure(vec![
2390            CosemDataType::LongUnsigned(entry.sap),
2391            CosemDataType::OctetString(entry.logical_device_name),
2392        ])
2393    }
2394}
2395
2396impl TryFrom<&CosemDataType> for SapAssignmentEntry {
2397    type Error = String;
2398    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2399        match value {
2400            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2401                let sap = match &fields[0] {
2402                    CosemDataType::LongUnsigned(v) => *v,
2403                    CosemDataType::Unsigned(v) => u16::from(*v),
2404                    _ => return Err("SAP must be long-unsigned".to_string()),
2405                };
2406                let logical_device_name = match &fields[1] {
2407                    CosemDataType::OctetString(v) => v.clone(),
2408                    _ => return Err("logical_device_name must be octet-string".to_string()),
2409                };
2410                Ok(SapAssignmentEntry { sap, logical_device_name })
2411            }
2412            _ => Err("expected structure {SAP, logical_device_name}".to_string()),
2413        }
2414    }
2415}
2416
2417/// `gsm_adjacent_cell` — structure { cell_id, signal_quality, signal_strength }
2418/// Used in GSM Diagnostic (attr 9).
2419#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2420pub struct GsmAdjacentCell {
2421    /// Cell ID.
2422    pub cell_id: Vec<u8>,
2423    /// Signal quality.
2424    pub signal_quality: Vec<u8>,
2425    /// Signal strength.
2426    pub signal_strength: Vec<u8>,
2427}
2428
2429impl From<GsmAdjacentCell> for CosemDataType {
2430    fn from(cell: GsmAdjacentCell) -> Self {
2431        CosemDataType::Structure(vec![
2432            CosemDataType::OctetString(cell.cell_id),
2433            CosemDataType::OctetString(cell.signal_quality),
2434            CosemDataType::OctetString(cell.signal_strength),
2435        ])
2436    }
2437}
2438
2439impl TryFrom<&CosemDataType> for GsmAdjacentCell {
2440    type Error = String;
2441    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2442        match value {
2443            CosemDataType::Structure(fields) if fields.len() >= 3 => {
2444                let cell_id = match &fields[0] {
2445                    CosemDataType::OctetString(v) => v.clone(),
2446                    _ => return Err("cell_id must be octet-string".to_string()),
2447                };
2448                let signal_quality = match &fields[1] {
2449                    CosemDataType::OctetString(v) => v.clone(),
2450                    _ => return Err("signal_quality must be octet-string".to_string()),
2451                };
2452                let signal_strength = match &fields[2] {
2453                    CosemDataType::OctetString(v) => v.clone(),
2454                    _ => return Err("signal_strength must be octet-string".to_string()),
2455                };
2456                Ok(GsmAdjacentCell { cell_id, signal_quality, signal_strength })
2457            }
2458            _ => Err("expected structure {cell_id, signal_quality, signal_strength}".to_string()),
2459        }
2460    }
2461}
2462
2463/// `protection_object` — structure { class_id, logical_name, attribute_index }
2464/// Used in Data Protection and Security Setup.
2465#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2466pub struct ProtectionObject {
2467    /// COSEM class identifier.
2468    pub class_id: u16,
2469    /// OBIS logical name.
2470    pub logical_name: ObisCode,
2471    /// Attribute index.
2472    pub attribute_index: i8,
2473}
2474
2475impl From<ProtectionObject> for CosemDataType {
2476    fn from(po: ProtectionObject) -> Self {
2477        CosemDataType::Structure(vec![
2478            CosemDataType::LongUnsigned(po.class_id),
2479            CosemDataType::OctetString(po.logical_name.to_bytes()),
2480            CosemDataType::Integer(po.attribute_index),
2481        ])
2482    }
2483}
2484
2485impl TryFrom<&CosemDataType> for ProtectionObject {
2486    type Error = String;
2487    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2488        match value {
2489            CosemDataType::Structure(fields) if fields.len() >= 3 => {
2490                let class_id = match &fields[0] {
2491                    CosemDataType::LongUnsigned(v) => *v,
2492                    _ => return Err("class_id must be long-unsigned".to_string()),
2493                };
2494                let logical_name = match &fields[1] {
2495                    CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
2496                        ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
2497                    }
2498                    _ => return Err("logical_name must be 6-byte octet-string".to_string()),
2499                };
2500                let attribute_index = match &fields[2] {
2501                    CosemDataType::Integer(v) => *v,
2502                    CosemDataType::Long(v) => {
2503                        i8::try_from(*v).map_err(|_| "attribute_index must be integer".to_string())?
2504                    }
2505                    _ => return Err("attribute_index must be integer".to_string()),
2506                };
2507                Ok(ProtectionObject { class_id, logical_name, attribute_index })
2508            }
2509            _ => Err("expected structure {class_id, logical_name, attribute_index}".to_string()),
2510        }
2511    }
2512}
2513
2514/// `ip_option` — structure { option_type: unsigned, option_value: octet-string }
2515/// Used in IPv4/IPv6 setup.
2516#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2517pub struct IpOption {
2518    /// IP option type code.
2519    pub option_type: u8,
2520    /// IP option value data.
2521    pub option_value: Vec<u8>,
2522}
2523
2524impl From<IpOption> for CosemDataType {
2525    fn from(opt: IpOption) -> Self {
2526        CosemDataType::Structure(vec![
2527            CosemDataType::Unsigned(opt.option_type),
2528            CosemDataType::OctetString(opt.option_value),
2529        ])
2530    }
2531}
2532
2533impl TryFrom<&CosemDataType> for IpOption {
2534    type Error = String;
2535    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2536        match value {
2537            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2538                let option_type = match &fields[0] {
2539                    CosemDataType::Unsigned(v) => *v,
2540                    _ => return Err("option_type must be unsigned".to_string()),
2541                };
2542                let option_value = match &fields[1] {
2543                    CosemDataType::OctetString(v) => v.clone(),
2544                    _ => return Err("option_value must be octet-string".to_string()),
2545                };
2546                Ok(IpOption { option_type, option_value })
2547            }
2548            _ => Err("expected structure {option_type, option_value}".to_string()),
2549        }
2550    }
2551}
2552
2553/// `neighbor_discovery_setup` — structure { ip_address, hardware_address }
2554/// Used in IPv6 neighbor discovery.
2555#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2556pub struct NeighborDiscoverySetup {
2557    /// IP address of the neighbor.
2558    pub ip_address: Vec<u8>,
2559    /// Hardware (MAC) address.
2560    pub hardware_address: Vec<u8>,
2561}
2562
2563impl From<NeighborDiscoverySetup> for CosemDataType {
2564    fn from(nd: NeighborDiscoverySetup) -> Self {
2565        CosemDataType::Structure(vec![
2566            CosemDataType::OctetString(nd.ip_address),
2567            CosemDataType::OctetString(nd.hardware_address),
2568        ])
2569    }
2570}
2571
2572impl TryFrom<&CosemDataType> for NeighborDiscoverySetup {
2573    type Error = String;
2574    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2575        match value {
2576            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2577                let ip_address = match &fields[0] {
2578                    CosemDataType::OctetString(v) => v.clone(),
2579                    _ => return Err("ip_address must be octet-string".to_string()),
2580                };
2581                let hardware_address = match &fields[1] {
2582                    CosemDataType::OctetString(v) => v.clone(),
2583                    _ => return Err("hardware_address must be octet-string".to_string()),
2584                };
2585                Ok(NeighborDiscoverySetup { ip_address, hardware_address })
2586            }
2587            _ => Err("expected structure {ip_address, hardware_address}".to_string()),
2588        }
2589    }
2590}
2591
2592// ============================================================================
2593// Additional typed structures (Association LN v2, schedules, GPRS, GSM, etc.)
2594// ============================================================================
2595
2596/// User entry for Association LN v2 user_list.
2597/// Structure { user_id: unsigned, user_name: visible-string }
2598#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2599pub struct User {
2600    /// User identifier.
2601    pub user_id: u8,
2602    /// User name (visible string).
2603    pub user_name: Vec<u8>,
2604}
2605
2606impl From<User> for CosemDataType {
2607    fn from(u: User) -> Self {
2608        CosemDataType::Structure(vec![CosemDataType::Unsigned(u.user_id), CosemDataType::OctetString(u.user_name)])
2609    }
2610}
2611
2612impl TryFrom<&CosemDataType> for User {
2613    type Error = String;
2614
2615    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2616        match value {
2617            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2618                let user_id = match &fields[0] {
2619                    CosemDataType::Unsigned(v) => *v,
2620                    _ => return Err("user_id must be unsigned".to_string()),
2621                };
2622                let user_name = match &fields[1] {
2623                    CosemDataType::OctetString(v) => v.clone(),
2624                    _ => return Err("user_name must be octet-string".to_string()),
2625                };
2626                Ok(User { user_id, user_name })
2627            }
2628            _ => Err("expected structure {user_id, user_name}".to_string()),
2629        }
2630    }
2631}
2632
2633/// Execution time structure for Single Action Schedule.
2634/// Structure { time: octet-string, date: octet-string }
2635#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2636pub struct ExecutionTime {
2637    /// Time value (octet-string).
2638    pub time: Vec<u8>,
2639    /// Date value (octet-string).
2640    pub date: Vec<u8>,
2641}
2642
2643impl From<ExecutionTime> for CosemDataType {
2644    fn from(et: ExecutionTime) -> Self {
2645        CosemDataType::Structure(vec![CosemDataType::OctetString(et.time), CosemDataType::OctetString(et.date)])
2646    }
2647}
2648
2649impl TryFrom<&CosemDataType> for ExecutionTime {
2650    type Error = String;
2651
2652    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2653        match value {
2654            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2655                let time = match &fields[0] {
2656                    CosemDataType::OctetString(v) => v.clone(),
2657                    _ => return Err("time must be octet-string".to_string()),
2658                };
2659                let date = match &fields[1] {
2660                    CosemDataType::OctetString(v) => v.clone(),
2661                    _ => return Err("date must be octet-string".to_string()),
2662                };
2663                Ok(ExecutionTime { time, date })
2664            }
2665            _ => Err("expected structure {time, date}".to_string()),
2666        }
2667    }
2668}
2669
2670/// GSM service parameter for GPRS Modem Setup.
2671/// Structure { delay_class, reliability_class, precedence_class, peak_throughput, mean_throughput }
2672#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2673pub struct GsmServiceParameter {
2674    /// Delay class.
2675    pub delay_class: u8,
2676    /// Reliability class.
2677    pub reliability_class: u8,
2678    /// Precedence class.
2679    pub precedence_class: u8,
2680    /// Peak throughput class.
2681    pub peak_throughput: u8,
2682    /// Mean throughput class.
2683    pub mean_throughput: u8,
2684}
2685
2686impl From<GsmServiceParameter> for CosemDataType {
2687    fn from(p: GsmServiceParameter) -> Self {
2688        CosemDataType::Structure(vec![
2689            CosemDataType::Unsigned(p.delay_class),
2690            CosemDataType::Unsigned(p.reliability_class),
2691            CosemDataType::Unsigned(p.precedence_class),
2692            CosemDataType::Unsigned(p.peak_throughput),
2693            CosemDataType::Unsigned(p.mean_throughput),
2694        ])
2695    }
2696}
2697
2698impl TryFrom<&CosemDataType> for GsmServiceParameter {
2699    type Error = String;
2700
2701    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2702        match value {
2703            CosemDataType::Structure(fields) if fields.len() >= 5 => {
2704                let get_u8 = |f: &CosemDataType| -> Result<u8, String> {
2705                    match f {
2706                        CosemDataType::Unsigned(v) => Ok(*v),
2707                        _ => Err("must be unsigned".to_string()),
2708                    }
2709                };
2710                Ok(GsmServiceParameter {
2711                    delay_class: get_u8(&fields[0])?,
2712                    reliability_class: get_u8(&fields[1])?,
2713                    precedence_class: get_u8(&fields[2])?,
2714                    peak_throughput: get_u8(&fields[3])?,
2715                    mean_throughput: get_u8(&fields[4])?,
2716                })
2717            }
2718            _ => Err("expected structure {delay_class, reliability_class, precedence_class, peak_throughput, mean_throughput}".to_string()),
2719        }
2720    }
2721}
2722
2723/// Quality of Service structure for GPRS Modem Setup.
2724/// Structure { default: gsm_service_parameter, requested: gsm_service_parameter }
2725#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2726pub struct QualityOfService {
2727    /// Default quality of service parameters.
2728    pub default: GsmServiceParameter,
2729    /// Requested quality of service parameters.
2730    pub requested: GsmServiceParameter,
2731}
2732
2733impl From<QualityOfService> for CosemDataType {
2734    fn from(qos: QualityOfService) -> Self {
2735        CosemDataType::Structure(vec![CosemDataType::from(qos.default), CosemDataType::from(qos.requested)])
2736    }
2737}
2738
2739impl TryFrom<&CosemDataType> for QualityOfService {
2740    type Error = String;
2741
2742    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2743        match value {
2744            CosemDataType::Structure(fields) if fields.len() >= 2 => {
2745                let default = GsmServiceParameter::try_from(&fields[0])?;
2746                let requested = GsmServiceParameter::try_from(&fields[1])?;
2747                Ok(QualityOfService { default, requested })
2748            }
2749            _ => Err("expected structure {default, requested}".to_string()),
2750        }
2751    }
2752}
2753
2754/// Cell information for GSM Diagnostic.
2755/// Structure with cell_id, location_id, imsi, imei, etc.
2756#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2757pub struct CellInfo {
2758    /// Cell ID.
2759    pub cell_id: Vec<u8>,
2760    /// Location area ID.
2761    pub location_id: Vec<u8>,
2762    /// IMSI.
2763    pub imsi: Vec<u8>,
2764    /// IMEI.
2765    pub imei: Vec<u8>,
2766    /// Routing area code.
2767    pub rn: Vec<u8>,
2768    /// Cell number.
2769    pub cn: Vec<u8>,
2770    /// Signal quality.
2771    pub signal_quality: Vec<u8>,
2772    /// Signal strength.
2773    pub signal_strength: Vec<u8>,
2774    /// Channel number.
2775    pub channel_number: Vec<u8>,
2776    /// Cell parameter ID.
2777    pub cell_parameter_id: Vec<u8>,
2778    /// Base station ID code.
2779    pub bsic: Vec<u8>,
2780    /// SIM card ICCID.
2781    pub iccid: Vec<u8>,
2782    /// Location area code.
2783    pub lac: Vec<u8>,
2784    /// Mobile country code.
2785    pub mcc: Vec<u8>,
2786    /// Mobile network code.
2787    pub mnc: Vec<u8>,
2788    /// Temporary mobile subscriber ID.
2789    pub tmsi: Vec<u8>,
2790    /// Temporary mobile group ID.
2791    pub tmgi: Vec<u8>,
2792    /// GPRS status.
2793    pub gprs_status: Vec<u8>,
2794    /// Routing area code.
2795    pub routing_area_code: Vec<u8>,
2796    /// Geographic address.
2797    pub geographic_address: Vec<u8>,
2798    /// Access point name.
2799    pub access_point_name: Vec<u8>,
2800    /// Data transport state.
2801    pub data_transport_state: Vec<u8>,
2802    /// NMA message.
2803    pub nma_message: Vec<u8>,
2804}
2805
2806impl From<CellInfo> for CosemDataType {
2807    fn from(ci: CellInfo) -> Self {
2808        CosemDataType::Structure(vec![
2809            CosemDataType::OctetString(ci.cell_id),
2810            CosemDataType::OctetString(ci.location_id),
2811            CosemDataType::OctetString(ci.imsi),
2812            CosemDataType::OctetString(ci.imei),
2813            CosemDataType::OctetString(ci.rn),
2814            CosemDataType::OctetString(ci.cn),
2815            CosemDataType::OctetString(ci.signal_quality),
2816            CosemDataType::OctetString(ci.signal_strength),
2817            CosemDataType::OctetString(ci.channel_number),
2818            CosemDataType::OctetString(ci.cell_parameter_id),
2819            CosemDataType::OctetString(ci.bsic),
2820            CosemDataType::OctetString(ci.iccid),
2821            CosemDataType::OctetString(ci.lac),
2822            CosemDataType::OctetString(ci.mcc),
2823            CosemDataType::OctetString(ci.mnc),
2824            CosemDataType::OctetString(ci.tmsi),
2825            CosemDataType::OctetString(ci.tmgi),
2826            CosemDataType::OctetString(ci.gprs_status),
2827            CosemDataType::OctetString(ci.routing_area_code),
2828            CosemDataType::OctetString(ci.geographic_address),
2829            CosemDataType::OctetString(ci.access_point_name),
2830            CosemDataType::OctetString(ci.data_transport_state),
2831            CosemDataType::OctetString(ci.nma_message),
2832        ])
2833    }
2834}
2835
2836impl TryFrom<&CosemDataType> for CellInfo {
2837    type Error = String;
2838
2839    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2840        match value {
2841            CosemDataType::Structure(fields) if fields.len() >= 23 => {
2842                let oct = |f: &CosemDataType| -> Result<Vec<u8>, String> {
2843                    match f {
2844                        CosemDataType::OctetString(v) => Ok(v.clone()),
2845                        _ => Err("must be octet-string".to_string()),
2846                    }
2847                };
2848                Ok(CellInfo {
2849                    cell_id: oct(&fields[0])?,
2850                    location_id: oct(&fields[1])?,
2851                    imsi: oct(&fields[2])?,
2852                    imei: oct(&fields[3])?,
2853                    rn: oct(&fields[4])?,
2854                    cn: oct(&fields[5])?,
2855                    signal_quality: oct(&fields[6])?,
2856                    signal_strength: oct(&fields[7])?,
2857                    channel_number: oct(&fields[8])?,
2858                    cell_parameter_id: oct(&fields[9])?,
2859                    bsic: oct(&fields[10])?,
2860                    iccid: oct(&fields[11])?,
2861                    lac: oct(&fields[12])?,
2862                    mcc: oct(&fields[13])?,
2863                    mnc: oct(&fields[14])?,
2864                    tmsi: oct(&fields[15])?,
2865                    tmgi: oct(&fields[16])?,
2866                    gprs_status: oct(&fields[17])?,
2867                    routing_area_code: oct(&fields[18])?,
2868                    geographic_address: oct(&fields[19])?,
2869                    access_point_name: oct(&fields[20])?,
2870                    data_transport_state: oct(&fields[21])?,
2871                    nma_message: oct(&fields[22])?,
2872                })
2873            }
2874            _ => Err("expected 23-element structure for CellInfo".to_string()),
2875        }
2876    }
2877}
2878
2879/// Push protection parameter (Push Setup v1+).
2880/// Structure { data: octet-string }
2881#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2882pub struct PushProtectionParameter {
2883    /// Protection data (octet-string).
2884    pub data: Vec<u8>,
2885}
2886
2887impl From<PushProtectionParameter> for CosemDataType {
2888    fn from(pp: PushProtectionParameter) -> Self {
2889        CosemDataType::Structure(vec![CosemDataType::OctetString(pp.data)])
2890    }
2891}
2892
2893impl TryFrom<&CosemDataType> for PushProtectionParameter {
2894    type Error = String;
2895
2896    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2897        match value {
2898            CosemDataType::Structure(fields) if !fields.is_empty() => {
2899                let data = match &fields[0] {
2900                    CosemDataType::OctetString(v) => v.clone(),
2901                    _ => return Err("data must be octet-string".to_string()),
2902                };
2903                Ok(PushProtectionParameter { data })
2904            }
2905            _ => Err("expected structure {data}".to_string()),
2906        }
2907    }
2908}
2909
2910/// Confirmation parameters for Push Setup v2.
2911/// Structure { data: octet-string }
2912#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2913pub struct ConfirmationParameters {
2914    /// Confirmation data (octet-string).
2915    pub data: Vec<u8>,
2916}
2917
2918impl From<ConfirmationParameters> for CosemDataType {
2919    fn from(cp: ConfirmationParameters) -> Self {
2920        CosemDataType::Structure(vec![CosemDataType::OctetString(cp.data)])
2921    }
2922}
2923
2924impl TryFrom<&CosemDataType> for ConfirmationParameters {
2925    type Error = String;
2926
2927    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2928        match value {
2929            CosemDataType::Structure(fields) if !fields.is_empty() => {
2930                let data = match &fields[0] {
2931                    CosemDataType::OctetString(v) => v.clone(),
2932                    _ => return Err("data must be octet-string".to_string()),
2933                };
2934                Ok(ConfirmationParameters { data })
2935            }
2936            _ => Err("expected structure {data}".to_string()),
2937        }
2938    }
2939}
2940
2941/// Certificate entry for Security Setup.
2942/// Structure { data: octet-string }
2943#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2944pub struct Certificate {
2945    /// Certificate data (octet-string).
2946    pub data: Vec<u8>,
2947}
2948
2949impl From<Certificate> for CosemDataType {
2950    fn from(c: Certificate) -> Self {
2951        CosemDataType::Structure(vec![CosemDataType::OctetString(c.data)])
2952    }
2953}
2954
2955impl TryFrom<&CosemDataType> for Certificate {
2956    type Error = String;
2957
2958    fn try_from(value: &CosemDataType) -> Result<Self, String> {
2959        match value {
2960            CosemDataType::Structure(fields) if !fields.is_empty() => {
2961                let data = match &fields[0] {
2962                    CosemDataType::OctetString(v) => v.clone(),
2963                    _ => return Err("data must be octet-string".to_string()),
2964                };
2965                Ok(Certificate { data })
2966            }
2967            _ => Err("expected structure {data}".to_string()),
2968        }
2969    }
2970}
2971
2972#[cfg(test)]
2973mod tests {
2974    use super::*;
2975    use crate::obis::ObisCode;
2976
2977    // Helper: round-trip a value through CosemDataType and back
2978    fn round_trip<
2979        T: for<'a> TryFrom<&'a CosemDataType, Error = String> + Into<CosemDataType> + Clone + PartialEq + std::fmt::Debug,
2980    >(
2981        val: &T,
2982    ) {
2983        let cd: CosemDataType = val.clone().into();
2984        let back = T::try_from(&cd).expect("TryFrom should succeed");
2985        assert_eq!(*val, back);
2986    }
2987
2988    fn obis(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> ObisCode {
2989        ObisCode::new(a, b, c, d, e, f)
2990    }
2991
2992    // ========================================================================
2993    // DateTime
2994    // ========================================================================
2995
2996    #[test]
2997    fn datetime_round_trip() {
2998        let dt = DateTime::new([0x07, 0xE5, 0x05, 0x01, 0x02, 0x10, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00]);
2999        round_trip(&dt);
3000    }
3001
3002    #[test]
3003    fn datetime_from_ymdhms() {
3004        let dt = DateTime::from_ymdhms(2025, 5, 1, 16, 30, 0);
3005        assert_eq!(dt.0[0..2], 2025u16.to_be_bytes());
3006        assert_eq!(dt.0[2], 5);
3007        assert_eq!(dt.0[3], 1);
3008        assert_eq!(dt.0[5], 16);
3009        assert_eq!(dt.0[6], 30);
3010    }
3011
3012    #[test]
3013    fn datetime_try_from_octet_string() {
3014        let bytes = vec![0x07, 0xE5, 0x01, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
3015        let cd = CosemDataType::OctetString(bytes);
3016        let dt = DateTime::try_from(&cd).unwrap();
3017        assert_eq!(dt.0[0..2], [0x07, 0xE5]);
3018    }
3019
3020    #[test]
3021    fn datetime_try_from_wrong_length() {
3022        let cd = CosemDataType::OctetString(vec![0u8; 10]);
3023        assert!(DateTime::try_from(&cd).is_err());
3024    }
3025
3026    // ========================================================================
3027    // ScalerUnit
3028    // ========================================================================
3029
3030    #[test]
3031    fn scaler_unit_round_trip() {
3032        let su = ScalerUnit::new(-2, 30);
3033        round_trip(&su);
3034    }
3035
3036    #[test]
3037    fn scaler_unit_apply() {
3038        let su = ScalerUnit::new(-2, 30);
3039        assert_eq!(su.apply(100), 1.0);
3040        assert_eq!(su.apply(12345), 123.45);
3041    }
3042
3043    #[test]
3044    fn scaler_unit_from_structure() {
3045        let cd = CosemDataType::Structure(vec![CosemDataType::Integer(0), CosemDataType::Enum(27)]);
3046        let su = ScalerUnit::try_from(&cd).unwrap();
3047        assert_eq!(su.scaler, 0);
3048        assert_eq!(su.unit, 27);
3049    }
3050
3051    #[test]
3052    fn scaler_unit_accepts_in_range_long_scaler() {
3053        let cd = CosemDataType::Structure(vec![CosemDataType::Long(-2), CosemDataType::Enum(30)]);
3054        let su = ScalerUnit::try_from(&cd).unwrap();
3055        assert_eq!(su.scaler, -2);
3056    }
3057
3058    #[test]
3059    fn scaler_unit_rejects_out_of_range_long_scaler() {
3060        // A `Long` scaler outside i8's range must be rejected, not silently
3061        // truncated to a different (wrong) in-range value.
3062        let cd = CosemDataType::Structure(vec![CosemDataType::Long(200), CosemDataType::Enum(30)]);
3063        assert!(ScalerUnit::try_from(&cd).is_err());
3064    }
3065
3066    // ========================================================================
3067    // CaptureObjectDefinition
3068    // ========================================================================
3069
3070    #[test]
3071    fn capture_object_definition_round_trip() {
3072        let cod = CaptureObjectDefinition::new(3, obis(0, 0, 1, 0, 0, 255), 2, 0);
3073        round_trip(&cod);
3074    }
3075
3076    #[test]
3077    fn capture_object_definition_rejects_negative_attribute_index() {
3078        let cd = CosemDataType::Structure(vec![
3079            CosemDataType::LongUnsigned(3),
3080            CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
3081            CosemDataType::Integer(-1),
3082            CosemDataType::Unsigned(0),
3083        ]);
3084        assert!(CaptureObjectDefinition::try_from(&cd).is_err());
3085    }
3086
3087    #[test]
3088    fn capture_object_definition_rejects_out_of_range_data_index() {
3089        let cd = CosemDataType::Structure(vec![
3090            CosemDataType::LongUnsigned(3),
3091            CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
3092            CosemDataType::Unsigned(2),
3093            CosemDataType::LongUnsigned(300),
3094        ]);
3095        assert!(CaptureObjectDefinition::try_from(&cd).is_err());
3096    }
3097
3098    // ========================================================================
3099    // SortMethod
3100    // ========================================================================
3101
3102    #[test]
3103    fn sort_method_from_u8() {
3104        assert_eq!(SortMethod::from_u8(1), Some(SortMethod::Fifo));
3105        assert_eq!(SortMethod::from_u8(2), Some(SortMethod::Lifo));
3106        assert_eq!(SortMethod::from_u8(3), Some(SortMethod::Largest));
3107        assert_eq!(SortMethod::from_u8(4), Some(SortMethod::Smallest));
3108        assert_eq!(SortMethod::from_u8(5), Some(SortMethod::NearestToZero));
3109        assert_eq!(SortMethod::from_u8(6), Some(SortMethod::FarthestFromZero));
3110        assert_eq!(SortMethod::from_u8(0), None);
3111        assert_eq!(SortMethod::from_u8(7), None);
3112    }
3113
3114    // ========================================================================
3115    // AssociationStatus
3116    // ========================================================================
3117
3118    #[test]
3119    fn association_status_from_u8() {
3120        assert_eq!(AssociationStatus::from_u8(0), Some(AssociationStatus::NonAssociated));
3121        assert_eq!(AssociationStatus::from_u8(1), Some(AssociationStatus::AssociationPending));
3122        assert_eq!(AssociationStatus::from_u8(2), Some(AssociationStatus::Associated));
3123        assert_eq!(AssociationStatus::from_u8(3), None);
3124    }
3125
3126    // ========================================================================
3127    // ClockBase
3128    // ========================================================================
3129
3130    #[test]
3131    fn clock_base_from_u8() {
3132        assert_eq!(ClockBase::from_u8(0), Some(ClockBase::None));
3133        assert_eq!(ClockBase::from_u8(1), Some(ClockBase::InternalCrystal));
3134        assert_eq!(ClockBase::from_u8(2), Some(ClockBase::MainsFrequency));
3135        assert_eq!(ClockBase::from_u8(3), Some(ClockBase::Gps));
3136        assert_eq!(ClockBase::from_u8(4), Some(ClockBase::RadioClock));
3137        assert_eq!(ClockBase::from_u8(5), None);
3138    }
3139
3140    // ========================================================================
3141    // AccessRight + AttributeAccessItem + MethodAccessItem
3142    // ========================================================================
3143
3144    #[test]
3145    fn attribute_access_item_round_trip() {
3146        let item = AttributeAccessItem { attribute_id: 2, access_mode: 1, access_selectors: None };
3147        round_trip(&item);
3148    }
3149
3150    #[test]
3151    fn attribute_access_item_with_selectors() {
3152        let item = AttributeAccessItem { attribute_id: 3, access_mode: 3, access_selectors: Some(vec![1, 2]) };
3153        let cd: CosemDataType = item.into();
3154        let back = AttributeAccessItem::try_from(&cd).unwrap();
3155        assert_eq!(back.access_selectors, Some(vec![1, 2]));
3156    }
3157
3158    #[test]
3159    fn attribute_access_item_rejects_out_of_range_long_attribute_id() {
3160        let cd = CosemDataType::Structure(vec![CosemDataType::Long(200), CosemDataType::Enum(1), CosemDataType::Null]);
3161        assert!(AttributeAccessItem::try_from(&cd).is_err());
3162    }
3163
3164    #[test]
3165    fn method_access_item_round_trip() {
3166        let item = MethodAccessItem { method_id: 1, access_mode: 1 };
3167        round_trip(&item);
3168    }
3169
3170    #[test]
3171    fn method_access_item_rejects_out_of_range_long_method_id() {
3172        let cd = CosemDataType::Structure(vec![CosemDataType::Long(200), CosemDataType::Enum(1)]);
3173        assert!(MethodAccessItem::try_from(&cd).is_err());
3174    }
3175
3176    #[test]
3177    fn access_right_round_trip() {
3178        let ar = AccessRight {
3179            attribute_access: vec![
3180                AttributeAccessItem { attribute_id: 1, access_mode: 1, access_selectors: None },
3181                AttributeAccessItem { attribute_id: 2, access_mode: 3, access_selectors: None },
3182            ],
3183            method_access: vec![MethodAccessItem { method_id: 1, access_mode: 1 }],
3184        };
3185        round_trip(&ar);
3186    }
3187
3188    // ========================================================================
3189    // ObjectListElement
3190    // ========================================================================
3191
3192    #[test]
3193    fn object_list_element_round_trip() {
3194        let ole = ObjectListElement {
3195            class_id: 3,
3196            version: 0,
3197            logical_name: obis(0, 0, 1, 0, 0, 255),
3198            access_rights: AccessRight { attribute_access: vec![], method_access: vec![] },
3199        };
3200        round_trip(&ole);
3201    }
3202
3203    #[test]
3204    fn object_list_element_rejects_out_of_range_long_unsigned_version() {
3205        let cd = CosemDataType::Structure(vec![
3206            CosemDataType::LongUnsigned(3),
3207            CosemDataType::LongUnsigned(300),
3208            CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
3209            CosemDataType::Array(vec![]),
3210        ]);
3211        assert!(ObjectListElement::try_from(&cd).is_err());
3212    }
3213
3214    // ========================================================================
3215    // AssociatedPartnersId
3216    // ========================================================================
3217
3218    #[test]
3219    fn associated_partners_id_round_trip() {
3220        let ap = AssociatedPartnersId { client_sap: 1, server_sap: 16 };
3221        round_trip(&ap);
3222    }
3223
3224    #[test]
3225    fn associated_partners_id_try_from_wrong_type() {
3226        let cd = CosemDataType::Null;
3227        assert!(AssociatedPartnersId::try_from(&cd).is_err());
3228    }
3229
3230    #[test]
3231    fn associated_partners_id_rejects_out_of_range_long_client_sap() {
3232        let cd = CosemDataType::Structure(vec![CosemDataType::Long(200), CosemDataType::LongUnsigned(16)]);
3233        assert!(AssociatedPartnersId::try_from(&cd).is_err());
3234    }
3235
3236    // ========================================================================
3237    // ContextName
3238    // ========================================================================
3239
3240    #[test]
3241    fn context_name_structure_round_trip() {
3242        let cn = ContextName::Structure {
3243            joint_iso_ctt: 2,
3244            country: 16,
3245            country_name: 756,
3246            identified_organization: 5,
3247            dlms_ua: 8,
3248            application_context: 1,
3249            context_id: 1,
3250        };
3251        round_trip(&cn);
3252    }
3253
3254    #[test]
3255    fn context_name_octet_string_round_trip() {
3256        let cn = ContextName::OctetString(vec![0x09, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x01, 0x01]);
3257        let cd: CosemDataType = cn.clone().into();
3258        let back = ContextName::try_from(&cd).unwrap();
3259        assert_eq!(cn, back);
3260    }
3261
3262    // ========================================================================
3263    // XDLMSContextInfo
3264    // ========================================================================
3265
3266    #[test]
3267    fn xdlms_context_info_round_trip() {
3268        let ctx = XDLMSContextInfo {
3269            conformance: vec![
3270                0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
3271                0x00,
3272            ],
3273            max_receive_pdu_size: 1024,
3274            max_send_pdu_size: 1024,
3275            dlms_version_number: 6,
3276            quality_of_service: -1,
3277            cyphering_info: vec![],
3278        };
3279        round_trip(&ctx);
3280    }
3281
3282    #[test]
3283    fn xdlms_context_info_rejects_out_of_range_long_quality_of_service() {
3284        let cd = CosemDataType::Structure(vec![
3285            CosemDataType::BitString(vec![0xFF]),
3286            CosemDataType::LongUnsigned(1024),
3287            CosemDataType::LongUnsigned(1024),
3288            CosemDataType::Unsigned(6),
3289            CosemDataType::Long(200),
3290            CosemDataType::OctetString(vec![]),
3291        ]);
3292        assert!(XDLMSContextInfo::try_from(&cd).is_err());
3293    }
3294
3295    // ========================================================================
3296    // ValueDefinition
3297    // ========================================================================
3298
3299    #[test]
3300    fn value_definition_round_trip() {
3301        let vd = ValueDefinition { class_id: 3, logical_name: obis(0, 0, 1, 0, 0, 255), attribute_index: 2 };
3302        round_trip(&vd);
3303    }
3304
3305    #[test]
3306    fn value_definition_rejects_out_of_range_long_attribute_index() {
3307        let cd = CosemDataType::Structure(vec![
3308            CosemDataType::LongUnsigned(3),
3309            CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
3310            CosemDataType::Long(200),
3311        ]);
3312        assert!(ValueDefinition::try_from(&cd).is_err());
3313    }
3314
3315    // ========================================================================
3316    // ActionItem
3317    // ========================================================================
3318
3319    #[test]
3320    fn action_item_round_trip() {
3321        let ai = ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 };
3322        round_trip(&ai);
3323    }
3324
3325    // ========================================================================
3326    // ActionSet
3327    // ========================================================================
3328
3329    #[test]
3330    fn action_set_round_trip() {
3331        let aset = ActionSet {
3332            action_up: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 },
3333            action_down: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 2 },
3334        };
3335        round_trip(&aset);
3336    }
3337
3338    // ========================================================================
3339    // ActionSpecification
3340    // ========================================================================
3341
3342    #[test]
3343    fn action_specification_round_trip() {
3344        let aspec = ActionSpecification {
3345            service_id: 1,
3346            class_id: 3,
3347            logical_name: obis(0, 0, 1, 0, 0, 255),
3348            index: 2,
3349            parameter: CosemDataType::Null,
3350        };
3351        round_trip(&aspec);
3352    }
3353
3354    #[test]
3355    fn action_specification_rejects_out_of_range_long_index() {
3356        let cd = CosemDataType::Structure(vec![
3357            CosemDataType::Enum(1),
3358            CosemDataType::LongUnsigned(3),
3359            CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
3360            CosemDataType::Long(200),
3361            CosemDataType::Null,
3362        ]);
3363        assert!(ActionSpecification::try_from(&cd).is_err());
3364    }
3365
3366    #[test]
3367    fn action_specification_with_parameter() {
3368        let aspec = ActionSpecification {
3369            service_id: 2,
3370            class_id: 9,
3371            logical_name: obis(0, 0, 10, 100, 0, 255),
3372            index: 1,
3373            parameter: CosemDataType::LongUnsigned(42),
3374        };
3375        let cd: CosemDataType = aspec.into();
3376        let back = ActionSpecification::try_from(&cd).unwrap();
3377        assert_eq!(back.parameter, CosemDataType::LongUnsigned(42));
3378    }
3379
3380    // ========================================================================
3381    // Script
3382    // ========================================================================
3383
3384    #[test]
3385    fn script_round_trip() {
3386        let script = Script {
3387            script_identifier: 1,
3388            actions: vec![ActionSpecification {
3389                service_id: 1,
3390                class_id: 3,
3391                logical_name: obis(0, 0, 1, 0, 0, 255),
3392                index: 2,
3393                parameter: CosemDataType::DoubleLongUnsigned(1000),
3394            }],
3395        };
3396        round_trip(&script);
3397    }
3398
3399    #[test]
3400    fn script_empty_actions() {
3401        let script = Script { script_identifier: 0, actions: vec![] };
3402        round_trip(&script);
3403    }
3404
3405    // ========================================================================
3406    // ScheduleTableEntry
3407    // ========================================================================
3408
3409    #[test]
3410    fn schedule_table_entry_round_trip() {
3411        let ste = ScheduleTableEntry {
3412            index: 1,
3413            enable: true,
3414            script_logical_name: obis(0, 0, 10, 100, 0, 255),
3415            script_selector: 1,
3416            switch_time: vec![0x10, 0x00, 0x00],
3417            validity_window: 0xFFFF,
3418            exec_weekdays: vec![0x7F],
3419            exec_specdays: vec![0x00],
3420            begin_date: vec![0x07, 0xE5, 0x01, 0x01, 0xFF],
3421            end_date: vec![0x07, 0xE5, 0x12, 0x31, 0xFF],
3422        };
3423        round_trip(&ste);
3424    }
3425
3426    // ========================================================================
3427    // SpecialDayEntry
3428    // ========================================================================
3429
3430    #[test]
3431    fn special_day_entry_round_trip() {
3432        let sde =
3433            SpecialDayEntry { index: 1, specialday_date: vec![0x07, 0xE5, 0x01, 0x01, 0xFF, 0xFF, 0xFF], day_id: 3 };
3434        round_trip(&sde);
3435    }
3436
3437    // ========================================================================
3438    // SeasonProfile
3439    // ========================================================================
3440
3441    #[test]
3442    fn season_profile_round_trip() {
3443        let sp = SeasonProfile {
3444            season_profile_name: b"Summer".to_vec(),
3445            season_start: vec![0x07, 0xE5, 0x04, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
3446            week_name: b"WeekA".to_vec(),
3447        };
3448        round_trip(&sp);
3449    }
3450
3451    // ========================================================================
3452    // WeekProfile
3453    // ========================================================================
3454
3455    #[test]
3456    fn week_profile_round_trip() {
3457        let wp = WeekProfile {
3458            week_profile_name: b"WeekA".to_vec(),
3459            monday: 1,
3460            tuesday: 2,
3461            wednesday: 3,
3462            thursday: 4,
3463            friday: 5,
3464            saturday: 6,
3465            sunday: 7,
3466        };
3467        round_trip(&wp);
3468    }
3469
3470    // ========================================================================
3471    // DayProfileAction + DayProfile
3472    // ========================================================================
3473
3474    #[test]
3475    fn day_profile_action_round_trip() {
3476        let dpa = DayProfileAction {
3477            start_time: vec![0x08, 0x00, 0x00],
3478            script_logical_name: obis(0, 0, 10, 100, 0, 255),
3479            script_selector: 1,
3480        };
3481        round_trip(&dpa);
3482    }
3483
3484    #[test]
3485    fn day_profile_round_trip() {
3486        let dp = DayProfile {
3487            day_id: 1,
3488            day_schedule: vec![
3489                DayProfileAction {
3490                    start_time: vec![0x08, 0x00, 0x00],
3491                    script_logical_name: obis(0, 0, 10, 100, 0, 255),
3492                    script_selector: 1,
3493                },
3494                DayProfileAction {
3495                    start_time: vec![0x18, 0x00, 0x00],
3496                    script_logical_name: obis(0, 0, 10, 100, 0, 255),
3497                    script_selector: 2,
3498                },
3499            ],
3500        };
3501        round_trip(&dp);
3502    }
3503
3504    #[test]
3505    fn day_profile_empty_schedule() {
3506        let dp = DayProfile { day_id: 1, day_schedule: vec![] };
3507        round_trip(&dp);
3508    }
3509
3510    // ========================================================================
3511    // SendDestinationAndMethod
3512    // ========================================================================
3513
3514    #[test]
3515    fn send_destination_and_method_round_trip() {
3516        let sdm =
3517            SendDestinationAndMethod { transport_service: 0, destination: b"192.168.1.100:4059".to_vec(), message: 2 };
3518        round_trip(&sdm);
3519    }
3520
3521    // ========================================================================
3522    // CommunicationWindow
3523    // ========================================================================
3524
3525    #[test]
3526    fn communication_window_round_trip() {
3527        let cw = CommunicationWindow {
3528            begin: DateTime::from_ymdhms(2025, 1, 1, 8, 0, 0),
3529            end: DateTime::from_ymdhms(2025, 12, 31, 18, 0, 0),
3530        };
3531        round_trip(&cw);
3532    }
3533
3534    // ========================================================================
3535    // EmergencyProfile
3536    // ========================================================================
3537
3538    #[test]
3539    fn emergency_profile_round_trip() {
3540        let ep = EmergencyProfile {
3541            emergency_profile_id: 1,
3542            emergency_activation_time: vec![0x07, 0xE5, 0x01, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
3543            emergency_duration: 3600,
3544        };
3545        round_trip(&ep);
3546    }
3547
3548    // ========================================================================
3549    // LimiterAction
3550    // ========================================================================
3551
3552    #[test]
3553    fn limiter_action_round_trip() {
3554        let la = LimiterAction {
3555            action_over_threshold: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 },
3556            action_under_threshold: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 2 },
3557        };
3558        round_trip(&la);
3559    }
3560
3561    // ========================================================================
3562    // ObjectDefinition
3563    // ========================================================================
3564
3565    #[test]
3566    fn object_definition_round_trip() {
3567        let od = ObjectDefinition { class_id: 3, logical_name: obis(0, 0, 1, 0, 0, 255) };
3568        round_trip(&od);
3569    }
3570
3571    // ========================================================================
3572    // RegisterActMask
3573    // ========================================================================
3574
3575    #[test]
3576    fn register_act_mask_round_trip() {
3577        let ram = RegisterActMask { mask_name: b"DayTariff".to_vec(), index_list: vec![1, 3, 5] };
3578        round_trip(&ram);
3579    }
3580
3581    // ========================================================================
3582    // ImageToActivateInfo
3583    // ========================================================================
3584
3585    #[test]
3586    fn image_to_activate_info_round_trip() {
3587        let itai = ImageToActivateInfo { image_block_number: 1, image_block_value: vec![0x01, 0x02, 0x03, 0x04] };
3588        round_trip(&itai);
3589    }
3590
3591    // ========================================================================
3592    // ExecutedScript
3593    // ========================================================================
3594
3595    #[test]
3596    fn executed_script_round_trip() {
3597        let es = ExecutedScript { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 };
3598        round_trip(&es);
3599    }
3600
3601    // ========================================================================
3602    // SapAssignmentEntry
3603    // ========================================================================
3604
3605    #[test]
3606    fn sap_assignment_entry_round_trip() {
3607        let sae = SapAssignmentEntry { sap: 1, logical_device_name: b"Meter01".to_vec() };
3608        round_trip(&sae);
3609    }
3610
3611    // ========================================================================
3612    // GsmAdjacentCell
3613    // ========================================================================
3614
3615    #[test]
3616    fn gsm_adjacent_cell_round_trip() {
3617        let gac =
3618            GsmAdjacentCell { cell_id: vec![0x01, 0x02], signal_quality: vec![0x03], signal_strength: vec![0x04] };
3619        round_trip(&gac);
3620    }
3621
3622    // ========================================================================
3623    // ProtectionObject
3624    // ========================================================================
3625
3626    #[test]
3627    fn protection_object_round_trip() {
3628        let po = ProtectionObject { class_id: 3, logical_name: obis(0, 0, 1, 0, 0, 255), attribute_index: 2 };
3629        round_trip(&po);
3630    }
3631
3632    #[test]
3633    fn protection_object_rejects_out_of_range_long_attribute_index() {
3634        let cd = CosemDataType::Structure(vec![
3635            CosemDataType::LongUnsigned(3),
3636            CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
3637            CosemDataType::Long(200),
3638        ]);
3639        assert!(ProtectionObject::try_from(&cd).is_err());
3640    }
3641
3642    // ========================================================================
3643    // IpOption
3644    // ========================================================================
3645
3646    #[test]
3647    fn ip_option_round_trip() {
3648        let io = IpOption { option_type: 7, option_value: vec![0xC0, 0xA8, 0x01, 0x01] };
3649        round_trip(&io);
3650    }
3651
3652    // ========================================================================
3653    // NeighborDiscoverySetup
3654    // ========================================================================
3655
3656    #[test]
3657    fn neighbor_discovery_setup_round_trip() {
3658        let nds = NeighborDiscoverySetup {
3659            ip_address: vec![
3660                0xFE, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
3661            ],
3662            hardware_address: vec![0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E],
3663        };
3664        round_trip(&nds);
3665    }
3666
3667    // ========================================================================
3668    // BER serialization round-trip tests
3669    // ========================================================================
3670
3671    #[test]
3672    fn ber_round_trip_access_right() {
3673        let ar = AccessRight {
3674            attribute_access: vec![AttributeAccessItem { attribute_id: 1, access_mode: 1, access_selectors: None }],
3675            method_access: vec![MethodAccessItem { method_id: 1, access_mode: 1 }],
3676        };
3677        let cd: CosemDataType = ar.clone().into();
3678        let mut buf = Vec::new();
3679        cd.serialize_ber(&mut buf).unwrap();
3680        let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
3681        assert!(rest.is_empty());
3682        let back = AccessRight::try_from(&decoded).unwrap();
3683        assert_eq!(ar, back);
3684    }
3685
3686    #[test]
3687    fn ber_round_trip_object_list_element() {
3688        let ole = ObjectListElement {
3689            class_id: 15,
3690            version: 1,
3691            logical_name: obis(0, 0, 40, 0, 0, 255),
3692            access_rights: AccessRight { attribute_access: vec![], method_access: vec![] },
3693        };
3694        let cd: CosemDataType = ole.clone().into();
3695        let mut buf = Vec::new();
3696        cd.serialize_ber(&mut buf).unwrap();
3697        let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
3698        assert!(rest.is_empty());
3699        let back = ObjectListElement::try_from(&decoded).unwrap();
3700        assert_eq!(ole, back);
3701    }
3702
3703    #[test]
3704    fn ber_round_trip_script() {
3705        let script = Script {
3706            script_identifier: 42,
3707            actions: vec![ActionSpecification {
3708                service_id: 1,
3709                class_id: 3,
3710                logical_name: obis(0, 0, 1, 0, 0, 255),
3711                index: 2,
3712                parameter: CosemDataType::DoubleLongUnsigned(12345),
3713            }],
3714        };
3715        let cd: CosemDataType = script.clone().into();
3716        let mut buf = Vec::new();
3717        cd.serialize_ber(&mut buf).unwrap();
3718        let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
3719        assert!(rest.is_empty());
3720        let back = Script::try_from(&decoded).unwrap();
3721        assert_eq!(script, back);
3722    }
3723
3724    #[test]
3725    fn ber_round_trip_schedule_table_entry() {
3726        let ste = ScheduleTableEntry {
3727            index: 1,
3728            enable: true,
3729            script_logical_name: obis(0, 0, 10, 100, 0, 255),
3730            script_selector: 1,
3731            switch_time: vec![0x10, 0x00, 0x00],
3732            validity_window: 60,
3733            exec_weekdays: vec![0x7F],
3734            exec_specdays: vec![0x00],
3735            begin_date: vec![0x07, 0xE5, 0x01, 0x01, 0xFF],
3736            end_date: vec![0x07, 0xE5, 0x12, 0x31, 0xFF],
3737        };
3738        let cd: CosemDataType = ste.clone().into();
3739        let mut buf = Vec::new();
3740        cd.serialize_ber(&mut buf).unwrap();
3741        let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
3742        assert!(rest.is_empty());
3743        let back = ScheduleTableEntry::try_from(&decoded).unwrap();
3744        assert_eq!(ste, back);
3745    }
3746
3747    #[test]
3748    fn ber_round_trip_emergency_profile() {
3749        let ep = EmergencyProfile {
3750            emergency_profile_id: 5,
3751            emergency_activation_time: vec![0x07, 0xE5, 0x06, 0x15, 0xFF, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
3752            emergency_duration: 7200,
3753        };
3754        let cd: CosemDataType = ep.clone().into();
3755        let mut buf = Vec::new();
3756        cd.serialize_ber(&mut buf).unwrap();
3757        let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
3758        assert!(rest.is_empty());
3759        let back = EmergencyProfile::try_from(&decoded).unwrap();
3760        assert_eq!(ep, back);
3761    }
3762
3763    // ========================================================================
3764    // Error cases
3765    // ========================================================================
3766
3767    #[test]
3768    fn access_right_wrong_type() {
3769        assert!(AccessRight::try_from(&CosemDataType::Null).is_err());
3770        assert!(AccessRight::try_from(&CosemDataType::Unsigned(1)).is_err());
3771    }
3772
3773    #[test]
3774    fn action_item_wrong_type() {
3775        assert!(ActionItem::try_from(&CosemDataType::Null).is_err());
3776    }
3777
3778    #[test]
3779    fn context_name_wrong_type() {
3780        assert!(ContextName::try_from(&CosemDataType::Unsigned(1)).is_err());
3781    }
3782
3783    #[test]
3784    fn xdlms_context_info_wrong_fields() {
3785        let cd = CosemDataType::Structure(vec![CosemDataType::BitString(vec![0]), CosemDataType::LongUnsigned(1024)]);
3786        assert!(XDLMSContextInfo::try_from(&cd).is_err());
3787    }
3788
3789    #[test]
3790    fn value_definition_wrong_type() {
3791        assert!(ValueDefinition::try_from(&CosemDataType::Null).is_err());
3792    }
3793
3794    #[test]
3795    fn script_wrong_type() {
3796        assert!(Script::try_from(&CosemDataType::Null).is_err());
3797        assert!(Script::try_from(&CosemDataType::Array(vec![])).is_err());
3798    }
3799
3800    #[test]
3801    fn send_destination_and_method_wrong_type() {
3802        assert!(SendDestinationAndMethod::try_from(&CosemDataType::Null).is_err());
3803    }
3804
3805    #[test]
3806    fn emergency_profile_wrong_type() {
3807        assert!(EmergencyProfile::try_from(&CosemDataType::Null).is_err());
3808    }
3809
3810    #[test]
3811    fn image_to_activate_info_wrong_type() {
3812        assert!(ImageToActivateInfo::try_from(&CosemDataType::Null).is_err());
3813    }
3814
3815    // ========================================================================
3816    // Batch test: all struct types round-trip through BER
3817    // ========================================================================
3818
3819    #[test]
3820    fn all_types_ber_round_trip() {
3821        // Helper macro to test BER round-trip for a given value
3822        macro_rules! test_ber {
3823            ($val:expr, $type:ty) => {{
3824                let val: $type = $val;
3825                let cd: CosemDataType = val.clone().into();
3826                let mut buf = Vec::new();
3827                cd.serialize_ber(&mut buf).unwrap();
3828                let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
3829                assert!(rest.is_empty(), "trailing bytes");
3830                let back = <$type>::try_from(&decoded).unwrap();
3831                assert_eq!(val, back);
3832            }};
3833        }
3834
3835        test_ber!(ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 }, ActionItem);
3836        test_ber!(ObjectDefinition { class_id: 3, logical_name: obis(0, 0, 1, 0, 0, 255) }, ObjectDefinition);
3837        test_ber!(
3838            ExecutedScript { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 2 },
3839            ExecutedScript
3840        );
3841        test_ber!(
3842            ValueDefinition { class_id: 5, logical_name: obis(0, 0, 96, 1, 0, 255), attribute_index: 2 },
3843            ValueDefinition
3844        );
3845        test_ber!(
3846            ProtectionObject { class_id: 3, logical_name: obis(0, 0, 1, 0, 0, 255), attribute_index: 1 },
3847            ProtectionObject
3848        );
3849        test_ber!(SapAssignmentEntry { sap: 1, logical_device_name: b"Meter".to_vec() }, SapAssignmentEntry);
3850        test_ber!(IpOption { option_type: 7, option_value: vec![192, 168, 1, 1] }, IpOption);
3851        test_ber!(
3852            GsmAdjacentCell { cell_id: vec![1], signal_quality: vec![2], signal_strength: vec![3] },
3853            GsmAdjacentCell
3854        );
3855        test_ber!(RegisterActMask { mask_name: b"Day".to_vec(), index_list: vec![1, 2] }, RegisterActMask);
3856        test_ber!(ImageToActivateInfo { image_block_number: 1, image_block_value: vec![0xAA] }, ImageToActivateInfo);
3857        test_ber!(
3858            SpecialDayEntry { index: 1, specialday_date: vec![0x07, 0xE5, 0x01, 0x01, 0xFF, 0xFF, 0xFF], day_id: 1 },
3859            SpecialDayEntry
3860        );
3861        test_ber!(
3862            SeasonProfile {
3863                season_profile_name: b"Summer".to_vec(),
3864                season_start: vec![0u8; 12],
3865                week_name: b"W1".to_vec()
3866            },
3867            SeasonProfile
3868        );
3869        test_ber!(
3870            WeekProfile {
3871                week_profile_name: b"W1".to_vec(),
3872                monday: 1,
3873                tuesday: 2,
3874                wednesday: 3,
3875                thursday: 4,
3876                friday: 5,
3877                saturday: 6,
3878                sunday: 7
3879            },
3880            WeekProfile
3881        );
3882        test_ber!(
3883            DayProfileAction {
3884                start_time: vec![8, 0, 0],
3885                script_logical_name: obis(0, 0, 10, 100, 0, 255),
3886                script_selector: 1
3887            },
3888            DayProfileAction
3889        );
3890        test_ber!(
3891            DayProfile {
3892                day_id: 1,
3893                day_schedule: vec![DayProfileAction {
3894                    start_time: vec![8, 0, 0],
3895                    script_logical_name: obis(0, 0, 10, 100, 0, 255),
3896                    script_selector: 1
3897                }]
3898            },
3899            DayProfile
3900        );
3901        test_ber!(
3902            NeighborDiscoverySetup {
3903                ip_address: vec![0xFE, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
3904                hardware_address: vec![0, 1, 2, 3, 4, 5]
3905            },
3906            NeighborDiscoverySetup
3907        );
3908        test_ber!(AssociatedPartnersId { client_sap: 1, server_sap: 16 }, AssociatedPartnersId);
3909        test_ber!(
3910            XDLMSContextInfo {
3911                conformance: vec![0; 18],
3912                max_receive_pdu_size: 1024,
3913                max_send_pdu_size: 1024,
3914                dlms_version_number: 6,
3915                quality_of_service: -1,
3916                cyphering_info: vec![]
3917            },
3918            XDLMSContextInfo
3919        );
3920        test_ber!(
3921            CommunicationWindow {
3922                begin: DateTime::from_ymdhms(2025, 1, 1, 8, 0, 0),
3923                end: DateTime::from_ymdhms(2025, 12, 31, 18, 0, 0)
3924            },
3925            CommunicationWindow
3926        );
3927        test_ber!(
3928            EmergencyProfile {
3929                emergency_profile_id: 1,
3930                emergency_activation_time: vec![0u8; 12],
3931                emergency_duration: 3600
3932            },
3933            EmergencyProfile
3934        );
3935        test_ber!(
3936            LimiterAction {
3937                action_over_threshold: ActionItem {
3938                    script_logical_name: obis(0, 0, 10, 100, 0, 255),
3939                    script_selector: 1
3940                },
3941                action_under_threshold: ActionItem {
3942                    script_logical_name: obis(0, 0, 10, 100, 0, 255),
3943                    script_selector: 2
3944                },
3945            },
3946            LimiterAction
3947        );
3948        test_ber!(
3949            ActionSet {
3950                action_up: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 },
3951                action_down: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 2 },
3952            },
3953            ActionSet
3954        );
3955        test_ber!(
3956            SendDestinationAndMethod { transport_service: 0, destination: b"192.168.1.1:4059".to_vec(), message: 2 },
3957            SendDestinationAndMethod
3958        );
3959        test_ber!(
3960            ActionSpecification {
3961                service_id: 1,
3962                class_id: 3,
3963                logical_name: obis(0, 0, 1, 0, 0, 255),
3964                index: 2,
3965                parameter: CosemDataType::Null
3966            },
3967            ActionSpecification
3968        );
3969        test_ber!(Script { script_identifier: 1, actions: vec![] }, Script);
3970        test_ber!(
3971            ScheduleTableEntry {
3972                index: 1,
3973                enable: true,
3974                script_logical_name: obis(0, 0, 10, 100, 0, 255),
3975                script_selector: 1,
3976                switch_time: vec![0x10, 0, 0],
3977                validity_window: 60,
3978                exec_weekdays: vec![0x7F],
3979                exec_specdays: vec![0],
3980                begin_date: vec![0x07, 0xE5, 1, 1, 0xFF],
3981                end_date: vec![0x07, 0xE5, 12, 31, 0xFF],
3982            },
3983            ScheduleTableEntry
3984        );
3985        test_ber!(DateTime::new([0x07, 0xE5, 0x05, 0x01, 0x02, 0x10, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00]), DateTime);
3986        test_ber!(ScalerUnit::new(-2, 30), ScalerUnit);
3987        test_ber!(CaptureObjectDefinition::new(3, obis(0, 0, 1, 0, 0, 255), 2, 0), CaptureObjectDefinition);
3988        test_ber!(AttributeAccessItem { attribute_id: 1, access_mode: 1, access_selectors: None }, AttributeAccessItem);
3989        test_ber!(MethodAccessItem { method_id: 1, access_mode: 1 }, MethodAccessItem);
3990        test_ber!(
3991            AccessRight {
3992                attribute_access: vec![AttributeAccessItem { attribute_id: 1, access_mode: 1, access_selectors: None }],
3993                method_access: vec![MethodAccessItem { method_id: 1, access_mode: 1 }],
3994            },
3995            AccessRight
3996        );
3997        test_ber!(
3998            ObjectListElement {
3999                class_id: 3,
4000                version: 0,
4001                logical_name: obis(0, 0, 1, 0, 0, 255),
4002                access_rights: AccessRight { attribute_access: vec![], method_access: vec![] },
4003            },
4004            ObjectListElement
4005        );
4006        test_ber!(ContextName::OctetString(vec![0x09, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x01, 0x01]), ContextName);
4007    }
4008}