use crate::interface::InterfaceClass;
use crate::obis::ObisCode;
use crate::types::attrs::ProtectionObject;
use crate::types::{BerError, CosemDataType};
use serde::{Deserialize, Serialize};
use std::any::Any;
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DataProtectionConfig {
pub logical_name: ObisCode,
pub protection_buffer: Vec<u8>,
pub protection_object_list: Vec<ProtectionObject>,
pub protection_parameters_get: Vec<Vec<u8>>,
pub protection_parameters_set: Vec<Vec<u8>>,
pub required_protection: u8,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DataProtection {
logical_name: ObisCode,
protection_buffer: Vec<u8>,
protection_object_list: Vec<ProtectionObject>,
protection_parameters_get: Vec<Vec<u8>>,
protection_parameters_set: Vec<Vec<u8>>,
required_protection: u8,
}
impl DataProtection {
pub fn new(config: DataProtectionConfig) -> Self {
DataProtection {
logical_name: config.logical_name,
protection_buffer: config.protection_buffer,
protection_object_list: config.protection_object_list,
protection_parameters_get: config.protection_parameters_get,
protection_parameters_set: config.protection_parameters_set,
required_protection: config.required_protection,
}
}
fn get_protected_attributes(&self, _data: CosemDataType) -> CosemDataType {
CosemDataType::OctetString(self.protection_buffer.clone())
}
fn set_protected_attributes(&mut self, data: CosemDataType) -> Result<CosemDataType, String> {
match data {
CosemDataType::OctetString(bytes) => {
self.protection_buffer = bytes;
Ok(CosemDataType::Null)
}
CosemDataType::Structure(_) => Ok(CosemDataType::Null),
_ => Err("set_protected_attributes expects an octet-string or structure".to_string()),
}
}
fn invoke_protected_method(_data: CosemDataType) -> CosemDataType {
CosemDataType::Null
}
}
impl InterfaceClass for DataProtection {
fn class_id(&self) -> u16 {
30
}
fn version(&self) -> u8 {
0
}
fn logical_name(&self) -> &ObisCode {
&self.logical_name
}
fn attributes(&self) -> Vec<(u8, CosemDataType)> {
vec![
(1, CosemDataType::OctetString(self.logical_name.to_bytes())),
(2, CosemDataType::OctetString(self.protection_buffer.clone())),
(3, CosemDataType::Array(self.protection_object_list.iter().cloned().map(CosemDataType::from).collect())),
(
4,
CosemDataType::Array(
self.protection_parameters_get.iter().cloned().map(CosemDataType::OctetString).collect(),
),
),
(
5,
CosemDataType::Array(
self.protection_parameters_set.iter().cloned().map(CosemDataType::OctetString).collect(),
),
),
(6, CosemDataType::Enum(self.required_protection)),
]
}
fn methods(&self) -> Vec<(u8, String)> {
vec![
(1, "get_protected_attributes".to_string()),
(2, "set_protected_attributes".to_string()),
(3, "invoke_protected_method".to_string()),
]
}
fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
let mut seq_buf = Vec::new();
CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
for (_, attr) in self.attributes() {
attr.serialize_ber(&mut seq_buf)?;
}
buf.push(0x02); write_length(1 + self.attributes().len(), buf); buf.extend_from_slice(&seq_buf);
Ok(())
}
fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
if !rest.is_empty() {
return Err(BerError::InvalidTag);
}
let CosemDataType::Structure(seq) = tlv else {
return Err(BerError::InvalidTag);
};
if seq.len() != 7 {
return Err(BerError::InvalidLength);
}
if let CosemDataType::LongUnsigned(class_id) = seq[0] {
if class_id != self.class_id() {
return Err(BerError::InvalidValue);
}
} else {
return Err(BerError::InvalidTag);
}
if let CosemDataType::OctetString(obis) = &seq[1] {
if obis.len() == 6 {
self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
} else {
return Err(BerError::InvalidLength);
}
} else {
return Err(BerError::InvalidTag);
}
self.protection_buffer = match &seq[2] {
CosemDataType::OctetString(v) => v.clone(),
_ => return Err(BerError::InvalidTag),
};
self.protection_object_list = take_po_array(&seq[3])?;
self.protection_parameters_get = take_octet_string_array(&seq[4])?;
self.protection_parameters_set = take_octet_string_array(&seq[5])?;
self.required_protection = match seq[6] {
CosemDataType::Enum(v) => v,
_ => return Err(BerError::InvalidTag),
};
Ok(())
}
fn invoke_method(&mut self, method_id: u8, params: Option<CosemDataType>) -> Result<CosemDataType, String> {
let params = params.ok_or("Missing method parameter")?;
match method_id {
1 => Ok(self.get_protected_attributes(params)),
2 => self.set_protected_attributes(params),
3 => Ok(Self::invoke_protected_method(params)),
_ => Err(format!("Method {method_id} not supported for Data protection")),
}
}
fn as_any(&self) -> &dyn Any {
self
}
}
fn take_po_array(value: &CosemDataType) -> Result<Vec<ProtectionObject>, BerError> {
match value {
CosemDataType::Array(list) => {
list.iter().map(|item| ProtectionObject::try_from(item).map_err(|_| BerError::InvalidValue)).collect()
}
_ => Err(BerError::InvalidTag),
}
}
fn take_octet_string_array(value: &CosemDataType) -> Result<Vec<Vec<u8>>, BerError> {
match value {
CosemDataType::Array(list) => list
.iter()
.map(|item| match item {
CosemDataType::OctetString(v) => Ok(v.clone()),
_ => Err(BerError::InvalidTag),
})
.collect(),
_ => Err(BerError::InvalidTag),
}
}
#[allow(clippy::cast_possible_truncation)] fn write_length(length: usize, buf: &mut Vec<u8>) {
if length < 128 {
buf.push(length as u8);
} else {
let bytes = (length as u64).to_be_bytes();
let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
let num_octets = 8 - first_non_zero;
buf.push(0x80 | num_octets as u8);
buf.extend_from_slice(&bytes[first_non_zero..]);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> DataProtection {
DataProtection::new(DataProtectionConfig {
logical_name: ObisCode::new(0, 0, 30, 0, 0, 255),
protection_buffer: vec![0x01, 0x02, 0x03],
protection_object_list: vec![],
protection_parameters_get: vec![],
protection_parameters_set: vec![],
required_protection: 1,
})
}
#[test]
fn class_id_and_attributes() {
let obj = sample();
assert_eq!(obj.class_id(), 30);
assert_eq!(obj.version(), 0);
assert_eq!(obj.attributes().len(), 6);
assert_eq!(obj.methods().len(), 3);
}
#[test]
fn round_trip() {
let obj = sample();
let mut buf = Vec::new();
obj.serialize_ber(&mut buf).unwrap();
let mut decoded = sample();
decoded.required_protection = 9;
decoded.deserialize_ber(&buf).unwrap();
assert_eq!(decoded.attributes(), obj.attributes());
}
#[test]
fn get_and_set_protection_buffer() {
let mut obj = sample();
assert_eq!(
obj.invoke_method(1, Some(CosemDataType::Null)).unwrap(),
CosemDataType::OctetString(vec![0x01, 0x02, 0x03])
);
obj.invoke_method(2, Some(CosemDataType::OctetString(vec![0xAA, 0xBB]))).unwrap();
assert_eq!(obj.attributes()[1].1, CosemDataType::OctetString(vec![0xAA, 0xBB]));
}
}