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 {
484 Self::numeric(obis, unit, scaler, SmlValue::Int(value))
485 }
486
487 pub const fn unsigned(obis: Obis, unit: Unit, scaler: i8, value: u64) -> Self {
498 Self::numeric(obis, unit, scaler, SmlValue::Uint(value))
499 }
500
501 const fn numeric(obis: Obis, unit: Unit, scaler: i8, value: SmlValue<'a>) -> Self {
502 Self {
503 obis,
504 status: None,
505 val_time: None,
506 unit: Some(unit),
507 scaler: Some(scaler),
508 value,
509 value_signature: None,
510 }
511 }
512
513 pub const fn bytes(obis: Obis, value: &'a [u8]) -> Self {
515 Self {
516 obis,
517 status: None,
518 val_time: None,
519 unit: None,
520 scaler: None,
521 value: SmlValue::Bytes(value),
522 value_signature: None,
523 }
524 }
525}
526
527impl<'a> Element<'a> for ListEntry<'a> {
528 fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
529 let (options, dzg) = (ctx.options, ctx.dzg);
530 r.list(7)?;
531 let obis = Obis::from_bytes(r.octet_string()?)?;
532 let status = r.opt_unsigned()?;
533 let val_time = Time::read_opt(r, options)?;
534 let unit = r
535 .opt_unsigned()?
536 .map(|u| u8::try_from(u).map(Unit))
537 .transpose()
538 .map_err(|_| Error::ValueOutOfRange)?;
539 let scaler = r.opt_integer()?.map(i8::try_from).transpose().map_err(|_| Error::ValueOutOfRange)?;
540 let (mut value, width) = SmlValue::read(r, options)?;
541 if dzg && obis.is_active_power() {
542 value = dzg_unsigned(value, width);
543 }
544 let value_signature = r.opt_octet_string()?;
545 Ok(Self { obis, status, val_time, unit, scaler, value, value_signature })
546 }
547
548 fn write(&self, w: &mut Writer<'_>) -> Result<()> {
549 ListEntry::write(self, w)
550 }
551}
552
553impl ListEntry<'_> {
554 pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
556 w.list(7)?;
557 w.octet_string(&self.obis.0)?;
558 match self.status {
559 Some(s) => w.unsigned_min(s)?,
560 None => w.absent()?,
561 }
562 Time::write_opt(self.val_time, w)?;
563 match self.unit {
564 Some(u) => w.unsigned(u64::from(u.0), 1)?,
565 None => w.absent()?,
566 }
567 match self.scaler {
568 Some(s) => w.integer(i64::from(s), 1)?,
569 None => w.absent()?,
570 }
571 self.value.write(w)?;
572 w.opt_octet_string(self.value_signature)
573 }
574
575 pub fn quantity(&self) -> Option<Quantity> {
577 let mantissa = self.value.as_integer()?;
578 Some(Quantity { mantissa, exponent: self.scaler.unwrap_or(0), unit: self.unit })
579 }
580}
581
582fn dzg_unsigned(value: SmlValue<'_>, width: usize) -> SmlValue<'_> {
585 match value {
586 SmlValue::Int(v) if v < 0 && (1..=3).contains(&width) => {
587 let bits = u64::from_be_bytes(v.to_be_bytes());
588 SmlValue::Uint(bits & ((1u64 << (8 * width)) - 1))
589 }
590 other => other,
591 }
592}
593
594impl<'a> Message<'a> {
595 pub fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<Self> {
597 let start = r.position();
598 r.list(6)?;
599 let transaction_id = r.octet_string()?;
600 let group_no = u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
601 let abort_on_error = u8::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
602 let body = Body::read(r, options)?;
603 let crc_end = r.position();
604 if r.clone().read_tl().is_ok_and(|tl| tl.kind == Kind::Unsigned && tl.len > 2) {
606 return Err(Error::InvalidLength);
607 }
608 let found = u16::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
609 let covered = r.slice(start, crc_end)?;
610 let computed = x25(covered);
611 let accepted = match options.crc {
612 CrcCheck::Lenient => options.crc.accepts(computed, kermit(covered), found),
613 check => check.accepts(computed, 0, found),
614 };
615 if !accepted {
616 return Err(Error::MessageCrc { computed, found });
617 }
618 r.end_of_message()?;
619 Ok(Self { transaction_id, group_no, abort_on_error, body })
620 }
621
622 pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
634 let start = w.position();
635 w.list(6)?;
636 w.octet_string(self.transaction_id)?;
637 w.unsigned(u64::from(self.group_no), 1)?;
638 w.unsigned(u64::from(self.abort_on_error), 1)?;
639 self.body.write(w)?;
640 let crc = x25(w.written().get(start..).unwrap_or(&[]));
641 w.unsigned(u64::from(crc.swap_bytes()), 2)?;
642 w.end_of_message()
643 }
644}
645
646fn read_u8(r: &mut Reader<'_>) -> Result<Option<u8>> {
647 r.opt_unsigned()?.map(u8::try_from).transpose().map_err(|_| Error::ValueOutOfRange)
648}
649
650fn write_opt_u8(w: &mut Writer<'_>, v: Option<u8>) -> Result<()> {
651 match v {
652 Some(v) => w.unsigned(u64::from(v), 1),
653 None => w.absent(),
654 }
655}
656
657fn opt_server_id<'a>(r: &mut Reader<'a>) -> Result<Option<ServerId<'a>>> {
658 Ok(r.opt_octet_string()?.map(ServerId::new))
659}
660
661fn write_opt_server_id(w: &mut Writer<'_>, id: Option<ServerId<'_>>) -> Result<()> {
662 w.opt_octet_string(id.map(|id| id.as_bytes()))
663}
664
665impl<'a> Body<'a> {
666 pub const fn tag(&self) -> u32 {
668 match self {
669 Self::OpenRequest(_) => tag::OPEN_REQUEST,
670 Self::OpenResponse(_) => tag::OPEN_RESPONSE,
671 Self::CloseRequest(_) => tag::CLOSE_REQUEST,
672 Self::CloseResponse(_) => tag::CLOSE_RESPONSE,
673 Self::GetListRequest(_) => tag::GET_LIST_REQUEST,
674 Self::GetListResponse(_) => tag::GET_LIST_RESPONSE,
675 Self::Attention(_) => tag::ATTENTION_RESPONSE,
676 Self::GetProcParameterRequest(_) => tag::GET_PROC_PARAMETER_REQUEST,
677 Self::GetProcParameterResponse(_) => tag::GET_PROC_PARAMETER_RESPONSE,
678 Self::SetProcParameterRequest(_) => tag::SET_PROC_PARAMETER_REQUEST,
679 Self::GetProfilePackRequest(_) => tag::GET_PROFILE_PACK_REQUEST,
680 Self::GetProfileListRequest(_) => tag::GET_PROFILE_LIST_REQUEST,
681 Self::GetProfileListResponse(_) => tag::GET_PROFILE_LIST_RESPONSE,
682 Self::GetProfilePackResponse(_) => tag::GET_PROFILE_PACK_RESPONSE,
683 Self::Other { tag, .. } => *tag,
684 }
685 }
686
687 #[allow(clippy::too_many_lines)] fn read(r: &mut Reader<'a>, options: ParseOptions) -> Result<Self> {
689 r.list(2)?;
690 let tag = u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?;
691 let ctx = Ctx::new(options);
692 Ok(match tag {
693 tag::OPEN_REQUEST => {
694 r.list(7)?;
695 Self::OpenRequest(OpenRequest {
696 codepage: r.opt_octet_string()?,
697 client_id: r.octet_string()?,
698 req_file_id: r.octet_string()?,
699 server_id: opt_server_id(r)?,
700 username: r.opt_octet_string()?,
701 password: r.opt_octet_string()?,
702 sml_version: read_u8(r)?,
703 })
704 }
705 tag::OPEN_RESPONSE => {
706 r.list(6)?;
707 Self::OpenResponse(OpenResponse {
708 codepage: r.opt_octet_string()?,
709 client_id: r.opt_octet_string()?,
710 req_file_id: r.octet_string()?,
711 server_id: ServerId::new(r.octet_string()?),
712 ref_time: Time::read_opt(r, options)?,
713 sml_version: read_u8(r)?,
714 })
715 }
716 tag::CLOSE_REQUEST => {
717 r.list(1)?;
718 Self::CloseRequest(CloseRequest { global_signature: r.opt_octet_string()? })
719 }
720 tag::CLOSE_RESPONSE => {
721 r.list(1)?;
722 Self::CloseResponse(CloseResponse { global_signature: r.opt_octet_string()? })
723 }
724 tag::GET_LIST_REQUEST => {
725 r.list(5)?;
726 Self::GetListRequest(GetListRequest {
727 client_id: r.octet_string()?,
728 server_id: opt_server_id(r)?,
729 username: r.opt_octet_string()?,
730 password: r.opt_octet_string()?,
731 list_name: r.opt_octet_string()?,
732 })
733 }
734 tag::GET_LIST_RESPONSE => {
735 r.list(7)?;
736 let client_id = r.opt_octet_string()?;
737 let server_id = ServerId::new(r.octet_string()?);
738 let list_name = r.opt_octet_string()?;
739 let act_sensor_time = Time::read_opt(r, options)?;
740 let dzg = options.dzg_power && server_id.manufacturer() == Some("DZG");
741 let entries = Seq::read(r, Ctx { dzg, ..Ctx::new(options) })?;
742 Self::GetListResponse(GetListResponse {
743 client_id,
744 server_id,
745 list_name,
746 act_sensor_time,
747 entries,
748 list_signature: r.opt_octet_string()?,
749 act_gateway_time: Time::read_opt(r, options)?,
750 })
751 }
752 tag::ATTENTION_RESPONSE => {
753 r.list(4)?;
754 let server_id = ServerId::new(r.octet_string()?);
755 let number = r.octet_string()?;
756 let message = r.opt_octet_string()?;
757 let details = if r.absent() {
758 None
759 } else {
760 let from = r.position();
761 r.skip()?;
762 Some(r.slice(from, r.position())?)
763 };
764 Self::Attention(Attention { server_id, number, message, details })
765 }
766 tag::GET_PROC_PARAMETER_REQUEST => {
767 r.list(5)?;
768 Self::GetProcParameterRequest(GetProcParameterRequest {
769 server_id: opt_server_id(r)?,
770 username: r.opt_octet_string()?,
771 password: r.opt_octet_string()?,
772 tree_path: Seq::read(r, ctx)?,
773 attribute: r.opt_octet_string()?,
774 })
775 }
776 tag::GET_PROC_PARAMETER_RESPONSE => {
777 r.list(3)?;
778 Self::GetProcParameterResponse(GetProcParameterResponse {
779 server_id: ServerId::new(r.octet_string()?),
780 tree_path: Seq::read(r, ctx)?,
781 tree: Tree::read(r, ctx)?,
782 })
783 }
784 tag::SET_PROC_PARAMETER_REQUEST => {
785 r.list(5)?;
786 Self::SetProcParameterRequest(SetProcParameterRequest {
787 server_id: opt_server_id(r)?,
788 username: r.opt_octet_string()?,
789 password: r.opt_octet_string()?,
790 tree_path: Seq::read(r, ctx)?,
791 tree: Tree::read(r, ctx)?,
792 })
793 }
794 tag::GET_PROFILE_PACK_REQUEST => Self::GetProfilePackRequest(GetProfileRequest::read(r, ctx)?),
795 tag::GET_PROFILE_LIST_REQUEST => Self::GetProfileListRequest(GetProfileRequest::read(r, ctx)?),
796 tag::GET_PROFILE_LIST_RESPONSE => {
797 r.list(9)?;
798 Self::GetProfileListResponse(GetProfileListResponse {
799 server_id: ServerId::new(r.octet_string()?),
800 act_time: Time::read(r, options)?,
801 reg_period: u32::try_from(r.unsigned()?).map_err(|_| Error::ValueOutOfRange)?,
802 tree_path: Seq::read(r, ctx)?,
803 val_time: Time::read(r, options)?,
804 status: r.unsigned()?,
805 entries: Seq::read(r, ctx)?,
806 rawdata: r.opt_octet_string()?,
807 period_signature: r.opt_octet_string()?,
808 })
809 }
810 tag::GET_PROFILE_PACK_RESPONSE => {
811 Self::GetProfilePackResponse(GetProfilePackResponse::read(r, ctx)?)
812 }
813 other => {
814 let from = r.position();
815 r.skip()?;
816 Self::Other { tag: other, raw: r.slice(from, r.position())? }
817 }
818 })
819 }
820
821 pub fn write(&self, w: &mut Writer<'_>) -> Result<()> {
823 w.list(2)?;
824 w.unsigned(u64::from(self.tag()), 4)?;
825 match *self {
826 Self::OpenRequest(o) => {
827 w.list(7)?;
828 w.opt_octet_string(o.codepage)?;
829 w.octet_string(o.client_id)?;
830 w.octet_string(o.req_file_id)?;
831 write_opt_server_id(w, o.server_id)?;
832 w.opt_octet_string(o.username)?;
833 w.opt_octet_string(o.password)?;
834 write_opt_u8(w, o.sml_version)
835 }
836 Self::OpenResponse(o) => {
837 w.list(6)?;
838 w.opt_octet_string(o.codepage)?;
839 w.opt_octet_string(o.client_id)?;
840 w.octet_string(o.req_file_id)?;
841 w.octet_string(o.server_id.as_bytes())?;
842 Time::write_opt(o.ref_time, w)?;
843 write_opt_u8(w, o.sml_version)
844 }
845 Self::CloseRequest(CloseRequest { global_signature })
846 | Self::CloseResponse(CloseResponse { global_signature }) => {
847 w.list(1)?;
848 w.opt_octet_string(global_signature)
849 }
850 Self::GetListRequest(g) => {
851 w.list(5)?;
852 w.octet_string(g.client_id)?;
853 write_opt_server_id(w, g.server_id)?;
854 w.opt_octet_string(g.username)?;
855 w.opt_octet_string(g.password)?;
856 w.opt_octet_string(g.list_name)
857 }
858 Self::GetListResponse(g) => {
859 w.list(7)?;
860 w.opt_octet_string(g.client_id)?;
861 w.octet_string(g.server_id.as_bytes())?;
862 w.opt_octet_string(g.list_name)?;
863 Time::write_opt(g.act_sensor_time, w)?;
864 g.entries.write(w)?;
865 w.opt_octet_string(g.list_signature)?;
866 Time::write_opt(g.act_gateway_time, w)
867 }
868 Self::Attention(a) => {
869 w.list(4)?;
870 w.octet_string(a.server_id.as_bytes())?;
871 w.octet_string(a.number)?;
872 w.opt_octet_string(a.message)?;
873 match a.details {
874 Some(raw) => w.raw(one_element(raw)?),
875 None => w.absent(),
876 }
877 }
878 Self::GetProcParameterRequest(g) => {
879 w.list(5)?;
880 write_opt_server_id(w, g.server_id)?;
881 w.opt_octet_string(g.username)?;
882 w.opt_octet_string(g.password)?;
883 g.tree_path.write(w)?;
884 w.opt_octet_string(g.attribute)
885 }
886 Self::GetProcParameterResponse(g) => {
887 w.list(3)?;
888 w.octet_string(g.server_id.as_bytes())?;
889 g.tree_path.write(w)?;
890 g.tree.write(w)
891 }
892 Self::SetProcParameterRequest(s) => {
893 w.list(5)?;
894 write_opt_server_id(w, s.server_id)?;
895 w.opt_octet_string(s.username)?;
896 w.opt_octet_string(s.password)?;
897 s.tree_path.write(w)?;
898 s.tree.write(w)
899 }
900 Self::GetProfilePackRequest(g) | Self::GetProfileListRequest(g) => g.write(w),
901 Self::GetProfileListResponse(g) => {
902 w.list(9)?;
903 w.octet_string(g.server_id.as_bytes())?;
904 g.act_time.write(w)?;
905 w.unsigned(u64::from(g.reg_period), 4)?;
906 g.tree_path.write(w)?;
907 g.val_time.write(w)?;
908 w.unsigned(g.status, 8)?;
909 g.entries.write(w)?;
910 w.opt_octet_string(g.rawdata)?;
911 w.opt_octet_string(g.period_signature)
912 }
913 Self::GetProfilePackResponse(g) => g.write(w),
914 Self::Other { raw, .. } => w.raw(one_element(raw)?),
915 }
916 }
917}
918
919impl<'a> GetProfileRequest<'a> {
920 fn read(r: &mut Reader<'a>, ctx: Ctx) -> Result<Self> {
921 r.list(9)?;
922 Ok(Self {
923 server_id: opt_server_id(r)?,
924 username: r.opt_octet_string()?,
925 password: r.opt_octet_string()?,
926 with_rawdata: if r.absent() { None } else { Some(r.boolean()?) },
927 begin_time: Time::read_opt(r, ctx.options)?,
928 end_time: Time::read_opt(r, ctx.options)?,
929 tree_path: Seq::read(r, ctx)?,
930 objects: Seq::read_opt(r, ctx)?,
931 details: Tree::read_opt(r, ctx)?,
932 })
933 }
934
935 fn write(&self, w: &mut Writer<'_>) -> Result<()> {
936 w.list(9)?;
937 write_opt_server_id(w, self.server_id)?;
938 w.opt_octet_string(self.username)?;
939 w.opt_octet_string(self.password)?;
940 match self.with_rawdata {
941 Some(b) => w.boolean(b)?,
942 None => w.absent()?,
943 }
944 Time::write_opt(self.begin_time, w)?;
945 Time::write_opt(self.end_time, w)?;
946 self.tree_path.write(w)?;
947 Seq::write_opt(self.objects, w)?;
948 Tree::write_opt(self.details.as_ref(), w)
949 }
950}
951
952fn one_element(raw: &[u8]) -> Result<&[u8]> {
955 let mut r = Reader::new(raw);
956 r.skip()?;
957 if r.is_empty() { Ok(raw) } else { Err(Error::InvalidLength) }
958}
959
960#[derive(Clone, Debug)] pub struct Messages<'a> {
966 r: Reader<'a>,
967 options: ParseOptions,
968 done: bool,
969 last: usize,
970}
971
972impl<'a> Messages<'a> {
973 pub const fn new(payload: &'a [u8], options: ParseOptions) -> Self {
975 Self { r: Reader::new(payload), options, done: false, last: 0 }
976 }
977
978 pub const fn offset(&self) -> usize {
981 self.last
982 }
983}
984
985impl<'a> Iterator for Messages<'a> {
986 type Item = Result<Message<'a>>;
987
988 fn next(&mut self) -> Option<Self::Item> {
989 if self.done || self.r.is_empty() {
990 return None;
991 }
992 self.last = self.r.position();
993 let item = Message::read(&mut self.r, self.options);
994 self.done = item.is_err();
995 Some(item)
996 }
997}
998
999pub fn readout_with(payload: &[u8], options: ParseOptions) -> Result<GetListResponse<'_>> {
1002 let mut list = None;
1003 for message in Messages::new(payload, options) {
1004 if let (None, Body::GetListResponse(l)) = (list, message?.body) {
1005 list = Some(l);
1006 }
1007 }
1008 list.ok_or(Error::NoReadings)
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013 extern crate std;
1014 use super::*;
1015 use std::format;
1016
1017 #[test]
1019 fn debug_never_prints_a_password() {
1020 let open = OpenRequest {
1021 codepage: None,
1022 client_id: b"client",
1023 req_file_id: b"1",
1024 server_id: None,
1025 username: Some(b"user"),
1026 password: Some(b"secret"),
1027 sml_version: None,
1028 };
1029 let shown = format!("{open:?} {:?}", Body::OpenRequest(open));
1030 assert!(!shown.contains("secret") && !shown.contains("115, 101, 99"), "{shown}");
1031 assert!(shown.contains("<redacted>"));
1032 let get = GetListRequest {
1033 client_id: b"c",
1034 server_id: None,
1035 username: None,
1036 password: Some(b"pw"),
1037 list_name: None,
1038 };
1039 let shown = format!("{get:?}");
1040 assert!(!shown.contains("112, 119") && shown.contains("<redacted>"), "{shown}");
1041 let none = GetListRequest { password: None, ..get };
1042 assert!(format!("{none:?}").contains("password: None"));
1043 }
1044
1045 #[test]
1048 fn redact_every_credential_carrying_request() {
1049 let pw: &[u8] = b"hunter2";
1050 let path = NameList::from_slice(&[b"p"]);
1051 let tree = Tree { name: b"n", value: None, children: None };
1052 let profile = GetProfileRequest {
1053 server_id: None,
1054 username: Some(b"u"),
1055 password: Some(pw),
1056 with_rawdata: None,
1057 begin_time: None,
1058 end_time: None,
1059 tree_path: path,
1060 objects: None,
1061 details: None,
1062 };
1063 let bodies = [
1064 Body::OpenRequest(OpenRequest {
1065 codepage: None,
1066 client_id: b"c",
1067 req_file_id: b"f",
1068 server_id: None,
1069 username: Some(b"u"),
1070 password: Some(pw),
1071 sml_version: None,
1072 }),
1073 Body::GetListRequest(GetListRequest {
1074 client_id: b"c",
1075 server_id: None,
1076 username: None,
1077 password: Some(pw),
1078 list_name: None,
1079 }),
1080 Body::GetProcParameterRequest(GetProcParameterRequest {
1081 server_id: None,
1082 username: None,
1083 password: Some(pw),
1084 tree_path: path,
1085 attribute: None,
1086 }),
1087 Body::SetProcParameterRequest(SetProcParameterRequest {
1088 server_id: None,
1089 username: None,
1090 password: Some(pw),
1091 tree_path: path,
1092 tree,
1093 }),
1094 Body::GetProfilePackRequest(profile),
1095 Body::GetProfileListRequest(profile),
1096 ];
1097 for body in bodies {
1098 let message = Message { transaction_id: b"t", group_no: 0, abort_on_error: 0, body };
1099 let shown = format!("{body:?} {message:?} {message:#?}");
1100 assert!(!shown.contains("hunter2") && !shown.contains("104, 117, 110"), "{shown}");
1101 assert!(shown.contains("<redacted>"), "{shown}");
1102 let mut buf = [0u8; 256];
1104 let mut w = Writer::new(&mut buf);
1105 message.write(&mut w).unwrap();
1106 let n = w.position();
1107 let again = Message::read(&mut Reader::new(&buf[..n]), ParseOptions::default()).unwrap();
1108 assert_eq!(again, message);
1109 assert!(!format!("{again:?}").contains("104, 117, 110"));
1110 }
1111 }
1112
1113 #[test]
1115 fn debug_of_parsers_never_prints_payload_bytes() {
1116 let payload = b"\x76secret-password";
1117 let shown = format!(
1118 "{:?} {:?} {:?}",
1119 Messages::new(payload, ParseOptions::default()),
1120 Reader::new(payload),
1121 crate::Decoder::new([0u8; 8])
1122 );
1123 assert!(!shown.contains("115, 101, 99") && !shown.contains("secret"), "{shown}");
1124 }
1125
1126 #[test]
1127 fn raw_parts_must_be_one_element_or_nothing_is_written() {
1128 let mut buf = [0u8; 64];
1129 for raw in [&[][..], &[0x01, 0x01], &[0x72, 0x01]] {
1130 let m = Message {
1131 transaction_id: b"t",
1132 group_no: 0,
1133 abort_on_error: 0,
1134 body: Body::Other { tag: 0x500, raw },
1135 };
1136 assert!(m.write(&mut Writer::new(&mut buf)).is_err(), "{raw:02x?}");
1137 let a =
1138 Attention { server_id: ServerId::new(b"s"), number: b"n", message: None, details: Some(raw) };
1139 let m = Message { body: Body::Attention(a), ..m };
1140 assert!(m.write(&mut Writer::new(&mut buf)).is_err(), "{raw:02x?}");
1141 }
1142 }
1143
1144 #[test]
1145 fn lists_compare_by_what_they_yield() {
1146 let dzg_meter: &[u8] = &[0x0a, 0x01, b'D', b'Z', b'G', 0, 2, 0x82, 0x22, 0x5e];
1147 let entries = [ListEntry::number(Obis::POWER, Unit::W, -2, -29_912)];
1148 let body = Body::GetListResponse(GetListResponse {
1149 client_id: None,
1150 server_id: ServerId::new(dzg_meter),
1151 list_name: None,
1152 act_sensor_time: None,
1153 entries: ListEntries::from_slice(&entries),
1154 list_signature: None,
1155 act_gateway_time: None,
1156 });
1157 let mut buf = [0u8; 128];
1158 let mut w = Writer::new(&mut buf);
1159 Message { transaction_id: b"t", group_no: 0, abort_on_error: 0, body }.write(&mut w).unwrap();
1160 let n = w.position();
1161 let plain = readout_with(&buf[..n], ParseOptions::default()).unwrap();
1162 let fixed = readout_with(&buf[..n], ParseOptions::default().with_dzg_power(true)).unwrap();
1163 let off =
1164 readout_with(&buf[..n], ParseOptions { crc: CrcCheck::Off, ..ParseOptions::default() }).unwrap();
1165 assert_eq!(plain.entries, ListEntries::from_slice(&entries));
1167 assert_eq!(plain.entries, off.entries);
1168 assert_ne!(plain.entries, fixed.entries);
1169 assert_eq!(format!("{:?}", plain.entries), "Seq { len: 1, .. }");
1170 }
1171
1172 #[test]
1173 fn dzg_correction_only_touches_short_negatives() {
1174 assert_eq!(dzg_unsigned(SmlValue::Int(0), 2), SmlValue::Int(0));
1175 assert_eq!(dzg_unsigned(SmlValue::Int(-29_912), 2), SmlValue::Uint(35_624));
1176 assert_eq!(dzg_unsigned(SmlValue::Int(-1), 1), SmlValue::Uint(255));
1177 assert_eq!(dzg_unsigned(SmlValue::Int(-1), 3), SmlValue::Uint(0xFF_FFFF));
1178 assert_eq!(dzg_unsigned(SmlValue::Int(-60_525), 4), SmlValue::Int(-60_525));
1179 assert_eq!(dzg_unsigned(SmlValue::Int(5), 2), SmlValue::Int(5));
1180 assert_eq!(dzg_unsigned(SmlValue::Uint(5), 2), SmlValue::Uint(5));
1181 }
1182}