use alloc::string::String;
use alloc::vec::Vec;
use super::Client;
use crate::common::{EntryTime, Error, Fc, ObjectReference, Result};
use crate::proto::data::{DataView, Typed, Value};
use crate::proto::mms::journal::{AfterEntry, REASON_CODE_TAG, TimeOfDay};
use crate::proto::mms::report::{ReasonCode, TrgOps};
use crate::proto::mms::{ConfirmedRequest, ConfirmedResponse, Mms, ObjectName, ReadJournal};
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LogEntry {
pub entry_id: Vec<u8>,
pub occurred: EntryTime,
pub variables: Vec<(String, Value)>,
pub reason: Option<ReasonCode>,
pub annotation: Option<String>,
}
impl LogEntry {
pub fn resume_point(&self) -> (Vec<u8>, EntryTime) {
(self.entry_id.clone(), self.occurred)
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LogPage {
pub entries: Vec<LogEntry>,
pub more_follows: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Lcb {
pub reference: String,
pub log_ena: bool,
pub log_ref: Option<String>,
pub data_set: Option<String>,
pub old_entry_time: Option<EntryTime>,
pub new_entry_time: Option<EntryTime>,
pub old_entry: Option<Vec<u8>>,
pub new_entry: Option<Vec<u8>>,
pub trg_ops: Option<TrgOps>,
pub intg_pd: Option<u32>,
}
impl Lcb {
pub fn oldest(&self) -> Option<(Vec<u8>, EntryTime)> {
Some((self.old_entry.clone()?, self.old_entry_time?))
}
}
const LCB_ATTRIBUTES: &[&str] = &["LogEna", "LogRef", "DatSet", "OldEntrTm", "NewEntrTm", "OldEnt", "NewEnt", "TrgOps", "IntgPd", "OldEntr", "NewEntr"];
impl<S: std::io::Read + std::io::Write> Client<S> {
pub fn read_lcb(&mut self, reference: &str, fc: Fc) -> Result<Lcb> {
let base = lcb_base(reference, fc)?;
let names: Vec<String> = LCB_ATTRIBUTES.iter().map(|a| alloc::format!("{base}${a}")).collect();
let refs: Vec<(&str, Fc)> = names.iter().map(|n| (n.as_str(), Fc::LG)).collect();
let values = self.read_many_results(&refs)?;
let mut lcb = Lcb { reference: base, ..Lcb::default() };
for (attribute, value) in LCB_ATTRIBUTES.iter().zip(values) {
let Ok(v) = value else { continue };
match *attribute {
"LogEna" => lcb.log_ena = v.as_bool().unwrap_or(false),
"LogRef" => lcb.log_ref = v.as_str().map(String::from),
"DatSet" => lcb.data_set = v.as_str().map(String::from),
"OldEntrTm" => lcb.old_entry_time = entry_time(&v),
"NewEntrTm" => lcb.new_entry_time = entry_time(&v),
"OldEnt" | "OldEntr" => lcb.old_entry = lcb.old_entry.take().or_else(|| octets(&v)),
"NewEnt" | "NewEntr" => lcb.new_entry = lcb.new_entry.take().or_else(|| octets(&v)),
"TrgOps" => lcb.trg_ops = TrgOps::from_value(&v),
"IntgPd" => lcb.intg_pd = v.as_u64().and_then(|n| u32::try_from(n).ok()),
_ => {}
}
}
if lcb.log_ref.is_none() && lcb.data_set.is_none() && lcb.old_entry.is_none() {
return Err(Error::NotFound("log control block"));
}
Ok(lcb)
}
pub fn set_log_enabled(&mut self, reference: &str, fc: Fc, on: bool) -> Result<()> {
let base = lcb_base(reference, fc)?;
match self.write_many(&[(alloc::format!("{base}$LogEna"), Value::Boolean(on))])?.into_iter().next() {
Some(r) => r,
None => Err(Error::InvalidValue("empty Write response")),
}
}
pub fn query_log_by_time(&mut self, log: &str, from: EntryTime, to: Option<EntryTime>) -> Result<LogPage> {
let (domain, item) = log_name(log)?;
let name = ObjectName::DomainSpecific { domain: &domain, item: &item };
self.read_journal(&ReadJournal::by_time(name, TimeOfDay::dated(from), Some(TimeOfDay::dated(to.unwrap_or(EntryTime::MAX)))))
}
pub fn query_log_after_entry(&mut self, log: &str, entry_id: &[u8], time: EntryTime) -> Result<LogPage> {
let (domain, item) = log_name(log)?;
let name = ObjectName::DomainSpecific { domain: &domain, item: &item };
self.read_journal(&ReadJournal::after_entry(name, AfterEntry { time: TimeOfDay::dated(time), entry_id }))
}
pub fn read_whole_log(&mut self, log: &str, from: EntryTime, max_entries: usize) -> Result<Vec<LogEntry>> {
let mut out = Vec::new();
let mut page = self.query_log_by_time(log, from, None)?;
loop {
let resume = page.entries.last().map(LogEntry::resume_point);
out.append(&mut page.entries);
if !page.more_follows {
return Ok(out);
}
if out.len() >= max_entries {
return Err(Error::LimitExceeded { limit: "max_entries", value: out.len() });
}
let Some((entry_id, time)) = resume else { return Ok(out) };
page = self.query_log_after_entry(log, &entry_id, time)?;
}
}
fn read_journal(&mut self, request: &ReadJournal<'_>) -> Result<LogPage> {
let pdu = self.call(&ConfirmedRequest::ReadJournal(request.clone()))?;
let Mms::ConfirmedResponse { service: ConfirmedResponse::ReadJournal { entries, more_follows }, .. } = Mms::parse(&pdu, &self.limits)? else {
return Err(Error::InvalidValue("not a ReadJournal response"));
};
let mut out = Vec::with_capacity(entries.len());
for e in &entries {
let mut variables = Vec::with_capacity(e.variables.len());
let mut reason = None;
for v in &e.variables {
let value = DataView::from_tlv(v.value)?.to_owned(&self.limits)?;
if v.tag == REASON_CODE_TAG {
reason = ReasonCode::from_value(&value);
continue;
}
variables.push((String::from(v.tag), value));
}
out.push(LogEntry { entry_id: e.entry_id.to_vec(), occurred: e.occurred.time, variables, reason, annotation: e.annotation.map(String::from) });
}
Ok(LogPage { entries: out, more_follows })
}
}
fn log_name(log: &str) -> Result<(String, String)> {
let (ld, rest) = log.split_once('/').ok_or(Error::InvalidReference("a log is `LD/LN$LogName`"))?;
if ld.is_empty() || rest.is_empty() {
return Err(Error::InvalidReference("a log is `LD/LN$LogName`"));
}
Ok((String::from(ld), rest.replace('.', "$")))
}
fn lcb_base(reference: &str, fc: Fc) -> Result<String> {
let parsed = ObjectReference::parse(reference)?;
let fc = parsed.fc.unwrap_or(fc);
if fc != Fc::LG {
return Err(Error::InvalidReference("a log control block is under LG"));
}
let (domain, item) = parsed.to_mms(fc);
Ok(alloc::format!("{domain}/{item}"))
}
fn entry_time(v: &Value) -> Option<EntryTime> {
match v {
Value::BinaryTime(b) => <[u8; 6]>::try_from(b.as_slice()).ok().map(EntryTime::from_octets),
Value::UtcTime(t) => Some(EntryTime::from_unix_millis(t.to_unix_nanos() / 1_000_000)),
_ => None,
}
}
fn octets(v: &Value) -> Option<Vec<u8>> {
match v {
Value::OctetString(b) | Value::BinaryTime(b) => Some(b.clone()),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_log_reference_splits_into_the_journal_a_server_knows() {
assert_eq!(log_name("IED1LD0/LLN0$GeneralLog").unwrap(), (String::from("IED1LD0"), String::from("LLN0$GeneralLog")));
assert_eq!(log_name("IED1LD0/LLN0.EventLog").unwrap(), (String::from("IED1LD0"), String::from("LLN0$EventLog")));
assert!(log_name("nolyslash").is_err());
assert!(log_name("IED1LD0/").is_err());
}
#[test]
fn a_control_block_reference_must_name_the_log_constraint() {
assert_eq!(lcb_base("IED1LD0/LLN0$LG$lcb01", Fc::ST).unwrap(), "IED1LD0/LLN0$LG$lcb01");
assert_eq!(lcb_base("IED1LD0/LLN0.lcb01", Fc::LG).unwrap(), "IED1LD0/LLN0$LG$lcb01");
assert!(lcb_base("IED1LD0/LLN0.lcb01", Fc::RP).is_err());
}
}