use crate::axdr::Data;
use crate::codec::{Error, ErrorKind, Result};
use crate::obis::Obis;
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct AttributeAccess: u8 {
const READ = 0x01;
const WRITE = 0x02;
const AUTHENTICATED_REQUEST = 0x04;
const ENCRYPTED_REQUEST = 0x08;
const DIGITALLY_SIGNED_REQUEST = 0x10;
const AUTHENTICATED_RESPONSE = 0x20;
const ENCRYPTED_RESPONSE = 0x40;
const DIGITALLY_SIGNED_RESPONSE = 0x80;
}
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct MethodAccess: u8 {
const ACCESS = 0x01;
const AUTHENTICATED_REQUEST = 0x04;
const ENCRYPTED_REQUEST = 0x08;
const DIGITALLY_SIGNED_REQUEST = 0x10;
const AUTHENTICATED_RESPONSE = 0x20;
const ENCRYPTED_RESPONSE = 0x40;
const DIGITALLY_SIGNED_RESPONSE = 0x80;
}
}
impl AttributeAccess {
#[must_use]
pub const fn from_legacy(mode: u8) -> Self {
match mode {
1 => Self::READ,
2 => Self::WRITE,
3 => Self::from_bits_truncate(Self::READ.bits() | Self::WRITE.bits()),
4 => Self::from_bits_truncate(Self::READ.bits() | Self::AUTHENTICATED_REQUEST.bits()),
5 => Self::from_bits_truncate(Self::WRITE.bits() | Self::AUTHENTICATED_REQUEST.bits()),
6 => Self::from_bits_truncate(
Self::READ.bits() | Self::WRITE.bits() | Self::AUTHENTICATED_REQUEST.bits(),
),
_ => Self::empty(),
}
}
#[must_use]
pub const fn can_read(self) -> bool {
self.contains(Self::READ)
}
#[must_use]
pub const fn can_write(self) -> bool {
self.contains(Self::WRITE)
}
#[must_use]
pub const fn requires_protection(self) -> bool {
self.intersects(Self::from_bits_truncate(
Self::AUTHENTICATED_REQUEST.bits()
| Self::ENCRYPTED_REQUEST.bits()
| Self::DIGITALLY_SIGNED_REQUEST.bits(),
))
}
}
impl MethodAccess {
#[must_use]
pub const fn from_legacy(mode: u8) -> Self {
match mode {
1 => Self::ACCESS,
2 => Self::from_bits_truncate(Self::ACCESS.bits() | Self::AUTHENTICATED_REQUEST.bits()),
_ => Self::empty(),
}
}
#[must_use]
pub const fn can_invoke(self) -> bool {
self.contains(Self::ACCESS)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssociationVersion {
Legacy,
V3,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttributeRight {
pub attribute_id: i8,
pub access: AttributeAccess,
pub has_selectors: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MethodRight {
pub method_id: i8,
pub access: MethodAccess,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ObjectListEntry<'a> {
pub class_id: u16,
pub version: u8,
pub logical_name: Obis,
pub access_rights: Option<Data<'a>>,
}
impl<'a> ObjectListEntry<'a> {
pub fn from_data(d: &Data<'a>) -> Result<Self> {
let s = d.as_structure().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?;
let class_id =
u16::try_from(s.get(0)?.as_u64().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?)
.map_err(|_| Error::new(ErrorKind::InvalidValue, 0))?;
let version = u8::try_from(s.get(1)?.as_u64().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?)
.map_err(|_| Error::new(ErrorKind::InvalidValue, 0))?;
let logical_name = s.get(2)?.as_obis().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?;
let access_rights = s.get(3).ok();
Ok(Self { class_id, version, logical_name, access_rights })
}
pub fn for_each_attribute_right(
&self,
version: AssociationVersion,
mut f: impl FnMut(AttributeRight) -> Result<()>,
) -> Result<()> {
let Some(rights) = self.access_rights else { return Ok(()) };
let Some(s) = rights.as_structure() else { return Ok(()) };
let Ok(list) = s.get(0) else { return Ok(()) };
let Some(list) = list.as_array() else { return Ok(()) };
for entry in &list {
let entry = entry?;
let e = entry.as_structure().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?;
let attribute_id =
i8::try_from(e.get(0)?.as_i64().ok_or_else(|| Error::new(ErrorKind::InvalidValue, 0))?)
.map_err(|_| Error::new(ErrorKind::InvalidValue, 0))?;
let mode = e.get(1)?;
let access = match version {
AssociationVersion::Legacy => {
AttributeAccess::from_legacy(u8::try_from(mode.as_u64().unwrap_or(0)).unwrap_or(0))
}
AssociationVersion::V3 => AttributeAccess::from_bits_truncate(match mode {
Data::BitString(b) => (b.to_u32() >> b.len().saturating_sub(8).min(24)) as u8,
other => u8::try_from(other.as_u64().unwrap_or(0)).unwrap_or(0),
}),
};
let has_selectors = e.get(2).is_ok_and(|d| !matches!(d, Data::Null));
f(AttributeRight { attribute_id, access, has_selectors })?;
}
Ok(())
}
}
#[must_use]
pub fn access_byte(d: &Data<'_>) -> Option<u8> {
match d {
Data::BitString(b) => b.as_bytes().first().copied(),
other => u8::try_from(other.as_u64()?).ok(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codec::Decode;
#[test]
fn version_three_flags_are_the_bits_the_standard_numbers() {
assert_eq!(AttributeAccess::READ.bits(), 1);
assert_eq!(AttributeAccess::WRITE.bits(), 2);
assert_eq!(AttributeAccess::AUTHENTICATED_REQUEST.bits(), 4);
assert_eq!(AttributeAccess::DIGITALLY_SIGNED_RESPONSE.bits(), 128);
assert_eq!(MethodAccess::ACCESS.bits(), 1);
assert_eq!(MethodAccess::AUTHENTICATED_REQUEST.bits(), 4);
}
#[test]
fn the_legacy_enumeration_maps_onto_the_same_flags() {
assert_eq!(AttributeAccess::from_legacy(1), AttributeAccess::READ);
assert_eq!(AttributeAccess::from_legacy(3), AttributeAccess::READ | AttributeAccess::WRITE);
assert_eq!(
AttributeAccess::from_legacy(4),
AttributeAccess::READ | AttributeAccess::AUTHENTICATED_REQUEST
);
assert_eq!(AttributeAccess::from_legacy(0), AttributeAccess::empty());
assert!(AttributeAccess::from_legacy(4).requires_protection());
assert!(!AttributeAccess::from_legacy(3).requires_protection());
}
#[test]
fn an_object_list_entry_decodes() {
let raw = [
0x02, 0x04, 0x12, 0x00, 0x03, 0x11, 0x00, 0x09, 0x06, 1, 0, 1, 8, 0, 255, 0x02, 0x02, 0x01, 0x00, 0x01, 0x00,
];
let d = Data::from_bytes(&raw).unwrap();
let e = ObjectListEntry::from_data(&d).unwrap();
assert_eq!(e.class_id, 3);
assert_eq!(e.version, 0);
assert_eq!(e.logical_name, Obis::new(1, 0, 1, 8, 0, 255));
assert!(e.access_rights.is_some());
}
#[test]
fn attribute_rights_decode_in_both_shapes() {
let raw = [
0x02, 0x04, 0x12, 0x00, 0x03, 0x11, 0x00, 0x09, 0x06, 1, 0, 1, 8, 0, 255, 0x02, 0x02, 0x01, 0x02, 0x02, 0x03, 0x0F, 0x02, 0x16, 0x03, 0x00, 0x02, 0x03, 0x0F, 0x03, 0x16, 0x01, 0x00, 0x01, 0x00,
];
let d = Data::from_bytes(&raw).unwrap();
let e = ObjectListEntry::from_data(&d).unwrap();
let mut got = alloc::vec::Vec::new();
e.for_each_attribute_right(AssociationVersion::Legacy, |r| {
got.push((r.attribute_id, r.access));
Ok(())
})
.unwrap();
assert_eq!(got.len(), 2);
assert_eq!(got[0].0, 2);
assert_eq!(got[0].1, AttributeAccess::READ | AttributeAccess::WRITE);
assert_eq!(got[1].1, AttributeAccess::READ);
}
#[test]
fn a_bit_string_access_mode_reads_its_first_byte() {
let d = Data::from_bytes(&[0x04, 0x08, 0b0000_0011]).unwrap();
assert_eq!(access_byte(&d), Some(0b0000_0011));
}
}