pub struct Decoder<B> { /* private fields */ }Expand description
A sans-I/O transport decoder that assembles frames in a buffer of type B.
Feed it bytes as they arrive, from an optical head, a serial line or a capture file, and it hands out each complete, verified payload. It never allocates and never panics. Garbage before a start sequence is skipped.
The buffer can be owned ([u8; N], or a Vec<u8> with std) or borrowed
(&mut [u8]). Its length is the largest frame accepted.
use sml_kit::{Decoder, encode_frame};
let mut wire = [0u8; 64];
let n = encode_frame(&[0x01, 0x02, 0x03], &mut wire).unwrap();
let mut decoder = Decoder::new([0u8; 64]);
let mut frames = 0;
decoder.push_slice(&wire[..n], |frame| {
assert_eq!(frame.unwrap(), &[0x01, 0x02, 0x03]);
frames += 1;
});
assert_eq!(frames, 1);Implementations§
Source§impl<B: AsRef<[u8]> + AsMut<[u8]>> Decoder<B>
impl<B: AsRef<[u8]> + AsMut<[u8]>> Decoder<B>
Sourcepub fn new(buf: B) -> Self
pub fn new(buf: B) -> Self
A decoder that assembles frames in buf. A frame larger than buf is reported
as Error::BufferFull and skipped.
Examples found in repository?
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}More examples
11fn main() -> Result<(), sml_kit::Error> {
12 // What a basic meter pushes on its optical interface, roughly every second.
13 let entries = [
14 ListEntry::bytes(Obis::MANUFACTURER, b"SIM"),
15 ListEntry::bytes(Obis::DEVICE_ID, &[0x0A, 0x01, 0x53, 0x49, 0x4D, 0, 0, 0, 0, 1]),
16 ListEntry::number(Obis::ENERGY_IMPORT, Unit::WH, -1, 123_456_789),
17 ListEntry::number(Obis::ENERGY_EXPORT, Unit::WH, -1, 4_200),
18 ListEntry::number(Obis::POWER, Unit::W, 0, 1_337),
19 ];
20 let telegram = Telegram {
21 server_id: &[0x0A, 0x01, 0x53, 0x49, 0x4D, 0, 0, 0, 0, 1],
22 file_id: b"F1",
23 entries: &entries,
24 };
25
26 let mut payload = [0u8; 512];
27 let len = telegram.write(&mut payload)?;
28 let mut wire = [0u8; 600];
29 let wire_len = encode_frame(&payload[..len], &mut wire)?;
30 println!("{wire_len} bytes on the wire");
31
32 // The receiving side: bytes in, verified frames out, readings in one call.
33 let mut decoder = Decoder::new([0u8; 1024]);
34 let mut result = Ok(());
35 decoder.push_slice(&wire[..wire_len], |frame| {
36 let list = match frame.and_then(readout) {
37 Ok(list) => list,
38 Err(e) => return result = Err(e),
39 };
40 println!("meter {}", list.server_id);
41 for entry in list.entries {
42 match entry {
43 Ok(e) => match e.quantity() {
44 Some(q) => println!("{:<24} {q}", e.obis.to_string()),
45 None => println!("{:<24} {:02x?}", e.obis.to_string(), e.value),
46 },
47 Err(err) => result = Err(err),
48 }
49 }
50 });
51 result
52}Sourcepub fn with_crc_check(self, check: CrcCheck) -> Self
pub fn with_crc_check(self, check: CrcCheck) -> Self
Set how the frame CRC is checked. CrcCheck::Strict by default.
Examples found in repository?
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}Sourcepub fn reset(&mut self)
pub fn reset(&mut self)
Forget any frame in progress and look for the next start sequence, e.g. after a serial-port timeout.
Sourcepub fn into_inner(self) -> B
pub fn into_inner(self) -> B
The buffer frames are assembled in.
Sourcepub fn push_slice(&mut self, data: &[u8], on_frame: impl FnMut(Result<&[u8]>))
pub fn push_slice(&mut self, data: &[u8], on_frame: impl FnMut(Result<&[u8]>))
Feed every byte of data, calling on_frame for each complete frame or error.
Examples found in repository?
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}More examples
11fn main() -> Result<(), sml_kit::Error> {
12 // What a basic meter pushes on its optical interface, roughly every second.
13 let entries = [
14 ListEntry::bytes(Obis::MANUFACTURER, b"SIM"),
15 ListEntry::bytes(Obis::DEVICE_ID, &[0x0A, 0x01, 0x53, 0x49, 0x4D, 0, 0, 0, 0, 1]),
16 ListEntry::number(Obis::ENERGY_IMPORT, Unit::WH, -1, 123_456_789),
17 ListEntry::number(Obis::ENERGY_EXPORT, Unit::WH, -1, 4_200),
18 ListEntry::number(Obis::POWER, Unit::W, 0, 1_337),
19 ];
20 let telegram = Telegram {
21 server_id: &[0x0A, 0x01, 0x53, 0x49, 0x4D, 0, 0, 0, 0, 1],
22 file_id: b"F1",
23 entries: &entries,
24 };
25
26 let mut payload = [0u8; 512];
27 let len = telegram.write(&mut payload)?;
28 let mut wire = [0u8; 600];
29 let wire_len = encode_frame(&payload[..len], &mut wire)?;
30 println!("{wire_len} bytes on the wire");
31
32 // The receiving side: bytes in, verified frames out, readings in one call.
33 let mut decoder = Decoder::new([0u8; 1024]);
34 let mut result = Ok(());
35 decoder.push_slice(&wire[..wire_len], |frame| {
36 let list = match frame.and_then(readout) {
37 Ok(list) => list,
38 Err(e) => return result = Err(e),
39 };
40 println!("meter {}", list.server_id);
41 for entry in list.entries {
42 match entry {
43 Ok(e) => match e.quantity() {
44 Some(q) => println!("{:<24} {q}", e.obis.to_string()),
45 None => println!("{:<24} {:02x?}", e.obis.to_string(), e.value),
46 },
47 Err(err) => result = Err(err),
48 }
49 }
50 });
51 result
52}