use alloc::string::String;
use alloc::vec::Vec;
use super::Client;
use crate::common::{EntryTime, Error, Fc, ObjectReference, Result};
use crate::proto::data::{Typed, Value};
use crate::proto::mms::report::{OptFlds, TrgOps};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Rcb {
pub reference: String,
pub buffered: bool,
pub rpt_id: Option<String>,
pub rpt_ena: bool,
pub data_set: Option<String>,
pub conf_rev: Option<u32>,
pub opt_flds: Option<OptFlds>,
pub buf_tm: Option<u32>,
pub sq_num: Option<u32>,
pub trg_ops: Option<TrgOps>,
pub intg_pd: Option<u32>,
pub gi: Option<bool>,
pub resv: Option<bool>,
pub purge_buf: Option<bool>,
pub entry_id: Option<Vec<u8>>,
pub time_of_entry: Option<EntryTime>,
pub resv_tms: Option<i64>,
pub owner: Option<Vec<u8>>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RcbSettings {
pub rpt_id: Option<String>,
pub data_set: Option<String>,
pub opt_flds: Option<OptFlds>,
pub trg_ops: Option<TrgOps>,
pub buf_tm: Option<u32>,
pub intg_pd: Option<u32>,
pub resv_tms: Option<i64>,
pub entry_id: Option<Vec<u8>>,
}
impl RcbSettings {
pub fn new() -> RcbSettings {
RcbSettings::default()
}
#[must_use]
pub fn with_useful_fields(mut self) -> RcbSettings {
self.opt_flds = Some(
OptFlds::NONE
.with_sequence_number(true)
.with_report_time_stamp(true)
.with_data_set_name(true)
.with_reason_for_inclusion(true)
.with_conf_revision(true),
);
self
}
#[must_use]
pub const fn with_trg_ops(mut self, trg_ops: TrgOps) -> RcbSettings {
self.trg_ops = Some(trg_ops);
self
}
#[must_use]
pub const fn with_buf_tm(mut self, ms: u32) -> RcbSettings {
self.buf_tm = Some(ms);
self
}
#[must_use]
pub const fn with_intg_pd(mut self, ms: u32) -> RcbSettings {
self.intg_pd = Some(ms);
self
}
#[must_use]
pub fn resume_after(mut self, entry_id: Vec<u8>) -> RcbSettings {
self.entry_id = Some(entry_id);
self
}
}
const COMMON: &[&str] = &["RptID", "RptEna", "DatSet", "ConfRev", "OptFlds", "BufTm", "SqNum", "TrgOps", "IntgPd", "GI", "Owner"];
const BUFFERED: &[&str] = &["PurgeBuf", "EntryID", "TimeOfEntry", "TimeofEntry", "ResvTms"];
const UNBUFFERED: &[&str] = &["Resv"];
impl Client {
pub fn read_rcb(&mut self, reference: &str, fc: Fc) -> Result<Rcb> {
let (base, buffered) = rcb_base(reference, fc)?;
let names: Vec<String> = attribute_names(buffered).map(|a| alloc::format!("{base}${a}")).collect();
let refs: Vec<(&str, Fc)> = names.iter().map(|n| (n.as_str(), Fc::ST)).collect();
let values = self.read_many_results(&refs)?;
let mut rcb = Rcb { reference: base.clone(), buffered, ..Rcb::default() };
for (attribute, value) in attribute_names(buffered).zip(values) {
let Ok(v) = value else { continue };
match attribute {
"RptID" => rcb.rpt_id = v.as_str().map(String::from),
"RptEna" => rcb.rpt_ena = v.as_bool().unwrap_or(false),
"DatSet" => rcb.data_set = v.as_str().map(String::from),
"ConfRev" => rcb.conf_rev = unsigned(&v),
"OptFlds" => rcb.opt_flds = OptFlds::from_value(&v),
"BufTm" => rcb.buf_tm = unsigned(&v),
"SqNum" => rcb.sq_num = unsigned(&v),
"TrgOps" => rcb.trg_ops = TrgOps::from_value(&v),
"IntgPd" => rcb.intg_pd = unsigned(&v),
"GI" => rcb.gi = v.as_bool(),
"Resv" => rcb.resv = v.as_bool(),
"PurgeBuf" => rcb.purge_buf = v.as_bool(),
"EntryID" => rcb.entry_id = octets(&v),
"TimeOfEntry" | "TimeofEntry" => {
if let Value::BinaryTime(b) = &v {
rcb.time_of_entry = <[u8; 6]>::try_from(b.as_slice()).ok().map(EntryTime::from_octets).or(rcb.time_of_entry);
}
}
"ResvTms" => rcb.resv_tms = v.as_i64(),
"Owner" => rcb.owner = octets(&v),
_ => {}
}
}
if rcb.rpt_id.is_none() && rcb.data_set.is_none() && rcb.opt_flds.is_none() {
return Err(Error::NotFound("report control block"));
}
Ok(rcb)
}
pub fn write_rcb(&mut self, reference: &str, fc: Fc, settings: &RcbSettings) -> Result<()> {
let (base, buffered) = rcb_base(reference, fc)?;
let writes = settings_writes(&base, buffered, settings);
if writes.is_empty() {
return Ok(());
}
self.write_many(&writes)?.into_iter().collect::<Result<Vec<()>>>().map(|_| ())
}
pub fn enable_rcb(&mut self, reference: &str, fc: Fc, settings: &RcbSettings) -> Result<Rcb> {
let (base, buffered) = rcb_base(reference, fc)?;
if !settings_writes(&base, buffered, settings).is_empty() && self.read_rcb(&base, fc)?.rpt_ena {
self.write_one(&alloc::format!("{base}$RptEna"), Value::Boolean(false))?;
}
self.write_rcb(&base, fc, settings)?;
self.write_one(&alloc::format!("{base}$RptEna"), Value::Boolean(true))?;
let rcb = self.read_rcb(&base, fc)?;
if !rcb.rpt_ena {
return Err(Error::InvalidValue("the server accepted the write but did not enable reporting"));
}
Ok(rcb)
}
pub fn disable_rcb(&mut self, reference: &str, fc: Fc) -> Result<()> {
let (base, _) = rcb_base(reference, fc)?;
self.write_one(&alloc::format!("{base}$RptEna"), Value::Boolean(false))
}
pub fn general_interrogation(&mut self, reference: &str, fc: Fc) -> Result<()> {
let (base, _) = rcb_base(reference, fc)?;
self.write_one(&alloc::format!("{base}$GI"), Value::Boolean(true))
}
fn write_one(&mut self, reference: &str, value: Value) -> Result<()> {
match self.write_many(&[(String::from(reference), value)])?.into_iter().next() {
Some(r) => r,
None => Err(Error::InvalidValue("empty Write response")),
}
}
}
fn attribute_names(buffered: bool) -> impl Iterator<Item = &'static str> {
COMMON.iter().chain(if buffered { BUFFERED } else { UNBUFFERED }).copied()
}
fn settings_writes(base: &str, buffered: bool, s: &RcbSettings) -> Vec<(String, Value)> {
let mut out = Vec::new();
let mut push = |name: &str, v: Value| out.push((alloc::format!("{base}${name}"), v));
if let Some(v) = &s.rpt_id {
push("RptID", Value::VisibleString(v.clone()));
}
if let Some(v) = &s.data_set {
push("DatSet", Value::VisibleString(v.clone()));
}
if let Some(v) = s.opt_flds {
push("OptFlds", v.to_value());
}
if let Some(v) = s.trg_ops {
push("TrgOps", v.to_value());
}
if let Some(v) = s.buf_tm {
push("BufTm", Value::Unsigned(u64::from(v)));
}
if let Some(v) = s.intg_pd {
push("IntgPd", Value::Unsigned(u64::from(v)));
}
if buffered {
if let Some(v) = s.resv_tms {
push("ResvTms", Value::Integer(v));
}
if let Some(v) = &s.entry_id {
push("EntryID", Value::OctetString(v.clone()));
}
}
out
}
fn rcb_base(reference: &str, fc: Fc) -> Result<(String, bool)> {
let parsed = ObjectReference::parse(reference)?;
let fc = parsed.fc.unwrap_or(fc);
if !matches!(fc, Fc::RP | Fc::BR) {
return Err(Error::InvalidReference("a report control block is under RP or BR"));
}
let (domain, item) = parsed.to_mms(fc);
Ok((alloc::format!("{domain}/{item}"), matches!(fc, Fc::BR)))
}
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,
}
}
fn octets(v: &Value) -> Option<Vec<u8>> {
match v {
Value::OctetString(b) | Value::BinaryTime(b) => Some(b.clone()),
Value::VisibleString(s) | Value::MmsString(s) => Some(s.as_bytes().to_vec()),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_reference_normalises_from_either_spelling() {
assert_eq!(rcb_base("IED1LD0/LLN0$RP$urcb01", Fc::BR).unwrap(), (String::from("IED1LD0/LLN0$RP$urcb01"), false));
assert_eq!(rcb_base("IED1LD0/LLN0.urcb01", Fc::RP).unwrap(), (String::from("IED1LD0/LLN0$RP$urcb01"), false));
assert_eq!(rcb_base("IED1LD0/LLN0.brcb01", Fc::BR).unwrap(), (String::from("IED1LD0/LLN0$BR$brcb01"), true));
assert!(rcb_base("IED1LD0/LLN0.urcb01", Fc::ST).is_err());
assert!(rcb_base("IED1LD0/LLN0$MX$x", Fc::RP).is_err());
}
#[test]
fn a_buffered_block_has_different_attributes_from_an_unbuffered_one() {
let buffered: Vec<&str> = attribute_names(true).collect();
let unbuffered: Vec<&str> = attribute_names(false).collect();
assert!(buffered.contains(&"EntryID") && buffered.contains(&"ResvTms") && buffered.contains(&"PurgeBuf"));
assert!(buffered.contains(&"TimeOfEntry") && buffered.contains(&"TimeofEntry"));
assert!(!buffered.contains(&"Resv"));
assert!(unbuffered.contains(&"Resv"));
assert!(!unbuffered.contains(&"EntryID"));
assert!(buffered.contains(&"Owner") && unbuffered.contains(&"Owner"));
}
#[test]
fn settings_are_written_by_name_and_only_when_set() {
let v = settings_writes("LD/LLN0$RP$u", false, &RcbSettings::new());
assert!(v.is_empty(), "{v:?}");
let s = RcbSettings::new().with_useful_fields().with_trg_ops(TrgOps::EVENTS).with_buf_tm(100).with_intg_pd(1000);
let writes = settings_writes("LD/LLN0$RP$u", false, &s);
let names: Vec<&str> = writes.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["LD/LLN0$RP$u$OptFlds", "LD/LLN0$RP$u$TrgOps", "LD/LLN0$RP$u$BufTm", "LD/LLN0$RP$u$IntgPd"]);
let resumed = RcbSettings::new().resume_after(alloc::vec![1, 2, 3, 4, 5, 6, 7, 8]);
let v = settings_writes("LD/LLN0$RP$u", false, &resumed);
assert!(v.is_empty(), "{v:?}");
assert_eq!(settings_writes("LD/LLN0$BR$b", true, &resumed).len(), 1);
}
}