use core::fmt;
use crate::crc::{CrcCheck, kermit, x25};
use crate::seq::{Ctx, Element, Seq};
use crate::tl::{Kind, Reader, Writer};
use crate::tree::{NameList, PeriodEntries, Tree};
use crate::value::{Quantity, SmlValue, Time, Unit};
use crate::{Error, GetProfilePackResponse, Obis, Result, ServerId};
pub mod tag {
pub const OPEN_REQUEST: u32 = 0x0000_0100;
pub const OPEN_RESPONSE: u32 = 0x0000_0101;
pub const CLOSE_REQUEST: u32 = 0x0000_0200;
pub const CLOSE_RESPONSE: u32 = 0x0000_0201;
pub const GET_PROFILE_PACK_REQUEST: u32 = 0x0000_0300;
pub const GET_PROFILE_PACK_RESPONSE: u32 = 0x0000_0301;
pub const GET_PROFILE_LIST_REQUEST: u32 = 0x0000_0400;
pub const GET_PROFILE_LIST_RESPONSE: u32 = 0x0000_0401;
pub const GET_PROC_PARAMETER_REQUEST: u32 = 0x0000_0500;
pub const GET_PROC_PARAMETER_RESPONSE: u32 = 0x0000_0501;
pub const SET_PROC_PARAMETER_REQUEST: u32 = 0x0000_0600;
pub const GET_LIST_REQUEST: u32 = 0x0000_0700;
pub const GET_LIST_RESPONSE: u32 = 0x0000_0701;
pub const ATTENTION_RESPONSE: u32 = 0x0000_FF01;
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct ParseOptions {
pub crc: CrcCheck,
pub bare_time: bool,
pub dzg_power: bool,
}
impl ParseOptions {
pub const fn lenient() -> Self {
Self { crc: CrcCheck::Lenient, bare_time: true, dzg_power: false }
}
#[must_use]
pub const fn with_dzg_power(mut self, on: bool) -> Self {
self.dzg_power = on;
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Message<'a> {
pub transaction_id: &'a [u8],
pub group_no: u8,
pub abort_on_error: u8,
pub body: Body<'a>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Body<'a> {
OpenRequest(OpenRequest<'a>),
OpenResponse(OpenResponse<'a>),
CloseRequest(CloseRequest<'a>),
CloseResponse(CloseResponse<'a>),
GetListRequest(GetListRequest<'a>),
GetListResponse(GetListResponse<'a>),
Attention(Attention<'a>),
GetProcParameterRequest(GetProcParameterRequest<'a>),
GetProcParameterResponse(GetProcParameterResponse<'a>),
SetProcParameterRequest(SetProcParameterRequest<'a>),
GetProfilePackRequest(GetProfileRequest<'a>),
GetProfileListRequest(GetProfileRequest<'a>),
GetProfileListResponse(GetProfileListResponse<'a>),
GetProfilePackResponse(GetProfilePackResponse<'a>),
Other {
tag: u32,
raw: &'a [u8],
},
}
struct Redacted(bool);
impl fmt::Debug for Redacted {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(if self.0 { "Some(<redacted>)" } else { "None" })
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct OpenRequest<'a> {
pub codepage: Option<&'a [u8]>,
pub client_id: &'a [u8],
pub req_file_id: &'a [u8],
pub server_id: Option<ServerId<'a>>,
pub username: Option<&'a [u8]>,
pub password: Option<&'a [u8]>,
pub sml_version: Option<u8>,
}
impl fmt::Debug for OpenRequest<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OpenRequest")
.field("codepage", &self.codepage)
.field("client_id", &self.client_id)
.field("req_file_id", &self.req_file_id)
.field("server_id", &self.server_id)
.field("username", &self.username)
.field("password", &Redacted(self.password.is_some()))
.field("sml_version", &self.sml_version)
.finish()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OpenResponse<'a> {
pub codepage: Option<&'a [u8]>,
pub client_id: Option<&'a [u8]>,
pub req_file_id: &'a [u8],
pub server_id: ServerId<'a>,
pub ref_time: Option<Time>,
pub sml_version: Option<u8>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CloseRequest<'a> {
pub global_signature: Option<&'a [u8]>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CloseResponse<'a> {
pub global_signature: Option<&'a [u8]>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct GetListRequest<'a> {
pub client_id: &'a [u8],
pub server_id: Option<ServerId<'a>>,
pub username: Option<&'a [u8]>,
pub password: Option<&'a [u8]>,
pub list_name: Option<&'a [u8]>,
}
impl fmt::Debug for GetListRequest<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GetListRequest")
.field("client_id", &self.client_id)
.field("server_id", &self.server_id)
.field("username", &self.username)
.field("password", &Redacted(self.password.is_some()))
.field("list_name", &self.list_name)
.finish()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Attention<'a> {
pub server_id: ServerId<'a>,
pub number: &'a [u8],
pub message: Option<&'a [u8]>,
pub details: Option<&'a [u8]>,
}
impl Attention<'_> {
pub fn description(&self) -> Option<&'static str> {
crate::attention::describe(self.number)
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct GetProcParameterRequest<'a> {
pub server_id: Option<ServerId<'a>>,
pub username: Option<&'a [u8]>,
pub password: Option<&'a [u8]>,
pub tree_path: NameList<'a>,
pub attribute: Option<&'a [u8]>,
}
impl fmt::Debug for GetProcParameterRequest<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GetProcParameterRequest")
.field("server_id", &self.server_id)
.field("username", &self.username)
.field("password", &Redacted(self.password.is_some()))
.field("tree_path", &self.tree_path)
.field("attribute", &self.attribute)
.finish()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GetProcParameterResponse<'a> {
pub server_id: ServerId<'a>,
pub tree_path: NameList<'a>,
pub tree: Tree<'a>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct SetProcParameterRequest<'a> {
pub server_id: Option<ServerId<'a>>,
pub username: Option<&'a [u8]>,
pub password: Option<&'a [u8]>,
pub tree_path: NameList<'a>,
pub tree: Tree<'a>,
}
impl fmt::Debug for SetProcParameterRequest<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SetProcParameterRequest")
.field("server_id", &self.server_id)
.field("username", &self.username)
.field("password", &Redacted(self.password.is_some()))
.field("tree_path", &self.tree_path)
.field("tree", &self.tree)
.finish()
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct GetProfileRequest<'a> {
pub server_id: Option<ServerId<'a>>,
pub username: Option<&'a [u8]>,
pub password: Option<&'a [u8]>,
pub with_rawdata: Option<bool>,
pub begin_time: Option<Time>,
pub end_time: Option<Time>,
pub tree_path: NameList<'a>,
pub objects: Option<NameList<'a>>,
pub details: Option<Tree<'a>>,
}
impl fmt::Debug for GetProfileRequest<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GetProfileRequest")
.field("server_id", &self.server_id)
.field("username", &self.username)
.field("password", &Redacted(self.password.is_some()))
.field("with_rawdata", &self.with_rawdata)
.field("begin_time", &self.begin_time)
.field("end_time", &self.end_time)
.field("tree_path", &self.tree_path)
.field("objects", &self.objects)
.field("details", &self.details)
.finish()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GetProfileListResponse<'a> {
pub server_id: ServerId<'a>,
pub act_time: Time,
pub reg_period: u32,
pub tree_path: NameList<'a>,
pub val_time: Time,
pub status: u64,
pub entries: PeriodEntries<'a>,
pub rawdata: Option<&'a [u8]>,
pub period_signature: Option<&'a [u8]>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GetListResponse<'a> {
pub client_id: Option<&'a [u8]>,
pub server_id: ServerId<'a>,
pub list_name: Option<&'a [u8]>,
pub act_sensor_time: Option<Time>,
pub entries: ListEntries<'a>,
pub list_signature: Option<&'a [u8]>,
pub act_gateway_time: Option<Time>,
}
impl<'a> GetListResponse<'a> {
pub fn get(&self, obis: Obis) -> Option<ListEntry<'a>> {
self.entries.iter().filter_map(core::result::Result::ok).find(|e| e.obis == obis)
}
pub fn quantity(&self, obis: Obis) -> Option<Quantity> {
self.get(obis).and_then(|e| e.quantity())
}
}
pub type ListEntries<'a> = Seq<'a, ListEntry<'a>>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ListEntry<'a> {
pub obis: Obis,
pub status: Option<u64>,
pub val_time: Option<Time>,
pub unit: Option<Unit>,
pub scaler: Option<i8>,
pub value: SmlValue<'a>,
pub value_signature: Option<&'a [u8]>,
}
impl<'a> ListEntry<'a> {
pub const fn number(obis: Obis, unit: Unit, scaler: i8, value: i64) -> Self {
Self::numeric(obis, unit, scaler, SmlValue::Int(value))
}
pub const fn unsigned(obis: Obis, unit: Unit, scaler: i8, value: u64) -> Self {
Self::numeric(obis, unit, scaler, SmlValue::Uint(value))
}
const fn numeric(obis: Obis, unit: Unit, scaler: i8, value: SmlValue<'a>) -> Self {
Self {
obis,
status: None,
val_time: None,
unit: Some(unit),
scaler: Some(scaler),
value,
value_signature: None,
}
}
pub const fn bytes(obis: Obis, value: &'a [u8]) -> Self {
Self {
obis,
status: None,
val_time: None,
unit: None,
scaler: None,
value: SmlValue::Bytes(value),
value_signature: None,
}
}
}
impl<'a> Element<'a> for ListEntry<'a> {
fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
let (options, dzg) = (ctx.options, ctx.dzg);
r.list(7)?;
let obis = Obis::from_bytes(r.octet_string()?)?;
let status = r.opt_unsigned()?;
let val_time = Time::read_opt(r, options)?;
let unit = r
.opt_unsigned()?
.map(|u| u8::try_from(u).map(Unit))
.transpose()
.map_err(|_| Error::ValueOutOfRange)?;
let scaler = r.opt_integer()?.map(i8::try_from).transpose().map_err(|_| Error::ValueOutOfRange)?;
let (mut value, width) = SmlValue::read(r, options)?;
if dzg && obis.is_active_power() {
value = dzg_unsigned(value, width);
}
let value_signature = r.opt_octet_string()?;
Ok(Self { obis, status, val_time, unit, scaler, value, value_signature })
}
fn write(&self, w: &mut Writer<'_>) -> Result<()> {
ListEntry::write(self, w)
}
}
impl ListEntry<'_> {
pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
w.list(7)?;
w.octet_string(&self.obis.0)?;
match self.status {
Some(s) => w.unsigned_min(s)?,
None => w.absent()?,
}
Time::write_opt(self.val_time, w)?;
match self.unit {
Some(u) => w.unsigned(u64::from(u.0), 1)?,
None => w.absent()?,
}
match self.scaler {
Some(s) => w.integer(i64::from(s), 1)?,
None => w.absent()?,
}
self.value.write(w)?;
w.opt_octet_string(self.value_signature)
}
pub fn quantity(&self) -> Option<Quantity> {
let mantissa = self.value.as_integer()?;
Some(Quantity { mantissa, exponent: self.scaler.unwrap_or(0), unit: self.unit })
}
}
fn dzg_unsigned(value: SmlValue<'_>, width: usize) -> SmlValue<'_> {
match value {
SmlValue::Int(v) if v < 0 && (1..=3).contains(&width) => {
let bits = u64::from_be_bytes(v.to_be_bytes());
SmlValue::Uint(bits & ((1u64 << (8 * width)) - 1))
}
other => other,
}
}
impl<'a> Message<'a> {
pub fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<Self> {
let start = r.position();
r.list(6)?;
let transaction_id = r.octet_string()?;
let group_no = u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
let abort_on_error = u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
let body = Body::read(r, options)?;
let crc_end = r.position();
if r.clone().read_tl().is_ok_and(|tl| tl.kind == Kind::Unsigned && tl.len > 2) {
return Err(Error::InvalidLength);
}
let found = u16::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
let covered = r.slice(start, crc_end)?;
let computed = x25(covered);
let accepted = match options.crc {
CrcCheck::Lenient => options.crc.accepts(computed, kermit(covered), found),
check => check.accepts(computed, 0, found),
};
if !accepted {
return Err(Error::MessageCrc { computed, found });
}
r.end_of_message()?;
Ok(Self { transaction_id, group_no, abort_on_error, body })
}
pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
let start = w.position();
w.list(6)?;
w.octet_string(self.transaction_id)?;
w.unsigned(u64::from(self.group_no), 1)?;
w.unsigned(u64::from(self.abort_on_error), 1)?;
self.body.write(w)?;
let crc = x25(w.written().get(start..).unwrap_or(&[]));
w.unsigned(u64::from(crc.swap_bytes()), 2)?;
w.end_of_message()
}
}
fn read_u8(r: &mut Reader<'_>) -> Result<Option<u8>> {
r.opt_unsigned()?.map(u8::try_from).transpose().map_err(|_| Error::ValueOutOfRange)
}
fn write_opt_u8(w: &mut Writer<'_>, v: Option<u8>) -> Result<()> {
match v {
Some(v) => w.unsigned(u64::from(v), 1),
None => w.absent(),
}
}
fn opt_server_id<'a>(r: &mut Reader<'a>) -> Result<Option<ServerId<'a>>> {
Ok(r.opt_octet_string()?.map(ServerId::new))
}
fn write_opt_server_id(w: &mut Writer<'_>, id: Option<ServerId<'_>>) -> Result<()> {
w.opt_octet_string(id.map(|id| id.as_bytes()))
}
impl<'a> Body<'a> {
pub const fn tag(&self) -> u32 {
match self {
Self::OpenRequest(_) => tag::OPEN_REQUEST,
Self::OpenResponse(_) => tag::OPEN_RESPONSE,
Self::CloseRequest(_) => tag::CLOSE_REQUEST,
Self::CloseResponse(_) => tag::CLOSE_RESPONSE,
Self::GetListRequest(_) => tag::GET_LIST_REQUEST,
Self::GetListResponse(_) => tag::GET_LIST_RESPONSE,
Self::Attention(_) => tag::ATTENTION_RESPONSE,
Self::GetProcParameterRequest(_) => tag::GET_PROC_PARAMETER_REQUEST,
Self::GetProcParameterResponse(_) => tag::GET_PROC_PARAMETER_RESPONSE,
Self::SetProcParameterRequest(_) => tag::SET_PROC_PARAMETER_REQUEST,
Self::GetProfilePackRequest(_) => tag::GET_PROFILE_PACK_REQUEST,
Self::GetProfileListRequest(_) => tag::GET_PROFILE_LIST_REQUEST,
Self::GetProfileListResponse(_) => tag::GET_PROFILE_LIST_RESPONSE,
Self::GetProfilePackResponse(_) => tag::GET_PROFILE_PACK_RESPONSE,
Self::Other { tag, .. } => *tag,
}
}
#[allow(clippy::too_many_lines)] fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<Self> {
r.list(2)?;
let tag = u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
let ctx = Ctx::new(options);
Ok(match tag {
tag::OPEN_REQUEST => {
r.list(7)?;
Self::OpenRequest(OpenRequest {
codepage: r.opt_octet_string()?,
client_id: r.octet_string()?,
req_file_id: r.octet_string()?,
server_id: opt_server_id(r)?,
username: r.opt_octet_string()?,
password: r.opt_octet_string()?,
sml_version: read_u8(r)?,
})
}
tag::OPEN_RESPONSE => {
r.list(6)?;
Self::OpenResponse(OpenResponse {
codepage: r.opt_octet_string()?,
client_id: r.opt_octet_string()?,
req_file_id: r.octet_string()?,
server_id: ServerId::new(r.octet_string()?),
ref_time: Time::read_opt(r, options)?,
sml_version: read_u8(r)?,
})
}
tag::CLOSE_REQUEST => {
r.list(1)?;
Self::CloseRequest(CloseRequest { global_signature: r.opt_octet_string()? })
}
tag::CLOSE_RESPONSE => {
r.list(1)?;
Self::CloseResponse(CloseResponse { global_signature: r.opt_octet_string()? })
}
tag::GET_LIST_REQUEST => {
r.list(5)?;
Self::GetListRequest(GetListRequest {
client_id: r.octet_string()?,
server_id: opt_server_id(r)?,
username: r.opt_octet_string()?,
password: r.opt_octet_string()?,
list_name: r.opt_octet_string()?,
})
}
tag::GET_LIST_RESPONSE => {
r.list(7)?;
let client_id = r.opt_octet_string()?;
let server_id = ServerId::new(r.octet_string()?);
let list_name = r.opt_octet_string()?;
let act_sensor_time = Time::read_opt(r, options)?;
let dzg = options.dzg_power && server_id.manufacturer() == Some("DZG");
let entries = Seq::read(r, Ctx { dzg, ..Ctx::new(options) })?;
Self::GetListResponse(GetListResponse {
client_id,
server_id,
list_name,
act_sensor_time,
entries,
list_signature: r.opt_octet_string()?,
act_gateway_time: Time::read_opt(r, options)?,
})
}
tag::ATTENTION_RESPONSE => {
r.list(4)?;
let server_id = ServerId::new(r.octet_string()?);
let number = r.octet_string()?;
let message = r.opt_octet_string()?;
let details = if r.absent() {
None
} else {
let from = r.position();
r.skip()?;
Some(r.slice(from, r.position())?)
};
Self::Attention(Attention { server_id, number, message, details })
}
tag::GET_PROC_PARAMETER_REQUEST => {
r.list(5)?;
Self::GetProcParameterRequest(GetProcParameterRequest {
server_id: opt_server_id(r)?,
username: r.opt_octet_string()?,
password: r.opt_octet_string()?,
tree_path: Seq::read(r, ctx)?,
attribute: r.opt_octet_string()?,
})
}
tag::GET_PROC_PARAMETER_RESPONSE => {
r.list(3)?;
Self::GetProcParameterResponse(GetProcParameterResponse {
server_id: ServerId::new(r.octet_string()?),
tree_path: Seq::read(r, ctx)?,
tree: Tree::read(r, ctx)?,
})
}
tag::SET_PROC_PARAMETER_REQUEST => {
r.list(5)?;
Self::SetProcParameterRequest(SetProcParameterRequest {
server_id: opt_server_id(r)?,
username: r.opt_octet_string()?,
password: r.opt_octet_string()?,
tree_path: Seq::read(r, ctx)?,
tree: Tree::read(r, ctx)?,
})
}
tag::GET_PROFILE_PACK_REQUEST => Self::GetProfilePackRequest(GetProfileRequest::read(r, ctx)?),
tag::GET_PROFILE_LIST_REQUEST => Self::GetProfileListRequest(GetProfileRequest::read(r, ctx)?),
tag::GET_PROFILE_LIST_RESPONSE => {
r.list(9)?;
Self::GetProfileListResponse(GetProfileListResponse {
server_id: ServerId::new(r.octet_string()?),
act_time: Time::read(r, options)?,
reg_period: u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?,
tree_path: Seq::read(r, ctx)?,
val_time: Time::read(r, options)?,
status: r.unsigned()?,
entries: Seq::read(r, ctx)?,
rawdata: r.opt_octet_string()?,
period_signature: r.opt_octet_string()?,
})
}
tag::GET_PROFILE_PACK_RESPONSE => {
Self::GetProfilePackResponse(GetProfilePackResponse::read(r, ctx)?)
}
other => {
let from = r.position();
r.skip()?;
Self::Other { tag: other, raw: r.slice(from, r.position())? }
}
})
}
pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
w.list(2)?;
w.unsigned(u64::from(self.tag()), 4)?;
match *self {
Self::OpenRequest(o) => {
w.list(7)?;
w.opt_octet_string(o.codepage)?;
w.octet_string(o.client_id)?;
w.octet_string(o.req_file_id)?;
write_opt_server_id(w, o.server_id)?;
w.opt_octet_string(o.username)?;
w.opt_octet_string(o.password)?;
write_opt_u8(w, o.sml_version)
}
Self::OpenResponse(o) => {
w.list(6)?;
w.opt_octet_string(o.codepage)?;
w.opt_octet_string(o.client_id)?;
w.octet_string(o.req_file_id)?;
w.octet_string(o.server_id.as_bytes())?;
Time::write_opt(o.ref_time, w)?;
write_opt_u8(w, o.sml_version)
}
Self::CloseRequest(CloseRequest { global_signature })
| Self::CloseResponse(CloseResponse { global_signature }) => {
w.list(1)?;
w.opt_octet_string(global_signature)
}
Self::GetListRequest(g) => {
w.list(5)?;
w.octet_string(g.client_id)?;
write_opt_server_id(w, g.server_id)?;
w.opt_octet_string(g.username)?;
w.opt_octet_string(g.password)?;
w.opt_octet_string(g.list_name)
}
Self::GetListResponse(g) => {
w.list(7)?;
w.opt_octet_string(g.client_id)?;
w.octet_string(g.server_id.as_bytes())?;
w.opt_octet_string(g.list_name)?;
Time::write_opt(g.act_sensor_time, w)?;
g.entries.write(w)?;
w.opt_octet_string(g.list_signature)?;
Time::write_opt(g.act_gateway_time, w)
}
Self::Attention(a) => {
w.list(4)?;
w.octet_string(a.server_id.as_bytes())?;
w.octet_string(a.number)?;
w.opt_octet_string(a.message)?;
match a.details {
Some(raw) => w.raw(one_element(raw)?),
None => w.absent(),
}
}
Self::GetProcParameterRequest(g) => {
w.list(5)?;
write_opt_server_id(w, g.server_id)?;
w.opt_octet_string(g.username)?;
w.opt_octet_string(g.password)?;
g.tree_path.write(w)?;
w.opt_octet_string(g.attribute)
}
Self::GetProcParameterResponse(g) => {
w.list(3)?;
w.octet_string(g.server_id.as_bytes())?;
g.tree_path.write(w)?;
g.tree.write(w)
}
Self::SetProcParameterRequest(s) => {
w.list(5)?;
write_opt_server_id(w, s.server_id)?;
w.opt_octet_string(s.username)?;
w.opt_octet_string(s.password)?;
s.tree_path.write(w)?;
s.tree.write(w)
}
Self::GetProfilePackRequest(g) | Self::GetProfileListRequest(g) => g.write(w),
Self::GetProfileListResponse(g) => {
w.list(9)?;
w.octet_string(g.server_id.as_bytes())?;
g.act_time.write(w)?;
w.unsigned(u64::from(g.reg_period), 4)?;
g.tree_path.write(w)?;
g.val_time.write(w)?;
w.unsigned(g.status, 8)?;
g.entries.write(w)?;
w.opt_octet_string(g.rawdata)?;
w.opt_octet_string(g.period_signature)
}
Self::GetProfilePackResponse(g) => g.write(w),
Self::Other { raw, .. } => w.raw(one_element(raw)?),
}
}
}
impl<'a> GetProfileRequest<'a> {
fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
r.list(9)?;
Ok(Self {
server_id: opt_server_id(r)?,
username: r.opt_octet_string()?,
password: r.opt_octet_string()?,
with_rawdata: if r.absent() { None } else { Some(r.boolean()?) },
begin_time: Time::read_opt(r, ctx.options)?,
end_time: Time::read_opt(r, ctx.options)?,
tree_path: Seq::read(r, ctx)?,
objects: Seq::read_opt(r, ctx)?,
details: Tree::read_opt(r, ctx)?,
})
}
fn write(&self, w: &mut Writer<'_>) -> Result<()> {
w.list(9)?;
write_opt_server_id(w, self.server_id)?;
w.opt_octet_string(self.username)?;
w.opt_octet_string(self.password)?;
match self.with_rawdata {
Some(b) => w.boolean(b)?,
None => w.absent()?,
}
Time::write_opt(self.begin_time, w)?;
Time::write_opt(self.end_time, w)?;
self.tree_path.write(w)?;
Seq::write_opt(self.objects, w)?;
Tree::write_opt(self.details.as_ref(), w)
}
}
fn one_element(raw: &[u8]) -> Result<&[u8]> {
let mut r = Reader::new(raw);
r.skip()?;
if r.is_empty() { Ok(raw) } else { Err(Error::InvalidLength) }
}
#[derive(Clone, Debug)] pub struct Messages<'a> {
r: Reader<'a>,
options: ParseOptions,
done: bool,
last: usize,
}
impl<'a> Messages<'a> {
pub const fn new(payload: &'a [u8], options: ParseOptions) -> Self {
Self { r: Reader::new(payload), options, done: false, last: 0 }
}
pub const fn offset(&self) -> usize {
self.last
}
}
impl<'a> Iterator for Messages<'a> {
type Item = Result<Message<'a>>;
fn next(&mut self) -> Option<Self::Item> {
if self.done || self.r.is_empty() {
return None;
}
self.last = self.r.position();
let item = Message::read(&mut self.r, self.options);
self.done = item.is_err();
Some(item)
}
}
pub fn readout_with(payload: &[u8], options: ParseOptions) -> Result<GetListResponse<'_>> {
let mut list = None;
for message in Messages::new(payload, options) {
if let (None, Body::GetListResponse(l)) = (list, message?.body) {
list = Some(l);
}
}
list.ok_or(Error::NoReadings)
}
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
use std::format;
#[test]
fn debug_never_prints_a_password() {
let open = OpenRequest {
codepage: None,
client_id: b"client",
req_file_id: b"1",
server_id: None,
username: Some(b"user"),
password: Some(b"secret"),
sml_version: None,
};
let shown = format!("{open:?} {:?}", Body::OpenRequest(open));
assert!(!shown.contains("secret") && !shown.contains("115, 101, 99"), "{shown}");
assert!(shown.contains("<redacted>"));
let get = GetListRequest {
client_id: b"c",
server_id: None,
username: None,
password: Some(b"pw"),
list_name: None,
};
let shown = format!("{get:?}");
assert!(!shown.contains("112, 119") && shown.contains("<redacted>"), "{shown}");
let none = GetListRequest { password: None, ..get };
assert!(format!("{none:?}").contains("password: None"));
}
#[test]
fn redact_every_credential_carrying_request() {
let pw: &[u8] = b"hunter2";
let path = NameList::from_slice(&[b"p"]);
let tree = Tree { name: b"n", value: None, children: None };
let profile = GetProfileRequest {
server_id: None,
username: Some(b"u"),
password: Some(pw),
with_rawdata: None,
begin_time: None,
end_time: None,
tree_path: path,
objects: None,
details: None,
};
let bodies = [
Body::OpenRequest(OpenRequest {
codepage: None,
client_id: b"c",
req_file_id: b"f",
server_id: None,
username: Some(b"u"),
password: Some(pw),
sml_version: None,
}),
Body::GetListRequest(GetListRequest {
client_id: b"c",
server_id: None,
username: None,
password: Some(pw),
list_name: None,
}),
Body::GetProcParameterRequest(GetProcParameterRequest {
server_id: None,
username: None,
password: Some(pw),
tree_path: path,
attribute: None,
}),
Body::SetProcParameterRequest(SetProcParameterRequest {
server_id: None,
username: None,
password: Some(pw),
tree_path: path,
tree,
}),
Body::GetProfilePackRequest(profile),
Body::GetProfileListRequest(profile),
];
for body in bodies {
let message = Message { transaction_id: b"t", group_no: 0, abort_on_error: 0, body };
let shown = format!("{body:?} {message:?} {message:#?}");
assert!(!shown.contains("hunter2") && !shown.contains("104, 117, 110"), "{shown}");
assert!(shown.contains("<redacted>"), "{shown}");
let mut buf = [0u8; 256];
let mut w = Writer::new(&mut buf);
message.write(&mut w).unwrap();
let n = w.position();
let again = Message::read(&mut Reader::new(&buf[..n]), ParseOptions::default()).unwrap();
assert_eq!(again, message);
assert!(!format!("{again:?}").contains("104, 117, 110"));
}
}
#[test]
fn debug_of_parsers_never_prints_payload_bytes() {
let payload = b"\x76secret-password";
let shown = format!(
"{:?} {:?} {:?}",
Messages::new(payload, ParseOptions::default()),
Reader::new(payload),
crate::Decoder::new([0u8; 8])
);
assert!(!shown.contains("115, 101, 99") && !shown.contains("secret"), "{shown}");
}
#[test]
fn raw_parts_must_be_one_element_or_nothing_is_written() {
let mut buf = [0u8; 64];
for raw in [&[][..], &[0x01, 0x01], &[0x72, 0x01]] {
let m = Message {
transaction_id: b"t",
group_no: 0,
abort_on_error: 0,
body: Body::Other { tag: 0x500, raw },
};
assert!(m.write(&mut Writer::new(&mut buf)).is_err(), "{raw:02x?}");
let a =
Attention { server_id: ServerId::new(b"s"), number: b"n", message: None, details: Some(raw) };
let m = Message { body: Body::Attention(a), ..m };
assert!(m.write(&mut Writer::new(&mut buf)).is_err(), "{raw:02x?}");
}
}
#[test]
fn lists_compare_by_what_they_yield() {
let dzg_meter: &[u8] = &[0x0a, 0x01, b'D', b'Z', b'G', 0, 2, 0x82, 0x22, 0x5e];
let entries = [ListEntry::number(Obis::POWER, Unit::W, -2, -29_912)];
let body = Body::GetListResponse(GetListResponse {
client_id: None,
server_id: ServerId::new(dzg_meter),
list_name: None,
act_sensor_time: None,
entries: ListEntries::from_slice(&entries),
list_signature: None,
act_gateway_time: None,
});
let mut buf = [0u8; 128];
let mut w = Writer::new(&mut buf);
Message { transaction_id: b"t", group_no: 0, abort_on_error: 0, body }.write(&mut w).unwrap();
let n = w.position();
let plain = readout_with(&buf[..n], ParseOptions::default()).unwrap();
let fixed = readout_with(&buf[..n], ParseOptions::default().with_dzg_power(true)).unwrap();
let off =
readout_with(&buf[..n], ParseOptions { crc: CrcCheck::Off, ..ParseOptions::default() }).unwrap();
assert_eq!(plain.entries, ListEntries::from_slice(&entries));
assert_eq!(plain.entries, off.entries);
assert_ne!(plain.entries, fixed.entries);
assert_eq!(format!("{:?}", plain.entries), "Seq { len: 1, .. }");
}
#[test]
fn dzg_correction_only_touches_short_negatives() {
assert_eq!(dzg_unsigned(SmlValue::Int(0), 2), SmlValue::Int(0));
assert_eq!(dzg_unsigned(SmlValue::Int(-29_912), 2), SmlValue::Uint(35_624));
assert_eq!(dzg_unsigned(SmlValue::Int(-1), 1), SmlValue::Uint(255));
assert_eq!(dzg_unsigned(SmlValue::Int(-1), 3), SmlValue::Uint(0xFF_FFFF));
assert_eq!(dzg_unsigned(SmlValue::Int(-60_525), 4), SmlValue::Int(-60_525));
assert_eq!(dzg_unsigned(SmlValue::Int(5), 2), SmlValue::Int(5));
assert_eq!(dzg_unsigned(SmlValue::Uint(5), 2), SmlValue::Uint(5));
}
}