use crate::obis::ObisCode;
use crate::types::CosemDataType;
use serde::{Deserialize, Serialize};
pub type LogicalName = ObisCode;
pub type Choice = CosemDataType;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DateTime(pub [u8; 12]);
impl DateTime {
pub fn new(bytes: [u8; 12]) -> Self {
Self(bytes)
}
pub fn as_bytes(&self) -> &[u8; 12] {
&self.0
}
pub fn from_ymdhms(year: u16, month: u8, day: u8, hour: u8, min: u8, sec: u8) -> Self {
let mut buf = [0u8; 12];
buf[0..2].copy_from_slice(&year.to_be_bytes());
buf[2] = month;
buf[3] = day;
buf[4] = 0xFF; buf[5] = hour;
buf[6] = min;
buf[7] = sec;
buf[8] = 0; buf[9..12].copy_from_slice(&[0, 0, 0]); Self(buf)
}
}
impl From<DateTime> for CosemDataType {
fn from(dt: DateTime) -> Self {
CosemDataType::OctetString(dt.0.to_vec())
}
}
impl TryFrom<&CosemDataType> for DateTime {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::DateTime(bytes) | CosemDataType::OctetString(bytes) if bytes.len() == 12 => {
let mut buf = [0u8; 12];
buf.copy_from_slice(bytes);
Ok(DateTime(buf))
}
_ => Err("expected 12-byte date-time or octet-string".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BitString(pub Vec<u8>);
impl BitString {
pub fn new(bytes: Vec<u8>) -> Self {
Self(bytes)
}
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
pub fn get(&self, n: usize) -> bool {
let byte = n / 8;
let bit = n % 8;
byte < self.0.len() && (self.0[byte] & (1 << (7 - bit))) != 0
}
}
impl From<BitString> for CosemDataType {
fn from(bs: BitString) -> Self {
CosemDataType::BitString(bs.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScalerUnit {
pub scaler: i8,
pub unit: u8,
}
impl ScalerUnit {
pub fn new(scaler: i8, unit: u8) -> Self {
Self { scaler, unit }
}
#[allow(clippy::cast_precision_loss)] pub fn apply(&self, raw: i64) -> f64 {
raw as f64 * 10f64.powi(i32::from(self.scaler))
}
}
impl From<ScalerUnit> for CosemDataType {
fn from(su: ScalerUnit) -> Self {
CosemDataType::Structure(vec![CosemDataType::Integer(su.scaler), CosemDataType::Enum(su.unit)])
}
}
impl TryFrom<&CosemDataType> for ScalerUnit {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let scaler = match &fields[0] {
CosemDataType::Integer(v) => *v,
CosemDataType::Long(v) => i8::try_from(*v).map_err(|_| "scaler must be integer".to_string())?,
_ => return Err("scaler must be integer".to_string()),
};
let unit = match &fields[1] {
CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
_ => return Err("unit must be enum".to_string()),
};
Ok(ScalerUnit { scaler, unit })
}
_ => Err("expected structure {scaler, unit}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CaptureObjectDefinition {
pub class_id: u16,
pub logical_name: ObisCode,
pub attribute_index: u8,
pub data_index: u8,
}
impl CaptureObjectDefinition {
pub fn new(class_id: u16, logical_name: ObisCode, attribute_index: u8, data_index: u8) -> Self {
Self { class_id, logical_name, attribute_index, data_index }
}
}
impl From<CaptureObjectDefinition> for CosemDataType {
fn from(cod: CaptureObjectDefinition) -> Self {
CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(cod.class_id),
CosemDataType::OctetString(cod.logical_name.to_bytes()),
CosemDataType::Unsigned(cod.attribute_index),
CosemDataType::Unsigned(cod.data_index),
])
}
}
impl TryFrom<&CosemDataType> for CaptureObjectDefinition {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 4 => {
let class_id = match &fields[0] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("class_id must be long-unsigned".to_string()),
};
let logical_name = match &fields[1] {
CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
}
_ => return Err("logical_name must be 6-byte octet-string".to_string()),
};
let attribute_index = match &fields[2] {
CosemDataType::Unsigned(v) => *v,
CosemDataType::Integer(v) => {
u8::try_from(*v).map_err(|_| "attribute_index must be unsigned".to_string())?
}
_ => return Err("attribute_index must be unsigned".to_string()),
};
let data_index = match &fields[3] {
CosemDataType::Unsigned(v) => *v,
CosemDataType::LongUnsigned(v) => {
u8::try_from(*v).map_err(|_| "data_index must be unsigned".to_string())?
}
_ => return Err("data_index must be unsigned".to_string()),
};
Ok(CaptureObjectDefinition { class_id, logical_name, attribute_index, data_index })
}
_ => Err("expected structure {class_id, logical_name, attribute_index, data_index}".to_string()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SortMethod {
Fifo = 1,
Lifo = 2,
Largest = 3,
Smallest = 4,
NearestToZero = 5,
FarthestFromZero = 6,
}
impl SortMethod {
pub fn from_u8(v: u8) -> Option<Self> {
match v {
1 => Some(Self::Fifo),
2 => Some(Self::Lifo),
3 => Some(Self::Largest),
4 => Some(Self::Smallest),
5 => Some(Self::NearestToZero),
6 => Some(Self::FarthestFromZero),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AssociationStatus {
NonAssociated = 0,
AssociationPending = 1,
Associated = 2,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataAttrs {
pub logical_name: LogicalName,
pub value: Choice,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterAttrs {
pub logical_name: LogicalName,
pub value: Choice,
pub scaler_unit: ScalerUnit,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtendedRegisterAttrs {
pub logical_name: LogicalName,
pub value: Choice,
pub scaler_unit: ScalerUnit,
pub status: Choice,
pub capture_time: Choice,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DemandRegisterAttrs {
pub logical_name: LogicalName,
pub current_average_value: Choice,
pub last_average_value: Choice,
pub scaler_unit: ScalerUnit,
pub status: Choice,
pub capture_time: Choice,
pub start_time_current: Choice,
pub period: u32,
pub number_of_periods: u16,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileGenericAttrs {
pub logical_name: LogicalName,
pub buffer: Vec<Choice>,
pub capture_objects: Vec<CaptureObjectDefinition>,
pub capture_period: u32,
pub sort_method: SortMethod,
pub sort_object: Option<CaptureObjectDefinition>,
pub entries_in_use: u32,
pub profile_entries: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClockAttrs {
pub logical_name: LogicalName,
pub time: DateTime,
pub time_zone: i16,
pub status: u8,
pub daylight_savings_begin: DateTime,
pub daylight_savings_end: DateTime,
pub daylight_savings_deviation: i8,
pub daylight_savings_enabled: bool,
pub clock_base: u8,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScriptTableAttrs {
pub logical_name: LogicalName,
pub scripts: Vec<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScheduleAttrs {
pub logical_name: LogicalName,
pub entries: Vec<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecialDaysTableAttrs {
pub logical_name: LogicalName,
pub entries: Vec<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssociationLnAttrs {
pub logical_name: LogicalName,
pub object_list: Vec<Choice>,
pub associated_partners_id: Choice,
pub application_context_name: Choice,
pub xdlms_context_info: Choice,
pub authentication_mechanism_name: u8,
pub secret: Vec<u8>,
pub association_status: AssociationStatus,
pub security_setup_reference: Option<ObisCode>,
pub user_list: Vec<Choice>,
pub current_user: Option<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SapAssignmentAttrs {
pub logical_name: LogicalName,
pub sap_assignment_list: Vec<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActivityCalendarAttrs {
pub logical_name: LogicalName,
pub calendar_name: Vec<u8>,
pub week_profile_table: Vec<Choice>,
pub day_profile_table: Vec<Choice>,
pub month_profile_table: Vec<Choice>,
pub active_calendar: Vec<u8>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterMonitorAttrs {
pub logical_name: LogicalName,
pub thresholds: Vec<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SingleActionScheduleAttrs {
pub logical_name: LogicalName,
pub executed_script: CaptureObjectDefinition,
pub execution_time: Vec<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageTransferAttrs {
pub logical_name: LogicalName,
pub block_size: u16,
pub transferred_blocks: u32,
pub last_block_number: u32,
pub transfer_status: u8,
pub image_transfer_enabled: bool,
pub image_transferred_block_status: Vec<u8>,
pub image_first_not_transferred_block_number: u32,
pub image_block_transfer_trigger: u8,
pub image_transfer_service_enable: bool,
pub image_activation_info: Vec<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisconnectControlAttrs {
pub logical_name: LogicalName,
pub output_state: bool,
pub control_mode: u8,
pub physical_output_name: Vec<u8>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LimiterAttrs {
pub logical_name: LogicalName,
pub monitored_value: Choice,
pub threshold_normal: Choice,
pub threshold_min_operation: Choice,
pub threshold_max_operation: Choice,
pub min_over_threshold_duration: u16,
pub min_under_threshold_duration: u16,
pub emergency_profile: CaptureObjectDefinition,
pub emergency_profile_action: u8,
pub active_calendar_name: Vec<u8>,
pub emergency_profile_group_id: u16,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TcpUdpSetupAttrs {
pub logical_name: LogicalName,
pub port: u16,
pub tcp_udp_protocol: Vec<u8>,
pub ip_reference: Vec<u8>,
pub maximum_simultaneous_connections: u16,
pub maximum_segment_size: u16,
pub inactivity_timeout: u16,
pub transport_security: u8,
pub password_setup: Vec<u8>,
pub password: Vec<u8>,
pub default_password_status: u8,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Ipv4SetupAttrs {
pub logical_name: LogicalName,
pub ip_address: [u8; 4],
pub subnet_mask: [u8; 4],
pub gateway_ip_address: [u8; 4],
pub use_dhcp: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Ipv6SetupAttrs {
pub logical_name: LogicalName,
pub ip_address: [u8; 16],
pub prefix_length: u8,
pub gateway_ip_address: [u8; 16],
pub use_dhcp: bool,
pub multicast_address: [u8; 16],
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MacAddressSetupAttrs {
pub logical_name: LogicalName,
pub unicast_mac_address: [u8; 6],
pub broadcast_mac_address: [u8; 6],
pub multicast_mac_address: [u8; 6],
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GprsModemSetupAttrs {
pub logical_name: LogicalName,
pub apn: Vec<u8>,
pub pin_code: Vec<u8>,
pub username: Vec<u8>,
pub password: Vec<u8>,
pub ask_for_password: bool,
pub ip_address: [u8; 4],
pub ip_port: u16,
pub transfer_services: Vec<u8>,
pub default_transfers: Vec<u8>,
pub gprs_timeout: u16,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GsmDiagnosticAttrs {
pub logical_name: LogicalName,
pub cell_id: Vec<u8>,
pub location_id: Vec<u8>,
pub imsi: Vec<u8>,
pub imei: Vec<u8>,
pub rn: Vec<u8>,
pub cn: Vec<u8>,
pub signal_quality: Vec<u8>,
pub signal_strength: Vec<u8>,
pub channel_number: Vec<u8>,
pub cell_parameter_id: Vec<u8>,
pub bsic: Vec<u8>,
pub iccid: Vec<u8>,
pub lac: Vec<u8>,
pub mcc: Vec<u8>,
pub mnc: Vec<u8>,
pub tmsi: Vec<u8>,
pub tmgi: Vec<u8>,
pub gprs_status: Vec<u8>,
pub routing_area_code: Vec<u8>,
pub geographic_address: Vec<u8>,
pub access_point_name: Vec<u8>,
pub data_transport_state: Vec<u8>,
pub nma_message: Vec<u8>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArbitratorAttrs {
pub logical_name: LogicalName,
pub capture_groups: Vec<CaptureObjectDefinition>,
pub action_groups: Vec<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IecHdlcSetupAttrs {
pub logical_name: LogicalName,
pub channel: u8,
pub wait: Vec<Choice>,
pub client_address: u16,
pub server_address: u16,
pub window_size_tx: u8,
pub window_size_rx: u8,
pub max_info_tx: u16,
pub max_info_rx: u16,
pub max_timeout_tx: u16,
pub max_retries_tx: u8,
pub max_timeout_respond: u16,
pub max_retries_respond: u8,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IecLocalPortSetupAttrs {
pub logical_name: LogicalName,
pub mode: u8,
pub communication_speed: u8,
pub max_size_info_field: u16,
pub device_address: Vec<u8>,
pub password1: Vec<u8>,
pub password2: Vec<u8>,
pub password3: Vec<u8>,
pub client_address: Vec<u8>,
pub point_to_point_address: Vec<u8>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MbusSlavePortSetupAttrs {
pub logical_name: LogicalName,
pub mbus_address: Vec<u8>,
pub identification_number: Vec<u8>,
pub manufacturer_id: Vec<u8>,
pub data_type: Vec<u8>,
pub max_slave_pifs: u16,
pub max_master_pifs: u16,
pub character_encoding: Vec<u8>,
pub m_bus_mode: u8,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataProtectionAttrs {
pub logical_name: LogicalName,
pub protection_method: u8,
pub protection_key: Vec<u8>,
pub key_translation_table_1: Vec<Choice>,
pub key_translation_table_2: Vec<Choice>,
pub key_translation_table_3: Vec<Choice>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecuritySetupAttrs {
pub logical_name: LogicalName,
pub security_policy: u8,
pub security_suite: u8,
pub client_system_title: Vec<u8>,
pub server_system_title: Vec<u8>,
pub certificates: Vec<Choice>,
}
impl AssociationStatus {
pub fn from_u8(v: u8) -> Option<Self> {
match v {
0 => Some(Self::NonAssociated),
1 => Some(Self::AssociationPending),
2 => Some(Self::Associated),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClockBase {
None = 0,
InternalCrystal = 1,
MainsFrequency = 2,
Gps = 3,
RadioClock = 4,
}
impl ClockBase {
pub fn from_u8(v: u8) -> Option<Self> {
match v {
0 => Some(Self::None),
1 => Some(Self::InternalCrystal),
2 => Some(Self::MainsFrequency),
3 => Some(Self::Gps),
4 => Some(Self::RadioClock),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccessRight {
pub attribute_access: Vec<AttributeAccessItem>,
pub method_access: Vec<MethodAccessItem>,
}
impl From<AccessRight> for CosemDataType {
fn from(ar: AccessRight) -> Self {
CosemDataType::Structure(vec![
CosemDataType::Array(ar.attribute_access.into_iter().map(CosemDataType::from).collect()),
CosemDataType::Array(ar.method_access.into_iter().map(CosemDataType::from).collect()),
])
}
}
impl TryFrom<&CosemDataType> for AccessRight {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let attribute_access = match &fields[0] {
CosemDataType::Array(items) => {
items.iter().map(AttributeAccessItem::try_from).collect::<Result<Vec<_>, _>>()?
}
_ => return Err("attribute_access must be array".to_string()),
};
let method_access = match &fields[1] {
CosemDataType::Array(items) => {
items.iter().map(MethodAccessItem::try_from).collect::<Result<Vec<_>, _>>()?
}
_ => return Err("method_access must be array".to_string()),
};
Ok(AccessRight { attribute_access, method_access })
}
_ => Err("expected structure {attribute_access, method_access}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttributeAccessItem {
pub attribute_id: i8,
pub access_mode: u8,
pub access_selectors: Option<Vec<i8>>,
}
impl From<AttributeAccessItem> for CosemDataType {
fn from(item: AttributeAccessItem) -> Self {
let access_selectors = item.access_selectors.map_or(CosemDataType::Null, |ids| {
CosemDataType::Array(ids.into_iter().map(CosemDataType::Integer).collect())
});
CosemDataType::Structure(vec![
CosemDataType::Integer(item.attribute_id),
CosemDataType::Enum(item.access_mode),
access_selectors,
])
}
}
impl TryFrom<&CosemDataType> for AttributeAccessItem {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 3 => {
let attribute_id = match &fields[0] {
CosemDataType::Integer(v) => *v,
CosemDataType::Long(v) => {
i8::try_from(*v).map_err(|_| "attribute_id must be integer".to_string())?
}
_ => return Err("attribute_id must be integer".to_string()),
};
let access_mode = match &fields[1] {
CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
_ => return Err("access_mode must be enum".to_string()),
};
let access_selectors = match &fields[2] {
CosemDataType::Array(items) => {
let ids = items
.iter()
.map(|item| match item {
CosemDataType::Integer(v) => Ok(*v),
CosemDataType::Long(v) => {
i8::try_from(*v).map_err(|_| "selector must be integer".to_string())
}
_ => Err("selector must be integer".to_string()),
})
.collect::<Result<Vec<_>, _>>()?;
Some(ids)
}
_ => None,
};
Ok(AttributeAccessItem { attribute_id, access_mode, access_selectors })
}
_ => Err("expected structure {attribute_id, access_mode, access_selectors}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MethodAccessItem {
pub method_id: i8,
pub access_mode: u8,
}
impl From<MethodAccessItem> for CosemDataType {
fn from(item: MethodAccessItem) -> Self {
CosemDataType::Structure(vec![CosemDataType::Integer(item.method_id), CosemDataType::Enum(item.access_mode)])
}
}
impl TryFrom<&CosemDataType> for MethodAccessItem {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let method_id = match &fields[0] {
CosemDataType::Integer(v) => *v,
CosemDataType::Long(v) => i8::try_from(*v).map_err(|_| "method_id must be integer".to_string())?,
_ => return Err("method_id must be integer".to_string()),
};
let access_mode = match &fields[1] {
CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
_ => return Err("access_mode must be enum".to_string()),
};
Ok(MethodAccessItem { method_id, access_mode })
}
_ => Err("expected structure {method_id, access_mode}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ObjectListElement {
pub class_id: u16,
pub version: u8,
pub logical_name: ObisCode,
pub access_rights: AccessRight,
}
impl From<ObjectListElement> for CosemDataType {
fn from(e: ObjectListElement) -> Self {
CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(e.class_id),
CosemDataType::Unsigned(e.version),
CosemDataType::OctetString(e.logical_name.to_bytes()),
CosemDataType::from(e.access_rights),
])
}
}
impl TryFrom<&CosemDataType> for ObjectListElement {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 4 => {
let class_id = match &fields[0] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("class_id must be long-unsigned".to_string()),
};
let version = match &fields[1] {
CosemDataType::Unsigned(v) => *v,
CosemDataType::LongUnsigned(v) => {
u8::try_from(*v).map_err(|_| "version must be unsigned".to_string())?
}
_ => return Err("version must be unsigned".to_string()),
};
let logical_name = match &fields[2] {
CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
}
_ => return Err("logical_name must be 6-byte octet-string".to_string()),
};
let access_rights = AccessRight::try_from(&fields[3])?;
Ok(ObjectListElement { class_id, version, logical_name, access_rights })
}
_ => Err("expected structure {class_id, version, logical_name, access_rights}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssociatedPartnersId {
pub client_sap: i8,
pub server_sap: u16,
}
impl From<AssociatedPartnersId> for CosemDataType {
fn from(ap: AssociatedPartnersId) -> Self {
CosemDataType::Structure(vec![
CosemDataType::Integer(ap.client_sap),
CosemDataType::LongUnsigned(ap.server_sap),
])
}
}
impl TryFrom<&CosemDataType> for AssociatedPartnersId {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let client_sap = match &fields[0] {
CosemDataType::Integer(v) => *v,
CosemDataType::Long(v) => i8::try_from(*v).map_err(|_| "client_SAP must be integer".to_string())?,
_ => return Err("client_SAP must be integer".to_string()),
};
let server_sap = match &fields[1] {
CosemDataType::LongUnsigned(v) => *v,
CosemDataType::Unsigned(v) => u16::from(*v),
_ => return Err("server_SAP must be long-unsigned".to_string()),
};
Ok(AssociatedPartnersId { client_sap, server_sap })
}
_ => Err("expected structure {client_SAP, server_SAP}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ContextName {
Structure {
joint_iso_ctt: u8,
country: u8,
country_name: u16,
identified_organization: u8,
dlms_ua: u8,
application_context: u8,
context_id: u8,
},
OctetString(Vec<u8>),
}
impl From<ContextName> for CosemDataType {
fn from(cn: ContextName) -> Self {
match cn {
ContextName::Structure {
joint_iso_ctt,
country,
country_name,
identified_organization,
dlms_ua,
application_context,
context_id,
} => CosemDataType::Structure(vec![
CosemDataType::Unsigned(joint_iso_ctt),
CosemDataType::Unsigned(country),
CosemDataType::LongUnsigned(country_name),
CosemDataType::Unsigned(identified_organization),
CosemDataType::Unsigned(dlms_ua),
CosemDataType::Unsigned(application_context),
CosemDataType::Unsigned(context_id),
]),
ContextName::OctetString(bytes) => CosemDataType::OctetString(bytes),
}
}
}
impl TryFrom<&CosemDataType> for ContextName {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 7 => {
let joint_iso_ctt = match &fields[0] {
CosemDataType::Unsigned(v) => *v,
_ => return Err("joint_iso_ctt must be unsigned".to_string()),
};
let country = match &fields[1] {
CosemDataType::Unsigned(v) => *v,
_ => return Err("country must be unsigned".to_string()),
};
let country_name = match &fields[2] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("country_name must be long-unsigned".to_string()),
};
let identified_organization = match &fields[3] {
CosemDataType::Unsigned(v) => *v,
_ => return Err("identified_organization must be unsigned".to_string()),
};
let dlms_ua = match &fields[4] {
CosemDataType::Unsigned(v) => *v,
_ => return Err("DLMS_UA must be unsigned".to_string()),
};
let application_context = match &fields[5] {
CosemDataType::Unsigned(v) => *v,
_ => return Err("application_context must be unsigned".to_string()),
};
let context_id = match &fields[6] {
CosemDataType::Unsigned(v) => *v,
_ => return Err("context_id must be unsigned".to_string()),
};
Ok(ContextName::Structure {
joint_iso_ctt,
country,
country_name,
identified_organization,
dlms_ua,
application_context,
context_id,
})
}
CosemDataType::OctetString(bytes) => Ok(ContextName::OctetString(bytes.clone())),
_ => Err("expected structure or octet-string for context_name".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct XDLMSContextInfo {
pub conformance: Vec<u8>,
pub max_receive_pdu_size: u16,
pub max_send_pdu_size: u16,
pub dlms_version_number: u8,
pub quality_of_service: i8,
pub cyphering_info: Vec<u8>,
}
impl From<XDLMSContextInfo> for CosemDataType {
fn from(ctx: XDLMSContextInfo) -> Self {
CosemDataType::Structure(vec![
CosemDataType::BitString(ctx.conformance),
CosemDataType::LongUnsigned(ctx.max_receive_pdu_size),
CosemDataType::LongUnsigned(ctx.max_send_pdu_size),
CosemDataType::Unsigned(ctx.dlms_version_number),
CosemDataType::Integer(ctx.quality_of_service),
CosemDataType::OctetString(ctx.cyphering_info),
])
}
}
impl TryFrom<&CosemDataType> for XDLMSContextInfo {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 6 => {
let conformance = match &fields[0] {
CosemDataType::BitString(v) => v.clone(),
_ => return Err("conformance must be bit-string".to_string()),
};
let max_receive_pdu_size = match &fields[1] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("max_receive_pdu_size must be long-unsigned".to_string()),
};
let max_send_pdu_size = match &fields[2] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("max_send_pdu_size must be long-unsigned".to_string()),
};
let dlms_version_number = match &fields[3] {
CosemDataType::Unsigned(v) => *v,
_ => return Err("dlms_version_number must be unsigned".to_string()),
};
let quality_of_service = match &fields[4] {
CosemDataType::Integer(v) => *v,
CosemDataType::Long(v) => {
i8::try_from(*v).map_err(|_| "quality_of_service must be integer".to_string())?
}
_ => return Err("quality_of_service must be integer".to_string()),
};
let cyphering_info = match &fields[5] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("cyphering_info must be octet-string".to_string()),
};
Ok(XDLMSContextInfo {
conformance,
max_receive_pdu_size,
max_send_pdu_size,
dlms_version_number,
quality_of_service,
cyphering_info,
})
}
_ => Err("expected structure for xDLMS_context_info".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValueDefinition {
pub class_id: u16,
pub logical_name: ObisCode,
pub attribute_index: i8,
}
impl From<ValueDefinition> for CosemDataType {
fn from(vd: ValueDefinition) -> Self {
CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(vd.class_id),
CosemDataType::OctetString(vd.logical_name.to_bytes()),
CosemDataType::Integer(vd.attribute_index),
])
}
}
impl TryFrom<&CosemDataType> for ValueDefinition {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 3 => {
let class_id = match &fields[0] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("class_id must be long-unsigned".to_string()),
};
let logical_name = match &fields[1] {
CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
}
_ => return Err("logical_name must be 6-byte octet-string".to_string()),
};
let attribute_index = match &fields[2] {
CosemDataType::Integer(v) => *v,
CosemDataType::Long(v) => {
i8::try_from(*v).map_err(|_| "attribute_index must be integer".to_string())?
}
_ => return Err("attribute_index must be integer".to_string()),
};
Ok(ValueDefinition { class_id, logical_name, attribute_index })
}
_ => Err("expected structure {class_id, logical_name, attribute_index}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActionItem {
pub script_logical_name: ObisCode,
pub script_selector: u16,
}
impl From<ActionItem> for CosemDataType {
fn from(ai: ActionItem) -> Self {
CosemDataType::Structure(vec![
CosemDataType::OctetString(ai.script_logical_name.to_bytes()),
CosemDataType::LongUnsigned(ai.script_selector),
])
}
}
impl TryFrom<&CosemDataType> for ActionItem {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let script_logical_name = match &fields[0] {
CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
}
_ => return Err("script_logical_name must be 6-byte octet-string".to_string()),
};
let script_selector = match &fields[1] {
CosemDataType::LongUnsigned(v) => *v,
CosemDataType::Unsigned(v) => u16::from(*v),
_ => return Err("script_selector must be long-unsigned".to_string()),
};
Ok(ActionItem { script_logical_name, script_selector })
}
_ => Err("expected structure {script_logical_name, script_selector}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActionSet {
pub action_up: ActionItem,
pub action_down: ActionItem,
}
impl From<ActionSet> for CosemDataType {
fn from(a: ActionSet) -> Self {
CosemDataType::Structure(vec![CosemDataType::from(a.action_up), CosemDataType::from(a.action_down)])
}
}
impl TryFrom<&CosemDataType> for ActionSet {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let action_up = ActionItem::try_from(&fields[0])?;
let action_down = ActionItem::try_from(&fields[1])?;
Ok(ActionSet { action_up, action_down })
}
_ => Err("expected structure {action_up, action_down}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionSpecification {
pub service_id: u8,
pub class_id: u16,
pub logical_name: ObisCode,
pub index: i8,
pub parameter: Choice,
}
impl From<ActionSpecification> for CosemDataType {
fn from(aspec: ActionSpecification) -> Self {
CosemDataType::Structure(vec![
CosemDataType::Enum(aspec.service_id),
CosemDataType::LongUnsigned(aspec.class_id),
CosemDataType::OctetString(aspec.logical_name.to_bytes()),
CosemDataType::Integer(aspec.index),
aspec.parameter,
])
}
}
impl TryFrom<&CosemDataType> for ActionSpecification {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 5 => {
let service_id = match &fields[0] {
CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
_ => return Err("service_id must be enum".to_string()),
};
let class_id = match &fields[1] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("class_id must be long-unsigned".to_string()),
};
let logical_name = match &fields[2] {
CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
}
_ => return Err("logical_name must be 6-byte octet-string".to_string()),
};
let index = match &fields[3] {
CosemDataType::Integer(v) => *v,
CosemDataType::Long(v) => i8::try_from(*v).map_err(|_| "index must be integer".to_string())?,
_ => return Err("index must be integer".to_string()),
};
let parameter = fields[4].clone();
Ok(ActionSpecification { service_id, class_id, logical_name, index, parameter })
}
_ => Err("expected structure {service_id, class_id, logical_name, index, parameter}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Script {
pub script_identifier: u16,
pub actions: Vec<ActionSpecification>,
}
impl From<Script> for CosemDataType {
fn from(s: Script) -> Self {
CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(s.script_identifier),
CosemDataType::Array(s.actions.into_iter().map(CosemDataType::from).collect()),
])
}
}
impl TryFrom<&CosemDataType> for Script {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let script_identifier = match &fields[0] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("script_identifier must be long-unsigned".to_string()),
};
let actions = match &fields[1] {
CosemDataType::Array(items) => {
items.iter().map(ActionSpecification::try_from).collect::<Result<Vec<_>, _>>()?
}
_ => return Err("actions must be array".to_string()),
};
Ok(Script { script_identifier, actions })
}
_ => Err("expected structure {script_identifier, actions}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScheduleTableEntry {
pub index: u16,
pub enable: bool,
pub script_logical_name: ObisCode,
pub script_selector: u16,
pub switch_time: Vec<u8>,
pub validity_window: u16,
pub exec_weekdays: Vec<u8>,
pub exec_specdays: Vec<u8>,
pub begin_date: Vec<u8>,
pub end_date: Vec<u8>,
}
impl From<ScheduleTableEntry> for CosemDataType {
fn from(e: ScheduleTableEntry) -> Self {
CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(e.index),
CosemDataType::Boolean(e.enable),
CosemDataType::OctetString(e.script_logical_name.to_bytes()),
CosemDataType::LongUnsigned(e.script_selector),
CosemDataType::OctetString(e.switch_time),
CosemDataType::LongUnsigned(e.validity_window),
CosemDataType::BitString(e.exec_weekdays),
CosemDataType::BitString(e.exec_specdays),
CosemDataType::OctetString(e.begin_date),
CosemDataType::OctetString(e.end_date),
])
}
}
impl TryFrom<&CosemDataType> for ScheduleTableEntry {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 10 => {
let index = match &fields[0] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("index must be long-unsigned".to_string()),
};
let enable = match &fields[1] {
CosemDataType::Boolean(v) => *v,
_ => return Err("enable must be boolean".to_string()),
};
let script_logical_name = match &fields[2] {
CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
}
_ => return Err("script_logical_name must be 6-byte octet-string".to_string()),
};
let script_selector = match &fields[3] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("script_selector must be long-unsigned".to_string()),
};
let switch_time = match &fields[4] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("switch_time must be octet-string".to_string()),
};
let validity_window = match &fields[5] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("validity_window must be long-unsigned".to_string()),
};
let exec_weekdays = match &fields[6] {
CosemDataType::BitString(v) => v.clone(),
_ => return Err("exec_weekdays must be bit-string".to_string()),
};
let exec_specdays = match &fields[7] {
CosemDataType::BitString(v) => v.clone(),
_ => return Err("exec_specdays must be bit-string".to_string()),
};
let begin_date = match &fields[8] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("begin_date must be octet-string".to_string()),
};
let end_date = match &fields[9] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("end_date must be octet-string".to_string()),
};
Ok(ScheduleTableEntry {
index,
enable,
script_logical_name,
script_selector,
switch_time,
validity_window,
exec_weekdays,
exec_specdays,
begin_date,
end_date,
})
}
_ => Err("expected 10-element structure for schedule_table_entry".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpecialDayEntry {
pub index: u16,
pub specialday_date: Vec<u8>,
pub day_id: u8,
}
impl From<SpecialDayEntry> for CosemDataType {
fn from(e: SpecialDayEntry) -> Self {
CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(e.index),
CosemDataType::OctetString(e.specialday_date),
CosemDataType::Unsigned(e.day_id),
])
}
}
impl TryFrom<&CosemDataType> for SpecialDayEntry {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 3 => {
let index = match &fields[0] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("index must be long-unsigned".to_string()),
};
let specialday_date = match &fields[1] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("specialday_date must be octet-string".to_string()),
};
let day_id = match &fields[2] {
CosemDataType::Unsigned(v) => *v,
_ => return Err("day_id must be unsigned".to_string()),
};
Ok(SpecialDayEntry { index, specialday_date, day_id })
}
_ => Err("expected structure {index, specialday_date, day_id}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SeasonProfile {
pub season_profile_name: Vec<u8>,
pub season_start: Vec<u8>,
pub week_name: Vec<u8>,
}
impl From<SeasonProfile> for CosemDataType {
fn from(sp: SeasonProfile) -> Self {
CosemDataType::Structure(vec![
CosemDataType::OctetString(sp.season_profile_name),
CosemDataType::OctetString(sp.season_start),
CosemDataType::OctetString(sp.week_name),
])
}
}
impl TryFrom<&CosemDataType> for SeasonProfile {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 3 => {
let season_profile_name = match &fields[0] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("season_profile_name must be octet-string".to_string()),
};
let season_start = match &fields[1] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("season_start must be octet-string".to_string()),
};
let week_name = match &fields[2] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("week_name must be octet-string".to_string()),
};
Ok(SeasonProfile { season_profile_name, season_start, week_name })
}
_ => Err("expected structure for season_profile".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WeekProfile {
pub week_profile_name: Vec<u8>,
pub monday: u8,
pub tuesday: u8,
pub wednesday: u8,
pub thursday: u8,
pub friday: u8,
pub saturday: u8,
pub sunday: u8,
}
impl From<WeekProfile> for CosemDataType {
fn from(wp: WeekProfile) -> Self {
CosemDataType::Structure(vec![
CosemDataType::OctetString(wp.week_profile_name),
CosemDataType::Unsigned(wp.monday),
CosemDataType::Unsigned(wp.tuesday),
CosemDataType::Unsigned(wp.wednesday),
CosemDataType::Unsigned(wp.thursday),
CosemDataType::Unsigned(wp.friday),
CosemDataType::Unsigned(wp.saturday),
CosemDataType::Unsigned(wp.sunday),
])
}
}
impl TryFrom<&CosemDataType> for WeekProfile {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 8 => {
let week_profile_name = match &fields[0] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("week_profile_name must be octet-string".to_string()),
};
let get_u8 = |f: &CosemDataType| -> Result<u8, String> {
match f {
CosemDataType::Unsigned(v) => Ok(*v),
_ => Err("day_id must be unsigned".to_string()),
}
};
Ok(WeekProfile {
week_profile_name,
monday: get_u8(&fields[1])?,
tuesday: get_u8(&fields[2])?,
wednesday: get_u8(&fields[3])?,
thursday: get_u8(&fields[4])?,
friday: get_u8(&fields[5])?,
saturday: get_u8(&fields[6])?,
sunday: get_u8(&fields[7])?,
})
}
_ => Err("expected 8-element structure for week_profile".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DayProfileAction {
pub start_time: Vec<u8>,
pub script_logical_name: ObisCode,
pub script_selector: u16,
}
impl From<DayProfileAction> for CosemDataType {
fn from(a: DayProfileAction) -> Self {
CosemDataType::Structure(vec![
CosemDataType::OctetString(a.start_time),
CosemDataType::OctetString(a.script_logical_name.to_bytes()),
CosemDataType::LongUnsigned(a.script_selector),
])
}
}
impl TryFrom<&CosemDataType> for DayProfileAction {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 3 => {
let start_time = match &fields[0] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("start_time must be octet-string".to_string()),
};
let script_logical_name = match &fields[1] {
CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
}
_ => return Err("script_logical_name must be 6-byte octet-string".to_string()),
};
let script_selector = match &fields[2] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("script_selector must be long-unsigned".to_string()),
};
Ok(DayProfileAction { start_time, script_logical_name, script_selector })
}
_ => Err("expected structure for day_profile_action".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DayProfile {
pub day_id: u8,
pub day_schedule: Vec<DayProfileAction>,
}
impl From<DayProfile> for CosemDataType {
fn from(dp: DayProfile) -> Self {
CosemDataType::Structure(vec![
CosemDataType::Unsigned(dp.day_id),
CosemDataType::Array(dp.day_schedule.into_iter().map(CosemDataType::from).collect()),
])
}
}
impl TryFrom<&CosemDataType> for DayProfile {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let day_id = match &fields[0] {
CosemDataType::Unsigned(v) => *v,
_ => return Err("day_id must be unsigned".to_string()),
};
let day_schedule = match &fields[1] {
CosemDataType::Array(items) => {
items.iter().map(DayProfileAction::try_from).collect::<Result<Vec<_>, _>>()?
}
_ => return Err("day_schedule must be array".to_string()),
};
Ok(DayProfile { day_id, day_schedule })
}
_ => Err("expected structure {day_id, day_schedule}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SendDestinationAndMethod {
pub transport_service: u8,
pub destination: Vec<u8>,
pub message: u8,
}
impl From<SendDestinationAndMethod> for CosemDataType {
fn from(s: SendDestinationAndMethod) -> Self {
CosemDataType::Structure(vec![
CosemDataType::Enum(s.transport_service),
CosemDataType::OctetString(s.destination),
CosemDataType::Enum(s.message),
])
}
}
impl TryFrom<&CosemDataType> for SendDestinationAndMethod {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 3 => {
let transport_service = match &fields[0] {
CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
_ => return Err("transport_service must be enum".to_string()),
};
let destination = match &fields[1] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("destination must be octet-string".to_string()),
};
let message = match &fields[2] {
CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
_ => return Err("message must be enum".to_string()),
};
Ok(SendDestinationAndMethod { transport_service, destination, message })
}
_ => Err("expected structure for send_destination_and_method".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommunicationWindow {
pub begin: DateTime,
pub end: DateTime,
}
impl From<CommunicationWindow> for CosemDataType {
fn from(cw: CommunicationWindow) -> Self {
CosemDataType::Structure(vec![
CosemDataType::OctetString(cw.begin.0.to_vec()),
CosemDataType::OctetString(cw.end.0.to_vec()),
])
}
}
impl TryFrom<&CosemDataType> for CommunicationWindow {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let begin = DateTime::try_from(&fields[0])?;
let end = DateTime::try_from(&fields[1])?;
Ok(CommunicationWindow { begin, end })
}
_ => Err("expected structure {begin, end}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmergencyProfile {
pub emergency_profile_id: u16,
pub emergency_activation_time: Vec<u8>,
pub emergency_duration: u32,
}
impl From<EmergencyProfile> for CosemDataType {
fn from(ep: EmergencyProfile) -> Self {
CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(ep.emergency_profile_id),
CosemDataType::OctetString(ep.emergency_activation_time),
CosemDataType::DoubleLongUnsigned(ep.emergency_duration),
])
}
}
impl TryFrom<&CosemDataType> for EmergencyProfile {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 3 => {
let emergency_profile_id = match &fields[0] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("emergency_profile_id must be long-unsigned".to_string()),
};
let emergency_activation_time = match &fields[1] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("emergency_activation_time must be octet-string".to_string()),
};
let emergency_duration = match &fields[2] {
CosemDataType::DoubleLongUnsigned(v) => *v,
_ => return Err("emergency_duration must be double-long-unsigned".to_string()),
};
Ok(EmergencyProfile { emergency_profile_id, emergency_activation_time, emergency_duration })
}
_ => Err("expected structure for emergency_profile".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LimiterAction {
pub action_over_threshold: ActionItem,
pub action_under_threshold: ActionItem,
}
impl From<LimiterAction> for CosemDataType {
fn from(a: LimiterAction) -> Self {
CosemDataType::Structure(vec![
CosemDataType::from(a.action_over_threshold),
CosemDataType::from(a.action_under_threshold),
])
}
}
impl TryFrom<&CosemDataType> for LimiterAction {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let action_over_threshold = ActionItem::try_from(&fields[0])?;
let action_under_threshold = ActionItem::try_from(&fields[1])?;
Ok(LimiterAction { action_over_threshold, action_under_threshold })
}
_ => Err("expected structure {action_over_threshold, action_under_threshold}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ObjectDefinition {
pub class_id: u16,
pub logical_name: ObisCode,
}
impl From<ObjectDefinition> for CosemDataType {
fn from(od: ObjectDefinition) -> Self {
CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(od.class_id),
CosemDataType::OctetString(od.logical_name.to_bytes()),
])
}
}
impl TryFrom<&CosemDataType> for ObjectDefinition {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let class_id = match &fields[0] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("class_id must be long-unsigned".to_string()),
};
let logical_name = match &fields[1] {
CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
}
_ => return Err("logical_name must be 6-byte octet-string".to_string()),
};
Ok(ObjectDefinition { class_id, logical_name })
}
_ => Err("expected structure {class_id, logical_name}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RegisterActMask {
pub mask_name: Vec<u8>,
pub index_list: Vec<u8>,
}
impl From<RegisterActMask> for CosemDataType {
fn from(m: RegisterActMask) -> Self {
CosemDataType::Structure(vec![
CosemDataType::OctetString(m.mask_name),
CosemDataType::Array(m.index_list.into_iter().map(CosemDataType::Unsigned).collect()),
])
}
}
impl TryFrom<&CosemDataType> for RegisterActMask {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let mask_name = match &fields[0] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("mask_name must be octet-string".to_string()),
};
let index_list = match &fields[1] {
CosemDataType::Array(items) => items
.iter()
.map(|item| match item {
CosemDataType::Unsigned(v) => Ok(*v),
_ => Err("index must be unsigned".to_string()),
})
.collect::<Result<Vec<_>, _>>()?,
_ => return Err("index_list must be array".to_string()),
};
Ok(RegisterActMask { mask_name, index_list })
}
_ => Err("expected structure {mask_name, index_list}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImageToActivateInfo {
pub image_block_number: u32,
pub image_block_value: Vec<u8>,
}
impl From<ImageToActivateInfo> for CosemDataType {
fn from(info: ImageToActivateInfo) -> Self {
CosemDataType::Structure(vec![
CosemDataType::DoubleLongUnsigned(info.image_block_number),
CosemDataType::OctetString(info.image_block_value),
])
}
}
impl TryFrom<&CosemDataType> for ImageToActivateInfo {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let image_block_number = match &fields[0] {
CosemDataType::DoubleLongUnsigned(v) => *v,
_ => return Err("image_block_number must be double-long-unsigned".to_string()),
};
let image_block_value = match &fields[1] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("image_block_value must be octet-string".to_string()),
};
Ok(ImageToActivateInfo { image_block_number, image_block_value })
}
_ => Err("expected structure for image_to_activate_info".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutedScript {
pub script_logical_name: ObisCode,
pub script_selector: u16,
}
impl From<ExecutedScript> for CosemDataType {
fn from(es: ExecutedScript) -> Self {
CosemDataType::Structure(vec![
CosemDataType::OctetString(es.script_logical_name.to_bytes()),
CosemDataType::LongUnsigned(es.script_selector),
])
}
}
impl TryFrom<&CosemDataType> for ExecutedScript {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let script_logical_name = match &fields[0] {
CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
}
_ => return Err("script_logical_name must be 6-byte octet-string".to_string()),
};
let script_selector = match &fields[1] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("script_selector must be long-unsigned".to_string()),
};
Ok(ExecutedScript { script_logical_name, script_selector })
}
_ => Err("expected structure {script_logical_name, script_selector}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SapAssignmentEntry {
pub sap: u16,
pub logical_device_name: Vec<u8>,
}
impl From<SapAssignmentEntry> for CosemDataType {
fn from(entry: SapAssignmentEntry) -> Self {
CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(entry.sap),
CosemDataType::OctetString(entry.logical_device_name),
])
}
}
impl TryFrom<&CosemDataType> for SapAssignmentEntry {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let sap = match &fields[0] {
CosemDataType::LongUnsigned(v) => *v,
CosemDataType::Unsigned(v) => u16::from(*v),
_ => return Err("SAP must be long-unsigned".to_string()),
};
let logical_device_name = match &fields[1] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("logical_device_name must be octet-string".to_string()),
};
Ok(SapAssignmentEntry { sap, logical_device_name })
}
_ => Err("expected structure {SAP, logical_device_name}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GsmAdjacentCell {
pub cell_id: Vec<u8>,
pub signal_quality: Vec<u8>,
pub signal_strength: Vec<u8>,
}
impl From<GsmAdjacentCell> for CosemDataType {
fn from(cell: GsmAdjacentCell) -> Self {
CosemDataType::Structure(vec![
CosemDataType::OctetString(cell.cell_id),
CosemDataType::OctetString(cell.signal_quality),
CosemDataType::OctetString(cell.signal_strength),
])
}
}
impl TryFrom<&CosemDataType> for GsmAdjacentCell {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 3 => {
let cell_id = match &fields[0] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("cell_id must be octet-string".to_string()),
};
let signal_quality = match &fields[1] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("signal_quality must be octet-string".to_string()),
};
let signal_strength = match &fields[2] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("signal_strength must be octet-string".to_string()),
};
Ok(GsmAdjacentCell { cell_id, signal_quality, signal_strength })
}
_ => Err("expected structure {cell_id, signal_quality, signal_strength}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProtectionObject {
pub class_id: u16,
pub logical_name: ObisCode,
pub attribute_index: i8,
}
impl From<ProtectionObject> for CosemDataType {
fn from(po: ProtectionObject) -> Self {
CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(po.class_id),
CosemDataType::OctetString(po.logical_name.to_bytes()),
CosemDataType::Integer(po.attribute_index),
])
}
}
impl TryFrom<&CosemDataType> for ProtectionObject {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 3 => {
let class_id = match &fields[0] {
CosemDataType::LongUnsigned(v) => *v,
_ => return Err("class_id must be long-unsigned".to_string()),
};
let logical_name = match &fields[1] {
CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
}
_ => return Err("logical_name must be 6-byte octet-string".to_string()),
};
let attribute_index = match &fields[2] {
CosemDataType::Integer(v) => *v,
CosemDataType::Long(v) => {
i8::try_from(*v).map_err(|_| "attribute_index must be integer".to_string())?
}
_ => return Err("attribute_index must be integer".to_string()),
};
Ok(ProtectionObject { class_id, logical_name, attribute_index })
}
_ => Err("expected structure {class_id, logical_name, attribute_index}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IpOption {
pub option_type: u8,
pub option_value: Vec<u8>,
}
impl From<IpOption> for CosemDataType {
fn from(opt: IpOption) -> Self {
CosemDataType::Structure(vec![
CosemDataType::Unsigned(opt.option_type),
CosemDataType::OctetString(opt.option_value),
])
}
}
impl TryFrom<&CosemDataType> for IpOption {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let option_type = match &fields[0] {
CosemDataType::Unsigned(v) => *v,
_ => return Err("option_type must be unsigned".to_string()),
};
let option_value = match &fields[1] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("option_value must be octet-string".to_string()),
};
Ok(IpOption { option_type, option_value })
}
_ => Err("expected structure {option_type, option_value}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NeighborDiscoverySetup {
pub ip_address: Vec<u8>,
pub hardware_address: Vec<u8>,
}
impl From<NeighborDiscoverySetup> for CosemDataType {
fn from(nd: NeighborDiscoverySetup) -> Self {
CosemDataType::Structure(vec![
CosemDataType::OctetString(nd.ip_address),
CosemDataType::OctetString(nd.hardware_address),
])
}
}
impl TryFrom<&CosemDataType> for NeighborDiscoverySetup {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let ip_address = match &fields[0] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("ip_address must be octet-string".to_string()),
};
let hardware_address = match &fields[1] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("hardware_address must be octet-string".to_string()),
};
Ok(NeighborDiscoverySetup { ip_address, hardware_address })
}
_ => Err("expected structure {ip_address, hardware_address}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct User {
pub user_id: u8,
pub user_name: Vec<u8>,
}
impl From<User> for CosemDataType {
fn from(u: User) -> Self {
CosemDataType::Structure(vec![CosemDataType::Unsigned(u.user_id), CosemDataType::OctetString(u.user_name)])
}
}
impl TryFrom<&CosemDataType> for User {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let user_id = match &fields[0] {
CosemDataType::Unsigned(v) => *v,
_ => return Err("user_id must be unsigned".to_string()),
};
let user_name = match &fields[1] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("user_name must be octet-string".to_string()),
};
Ok(User { user_id, user_name })
}
_ => Err("expected structure {user_id, user_name}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecutionTime {
pub time: Vec<u8>,
pub date: Vec<u8>,
}
impl From<ExecutionTime> for CosemDataType {
fn from(et: ExecutionTime) -> Self {
CosemDataType::Structure(vec![CosemDataType::OctetString(et.time), CosemDataType::OctetString(et.date)])
}
}
impl TryFrom<&CosemDataType> for ExecutionTime {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let time = match &fields[0] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("time must be octet-string".to_string()),
};
let date = match &fields[1] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("date must be octet-string".to_string()),
};
Ok(ExecutionTime { time, date })
}
_ => Err("expected structure {time, date}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GsmServiceParameter {
pub delay_class: u8,
pub reliability_class: u8,
pub precedence_class: u8,
pub peak_throughput: u8,
pub mean_throughput: u8,
}
impl From<GsmServiceParameter> for CosemDataType {
fn from(p: GsmServiceParameter) -> Self {
CosemDataType::Structure(vec![
CosemDataType::Unsigned(p.delay_class),
CosemDataType::Unsigned(p.reliability_class),
CosemDataType::Unsigned(p.precedence_class),
CosemDataType::Unsigned(p.peak_throughput),
CosemDataType::Unsigned(p.mean_throughput),
])
}
}
impl TryFrom<&CosemDataType> for GsmServiceParameter {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 5 => {
let get_u8 = |f: &CosemDataType| -> Result<u8, String> {
match f {
CosemDataType::Unsigned(v) => Ok(*v),
_ => Err("must be unsigned".to_string()),
}
};
Ok(GsmServiceParameter {
delay_class: get_u8(&fields[0])?,
reliability_class: get_u8(&fields[1])?,
precedence_class: get_u8(&fields[2])?,
peak_throughput: get_u8(&fields[3])?,
mean_throughput: get_u8(&fields[4])?,
})
}
_ => Err("expected structure {delay_class, reliability_class, precedence_class, peak_throughput, mean_throughput}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QualityOfService {
pub default: GsmServiceParameter,
pub requested: GsmServiceParameter,
}
impl From<QualityOfService> for CosemDataType {
fn from(qos: QualityOfService) -> Self {
CosemDataType::Structure(vec![CosemDataType::from(qos.default), CosemDataType::from(qos.requested)])
}
}
impl TryFrom<&CosemDataType> for QualityOfService {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 2 => {
let default = GsmServiceParameter::try_from(&fields[0])?;
let requested = GsmServiceParameter::try_from(&fields[1])?;
Ok(QualityOfService { default, requested })
}
_ => Err("expected structure {default, requested}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CellInfo {
pub cell_id: Vec<u8>,
pub location_id: Vec<u8>,
pub imsi: Vec<u8>,
pub imei: Vec<u8>,
pub rn: Vec<u8>,
pub cn: Vec<u8>,
pub signal_quality: Vec<u8>,
pub signal_strength: Vec<u8>,
pub channel_number: Vec<u8>,
pub cell_parameter_id: Vec<u8>,
pub bsic: Vec<u8>,
pub iccid: Vec<u8>,
pub lac: Vec<u8>,
pub mcc: Vec<u8>,
pub mnc: Vec<u8>,
pub tmsi: Vec<u8>,
pub tmgi: Vec<u8>,
pub gprs_status: Vec<u8>,
pub routing_area_code: Vec<u8>,
pub geographic_address: Vec<u8>,
pub access_point_name: Vec<u8>,
pub data_transport_state: Vec<u8>,
pub nma_message: Vec<u8>,
}
impl From<CellInfo> for CosemDataType {
fn from(ci: CellInfo) -> Self {
CosemDataType::Structure(vec![
CosemDataType::OctetString(ci.cell_id),
CosemDataType::OctetString(ci.location_id),
CosemDataType::OctetString(ci.imsi),
CosemDataType::OctetString(ci.imei),
CosemDataType::OctetString(ci.rn),
CosemDataType::OctetString(ci.cn),
CosemDataType::OctetString(ci.signal_quality),
CosemDataType::OctetString(ci.signal_strength),
CosemDataType::OctetString(ci.channel_number),
CosemDataType::OctetString(ci.cell_parameter_id),
CosemDataType::OctetString(ci.bsic),
CosemDataType::OctetString(ci.iccid),
CosemDataType::OctetString(ci.lac),
CosemDataType::OctetString(ci.mcc),
CosemDataType::OctetString(ci.mnc),
CosemDataType::OctetString(ci.tmsi),
CosemDataType::OctetString(ci.tmgi),
CosemDataType::OctetString(ci.gprs_status),
CosemDataType::OctetString(ci.routing_area_code),
CosemDataType::OctetString(ci.geographic_address),
CosemDataType::OctetString(ci.access_point_name),
CosemDataType::OctetString(ci.data_transport_state),
CosemDataType::OctetString(ci.nma_message),
])
}
}
impl TryFrom<&CosemDataType> for CellInfo {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if fields.len() >= 23 => {
let oct = |f: &CosemDataType| -> Result<Vec<u8>, String> {
match f {
CosemDataType::OctetString(v) => Ok(v.clone()),
_ => Err("must be octet-string".to_string()),
}
};
Ok(CellInfo {
cell_id: oct(&fields[0])?,
location_id: oct(&fields[1])?,
imsi: oct(&fields[2])?,
imei: oct(&fields[3])?,
rn: oct(&fields[4])?,
cn: oct(&fields[5])?,
signal_quality: oct(&fields[6])?,
signal_strength: oct(&fields[7])?,
channel_number: oct(&fields[8])?,
cell_parameter_id: oct(&fields[9])?,
bsic: oct(&fields[10])?,
iccid: oct(&fields[11])?,
lac: oct(&fields[12])?,
mcc: oct(&fields[13])?,
mnc: oct(&fields[14])?,
tmsi: oct(&fields[15])?,
tmgi: oct(&fields[16])?,
gprs_status: oct(&fields[17])?,
routing_area_code: oct(&fields[18])?,
geographic_address: oct(&fields[19])?,
access_point_name: oct(&fields[20])?,
data_transport_state: oct(&fields[21])?,
nma_message: oct(&fields[22])?,
})
}
_ => Err("expected 23-element structure for CellInfo".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PushProtectionParameter {
pub data: Vec<u8>,
}
impl From<PushProtectionParameter> for CosemDataType {
fn from(pp: PushProtectionParameter) -> Self {
CosemDataType::Structure(vec![CosemDataType::OctetString(pp.data)])
}
}
impl TryFrom<&CosemDataType> for PushProtectionParameter {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if !fields.is_empty() => {
let data = match &fields[0] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("data must be octet-string".to_string()),
};
Ok(PushProtectionParameter { data })
}
_ => Err("expected structure {data}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfirmationParameters {
pub data: Vec<u8>,
}
impl From<ConfirmationParameters> for CosemDataType {
fn from(cp: ConfirmationParameters) -> Self {
CosemDataType::Structure(vec![CosemDataType::OctetString(cp.data)])
}
}
impl TryFrom<&CosemDataType> for ConfirmationParameters {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if !fields.is_empty() => {
let data = match &fields[0] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("data must be octet-string".to_string()),
};
Ok(ConfirmationParameters { data })
}
_ => Err("expected structure {data}".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Certificate {
pub data: Vec<u8>,
}
impl From<Certificate> for CosemDataType {
fn from(c: Certificate) -> Self {
CosemDataType::Structure(vec![CosemDataType::OctetString(c.data)])
}
}
impl TryFrom<&CosemDataType> for Certificate {
type Error = String;
fn try_from(value: &CosemDataType) -> Result<Self, String> {
match value {
CosemDataType::Structure(fields) if !fields.is_empty() => {
let data = match &fields[0] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err("data must be octet-string".to_string()),
};
Ok(Certificate { data })
}
_ => Err("expected structure {data}".to_string()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::obis::ObisCode;
fn round_trip<
T: for<'a> TryFrom<&'a CosemDataType, Error = String> + Into<CosemDataType> + Clone + PartialEq + std::fmt::Debug,
>(
val: &T,
) {
let cd: CosemDataType = val.clone().into();
let back = T::try_from(&cd).expect("TryFrom should succeed");
assert_eq!(*val, back);
}
fn obis(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> ObisCode {
ObisCode::new(a, b, c, d, e, f)
}
#[test]
fn datetime_round_trip() {
let dt = DateTime::new([0x07, 0xE5, 0x05, 0x01, 0x02, 0x10, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00]);
round_trip(&dt);
}
#[test]
fn datetime_from_ymdhms() {
let dt = DateTime::from_ymdhms(2025, 5, 1, 16, 30, 0);
assert_eq!(dt.0[0..2], 2025u16.to_be_bytes());
assert_eq!(dt.0[2], 5);
assert_eq!(dt.0[3], 1);
assert_eq!(dt.0[5], 16);
assert_eq!(dt.0[6], 30);
}
#[test]
fn datetime_try_from_octet_string() {
let bytes = vec![0x07, 0xE5, 0x01, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
let cd = CosemDataType::OctetString(bytes);
let dt = DateTime::try_from(&cd).unwrap();
assert_eq!(dt.0[0..2], [0x07, 0xE5]);
}
#[test]
fn datetime_try_from_wrong_length() {
let cd = CosemDataType::OctetString(vec![0u8; 10]);
assert!(DateTime::try_from(&cd).is_err());
}
#[test]
fn scaler_unit_round_trip() {
let su = ScalerUnit::new(-2, 30);
round_trip(&su);
}
#[test]
fn scaler_unit_apply() {
let su = ScalerUnit::new(-2, 30);
assert_eq!(su.apply(100), 1.0);
assert_eq!(su.apply(12345), 123.45);
}
#[test]
fn scaler_unit_from_structure() {
let cd = CosemDataType::Structure(vec![CosemDataType::Integer(0), CosemDataType::Enum(27)]);
let su = ScalerUnit::try_from(&cd).unwrap();
assert_eq!(su.scaler, 0);
assert_eq!(su.unit, 27);
}
#[test]
fn scaler_unit_accepts_in_range_long_scaler() {
let cd = CosemDataType::Structure(vec![CosemDataType::Long(-2), CosemDataType::Enum(30)]);
let su = ScalerUnit::try_from(&cd).unwrap();
assert_eq!(su.scaler, -2);
}
#[test]
fn scaler_unit_rejects_out_of_range_long_scaler() {
let cd = CosemDataType::Structure(vec![CosemDataType::Long(200), CosemDataType::Enum(30)]);
assert!(ScalerUnit::try_from(&cd).is_err());
}
#[test]
fn capture_object_definition_round_trip() {
let cod = CaptureObjectDefinition::new(3, obis(0, 0, 1, 0, 0, 255), 2, 0);
round_trip(&cod);
}
#[test]
fn capture_object_definition_rejects_negative_attribute_index() {
let cd = CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(3),
CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
CosemDataType::Integer(-1),
CosemDataType::Unsigned(0),
]);
assert!(CaptureObjectDefinition::try_from(&cd).is_err());
}
#[test]
fn capture_object_definition_rejects_out_of_range_data_index() {
let cd = CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(3),
CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
CosemDataType::Unsigned(2),
CosemDataType::LongUnsigned(300),
]);
assert!(CaptureObjectDefinition::try_from(&cd).is_err());
}
#[test]
fn sort_method_from_u8() {
assert_eq!(SortMethod::from_u8(1), Some(SortMethod::Fifo));
assert_eq!(SortMethod::from_u8(2), Some(SortMethod::Lifo));
assert_eq!(SortMethod::from_u8(3), Some(SortMethod::Largest));
assert_eq!(SortMethod::from_u8(4), Some(SortMethod::Smallest));
assert_eq!(SortMethod::from_u8(5), Some(SortMethod::NearestToZero));
assert_eq!(SortMethod::from_u8(6), Some(SortMethod::FarthestFromZero));
assert_eq!(SortMethod::from_u8(0), None);
assert_eq!(SortMethod::from_u8(7), None);
}
#[test]
fn association_status_from_u8() {
assert_eq!(AssociationStatus::from_u8(0), Some(AssociationStatus::NonAssociated));
assert_eq!(AssociationStatus::from_u8(1), Some(AssociationStatus::AssociationPending));
assert_eq!(AssociationStatus::from_u8(2), Some(AssociationStatus::Associated));
assert_eq!(AssociationStatus::from_u8(3), None);
}
#[test]
fn clock_base_from_u8() {
assert_eq!(ClockBase::from_u8(0), Some(ClockBase::None));
assert_eq!(ClockBase::from_u8(1), Some(ClockBase::InternalCrystal));
assert_eq!(ClockBase::from_u8(2), Some(ClockBase::MainsFrequency));
assert_eq!(ClockBase::from_u8(3), Some(ClockBase::Gps));
assert_eq!(ClockBase::from_u8(4), Some(ClockBase::RadioClock));
assert_eq!(ClockBase::from_u8(5), None);
}
#[test]
fn attribute_access_item_round_trip() {
let item = AttributeAccessItem { attribute_id: 2, access_mode: 1, access_selectors: None };
round_trip(&item);
}
#[test]
fn attribute_access_item_with_selectors() {
let item = AttributeAccessItem { attribute_id: 3, access_mode: 3, access_selectors: Some(vec![1, 2]) };
let cd: CosemDataType = item.into();
let back = AttributeAccessItem::try_from(&cd).unwrap();
assert_eq!(back.access_selectors, Some(vec![1, 2]));
}
#[test]
fn attribute_access_item_rejects_out_of_range_long_attribute_id() {
let cd = CosemDataType::Structure(vec![CosemDataType::Long(200), CosemDataType::Enum(1), CosemDataType::Null]);
assert!(AttributeAccessItem::try_from(&cd).is_err());
}
#[test]
fn method_access_item_round_trip() {
let item = MethodAccessItem { method_id: 1, access_mode: 1 };
round_trip(&item);
}
#[test]
fn method_access_item_rejects_out_of_range_long_method_id() {
let cd = CosemDataType::Structure(vec![CosemDataType::Long(200), CosemDataType::Enum(1)]);
assert!(MethodAccessItem::try_from(&cd).is_err());
}
#[test]
fn access_right_round_trip() {
let ar = AccessRight {
attribute_access: vec![
AttributeAccessItem { attribute_id: 1, access_mode: 1, access_selectors: None },
AttributeAccessItem { attribute_id: 2, access_mode: 3, access_selectors: None },
],
method_access: vec![MethodAccessItem { method_id: 1, access_mode: 1 }],
};
round_trip(&ar);
}
#[test]
fn object_list_element_round_trip() {
let ole = ObjectListElement {
class_id: 3,
version: 0,
logical_name: obis(0, 0, 1, 0, 0, 255),
access_rights: AccessRight { attribute_access: vec![], method_access: vec![] },
};
round_trip(&ole);
}
#[test]
fn object_list_element_rejects_out_of_range_long_unsigned_version() {
let cd = CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(3),
CosemDataType::LongUnsigned(300),
CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
CosemDataType::Array(vec![]),
]);
assert!(ObjectListElement::try_from(&cd).is_err());
}
#[test]
fn associated_partners_id_round_trip() {
let ap = AssociatedPartnersId { client_sap: 1, server_sap: 16 };
round_trip(&ap);
}
#[test]
fn associated_partners_id_try_from_wrong_type() {
let cd = CosemDataType::Null;
assert!(AssociatedPartnersId::try_from(&cd).is_err());
}
#[test]
fn associated_partners_id_rejects_out_of_range_long_client_sap() {
let cd = CosemDataType::Structure(vec![CosemDataType::Long(200), CosemDataType::LongUnsigned(16)]);
assert!(AssociatedPartnersId::try_from(&cd).is_err());
}
#[test]
fn context_name_structure_round_trip() {
let cn = ContextName::Structure {
joint_iso_ctt: 2,
country: 16,
country_name: 756,
identified_organization: 5,
dlms_ua: 8,
application_context: 1,
context_id: 1,
};
round_trip(&cn);
}
#[test]
fn context_name_octet_string_round_trip() {
let cn = ContextName::OctetString(vec![0x09, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x01, 0x01]);
let cd: CosemDataType = cn.clone().into();
let back = ContextName::try_from(&cd).unwrap();
assert_eq!(cn, back);
}
#[test]
fn xdlms_context_info_round_trip() {
let ctx = XDLMSContextInfo {
conformance: vec![
0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00,
],
max_receive_pdu_size: 1024,
max_send_pdu_size: 1024,
dlms_version_number: 6,
quality_of_service: -1,
cyphering_info: vec![],
};
round_trip(&ctx);
}
#[test]
fn xdlms_context_info_rejects_out_of_range_long_quality_of_service() {
let cd = CosemDataType::Structure(vec![
CosemDataType::BitString(vec![0xFF]),
CosemDataType::LongUnsigned(1024),
CosemDataType::LongUnsigned(1024),
CosemDataType::Unsigned(6),
CosemDataType::Long(200),
CosemDataType::OctetString(vec![]),
]);
assert!(XDLMSContextInfo::try_from(&cd).is_err());
}
#[test]
fn value_definition_round_trip() {
let vd = ValueDefinition { class_id: 3, logical_name: obis(0, 0, 1, 0, 0, 255), attribute_index: 2 };
round_trip(&vd);
}
#[test]
fn value_definition_rejects_out_of_range_long_attribute_index() {
let cd = CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(3),
CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
CosemDataType::Long(200),
]);
assert!(ValueDefinition::try_from(&cd).is_err());
}
#[test]
fn action_item_round_trip() {
let ai = ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 };
round_trip(&ai);
}
#[test]
fn action_set_round_trip() {
let aset = ActionSet {
action_up: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 },
action_down: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 2 },
};
round_trip(&aset);
}
#[test]
fn action_specification_round_trip() {
let aspec = ActionSpecification {
service_id: 1,
class_id: 3,
logical_name: obis(0, 0, 1, 0, 0, 255),
index: 2,
parameter: CosemDataType::Null,
};
round_trip(&aspec);
}
#[test]
fn action_specification_rejects_out_of_range_long_index() {
let cd = CosemDataType::Structure(vec![
CosemDataType::Enum(1),
CosemDataType::LongUnsigned(3),
CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
CosemDataType::Long(200),
CosemDataType::Null,
]);
assert!(ActionSpecification::try_from(&cd).is_err());
}
#[test]
fn action_specification_with_parameter() {
let aspec = ActionSpecification {
service_id: 2,
class_id: 9,
logical_name: obis(0, 0, 10, 100, 0, 255),
index: 1,
parameter: CosemDataType::LongUnsigned(42),
};
let cd: CosemDataType = aspec.into();
let back = ActionSpecification::try_from(&cd).unwrap();
assert_eq!(back.parameter, CosemDataType::LongUnsigned(42));
}
#[test]
fn script_round_trip() {
let script = Script {
script_identifier: 1,
actions: vec![ActionSpecification {
service_id: 1,
class_id: 3,
logical_name: obis(0, 0, 1, 0, 0, 255),
index: 2,
parameter: CosemDataType::DoubleLongUnsigned(1000),
}],
};
round_trip(&script);
}
#[test]
fn script_empty_actions() {
let script = Script { script_identifier: 0, actions: vec![] };
round_trip(&script);
}
#[test]
fn schedule_table_entry_round_trip() {
let ste = ScheduleTableEntry {
index: 1,
enable: true,
script_logical_name: obis(0, 0, 10, 100, 0, 255),
script_selector: 1,
switch_time: vec![0x10, 0x00, 0x00],
validity_window: 0xFFFF,
exec_weekdays: vec![0x7F],
exec_specdays: vec![0x00],
begin_date: vec![0x07, 0xE5, 0x01, 0x01, 0xFF],
end_date: vec![0x07, 0xE5, 0x12, 0x31, 0xFF],
};
round_trip(&ste);
}
#[test]
fn special_day_entry_round_trip() {
let sde =
SpecialDayEntry { index: 1, specialday_date: vec![0x07, 0xE5, 0x01, 0x01, 0xFF, 0xFF, 0xFF], day_id: 3 };
round_trip(&sde);
}
#[test]
fn season_profile_round_trip() {
let sp = SeasonProfile {
season_profile_name: b"Summer".to_vec(),
season_start: vec![0x07, 0xE5, 0x04, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
week_name: b"WeekA".to_vec(),
};
round_trip(&sp);
}
#[test]
fn week_profile_round_trip() {
let wp = WeekProfile {
week_profile_name: b"WeekA".to_vec(),
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
sunday: 7,
};
round_trip(&wp);
}
#[test]
fn day_profile_action_round_trip() {
let dpa = DayProfileAction {
start_time: vec![0x08, 0x00, 0x00],
script_logical_name: obis(0, 0, 10, 100, 0, 255),
script_selector: 1,
};
round_trip(&dpa);
}
#[test]
fn day_profile_round_trip() {
let dp = DayProfile {
day_id: 1,
day_schedule: vec![
DayProfileAction {
start_time: vec![0x08, 0x00, 0x00],
script_logical_name: obis(0, 0, 10, 100, 0, 255),
script_selector: 1,
},
DayProfileAction {
start_time: vec![0x18, 0x00, 0x00],
script_logical_name: obis(0, 0, 10, 100, 0, 255),
script_selector: 2,
},
],
};
round_trip(&dp);
}
#[test]
fn day_profile_empty_schedule() {
let dp = DayProfile { day_id: 1, day_schedule: vec![] };
round_trip(&dp);
}
#[test]
fn send_destination_and_method_round_trip() {
let sdm =
SendDestinationAndMethod { transport_service: 0, destination: b"192.168.1.100:4059".to_vec(), message: 2 };
round_trip(&sdm);
}
#[test]
fn communication_window_round_trip() {
let cw = CommunicationWindow {
begin: DateTime::from_ymdhms(2025, 1, 1, 8, 0, 0),
end: DateTime::from_ymdhms(2025, 12, 31, 18, 0, 0),
};
round_trip(&cw);
}
#[test]
fn emergency_profile_round_trip() {
let ep = EmergencyProfile {
emergency_profile_id: 1,
emergency_activation_time: vec![0x07, 0xE5, 0x01, 0x01, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
emergency_duration: 3600,
};
round_trip(&ep);
}
#[test]
fn limiter_action_round_trip() {
let la = LimiterAction {
action_over_threshold: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 },
action_under_threshold: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 2 },
};
round_trip(&la);
}
#[test]
fn object_definition_round_trip() {
let od = ObjectDefinition { class_id: 3, logical_name: obis(0, 0, 1, 0, 0, 255) };
round_trip(&od);
}
#[test]
fn register_act_mask_round_trip() {
let ram = RegisterActMask { mask_name: b"DayTariff".to_vec(), index_list: vec![1, 3, 5] };
round_trip(&ram);
}
#[test]
fn image_to_activate_info_round_trip() {
let itai = ImageToActivateInfo { image_block_number: 1, image_block_value: vec![0x01, 0x02, 0x03, 0x04] };
round_trip(&itai);
}
#[test]
fn executed_script_round_trip() {
let es = ExecutedScript { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 };
round_trip(&es);
}
#[test]
fn sap_assignment_entry_round_trip() {
let sae = SapAssignmentEntry { sap: 1, logical_device_name: b"Meter01".to_vec() };
round_trip(&sae);
}
#[test]
fn gsm_adjacent_cell_round_trip() {
let gac =
GsmAdjacentCell { cell_id: vec![0x01, 0x02], signal_quality: vec![0x03], signal_strength: vec![0x04] };
round_trip(&gac);
}
#[test]
fn protection_object_round_trip() {
let po = ProtectionObject { class_id: 3, logical_name: obis(0, 0, 1, 0, 0, 255), attribute_index: 2 };
round_trip(&po);
}
#[test]
fn protection_object_rejects_out_of_range_long_attribute_index() {
let cd = CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(3),
CosemDataType::OctetString(vec![0, 0, 1, 0, 0, 255]),
CosemDataType::Long(200),
]);
assert!(ProtectionObject::try_from(&cd).is_err());
}
#[test]
fn ip_option_round_trip() {
let io = IpOption { option_type: 7, option_value: vec![0xC0, 0xA8, 0x01, 0x01] };
round_trip(&io);
}
#[test]
fn neighbor_discovery_setup_round_trip() {
let nds = NeighborDiscoverySetup {
ip_address: vec![
0xFE, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
],
hardware_address: vec![0x00, 0x1A, 0x2B, 0x3C, 0x4D, 0x5E],
};
round_trip(&nds);
}
#[test]
fn ber_round_trip_access_right() {
let ar = AccessRight {
attribute_access: vec![AttributeAccessItem { attribute_id: 1, access_mode: 1, access_selectors: None }],
method_access: vec![MethodAccessItem { method_id: 1, access_mode: 1 }],
};
let cd: CosemDataType = ar.clone().into();
let mut buf = Vec::new();
cd.serialize_ber(&mut buf).unwrap();
let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
assert!(rest.is_empty());
let back = AccessRight::try_from(&decoded).unwrap();
assert_eq!(ar, back);
}
#[test]
fn ber_round_trip_object_list_element() {
let ole = ObjectListElement {
class_id: 15,
version: 1,
logical_name: obis(0, 0, 40, 0, 0, 255),
access_rights: AccessRight { attribute_access: vec![], method_access: vec![] },
};
let cd: CosemDataType = ole.clone().into();
let mut buf = Vec::new();
cd.serialize_ber(&mut buf).unwrap();
let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
assert!(rest.is_empty());
let back = ObjectListElement::try_from(&decoded).unwrap();
assert_eq!(ole, back);
}
#[test]
fn ber_round_trip_script() {
let script = Script {
script_identifier: 42,
actions: vec![ActionSpecification {
service_id: 1,
class_id: 3,
logical_name: obis(0, 0, 1, 0, 0, 255),
index: 2,
parameter: CosemDataType::DoubleLongUnsigned(12345),
}],
};
let cd: CosemDataType = script.clone().into();
let mut buf = Vec::new();
cd.serialize_ber(&mut buf).unwrap();
let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
assert!(rest.is_empty());
let back = Script::try_from(&decoded).unwrap();
assert_eq!(script, back);
}
#[test]
fn ber_round_trip_schedule_table_entry() {
let ste = ScheduleTableEntry {
index: 1,
enable: true,
script_logical_name: obis(0, 0, 10, 100, 0, 255),
script_selector: 1,
switch_time: vec![0x10, 0x00, 0x00],
validity_window: 60,
exec_weekdays: vec![0x7F],
exec_specdays: vec![0x00],
begin_date: vec![0x07, 0xE5, 0x01, 0x01, 0xFF],
end_date: vec![0x07, 0xE5, 0x12, 0x31, 0xFF],
};
let cd: CosemDataType = ste.clone().into();
let mut buf = Vec::new();
cd.serialize_ber(&mut buf).unwrap();
let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
assert!(rest.is_empty());
let back = ScheduleTableEntry::try_from(&decoded).unwrap();
assert_eq!(ste, back);
}
#[test]
fn ber_round_trip_emergency_profile() {
let ep = EmergencyProfile {
emergency_profile_id: 5,
emergency_activation_time: vec![0x07, 0xE5, 0x06, 0x15, 0xFF, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
emergency_duration: 7200,
};
let cd: CosemDataType = ep.clone().into();
let mut buf = Vec::new();
cd.serialize_ber(&mut buf).unwrap();
let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
assert!(rest.is_empty());
let back = EmergencyProfile::try_from(&decoded).unwrap();
assert_eq!(ep, back);
}
#[test]
fn access_right_wrong_type() {
assert!(AccessRight::try_from(&CosemDataType::Null).is_err());
assert!(AccessRight::try_from(&CosemDataType::Unsigned(1)).is_err());
}
#[test]
fn action_item_wrong_type() {
assert!(ActionItem::try_from(&CosemDataType::Null).is_err());
}
#[test]
fn context_name_wrong_type() {
assert!(ContextName::try_from(&CosemDataType::Unsigned(1)).is_err());
}
#[test]
fn xdlms_context_info_wrong_fields() {
let cd = CosemDataType::Structure(vec![CosemDataType::BitString(vec![0]), CosemDataType::LongUnsigned(1024)]);
assert!(XDLMSContextInfo::try_from(&cd).is_err());
}
#[test]
fn value_definition_wrong_type() {
assert!(ValueDefinition::try_from(&CosemDataType::Null).is_err());
}
#[test]
fn script_wrong_type() {
assert!(Script::try_from(&CosemDataType::Null).is_err());
assert!(Script::try_from(&CosemDataType::Array(vec![])).is_err());
}
#[test]
fn send_destination_and_method_wrong_type() {
assert!(SendDestinationAndMethod::try_from(&CosemDataType::Null).is_err());
}
#[test]
fn emergency_profile_wrong_type() {
assert!(EmergencyProfile::try_from(&CosemDataType::Null).is_err());
}
#[test]
fn image_to_activate_info_wrong_type() {
assert!(ImageToActivateInfo::try_from(&CosemDataType::Null).is_err());
}
#[test]
fn all_types_ber_round_trip() {
macro_rules! test_ber {
($val:expr, $type:ty) => {{
let val: $type = $val;
let cd: CosemDataType = val.clone().into();
let mut buf = Vec::new();
cd.serialize_ber(&mut buf).unwrap();
let (decoded, rest) = CosemDataType::deserialize_ber(&buf).unwrap();
assert!(rest.is_empty(), "trailing bytes");
let back = <$type>::try_from(&decoded).unwrap();
assert_eq!(val, back);
}};
}
test_ber!(ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 }, ActionItem);
test_ber!(ObjectDefinition { class_id: 3, logical_name: obis(0, 0, 1, 0, 0, 255) }, ObjectDefinition);
test_ber!(
ExecutedScript { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 2 },
ExecutedScript
);
test_ber!(
ValueDefinition { class_id: 5, logical_name: obis(0, 0, 96, 1, 0, 255), attribute_index: 2 },
ValueDefinition
);
test_ber!(
ProtectionObject { class_id: 3, logical_name: obis(0, 0, 1, 0, 0, 255), attribute_index: 1 },
ProtectionObject
);
test_ber!(SapAssignmentEntry { sap: 1, logical_device_name: b"Meter".to_vec() }, SapAssignmentEntry);
test_ber!(IpOption { option_type: 7, option_value: vec![192, 168, 1, 1] }, IpOption);
test_ber!(
GsmAdjacentCell { cell_id: vec![1], signal_quality: vec![2], signal_strength: vec![3] },
GsmAdjacentCell
);
test_ber!(RegisterActMask { mask_name: b"Day".to_vec(), index_list: vec![1, 2] }, RegisterActMask);
test_ber!(ImageToActivateInfo { image_block_number: 1, image_block_value: vec![0xAA] }, ImageToActivateInfo);
test_ber!(
SpecialDayEntry { index: 1, specialday_date: vec![0x07, 0xE5, 0x01, 0x01, 0xFF, 0xFF, 0xFF], day_id: 1 },
SpecialDayEntry
);
test_ber!(
SeasonProfile {
season_profile_name: b"Summer".to_vec(),
season_start: vec![0u8; 12],
week_name: b"W1".to_vec()
},
SeasonProfile
);
test_ber!(
WeekProfile {
week_profile_name: b"W1".to_vec(),
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
sunday: 7
},
WeekProfile
);
test_ber!(
DayProfileAction {
start_time: vec![8, 0, 0],
script_logical_name: obis(0, 0, 10, 100, 0, 255),
script_selector: 1
},
DayProfileAction
);
test_ber!(
DayProfile {
day_id: 1,
day_schedule: vec![DayProfileAction {
start_time: vec![8, 0, 0],
script_logical_name: obis(0, 0, 10, 100, 0, 255),
script_selector: 1
}]
},
DayProfile
);
test_ber!(
NeighborDiscoverySetup {
ip_address: vec![0xFE, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
hardware_address: vec![0, 1, 2, 3, 4, 5]
},
NeighborDiscoverySetup
);
test_ber!(AssociatedPartnersId { client_sap: 1, server_sap: 16 }, AssociatedPartnersId);
test_ber!(
XDLMSContextInfo {
conformance: vec![0; 18],
max_receive_pdu_size: 1024,
max_send_pdu_size: 1024,
dlms_version_number: 6,
quality_of_service: -1,
cyphering_info: vec![]
},
XDLMSContextInfo
);
test_ber!(
CommunicationWindow {
begin: DateTime::from_ymdhms(2025, 1, 1, 8, 0, 0),
end: DateTime::from_ymdhms(2025, 12, 31, 18, 0, 0)
},
CommunicationWindow
);
test_ber!(
EmergencyProfile {
emergency_profile_id: 1,
emergency_activation_time: vec![0u8; 12],
emergency_duration: 3600
},
EmergencyProfile
);
test_ber!(
LimiterAction {
action_over_threshold: ActionItem {
script_logical_name: obis(0, 0, 10, 100, 0, 255),
script_selector: 1
},
action_under_threshold: ActionItem {
script_logical_name: obis(0, 0, 10, 100, 0, 255),
script_selector: 2
},
},
LimiterAction
);
test_ber!(
ActionSet {
action_up: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 1 },
action_down: ActionItem { script_logical_name: obis(0, 0, 10, 100, 0, 255), script_selector: 2 },
},
ActionSet
);
test_ber!(
SendDestinationAndMethod { transport_service: 0, destination: b"192.168.1.1:4059".to_vec(), message: 2 },
SendDestinationAndMethod
);
test_ber!(
ActionSpecification {
service_id: 1,
class_id: 3,
logical_name: obis(0, 0, 1, 0, 0, 255),
index: 2,
parameter: CosemDataType::Null
},
ActionSpecification
);
test_ber!(Script { script_identifier: 1, actions: vec![] }, Script);
test_ber!(
ScheduleTableEntry {
index: 1,
enable: true,
script_logical_name: obis(0, 0, 10, 100, 0, 255),
script_selector: 1,
switch_time: vec![0x10, 0, 0],
validity_window: 60,
exec_weekdays: vec![0x7F],
exec_specdays: vec![0],
begin_date: vec![0x07, 0xE5, 1, 1, 0xFF],
end_date: vec![0x07, 0xE5, 12, 31, 0xFF],
},
ScheduleTableEntry
);
test_ber!(DateTime::new([0x07, 0xE5, 0x05, 0x01, 0x02, 0x10, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00]), DateTime);
test_ber!(ScalerUnit::new(-2, 30), ScalerUnit);
test_ber!(CaptureObjectDefinition::new(3, obis(0, 0, 1, 0, 0, 255), 2, 0), CaptureObjectDefinition);
test_ber!(AttributeAccessItem { attribute_id: 1, access_mode: 1, access_selectors: None }, AttributeAccessItem);
test_ber!(MethodAccessItem { method_id: 1, access_mode: 1 }, MethodAccessItem);
test_ber!(
AccessRight {
attribute_access: vec![AttributeAccessItem { attribute_id: 1, access_mode: 1, access_selectors: None }],
method_access: vec![MethodAccessItem { method_id: 1, access_mode: 1 }],
},
AccessRight
);
test_ber!(
ObjectListElement {
class_id: 3,
version: 0,
logical_name: obis(0, 0, 1, 0, 0, 255),
access_rights: AccessRight { attribute_access: vec![], method_access: vec![] },
},
ObjectListElement
);
test_ber!(ContextName::OctetString(vec![0x09, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x01, 0x01]), ContextName);
}
}