1use crate::obis::ObisCode;
8use crate::types::CosemDataType;
9use serde::{Deserialize, Serialize};
10
11pub type LogicalName = ObisCode;
13
14pub type Choice = CosemDataType;
17
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct DateTime(pub [u8; 12]);
21
22impl DateTime {
23 pub fn new(bytes: [u8; 12]) -> Self {
25 Self(bytes)
26 }
27
28 pub fn as_bytes(&self) -> &[u8; 12] {
30 &self.0
31 }
32
33 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; buf[5] = hour;
41 buf[6] = min;
42 buf[7] = sec;
43 buf[8] = 0; buf[9..12].copy_from_slice(&[0, 0, 0]); Self(buf)
46 }
47}
48
49impl From<DateTime> for CosemDataType {
50 fn from(dt: DateTime) -> Self {
51 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct BitString(pub Vec<u8>);
74
75impl BitString {
76 pub fn new(bytes: Vec<u8>) -> Self {
78 Self(bytes)
79 }
80
81 pub fn as_bytes(&self) -> &[u8] {
83 &self.0
84 }
85
86 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103pub struct ScalerUnit {
104 pub scaler: i8,
106 pub unit: u8,
108}
109
110impl ScalerUnit {
111 pub fn new(scaler: i8, unit: u8) -> Self {
113 Self { scaler, unit }
114 }
115
116 #[allow(clippy::cast_precision_loss)] 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154pub struct CaptureObjectDefinition {
155 pub class_id: u16,
157 pub logical_name: ObisCode,
159 pub attribute_index: u8,
161 pub data_index: u8,
163}
164
165impl CaptureObjectDefinition {
166 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
222pub enum SortMethod {
223 Fifo = 1,
225 Lifo = 2,
227 Largest = 3,
229 Smallest = 4,
231 NearestToZero = 5,
233 FarthestFromZero = 6,
235}
236
237impl SortMethod {
238 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
254pub enum AssociationStatus {
255 NonAssociated = 0,
257 AssociationPending = 1,
259 Associated = 2,
261}
262
263#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct DataAttrs {
272 pub logical_name: LogicalName,
274 pub value: Choice,
276}
277
278#[derive(Debug, Clone, Serialize, Deserialize)]
283pub struct RegisterAttrs {
284 pub logical_name: LogicalName,
286 pub value: Choice,
288 pub scaler_unit: ScalerUnit,
290}
291
292#[derive(Debug, Clone, Serialize, Deserialize)]
299pub struct ExtendedRegisterAttrs {
300 pub logical_name: LogicalName,
302 pub value: Choice,
304 pub scaler_unit: ScalerUnit,
306 pub status: Choice,
308 pub capture_time: Choice,
310}
311
312#[derive(Debug, Clone, Serialize, Deserialize)]
323pub struct DemandRegisterAttrs {
324 pub logical_name: LogicalName,
326 pub current_average_value: Choice,
328 pub last_average_value: Choice,
330 pub scaler_unit: ScalerUnit,
332 pub status: Choice,
334 pub capture_time: Choice,
336 pub start_time_current: Choice,
338 pub period: u32,
340 pub number_of_periods: u16,
342}
343
344#[derive(Debug, Clone, Serialize, Deserialize)]
354pub struct ProfileGenericAttrs {
355 pub logical_name: LogicalName,
357 pub buffer: Vec<Choice>,
359 pub capture_objects: Vec<CaptureObjectDefinition>,
361 pub capture_period: u32,
363 pub sort_method: SortMethod,
365 pub sort_object: Option<CaptureObjectDefinition>,
367 pub entries_in_use: u32,
369 pub profile_entries: u32,
371}
372
373#[derive(Debug, Clone, Serialize, Deserialize)]
384pub struct ClockAttrs {
385 pub logical_name: LogicalName,
387 pub time: DateTime,
389 pub time_zone: i16,
391 pub status: u8,
393 pub daylight_savings_begin: DateTime,
395 pub daylight_savings_end: DateTime,
397 pub daylight_savings_deviation: i8,
399 pub daylight_savings_enabled: bool,
401 pub clock_base: u8,
403}
404
405#[derive(Debug, Clone, Serialize, Deserialize)]
409pub struct ScriptTableAttrs {
410 pub logical_name: LogicalName,
412 pub scripts: Vec<Choice>,
414}
415
416#[derive(Debug, Clone, Serialize, Deserialize)]
420pub struct ScheduleAttrs {
421 pub logical_name: LogicalName,
423 pub entries: Vec<Choice>,
425}
426
427#[derive(Debug, Clone, Serialize, Deserialize)]
431pub struct SpecialDaysTableAttrs {
432 pub logical_name: LogicalName,
434 pub entries: Vec<Choice>,
436}
437
438#[derive(Debug, Clone, Serialize, Deserialize)]
451pub struct AssociationLnAttrs {
452 pub logical_name: LogicalName,
454 pub object_list: Vec<Choice>,
456 pub associated_partners_id: Choice,
458 pub application_context_name: Choice,
460 pub xdlms_context_info: Choice,
462 pub authentication_mechanism_name: u8,
464 pub secret: Vec<u8>,
466 pub association_status: AssociationStatus,
468 pub security_setup_reference: Option<ObisCode>,
470 pub user_list: Vec<Choice>,
472 pub current_user: Option<Choice>,
474}
475
476#[derive(Debug, Clone, Serialize, Deserialize)]
480pub struct SapAssignmentAttrs {
481 pub logical_name: LogicalName,
483 pub sap_assignment_list: Vec<Choice>,
485}
486
487#[derive(Debug, Clone, Serialize, Deserialize)]
495pub struct ActivityCalendarAttrs {
496 pub logical_name: LogicalName,
498 pub calendar_name: Vec<u8>,
500 pub week_profile_table: Vec<Choice>,
502 pub day_profile_table: Vec<Choice>,
504 pub month_profile_table: Vec<Choice>,
506 pub active_calendar: Vec<u8>,
508}
509
510#[derive(Debug, Clone, Serialize, Deserialize)]
514pub struct RegisterMonitorAttrs {
515 pub logical_name: LogicalName,
517 pub thresholds: Vec<Choice>,
519}
520
521#[derive(Debug, Clone, Serialize, Deserialize)]
526pub struct SingleActionScheduleAttrs {
527 pub logical_name: LogicalName,
529 pub executed_script: CaptureObjectDefinition,
531 pub execution_time: Vec<Choice>,
533}
534
535#[derive(Debug, Clone, Serialize, Deserialize)]
548pub struct ImageTransferAttrs {
549 pub logical_name: LogicalName,
551 pub block_size: u16,
553 pub transferred_blocks: u32,
555 pub last_block_number: u32,
557 pub transfer_status: u8,
559 pub image_transfer_enabled: bool,
561 pub image_transferred_block_status: Vec<u8>,
563 pub image_first_not_transferred_block_number: u32,
565 pub image_block_transfer_trigger: u8,
567 pub image_transfer_service_enable: bool,
569 pub image_activation_info: Vec<Choice>,
571}
572
573#[derive(Debug, Clone, Serialize, Deserialize)]
579pub struct DisconnectControlAttrs {
580 pub logical_name: LogicalName,
582 pub output_state: bool,
584 pub control_mode: u8,
586 pub physical_output_name: Vec<u8>,
588}
589
590#[derive(Debug, Clone, Serialize, Deserialize)]
603pub struct LimiterAttrs {
604 pub logical_name: LogicalName,
606 pub monitored_value: Choice,
608 pub threshold_normal: Choice,
610 pub threshold_min_operation: Choice,
612 pub threshold_max_operation: Choice,
614 pub min_over_threshold_duration: u16,
616 pub min_under_threshold_duration: u16,
618 pub emergency_profile: CaptureObjectDefinition,
620 pub emergency_profile_action: u8,
622 pub active_calendar_name: Vec<u8>,
624 pub emergency_profile_group_id: u16,
626}
627
628#[derive(Debug, Clone, Serialize, Deserialize)]
641pub struct TcpUdpSetupAttrs {
642 pub logical_name: LogicalName,
644 pub port: u16,
646 pub tcp_udp_protocol: Vec<u8>,
648 pub ip_reference: Vec<u8>,
650 pub maximum_simultaneous_connections: u16,
652 pub maximum_segment_size: u16,
654 pub inactivity_timeout: u16,
656 pub transport_security: u8,
658 pub password_setup: Vec<u8>,
660 pub password: Vec<u8>,
662 pub default_password_status: u8,
664}
665
666#[derive(Debug, Clone, Serialize, Deserialize)]
673pub struct Ipv4SetupAttrs {
674 pub logical_name: LogicalName,
676 pub ip_address: [u8; 4],
678 pub subnet_mask: [u8; 4],
680 pub gateway_ip_address: [u8; 4],
682 pub use_dhcp: bool,
684}
685
686#[derive(Debug, Clone, Serialize, Deserialize)]
694pub struct Ipv6SetupAttrs {
695 pub logical_name: LogicalName,
697 pub ip_address: [u8; 16],
699 pub prefix_length: u8,
701 pub gateway_ip_address: [u8; 16],
703 pub use_dhcp: bool,
705 pub multicast_address: [u8; 16],
707}
708
709#[derive(Debug, Clone, Serialize, Deserialize)]
715pub struct MacAddressSetupAttrs {
716 pub logical_name: LogicalName,
718 pub unicast_mac_address: [u8; 6],
720 pub broadcast_mac_address: [u8; 6],
722 pub multicast_mac_address: [u8; 6],
724}
725
726#[derive(Debug, Clone, Serialize, Deserialize)]
739pub struct GprsModemSetupAttrs {
740 pub logical_name: LogicalName,
742 pub apn: Vec<u8>,
744 pub pin_code: Vec<u8>,
746 pub username: Vec<u8>,
748 pub password: Vec<u8>,
750 pub ask_for_password: bool,
752 pub ip_address: [u8; 4],
754 pub ip_port: u16,
756 pub transfer_services: Vec<u8>,
758 pub default_transfers: Vec<u8>,
760 pub gprs_timeout: u16,
762}
763
764#[derive(Debug, Clone, Serialize, Deserialize)]
790pub struct GsmDiagnosticAttrs {
791 pub logical_name: LogicalName,
793 pub cell_id: Vec<u8>,
795 pub location_id: Vec<u8>,
797 pub imsi: Vec<u8>,
799 pub imei: Vec<u8>,
801 pub rn: Vec<u8>,
803 pub cn: Vec<u8>,
805 pub signal_quality: Vec<u8>,
807 pub signal_strength: Vec<u8>,
809 pub channel_number: Vec<u8>,
811 pub cell_parameter_id: Vec<u8>,
813 pub bsic: Vec<u8>,
815 pub iccid: Vec<u8>,
817 pub lac: Vec<u8>,
819 pub mcc: Vec<u8>,
821 pub mnc: Vec<u8>,
823 pub tmsi: Vec<u8>,
825 pub tmgi: Vec<u8>,
827 pub gprs_status: Vec<u8>,
829 pub routing_area_code: Vec<u8>,
831 pub geographic_address: Vec<u8>,
833 pub access_point_name: Vec<u8>,
835 pub data_transport_state: Vec<u8>,
837 pub nma_message: Vec<u8>,
839}
840
841#[derive(Debug, Clone, Serialize, Deserialize)]
846pub struct ArbitratorAttrs {
847 pub logical_name: LogicalName,
849 pub capture_groups: Vec<CaptureObjectDefinition>,
851 pub action_groups: Vec<Choice>,
853}
854
855#[derive(Debug, Clone, Serialize, Deserialize)]
870pub struct IecHdlcSetupAttrs {
871 pub logical_name: LogicalName,
873 pub channel: u8,
875 pub wait: Vec<Choice>,
877 pub client_address: u16,
879 pub server_address: u16,
881 pub window_size_tx: u8,
883 pub window_size_rx: u8,
885 pub max_info_tx: u16,
887 pub max_info_rx: u16,
889 pub max_timeout_tx: u16,
891 pub max_retries_tx: u8,
893 pub max_timeout_respond: u16,
895 pub max_retries_respond: u8,
897}
898
899#[derive(Debug, Clone, Serialize, Deserialize)]
911pub struct IecLocalPortSetupAttrs {
912 pub logical_name: LogicalName,
914 pub mode: u8,
916 pub communication_speed: u8,
918 pub max_size_info_field: u16,
920 pub device_address: Vec<u8>,
922 pub password1: Vec<u8>,
924 pub password2: Vec<u8>,
926 pub password3: Vec<u8>,
928 pub client_address: Vec<u8>,
930 pub point_to_point_address: Vec<u8>,
932}
933
934#[derive(Debug, Clone, Serialize, Deserialize)]
945pub struct MbusSlavePortSetupAttrs {
946 pub logical_name: LogicalName,
948 pub mbus_address: Vec<u8>,
950 pub identification_number: Vec<u8>,
952 pub manufacturer_id: Vec<u8>,
954 pub data_type: Vec<u8>,
956 pub max_slave_pifs: u16,
958 pub max_master_pifs: u16,
960 pub character_encoding: Vec<u8>,
962 pub m_bus_mode: u8,
964}
965
966#[derive(Debug, Clone, Serialize, Deserialize)]
974pub struct DataProtectionAttrs {
975 pub logical_name: LogicalName,
977 pub protection_method: u8,
979 pub protection_key: Vec<u8>,
981 pub key_translation_table_1: Vec<Choice>,
983 pub key_translation_table_2: Vec<Choice>,
985 pub key_translation_table_3: Vec<Choice>,
987}
988
989#[derive(Debug, Clone, Serialize, Deserialize)]
997pub struct SecuritySetupAttrs {
998 pub logical_name: LogicalName,
1000 pub security_policy: u8,
1002 pub security_suite: u8,
1004 pub client_system_title: Vec<u8>,
1006 pub server_system_title: Vec<u8>,
1008 pub certificates: Vec<Choice>,
1010}
1011
1012impl AssociationStatus {
1013 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1026pub enum ClockBase {
1027 None = 0,
1029 InternalCrystal = 1,
1031 MainsFrequency = 2,
1033 Gps = 3,
1035 RadioClock = 4,
1037}
1038
1039impl ClockBase {
1040 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1060pub struct AccessRight {
1061 pub attribute_access: Vec<AttributeAccessItem>,
1063 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1102pub struct AttributeAccessItem {
1103 pub attribute_id: i8,
1105 pub access_mode: u8,
1107 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1165pub struct MethodAccessItem {
1166 pub method_id: i8,
1168 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1202pub struct ObjectListElement {
1203 pub class_id: u16,
1205 pub version: u8,
1207 pub logical_name: ObisCode,
1209 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1257pub struct AssociatedPartnersId {
1258 pub client_sap: i8,
1260 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1298pub enum ContextName {
1299 Structure {
1301 joint_iso_ctt: u8,
1303 country: u8,
1305 country_name: u16,
1307 identified_organization: u8,
1309 dlms_ua: u8,
1311 application_context: u8,
1313 context_id: u8,
1315 },
1316 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1397pub struct XDLMSContextInfo {
1398 pub conformance: Vec<u8>,
1400 pub max_receive_pdu_size: u16,
1402 pub max_send_pdu_size: u16,
1404 pub dlms_version_number: u8,
1406 pub quality_of_service: i8,
1408 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1474pub struct ValueDefinition {
1475 pub class_id: u16,
1477 pub logical_name: ObisCode,
1479 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1525pub struct ActionItem {
1526 pub script_logical_name: ObisCode,
1528 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1567pub struct ActionSet {
1568 pub action_up: ActionItem,
1570 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1597pub struct ActionSpecification {
1598 pub service_id: u8,
1600 pub class_id: u16,
1602 pub logical_name: ObisCode,
1604 pub index: i8,
1606 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1657pub struct Script {
1658 pub script_identifier: u16,
1660 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1698pub struct ScheduleTableEntry {
1699 pub index: u16,
1701 pub enable: bool,
1703 pub script_logical_name: ObisCode,
1705 pub script_selector: u16,
1707 pub switch_time: Vec<u8>,
1709 pub validity_window: u16,
1711 pub exec_weekdays: Vec<u8>,
1713 pub exec_specdays: Vec<u8>,
1715 pub begin_date: Vec<u8>,
1717 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1806pub struct SpecialDayEntry {
1807 pub index: u16,
1809 pub specialday_date: Vec<u8>,
1811 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1852pub struct SeasonProfile {
1853 pub season_profile_name: Vec<u8>,
1855 pub season_start: Vec<u8>,
1857 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1898pub struct WeekProfile {
1899 pub week_profile_name: Vec<u8>,
1901 pub monday: u8,
1903 pub tuesday: u8,
1905 pub wednesday: u8,
1907 pub thursday: u8,
1909 pub friday: u8,
1911 pub saturday: u8,
1913 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1966pub struct DayProfileAction {
1967 pub start_time: Vec<u8>,
1969 pub script_logical_name: ObisCode,
1971 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2014pub struct DayProfile {
2015 pub day_id: u8,
2017 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2055pub struct SendDestinationAndMethod {
2056 pub transport_service: u8,
2058 pub destination: Vec<u8>,
2060 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2101pub struct CommunicationWindow {
2102 pub begin: DateTime,
2104 pub end: DateTime,
2106}
2107
2108impl From<CommunicationWindow> for CosemDataType {
2109 fn from(cw: CommunicationWindow) -> Self {
2110 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2135pub struct EmergencyProfile {
2136 pub emergency_profile_id: u16,
2138 pub emergency_activation_time: Vec<u8>,
2140 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2181pub struct LimiterAction {
2182 pub action_over_threshold: ActionItem,
2184 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2214pub struct ObjectDefinition {
2215 pub class_id: u16,
2217 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2255pub struct RegisterActMask {
2256 pub mask_name: Vec<u8>,
2258 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2300pub struct ImageToActivateInfo {
2301 pub image_block_number: u32,
2303 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2339pub struct ExecutedScript {
2340 pub script_logical_name: ObisCode,
2342 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2380pub struct SapAssignmentEntry {
2381 pub sap: u16,
2383 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2420pub struct GsmAdjacentCell {
2421 pub cell_id: Vec<u8>,
2423 pub signal_quality: Vec<u8>,
2425 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2466pub struct ProtectionObject {
2467 pub class_id: u16,
2469 pub logical_name: ObisCode,
2471 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2517pub struct IpOption {
2518 pub option_type: u8,
2520 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2556pub struct NeighborDiscoverySetup {
2557 pub ip_address: Vec<u8>,
2559 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2599pub struct User {
2600 pub user_id: u8,
2602 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2636pub struct ExecutionTime {
2637 pub time: Vec<u8>,
2639 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2673pub struct GsmServiceParameter {
2674 pub delay_class: u8,
2676 pub reliability_class: u8,
2678 pub precedence_class: u8,
2680 pub peak_throughput: u8,
2682 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2726pub struct QualityOfService {
2727 pub default: GsmServiceParameter,
2729 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2757pub struct CellInfo {
2758 pub cell_id: Vec<u8>,
2760 pub location_id: Vec<u8>,
2762 pub imsi: Vec<u8>,
2764 pub imei: Vec<u8>,
2766 pub rn: Vec<u8>,
2768 pub cn: Vec<u8>,
2770 pub signal_quality: Vec<u8>,
2772 pub signal_strength: Vec<u8>,
2774 pub channel_number: Vec<u8>,
2776 pub cell_parameter_id: Vec<u8>,
2778 pub bsic: Vec<u8>,
2780 pub iccid: Vec<u8>,
2782 pub lac: Vec<u8>,
2784 pub mcc: Vec<u8>,
2786 pub mnc: Vec<u8>,
2788 pub tmsi: Vec<u8>,
2790 pub tmgi: Vec<u8>,
2792 pub gprs_status: Vec<u8>,
2794 pub routing_area_code: Vec<u8>,
2796 pub geographic_address: Vec<u8>,
2798 pub access_point_name: Vec<u8>,
2800 pub data_transport_state: Vec<u8>,
2802 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2882pub struct PushProtectionParameter {
2883 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2913pub struct ConfirmationParameters {
2914 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2944pub struct Certificate {
2945 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 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 #[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 #[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 let cd = CosemDataType::Structure(vec![CosemDataType::Long(200), CosemDataType::Enum(30)]);
3063 assert!(ScalerUnit::try_from(&cd).is_err());
3064 }
3065
3066 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[test]
3820 fn all_types_ber_round_trip() {
3821 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}