1use core::fmt;
21
22use crate::crc::{CrcCheck, kermit, x25};
23use crate::seq::{Ctx, Element, Seq};
24use crate::tl::{Kind, Reader, Writer};
25use crate::tree::{NameList, PeriodEntries, Tree};
26use crate::value::{Quantity, SmlValue, Time, Unit};
27use crate::{Error, GetProfilePackResponse, Obis, Result, ServerId};
28
29pub mod tag {
31 pub const OPEN_REQUEST: u32 = 0x0000_0100;
33 pub const OPEN_RESPONSE: u32 = 0x0000_0101;
35 pub const CLOSE_REQUEST: u32 = 0x0000_0200;
37 pub const CLOSE_RESPONSE: u32 = 0x0000_0201;
39 pub const GET_PROFILE_PACK_REQUEST: u32 = 0x0000_0300;
41 pub const GET_PROFILE_PACK_RESPONSE: u32 = 0x0000_0301;
43 pub const GET_PROFILE_LIST_REQUEST: u32 = 0x0000_0400;
45 pub const GET_PROFILE_LIST_RESPONSE: u32 = 0x0000_0401;
47 pub const GET_PROC_PARAMETER_REQUEST: u32 = 0x0000_0500;
49 pub const GET_PROC_PARAMETER_RESPONSE: u32 = 0x0000_0501;
51 pub const SET_PROC_PARAMETER_REQUEST: u32 = 0x0000_0600;
53 pub const GET_LIST_REQUEST: u32 = 0x0000_0700;
55 pub const GET_LIST_RESPONSE: u32 = 0x0000_0701;
57 pub const ATTENTION_RESPONSE: u32 = 0x0000_FF01;
59}
60
61#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
77pub struct ParseOptions {
78 pub crc: CrcCheck,
80 pub bare_time: bool,
83 pub dzg_power: bool,
96}
97
98impl ParseOptions {
99 pub const fn lenient() -> Self {
102 Self { crc: CrcCheck::Lenient, bare_time: true, dzg_power: false }
103 }
104
105 #[must_use]
107 pub const fn with_dzg_power(mut self, on: bool) -> Self {
108 self.dzg_power = on;
109 self
110 }
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct Message<'a> {
116 pub transaction_id: &'a [u8],
118 pub group_no: u8,
120 pub abort_on_error: u8,
122 pub body: Body<'a>,
124}
125
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128#[non_exhaustive]
129pub enum Body<'a> {
130 OpenRequest(OpenRequest<'a>),
132 OpenResponse(OpenResponse<'a>),
134 CloseRequest(CloseRequest<'a>),
136 CloseResponse(CloseResponse<'a>),
138 GetListRequest(GetListRequest<'a>),
140 GetListResponse(GetListResponse<'a>),
142 Attention(Attention<'a>),
144 GetProcParameterRequest(GetProcParameterRequest<'a>),
146 GetProcParameterResponse(GetProcParameterResponse<'a>),
148 SetProcParameterRequest(SetProcParameterRequest<'a>),
150 GetProfilePackRequest(GetProfileRequest<'a>),
152 GetProfileListRequest(GetProfileRequest<'a>),
154 GetProfileListResponse(GetProfileListResponse<'a>),
156 GetProfilePackResponse(GetProfilePackResponse<'a>),
158 Other {
161 tag: u32,
163 raw: &'a [u8],
165 },
166}
167
168struct Redacted(bool);
170
171impl fmt::Debug for Redacted {
172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173 f.write_str(if self.0 { "Some(<redacted>)" } else { "None" })
174 }
175}
176
177#[derive(Clone, Copy, PartialEq, Eq)]
179pub struct OpenRequest<'a> {
180 pub codepage: Option<&'a [u8]>,
182 pub client_id: &'a [u8],
184 pub req_file_id: &'a [u8],
186 pub server_id: Option<ServerId<'a>>,
188 pub username: Option<&'a [u8]>,
190 pub password: Option<&'a [u8]>,
192 pub sml_version: Option<u8>,
194}
195
196impl fmt::Debug for OpenRequest<'_> {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 f.debug_struct("OpenRequest")
199 .field("codepage", &self.codepage)
200 .field("client_id", &self.client_id)
201 .field("req_file_id", &self.req_file_id)
202 .field("server_id", &self.server_id)
203 .field("username", &self.username)
204 .field("password", &Redacted(self.password.is_some()))
205 .field("sml_version", &self.sml_version)
206 .finish()
207 }
208}
209
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
212pub struct OpenResponse<'a> {
213 pub codepage: Option<&'a [u8]>,
215 pub client_id: Option<&'a [u8]>,
217 pub req_file_id: &'a [u8],
219 pub server_id: ServerId<'a>,
221 pub ref_time: Option<Time>,
223 pub sml_version: Option<u8>,
225}
226
227#[derive(Clone, Copy, Debug, PartialEq, Eq)]
229pub struct CloseRequest<'a> {
230 pub global_signature: Option<&'a [u8]>,
232}
233
234#[derive(Clone, Copy, Debug, PartialEq, Eq)]
236pub struct CloseResponse<'a> {
237 pub global_signature: Option<&'a [u8]>,
240}
241
242#[derive(Clone, Copy, PartialEq, Eq)]
244pub struct GetListRequest<'a> {
245 pub client_id: &'a [u8],
247 pub server_id: Option<ServerId<'a>>,
249 pub username: Option<&'a [u8]>,
251 pub password: Option<&'a [u8]>,
253 pub list_name: Option<&'a [u8]>,
255}
256
257impl fmt::Debug for GetListRequest<'_> {
258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259 f.debug_struct("GetListRequest")
260 .field("client_id", &self.client_id)
261 .field("server_id", &self.server_id)
262 .field("username", &self.username)
263 .field("password", &Redacted(self.password.is_some()))
264 .field("list_name", &self.list_name)
265 .finish()
266 }
267}
268
269#[derive(Clone, Copy, Debug, PartialEq, Eq)]
271pub struct Attention<'a> {
272 pub server_id: ServerId<'a>,
274 pub number: &'a [u8],
276 pub message: Option<&'a [u8]>,
278 pub details: Option<&'a [u8]>,
280}
281
282impl Attention<'_> {
283 pub fn description(&self) -> Option<&'static str> {
285 crate::attention::describe(self.number)
286 }
287}
288
289#[derive(Clone, Copy, PartialEq, Eq)]
291pub struct GetProcParameterRequest<'a> {
292 pub server_id: Option<ServerId<'a>>,
294 pub username: Option<&'a [u8]>,
296 pub password: Option<&'a [u8]>,
298 pub tree_path: NameList<'a>,
300 pub attribute: Option<&'a [u8]>,
302}
303
304impl fmt::Debug for GetProcParameterRequest<'_> {
305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306 f.debug_struct("GetProcParameterRequest")
307 .field("server_id", &self.server_id)
308 .field("username", &self.username)
309 .field("password", &Redacted(self.password.is_some()))
310 .field("tree_path", &self.tree_path)
311 .field("attribute", &self.attribute)
312 .finish()
313 }
314}
315
316#[derive(Clone, Copy, Debug, PartialEq, Eq)]
318pub struct GetProcParameterResponse<'a> {
319 pub server_id: ServerId<'a>,
321 pub tree_path: NameList<'a>,
323 pub tree: Tree<'a>,
325}
326
327#[derive(Clone, Copy, PartialEq, Eq)]
333pub struct SetProcParameterRequest<'a> {
334 pub server_id: Option<ServerId<'a>>,
336 pub username: Option<&'a [u8]>,
338 pub password: Option<&'a [u8]>,
340 pub tree_path: NameList<'a>,
342 pub tree: Tree<'a>,
344}
345
346impl fmt::Debug for SetProcParameterRequest<'_> {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 f.debug_struct("SetProcParameterRequest")
349 .field("server_id", &self.server_id)
350 .field("username", &self.username)
351 .field("password", &Redacted(self.password.is_some()))
352 .field("tree_path", &self.tree_path)
353 .field("tree", &self.tree)
354 .finish()
355 }
356}
357
358#[derive(Clone, Copy, PartialEq, Eq)]
361pub struct GetProfileRequest<'a> {
362 pub server_id: Option<ServerId<'a>>,
364 pub username: Option<&'a [u8]>,
366 pub password: Option<&'a [u8]>,
368 pub with_rawdata: Option<bool>,
370 pub begin_time: Option<Time>,
372 pub end_time: Option<Time>,
374 pub tree_path: NameList<'a>,
376 pub objects: Option<NameList<'a>>,
378 pub details: Option<Tree<'a>>,
380}
381
382impl fmt::Debug for GetProfileRequest<'_> {
383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 f.debug_struct("GetProfileRequest")
385 .field("server_id", &self.server_id)
386 .field("username", &self.username)
387 .field("password", &Redacted(self.password.is_some()))
388 .field("with_rawdata", &self.with_rawdata)
389 .field("begin_time", &self.begin_time)
390 .field("end_time", &self.end_time)
391 .field("tree_path", &self.tree_path)
392 .field("objects", &self.objects)
393 .field("details", &self.details)
394 .finish()
395 }
396}
397
398#[derive(Clone, Copy, Debug, PartialEq, Eq)]
400pub struct GetProfileListResponse<'a> {
401 pub server_id: ServerId<'a>,
403 pub act_time: Time,
405 pub reg_period: u32,
407 pub tree_path: NameList<'a>,
409 pub val_time: Time,
411 pub status: u64,
413 pub entries: PeriodEntries<'a>,
415 pub rawdata: Option<&'a [u8]>,
417 pub period_signature: Option<&'a [u8]>,
419}
420
421#[derive(Clone, Copy, Debug, PartialEq, Eq)]
423pub struct GetListResponse<'a> {
424 pub client_id: Option<&'a [u8]>,
426 pub server_id: ServerId<'a>,
428 pub list_name: Option<&'a [u8]>,
430 pub act_sensor_time: Option<Time>,
432 pub entries: ListEntries<'a>,
434 pub list_signature: Option<&'a [u8]>,
436 pub act_gateway_time: Option<Time>,
438}
439
440impl<'a> GetListResponse<'a> {
441 pub fn get(&self, obis: Obis) -> Option<ListEntry<'a>> {
443 self.entries.iter().filter_map(core::result::Result::ok).find(|e| e.obis == obis)
444 }
445
446 pub fn quantity(&self, obis: Obis) -> Option<Quantity> {
448 self.get(obis).and_then(|e| e.quantity())
449 }
450}
451
452pub type ListEntries<'a> = Seq<'a, ListEntry<'a>>;
455
456#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
458pub struct ListEntry<'a> {
459 pub obis: Obis,
461 pub status: Option<u64>,
463 pub val_time: Option<Time>,
465 pub unit: Option<Unit>,
467 pub scaler: Option<i8>,
469 pub value: SmlValue<'a>,
471 pub value_signature: Option<&'a [u8]>,
473}
474
475impl<'a> ListEntry<'a> {
476 pub const fn number(obis: Obis, unit: Unit, scaler: i8, value: i64) -> Self {
478 Self {
479 obis,
480 status: None,
481 val_time: None,
482 unit: Some(unit),
483 scaler: Some(scaler),
484 value: SmlValue::Int(value),
485 value_signature: None,
486 }
487 }
488
489 pub const fn bytes(obis: Obis, value: &'a [u8]) -> Self {
491 Self {
492 obis,
493 status: None,
494 val_time: None,
495 unit: None,
496 scaler: None,
497 value: SmlValue::Bytes(value),
498 value_signature: None,
499 }
500 }
501}
502
503impl<'a> Element<'a> for ListEntry<'a> {
504 fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
505 let (options, dzg) = (ctx.options, ctx.dzg);
506 r.list(7)?;
507 let obis = Obis::from_bytes(r.octet_string()?)?;
508 let status = r.opt_unsigned()?;
509 let val_time = Time::read_opt(r, options)?;
510 let unit = r
511 .opt_unsigned()?
512 .map(|u| u8::try_from(u).map(Unit))
513 .transpose()
514 .map_err(|_| Error::ValueOutOfRange)?;
515 let scaler = r.opt_integer()?.map(i8::try_from).transpose().map_err(|_| Error::ValueOutOfRange)?;
516 let (mut value, width) = SmlValue::read(r, options)?;
517 if dzg && obis.is_active_power() {
518 value = dzg_unsigned(value, width);
519 }
520 let value_signature = r.opt_octet_string()?;
521 Ok(Self { obis, status, val_time, unit, scaler, value, value_signature })
522 }
523
524 fn write(&self, w: &mut Writer<'_>) -> Result<()> {
525 ListEntry::write(self, w)
526 }
527}
528
529impl ListEntry<'_> {
530 pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
532 w.list(7)?;
533 w.octet_string(&self.obis.0)?;
534 match self.status {
535 Some(s) => w.unsigned_min(s)?,
536 None => w.absent()?,
537 }
538 Time::write_opt(self.val_time, w)?;
539 match self.unit {
540 Some(u) => w.unsigned(u64::from(u.0), 1)?,
541 None => w.absent()?,
542 }
543 match self.scaler {
544 Some(s) => w.integer(i64::from(s), 1)?,
545 None => w.absent()?,
546 }
547 self.value.write(w)?;
548 w.opt_octet_string(self.value_signature)
549 }
550
551 pub fn quantity(&self) -> Option<Quantity> {
553 let mantissa = match self.value {
554 SmlValue::Int(v) => i128::from(v),
555 SmlValue::Uint(v) => i128::from(v),
556 SmlValue::Bool(_) | SmlValue::Bytes(_) | SmlValue::Time(_) => return None,
557 };
558 Some(Quantity { mantissa, exponent: self.scaler.unwrap_or(0), unit: self.unit })
559 }
560}
561
562fn dzg_unsigned(value: SmlValue<'_>, width: usize) -> SmlValue<'_> {
565 match value {
566 SmlValue::Int(v) if v < 0 && (1..=3).contains(&width) => {
567 let bits = u64::from_be_bytes(v.to_be_bytes());
568 SmlValue::Uint(bits & ((1u64 << (8 * width)) - 1))
569 }
570 other => other,
571 }
572}
573
574impl<'a> Message<'a> {
575 pub fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<Self> {
577 let start = r.position();
578 r.list(6)?;
579 let transaction_id = r.octet_string()?;
580 let group_no = u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
581 let abort_on_error = u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
582 let body = Body::read(r, options)?;
583 let crc_end = r.position();
584 if r.clone().read_tl().is_ok_and(|tl| tl.kind == Kind::Unsigned && tl.len > 2) {
586 return Err(Error::InvalidLength);
587 }
588 let found = u16::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
589 let covered = r.slice(start, crc_end)?;
590 let computed = x25(covered);
591 let accepted = match options.crc {
592 CrcCheck::Lenient => options.crc.accepts(computed, kermit(covered), found),
593 check => check.accepts(computed, 0, found),
594 };
595 if !accepted {
596 return Err(Error::MessageCrc { computed, found });
597 }
598 r.end_of_message()?;
599 Ok(Self { transaction_id, group_no, abort_on_error, body })
600 }
601
602 pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
614 let start = w.position();
615 w.list(6)?;
616 w.octet_string(self.transaction_id)?;
617 w.unsigned(u64::from(self.group_no), 1)?;
618 w.unsigned(u64::from(self.abort_on_error), 1)?;
619 self.body.write(w)?;
620 let crc = x25(w.written().get(start..).unwrap_or(&[]));
621 w.unsigned(u64::from(crc.swap_bytes()), 2)?;
622 w.end_of_message()
623 }
624}
625
626fn read_u8(r: &mut Reader<'_>) -> Result<Option<u8>> {
627 r.opt_unsigned()?.map(u8::try_from).transpose().map_err(|_| Error::ValueOutOfRange)
628}
629
630fn write_opt_u8(w: &mut Writer<'_>, v: Option<u8>) -> Result<()> {
631 match v {
632 Some(v) => w.unsigned(u64::from(v), 1),
633 None => w.absent(),
634 }
635}
636
637fn opt_server_id<'a>(r: &mut Reader<'a>) -> Result<Option<ServerId<'a>>> {
638 Ok(r.opt_octet_string()?.map(ServerId::new))
639}
640
641fn write_opt_server_id(w: &mut Writer<'_>, id: Option<ServerId<'_>>) -> Result<()> {
642 w.opt_octet_string(id.map(|id| id.as_bytes()))
643}
644
645impl<'a> Body<'a> {
646 pub const fn tag(&self) -> u32 {
648 match self {
649 Self::OpenRequest(_) => tag::OPEN_REQUEST,
650 Self::OpenResponse(_) => tag::OPEN_RESPONSE,
651 Self::CloseRequest(_) => tag::CLOSE_REQUEST,
652 Self::CloseResponse(_) => tag::CLOSE_RESPONSE,
653 Self::GetListRequest(_) => tag::GET_LIST_REQUEST,
654 Self::GetListResponse(_) => tag::GET_LIST_RESPONSE,
655 Self::Attention(_) => tag::ATTENTION_RESPONSE,
656 Self::GetProcParameterRequest(_) => tag::GET_PROC_PARAMETER_REQUEST,
657 Self::GetProcParameterResponse(_) => tag::GET_PROC_PARAMETER_RESPONSE,
658 Self::SetProcParameterRequest(_) => tag::SET_PROC_PARAMETER_REQUEST,
659 Self::GetProfilePackRequest(_) => tag::GET_PROFILE_PACK_REQUEST,
660 Self::GetProfileListRequest(_) => tag::GET_PROFILE_LIST_REQUEST,
661 Self::GetProfileListResponse(_) => tag::GET_PROFILE_LIST_RESPONSE,
662 Self::GetProfilePackResponse(_) => tag::GET_PROFILE_PACK_RESPONSE,
663 Self::Other { tag, .. } => *tag,
664 }
665 }
666
667 #[allow(clippy::too_many_lines)] fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<Self> {
669 r.list(2)?;
670 let tag = u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
671 let ctx = Ctx::new(options);
672 Ok(match tag {
673 tag::OPEN_REQUEST => {
674 r.list(7)?;
675 Self::OpenRequest(OpenRequest {
676 codepage: r.opt_octet_string()?,
677 client_id: r.octet_string()?,
678 req_file_id: r.octet_string()?,
679 server_id: opt_server_id(r)?,
680 username: r.opt_octet_string()?,
681 password: r.opt_octet_string()?,
682 sml_version: read_u8(r)?,
683 })
684 }
685 tag::OPEN_RESPONSE => {
686 r.list(6)?;
687 Self::OpenResponse(OpenResponse {
688 codepage: r.opt_octet_string()?,
689 client_id: r.opt_octet_string()?,
690 req_file_id: r.octet_string()?,
691 server_id: ServerId::new(r.octet_string()?),
692 ref_time: Time::read_opt(r, options)?,
693 sml_version: read_u8(r)?,
694 })
695 }
696 tag::CLOSE_REQUEST => {
697 r.list(1)?;
698 Self::CloseRequest(CloseRequest { global_signature: r.opt_octet_string()? })
699 }
700 tag::CLOSE_RESPONSE => {
701 r.list(1)?;
702 Self::CloseResponse(CloseResponse { global_signature: r.opt_octet_string()? })
703 }
704 tag::GET_LIST_REQUEST => {
705 r.list(5)?;
706 Self::GetListRequest(GetListRequest {
707 client_id: r.octet_string()?,
708 server_id: opt_server_id(r)?,
709 username: r.opt_octet_string()?,
710 password: r.opt_octet_string()?,
711 list_name: r.opt_octet_string()?,
712 })
713 }
714 tag::GET_LIST_RESPONSE => {
715 r.list(7)?;
716 let client_id = r.opt_octet_string()?;
717 let server_id = ServerId::new(r.octet_string()?);
718 let list_name = r.opt_octet_string()?;
719 let act_sensor_time = Time::read_opt(r, options)?;
720 let dzg = options.dzg_power && server_id.manufacturer() == Some("DZG");
721 let entries = Seq::read(r, Ctx { dzg, ..Ctx::new(options) })?;
722 Self::GetListResponse(GetListResponse {
723 client_id,
724 server_id,
725 list_name,
726 act_sensor_time,
727 entries,
728 list_signature: r.opt_octet_string()?,
729 act_gateway_time: Time::read_opt(r, options)?,
730 })
731 }
732 tag::ATTENTION_RESPONSE => {
733 r.list(4)?;
734 let server_id = ServerId::new(r.octet_string()?);
735 let number = r.octet_string()?;
736 let message = r.opt_octet_string()?;
737 let details = if r.absent() {
738 None
739 } else {
740 let from = r.position();
741 r.skip()?;
742 Some(r.slice(from, r.position())?)
743 };
744 Self::Attention(Attention { server_id, number, message, details })
745 }
746 tag::GET_PROC_PARAMETER_REQUEST => {
747 r.list(5)?;
748 Self::GetProcParameterRequest(GetProcParameterRequest {
749 server_id: opt_server_id(r)?,
750 username: r.opt_octet_string()?,
751 password: r.opt_octet_string()?,
752 tree_path: Seq::read(r, ctx)?,
753 attribute: r.opt_octet_string()?,
754 })
755 }
756 tag::GET_PROC_PARAMETER_RESPONSE => {
757 r.list(3)?;
758 Self::GetProcParameterResponse(GetProcParameterResponse {
759 server_id: ServerId::new(r.octet_string()?),
760 tree_path: Seq::read(r, ctx)?,
761 tree: Tree::read(r, ctx)?,
762 })
763 }
764 tag::SET_PROC_PARAMETER_REQUEST => {
765 r.list(5)?;
766 Self::SetProcParameterRequest(SetProcParameterRequest {
767 server_id: opt_server_id(r)?,
768 username: r.opt_octet_string()?,
769 password: r.opt_octet_string()?,
770 tree_path: Seq::read(r, ctx)?,
771 tree: Tree::read(r, ctx)?,
772 })
773 }
774 tag::GET_PROFILE_PACK_REQUEST => Self::GetProfilePackRequest(GetProfileRequest::read(r, ctx)?),
775 tag::GET_PROFILE_LIST_REQUEST => Self::GetProfileListRequest(GetProfileRequest::read(r, ctx)?),
776 tag::GET_PROFILE_LIST_RESPONSE => {
777 r.list(9)?;
778 Self::GetProfileListResponse(GetProfileListResponse {
779 server_id: ServerId::new(r.octet_string()?),
780 act_time: Time::read(r, options)?,
781 reg_period: u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?,
782 tree_path: Seq::read(r, ctx)?,
783 val_time: Time::read(r, options)?,
784 status: r.unsigned()?,
785 entries: Seq::read(r, ctx)?,
786 rawdata: r.opt_octet_string()?,
787 period_signature: r.opt_octet_string()?,
788 })
789 }
790 tag::GET_PROFILE_PACK_RESPONSE => {
791 Self::GetProfilePackResponse(GetProfilePackResponse::read(r, ctx)?)
792 }
793 other => {
794 let from = r.position();
795 r.skip()?;
796 Self::Other { tag: other, raw: r.slice(from, r.position())? }
797 }
798 })
799 }
800
801 pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
803 w.list(2)?;
804 w.unsigned(u64::from(self.tag()), 4)?;
805 match *self {
806 Self::OpenRequest(o) => {
807 w.list(7)?;
808 w.opt_octet_string(o.codepage)?;
809 w.octet_string(o.client_id)?;
810 w.octet_string(o.req_file_id)?;
811 write_opt_server_id(w, o.server_id)?;
812 w.opt_octet_string(o.username)?;
813 w.opt_octet_string(o.password)?;
814 write_opt_u8(w, o.sml_version)
815 }
816 Self::OpenResponse(o) => {
817 w.list(6)?;
818 w.opt_octet_string(o.codepage)?;
819 w.opt_octet_string(o.client_id)?;
820 w.octet_string(o.req_file_id)?;
821 w.octet_string(o.server_id.as_bytes())?;
822 Time::write_opt(o.ref_time, w)?;
823 write_opt_u8(w, o.sml_version)
824 }
825 Self::CloseRequest(CloseRequest { global_signature })
826 | Self::CloseResponse(CloseResponse { global_signature }) => {
827 w.list(1)?;
828 w.opt_octet_string(global_signature)
829 }
830 Self::GetListRequest(g) => {
831 w.list(5)?;
832 w.octet_string(g.client_id)?;
833 write_opt_server_id(w, g.server_id)?;
834 w.opt_octet_string(g.username)?;
835 w.opt_octet_string(g.password)?;
836 w.opt_octet_string(g.list_name)
837 }
838 Self::GetListResponse(g) => {
839 w.list(7)?;
840 w.opt_octet_string(g.client_id)?;
841 w.octet_string(g.server_id.as_bytes())?;
842 w.opt_octet_string(g.list_name)?;
843 Time::write_opt(g.act_sensor_time, w)?;
844 g.entries.write(w)?;
845 w.opt_octet_string(g.list_signature)?;
846 Time::write_opt(g.act_gateway_time, w)
847 }
848 Self::Attention(a) => {
849 w.list(4)?;
850 w.octet_string(a.server_id.as_bytes())?;
851 w.octet_string(a.number)?;
852 w.opt_octet_string(a.message)?;
853 match a.details {
854 Some(raw) => w.raw(one_element(raw)?),
855 None => w.absent(),
856 }
857 }
858 Self::GetProcParameterRequest(g) => {
859 w.list(5)?;
860 write_opt_server_id(w, g.server_id)?;
861 w.opt_octet_string(g.username)?;
862 w.opt_octet_string(g.password)?;
863 g.tree_path.write(w)?;
864 w.opt_octet_string(g.attribute)
865 }
866 Self::GetProcParameterResponse(g) => {
867 w.list(3)?;
868 w.octet_string(g.server_id.as_bytes())?;
869 g.tree_path.write(w)?;
870 g.tree.write(w)
871 }
872 Self::SetProcParameterRequest(s) => {
873 w.list(5)?;
874 write_opt_server_id(w, s.server_id)?;
875 w.opt_octet_string(s.username)?;
876 w.opt_octet_string(s.password)?;
877 s.tree_path.write(w)?;
878 s.tree.write(w)
879 }
880 Self::GetProfilePackRequest(g) | Self::GetProfileListRequest(g) => g.write(w),
881 Self::GetProfileListResponse(g) => {
882 w.list(9)?;
883 w.octet_string(g.server_id.as_bytes())?;
884 g.act_time.write(w)?;
885 w.unsigned(u64::from(g.reg_period), 4)?;
886 g.tree_path.write(w)?;
887 g.val_time.write(w)?;
888 w.unsigned(g.status, 8)?;
889 g.entries.write(w)?;
890 w.opt_octet_string(g.rawdata)?;
891 w.opt_octet_string(g.period_signature)
892 }
893 Self::GetProfilePackResponse(g) => g.write(w),
894 Self::Other { raw, .. } => w.raw(one_element(raw)?),
895 }
896 }
897}
898
899impl<'a> GetProfileRequest<'a> {
900 fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
901 r.list(9)?;
902 Ok(Self {
903 server_id: opt_server_id(r)?,
904 username: r.opt_octet_string()?,
905 password: r.opt_octet_string()?,
906 with_rawdata: if r.absent() { None } else { Some(r.boolean()?) },
907 begin_time: Time::read_opt(r, ctx.options)?,
908 end_time: Time::read_opt(r, ctx.options)?,
909 tree_path: Seq::read(r, ctx)?,
910 objects: Seq::read_opt(r, ctx)?,
911 details: Tree::read_opt(r, ctx)?,
912 })
913 }
914
915 fn write(&self, w: &mut Writer<'_>) -> Result<()> {
916 w.list(9)?;
917 write_opt_server_id(w, self.server_id)?;
918 w.opt_octet_string(self.username)?;
919 w.opt_octet_string(self.password)?;
920 match self.with_rawdata {
921 Some(b) => w.boolean(b)?,
922 None => w.absent()?,
923 }
924 Time::write_opt(self.begin_time, w)?;
925 Time::write_opt(self.end_time, w)?;
926 self.tree_path.write(w)?;
927 Seq::write_opt(self.objects, w)?;
928 Tree::write_opt(self.details.as_ref(), w)
929 }
930}
931
932fn one_element(raw: &[u8]) -> Result<&[u8]> {
935 let mut r = Reader::new(raw);
936 r.skip()?;
937 if r.is_empty() { Ok(raw) } else { Err(Error::InvalidLength) }
938}
939
940#[derive(Clone, Debug)] pub struct Messages<'a> {
946 r: Reader<'a>,
947 options: ParseOptions,
948 done: bool,
949 last: usize,
950}
951
952impl<'a> Messages<'a> {
953 pub const fn new(payload: &'a [u8], options: ParseOptions) -> Self {
955 Self { r: Reader::new(payload), options, done: false, last: 0 }
956 }
957
958 pub const fn offset(&self) -> usize {
961 self.last
962 }
963}
964
965impl<'a> Iterator for Messages<'a> {
966 type Item = Result<Message<'a>>;
967
968 fn next(&mut self) -> Option<Self::Item> {
969 if self.done || self.r.is_empty() {
970 return None;
971 }
972 self.last = self.r.position();
973 let item = Message::read(&mut self.r, self.options);
974 self.done = item.is_err();
975 Some(item)
976 }
977}
978
979pub fn readout_with(payload: &[u8], options: ParseOptions) -> Result<GetListResponse<'_>> {
982 let mut list = None;
983 for message in Messages::new(payload, options) {
984 if let (None, Body::GetListResponse(l)) = (list, message?.body) {
985 list = Some(l);
986 }
987 }
988 list.ok_or(Error::NoReadings)
989}
990
991#[cfg(test)]
992mod tests {
993 extern crate std;
994 use super::*;
995 use std::format;
996
997 #[test]
999 fn debug_never_prints_a_password() {
1000 let open = OpenRequest {
1001 codepage: None,
1002 client_id: b"client",
1003 req_file_id: b"1",
1004 server_id: None,
1005 username: Some(b"user"),
1006 password: Some(b"secret"),
1007 sml_version: None,
1008 };
1009 let shown = format!("{open:?} {:?}", Body::OpenRequest(open));
1010 assert!(!shown.contains("secret") && !shown.contains("115, 101, 99"), "{shown}");
1011 assert!(shown.contains("<redacted>"));
1012 let get = GetListRequest {
1013 client_id: b"c",
1014 server_id: None,
1015 username: None,
1016 password: Some(b"pw"),
1017 list_name: None,
1018 };
1019 let shown = format!("{get:?}");
1020 assert!(!shown.contains("112, 119") && shown.contains("<redacted>"), "{shown}");
1021 let none = GetListRequest { password: None, ..get };
1022 assert!(format!("{none:?}").contains("password: None"));
1023 }
1024
1025 #[test]
1028 fn redact_every_credential_carrying_request() {
1029 let pw: &[u8] = b"hunter2";
1030 let path = NameList::from_slice(&[b"p"]);
1031 let tree = Tree { name: b"n", value: None, children: None };
1032 let profile = GetProfileRequest {
1033 server_id: None,
1034 username: Some(b"u"),
1035 password: Some(pw),
1036 with_rawdata: None,
1037 begin_time: None,
1038 end_time: None,
1039 tree_path: path,
1040 objects: None,
1041 details: None,
1042 };
1043 let bodies = [
1044 Body::OpenRequest(OpenRequest {
1045 codepage: None,
1046 client_id: b"c",
1047 req_file_id: b"f",
1048 server_id: None,
1049 username: Some(b"u"),
1050 password: Some(pw),
1051 sml_version: None,
1052 }),
1053 Body::GetListRequest(GetListRequest {
1054 client_id: b"c",
1055 server_id: None,
1056 username: None,
1057 password: Some(pw),
1058 list_name: None,
1059 }),
1060 Body::GetProcParameterRequest(GetProcParameterRequest {
1061 server_id: None,
1062 username: None,
1063 password: Some(pw),
1064 tree_path: path,
1065 attribute: None,
1066 }),
1067 Body::SetProcParameterRequest(SetProcParameterRequest {
1068 server_id: None,
1069 username: None,
1070 password: Some(pw),
1071 tree_path: path,
1072 tree,
1073 }),
1074 Body::GetProfilePackRequest(profile),
1075 Body::GetProfileListRequest(profile),
1076 ];
1077 for body in bodies {
1078 let message = Message { transaction_id: b"t", group_no: 0, abort_on_error: 0, body };
1079 let shown = format!("{body:?} {message:?} {message:#?}");
1080 assert!(!shown.contains("hunter2") && !shown.contains("104, 117, 110"), "{shown}");
1081 assert!(shown.contains("<redacted>"), "{shown}");
1082 let mut buf = [0u8; 256];
1084 let mut w = Writer::new(&mut buf);
1085 message.write(&mut w).unwrap();
1086 let n = w.position();
1087 let again = Message::read(&mut Reader::new(&buf[..n]), ParseOptions::default()).unwrap();
1088 assert_eq!(again, message);
1089 assert!(!format!("{again:?}").contains("104, 117, 110"));
1090 }
1091 }
1092
1093 #[test]
1095 fn debug_of_parsers_never_prints_payload_bytes() {
1096 let payload = b"\x76secret-password";
1097 let shown = format!(
1098 "{:?} {:?} {:?}",
1099 Messages::new(payload, ParseOptions::default()),
1100 Reader::new(payload),
1101 crate::Decoder::new([0u8; 8])
1102 );
1103 assert!(!shown.contains("115, 101, 99") && !shown.contains("secret"), "{shown}");
1104 }
1105
1106 #[test]
1107 fn raw_parts_must_be_one_element_or_nothing_is_written() {
1108 let mut buf = [0u8; 64];
1109 for raw in [&[][..], &[0x01, 0x01], &[0x72, 0x01]] {
1110 let m = Message {
1111 transaction_id: b"t",
1112 group_no: 0,
1113 abort_on_error: 0,
1114 body: Body::Other { tag: 0x500, raw },
1115 };
1116 assert!(m.write(&mut Writer::new(&mut buf)).is_err(), "{raw:02x?}");
1117 let a =
1118 Attention { server_id: ServerId::new(b"s"), number: b"n", message: None, details: Some(raw) };
1119 let m = Message { body: Body::Attention(a), ..m };
1120 assert!(m.write(&mut Writer::new(&mut buf)).is_err(), "{raw:02x?}");
1121 }
1122 }
1123
1124 #[test]
1125 fn lists_compare_by_what_they_yield() {
1126 let dzg_meter: &[u8] = &[0x0a, 0x01, b'D', b'Z', b'G', 0, 2, 0x82, 0x22, 0x5e];
1127 let entries = [ListEntry::number(Obis::POWER, Unit::W, -2, -29_912)];
1128 let body = Body::GetListResponse(GetListResponse {
1129 client_id: None,
1130 server_id: ServerId::new(dzg_meter),
1131 list_name: None,
1132 act_sensor_time: None,
1133 entries: ListEntries::from_slice(&entries),
1134 list_signature: None,
1135 act_gateway_time: None,
1136 });
1137 let mut buf = [0u8; 128];
1138 let mut w = Writer::new(&mut buf);
1139 Message { transaction_id: b"t", group_no: 0, abort_on_error: 0, body }.write(&mut w).unwrap();
1140 let n = w.position();
1141 let plain = readout_with(&buf[..n], ParseOptions::default()).unwrap();
1142 let fixed = readout_with(&buf[..n], ParseOptions::default().with_dzg_power(true)).unwrap();
1143 let off =
1144 readout_with(&buf[..n], ParseOptions { crc: CrcCheck::Off, ..ParseOptions::default() }).unwrap();
1145 assert_eq!(plain.entries, ListEntries::from_slice(&entries));
1147 assert_eq!(plain.entries, off.entries);
1148 assert_ne!(plain.entries, fixed.entries);
1149 assert_eq!(format!("{:?}", plain.entries), "Seq { len: 1, .. }");
1150 }
1151
1152 #[test]
1153 fn dzg_correction_only_touches_short_negatives() {
1154 assert_eq!(dzg_unsigned(SmlValue::Int(0), 2), SmlValue::Int(0));
1155 assert_eq!(dzg_unsigned(SmlValue::Int(-29_912), 2), SmlValue::Uint(35_624));
1156 assert_eq!(dzg_unsigned(SmlValue::Int(-1), 1), SmlValue::Uint(255));
1157 assert_eq!(dzg_unsigned(SmlValue::Int(-1), 3), SmlValue::Uint(0xFF_FFFF));
1158 assert_eq!(dzg_unsigned(SmlValue::Int(-60_525), 4), SmlValue::Int(-60_525));
1159 assert_eq!(dzg_unsigned(SmlValue::Int(5), 2), SmlValue::Int(5));
1160 assert_eq!(dzg_unsigned(SmlValue::Uint(5), 2), SmlValue::Uint(5));
1161 }
1162}