use alloc::string::String;
use alloc::vec::Vec;
use super::Client;
use crate::common::{Error, Fc, ObjectReference, Result};
use crate::proto::data::{Typed, Value};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Sgcb {
pub reference: String,
pub num_of_sg: Option<u32>,
pub act_sg: Option<u32>,
pub edit_sg: Option<u32>,
pub cnf_edit: Option<bool>,
pub last_activation: Option<crate::common::EntryTime>,
pub resv_tms: Option<i64>,
}
const SGCB_ATTRIBUTES: &[&str] = &["NumOfSG", "ActSG", "EditSG", "CnfEdit", "LActTm", "ResvTms"];
impl<S: std::io::Read + std::io::Write> Client<S> {
pub fn read_sgcb(&mut self, reference: &str) -> Result<Sgcb> {
let base = sgcb_base(reference)?;
let names: Vec<String> = SGCB_ATTRIBUTES.iter().map(|a| alloc::format!("{base}${a}")).collect();
let refs: Vec<(&str, Fc)> = names.iter().map(|n| (n.as_str(), Fc::SP)).collect();
let values = self.read_many_results(&refs)?;
let mut sgcb = Sgcb { reference: base, ..Sgcb::default() };
for (attribute, value) in SGCB_ATTRIBUTES.iter().zip(values) {
let Ok(v) = value else { continue };
match *attribute {
"NumOfSG" => sgcb.num_of_sg = unsigned(&v),
"ActSG" => sgcb.act_sg = unsigned(&v),
"EditSG" => sgcb.edit_sg = unsigned(&v),
"CnfEdit" => sgcb.cnf_edit = v.as_bool(),
"LActTm" => {
sgcb.last_activation = match &v {
Value::BinaryTime(b) => <[u8; 6]>::try_from(b.as_slice()).ok().map(crate::common::EntryTime::from_octets),
Value::UtcTime(t) => Some(crate::common::EntryTime::from_unix_millis(t.to_unix_nanos() / 1_000_000)),
_ => None,
}
}
"ResvTms" => sgcb.resv_tms = v.as_i64(),
_ => {}
}
}
if sgcb.num_of_sg.is_none() && sgcb.act_sg.is_none() {
return Err(Error::NotFound("setting group control block"));
}
Ok(sgcb)
}
pub fn select_active_setting_group(&mut self, reference: &str, group: u32) -> Result<()> {
let base = sgcb_base(reference)?;
self.write_sgcb(&base, "ActSG", Value::Unsigned(u64::from(group)))
}
pub fn select_edit_setting_group(&mut self, reference: &str, group: u32) -> Result<()> {
let base = sgcb_base(reference)?;
self.write_sgcb(&base, "EditSG", Value::Unsigned(u64::from(group)))
}
pub fn confirm_edit_setting_group(&mut self, reference: &str) -> Result<()> {
let base = sgcb_base(reference)?;
self.write_sgcb(&base, "CnfEdit", Value::Boolean(true))
}
pub fn read_edit_setting(&mut self, setting: &str) -> Result<Value> {
self.read(setting, Fc::SE)
}
pub fn write_edit_setting(&mut self, setting: &str, value: &Value) -> Result<()> {
self.write(setting, Fc::SE, value)
}
pub fn edit_setting_group(&mut self, reference: &str, group: u32, settings: &[(&str, Value)]) -> Result<()> {
let base = sgcb_base(reference)?;
self.write_sgcb(&base, "EditSG", Value::Unsigned(u64::from(group)))?;
let mut writes = Vec::with_capacity(settings.len());
for (name, value) in settings {
let parsed = ObjectReference::parse(name)?;
let (domain, item) = parsed.to_mms(Fc::SE);
writes.push((alloc::format!("{domain}/{item}"), value.clone()));
}
let outcome = if writes.is_empty() { Ok(()) } else { self.write_many(&writes).and_then(|r| r.into_iter().collect::<Result<Vec<()>>>().map(|_| ())) };
match outcome {
Ok(()) => {
let confirmed = self.write_sgcb(&base, "CnfEdit", Value::Boolean(true));
let _ = self.write_sgcb(&base, "EditSG", Value::Unsigned(0));
confirmed
}
Err(e) => {
let _ = self.write_sgcb(&base, "EditSG", Value::Unsigned(0));
Err(e)
}
}
}
fn write_sgcb(&mut self, base: &str, attribute: &str, value: Value) -> Result<()> {
match self.write_many(&[(alloc::format!("{base}${attribute}"), value)])?.into_iter().next() {
Some(r) => r,
None => Err(Error::InvalidValue("empty Write response")),
}
}
}
fn sgcb_base(reference: &str) -> Result<String> {
let parsed = ObjectReference::parse(reference)?;
let fc = parsed.fc.unwrap_or(Fc::SP);
if fc != Fc::SP {
return Err(Error::InvalidReference("a setting group control block is under SP"));
}
let (domain, item) = parsed.to_mms(Fc::SP);
let item = if parsed.path().count() == 0 { alloc::format!("{item}$SGCB") } else { item };
Ok(alloc::format!("{domain}/{item}"))
}
fn unsigned(v: &Value) -> Option<u32> {
match v {
Value::Unsigned(n) => u32::try_from(*n).ok(),
Value::Integer(i) => u32::try_from(*i).ok(),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_reference_normalises_to_the_control_block_under_sp() {
assert_eq!(sgcb_base("IED1LD0/LLN0$SP$SGCB").unwrap(), "IED1LD0/LLN0$SP$SGCB");
assert_eq!(sgcb_base("IED1LD0/LLN0.SGCB").unwrap(), "IED1LD0/LLN0$SP$SGCB");
assert_eq!(sgcb_base("IED1LD0/LLN0").unwrap(), "IED1LD0/LLN0$SP$SGCB");
assert!(sgcb_base("IED1LD0/LLN0$ST$SGCB").is_err());
}
}