Skip to main content

Seq

Struct Seq 

Source
pub struct Seq<'a, T> { /* private fields */ }
Expand description

An SML SEQUENCE OF T, parsed lazily.

A sequence read from a frame keeps its encoded bytes and parses each element when iterated; one built for writing borrows a slice. Both behave the same, and a built sequence equals the decoded one:

use sml_kit::{ListEntries, ListEntry, Obis, Unit};

let entries = [ListEntry::number(Obis::POWER, Unit::W, 0, 1337)];
let list = ListEntries::from_slice(&entries);
assert_eq!(list.len(), 1);
assert_eq!(list.iter().next(), Some(Ok(entries[0])));

Debug shows only the length: the bytes of a request may hold credentials.

Implementations§

Source§

impl<'a, T> Seq<'a, T>

Source

pub const fn from_slice(items: &'a [T]) -> Self

A sequence of items, for writing.

Source

pub const fn len(&self) -> usize

How many elements the sequence has (for an encoded one: declares).

Source

pub const fn is_empty(&self) -> bool

Whether the sequence is empty.

Source§

impl<'a, T: Element<'a>> Seq<'a, T>

Source

pub fn iter(&self) -> SeqIter<'a, T> ⓘ

The elements, one at a time. An encoded sequence stops after the first element that fails to parse.

Examples found in repository?
examples/decode.rs (line 106)
100fn check(bytes: &[u8], options: ParseOptions) -> Result<usize, Error> {
101    let mut decoder = Decoder::new(vec![0u8; 64 * 1024]).with_crc_check(options.crc);
102    let mut result = Ok(0);
103    decoder.push_slice(bytes, |frame| {
104        let outcome = frame.and_then(|f| {
105            Messages::new(f, options).try_for_each(|m| match m?.body {
106                Body::GetListResponse(list) => list.entries.iter().try_for_each(|e| e.map(drop)),
107                _ => Ok(()),
108            })
109        });
110        result = match (result, outcome) {
111            (Ok(n), Ok(())) => Ok(n + 1),
112            (Ok(_), Err(e)) | (Err(e), _) => Err(e),
113        };
114    });
115    match result {
116        Ok(0) => Err(Error::UnexpectedEnd),
117        other => other,
118    }
119}
120
121/// Print every frame; the number of errors, and of frames whose power the DZG correction
122/// changes.
123fn print(bytes: &[u8], options: ParseOptions) -> (usize, (usize, usize)) {
124    let mut decoder = Decoder::new(vec![0u8; 64 * 1024]).with_crc_check(options.crc);
125    let (mut frames, mut errors) = (0, 0);
126    let mut dzg_frames = (0, 0); // (possible, confirmed by the status word)
127    decoder.push_slice(bytes, |frame| {
128        let frame = match frame {
129            Ok(f) => f,
130            Err(e) => {
131                errors += 1;
132                return eprintln!("frame error: {e}");
133            }
134        };
135        frames += 1;
136        println!("── frame {frames} · {} bytes", frame.len());
137        let mut messages = Messages::new(frame, options);
138        while let Some(message) = messages.next() {
139            match message {
140                Err(e) => {
141                    errors += 1;
142                    eprintln!("   message error at byte {}: {e}", messages.offset());
143                }
144                Ok(m) => match m.body {
145                    Body::GetListResponse(list) => {
146                        let time = list.act_sensor_time.map(|t| format!("  at {t}")).unwrap_or_default();
147                        println!("   GetListResponse  server {}{time}", list.server_id);
148                        match dzg_suspect(frame, options.with_dzg_power(false)) {
149                            Dzg::Unchanged => {}
150                            Dzg::Possible => dzg_frames.0 += 1,
151                            Dzg::Confirmed => dzg_frames.1 += 1,
152                        }
153                        for entry in list.entries {
154                            match entry {
155                                Ok(e) => println!("   {}", line(&e)),
156                                Err(err) => {
157                                    errors += 1;
158                                    eprintln!("   entry error: {err}");
159                                }
160                            }
161                        }
162                    }
163                    Body::OpenResponse(o) => println!("   OpenResponse     server {}", o.server_id),
164                    Body::CloseResponse(_) => println!("   CloseResponse"),
165                    Body::Attention(a) => {
166                        println!("   Attention        {:02x?} {}", a.number, a.description().unwrap_or(""));
167                    }
168                    Body::GetProcParameterResponse(r) => {
169                        println!("   GetProcParameterResponse  server {}", r.server_id);
170                        tree(&r.tree, 2);
171                    }
172                    Body::SetProcParameterRequest(r) => {
173                        println!("   SetProcParameterRequest");
174                        tree(&r.tree, 2);
175                    }
176                    Body::GetProfileListResponse(r) => {
177                        println!(
178                            "   GetProfileListResponse  server {}  period {} s",
179                            r.server_id, r.reg_period
180                        );
181                        for e in r.entries.iter().flatten() {
182                            let q = e.quantity().map_or_else(|| format!("{:?}", e.value), |q| q.to_string());
183                            println!("     {:<24} {q}", e.obis.to_string());
184                        }
185                    }
186                    Body::GetProfilePackResponse(p) => {
187                        println!(
188                            "   GetProfilePackResponse  server {}  period {} s",
189                            p.server_id, p.reg_period
190                        );
191                        for row in p.periods.iter().flatten() {
192                            let cells: Vec<String> = p
193                                .columns
194                                .iter()
195                                .flatten()
196                                .map(|c| {
197                                    p.quantity(&row, c.obis)
198                                        .map_or_else(|| "–".into(), |q| format!("{} {q}", c.obis))
199                                })
200                                .collect();
201                            println!("     {}  {}", row.val_time, cells.join("  "));
202                        }
203                    }
204                    Body::Other { tag, raw } => {
205                        println!("   body 0x{tag:08x} ({} bytes, not typed)", raw.len())
206                    }
207                    other => println!("   {other:?}"),
208                },
209            }
210        }
211    });
212    if frames == 0 && errors == 0 {
213        if looks_like_iec_62056_21(bytes) {
214            eprintln!(
215                "no SML frame: this is IEC 62056-21 text (D0), an older protocol, not SML. \
216                 Read it with an IEC 62056-21 parser."
217            );
218        } else {
219            eprintln!("no complete frame found: is the capture long enough (a few seconds) and 9600 8N1?");
220        }
221        errors += 1;
222    }
223    (errors, dzg_frames)
224}
Source

pub fn write(&self, w: &mut Writer<'_>) -> Result<()>

Write the sequence: its length, then every element.

Trait Implementations§

Source§

impl<T> Clone for Seq<'_, T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Copy for Seq<'_, T>

Source§

impl<T> Debug for Seq<'_, T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a, T: Element<'a>> Eq for Seq<'a, T>

Source§

impl<'a, T: Element<'a>> IntoIterator for Seq<'a, T>

Source§

type Item = Result<T, Error>

The type of the elements being iterated over.
Source§

type IntoIter = SeqIter<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, T: Element<'a>> IntoIterator for &Seq<'a, T>

Source§

type Item = Result<T, Error>

The type of the elements being iterated over.
Source§

type IntoIter = SeqIter<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, T: Element<'a>> PartialEq for Seq<'a, T>

Two sequences are equal when they yield equal elements (or equal errors), whether encoded or built.

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

Auto Trait Implementations§

§

impl<'a, T> Forget for Seq<'a, T>

§

impl<'a, T> Freeze for Seq<'a, T>
where &'a [u8]: Freeze, &'a [T]: Freeze,

§

impl<'a, T> Move for Seq<'a, T>

§

impl<'a, T> RefUnwindSafe for Seq<'a, T>
where T: RefUnwindSafe,

§

impl<'a, T> Send for Seq<'a, T>
where &'a [u8]: Send, &'a [T]: Send,

§

impl<'a, T> Sync for Seq<'a, T>
where T: Sync,

§

impl<'a, T> Unpin for Seq<'a, T>
where &'a [u8]: Unpin, &'a [T]: Unpin,

§

impl<'a, T> UnsafeUnpin for Seq<'a, T>
where &'a [u8]: UnsafeUnpin, &'a [T]: UnsafeUnpin,

§

impl<'a, T> UnwindSafe for Seq<'a, T>
where &'a [u8]: UnwindSafe, &'a [T]: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.