1pub use sml_kit as protocol;
14
15use crate::{Counts, Slot};
16use core::{fmt, ops::RangeInclusive};
17use protocol::{GetListResponse, GetProfilePackResponse, ListEntry, Obis, SmlValue, Unit};
18use smgw_core::taf15;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct Source<'a> {
23 pub channel: taf15::Channel<'a>,
25 pub server_id: &'a [u8],
27 pub profile: Obis,
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ReadError {
34 WrongSource,
36 Window,
38 Profile,
40 Period,
42 Column,
44 Unit,
46 Time,
48 OutsideRange,
50 Value,
52 Status,
54 TooManyRows,
56 Slot,
58 Decode(protocol::Error),
60 Capture(taf15::Error),
62}
63
64impl fmt::Display for ReadError {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.write_str(match self {
67 Self::WrongSource => "meter server ID or channel differs from commissioning",
68 Self::Window => "requested range is empty or outside the TAF 15 window",
69 Self::Profile => "the answer names a different profile",
70 Self::Period => "meter registration period differs from the commissioned interval",
71 Self::Column => "the commissioned register must appear exactly once",
72 Self::Unit => "expected the commissioned unit with a scaler",
73 Self::Time => "expected a calendar timestamp, not a seconds index",
74 Self::OutsideRange => "a row is outside the requested range",
75 Self::Value => "expected an integer register value",
76 Self::Status => "expected a meter status that fits in 32 bits",
77 Self::TooManyRows => "the answer has more rows than the commissioned window",
78 Self::Slot => "reception time is outside the slot",
79 Self::Decode(e) => return write!(f, "SML: {e}"),
80 Self::Capture(e) => return e.fmt(f),
81 })
82 }
83}
84
85impl core::error::Error for ReadError {
86 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
87 match self {
88 Self::Decode(e) => Some(e),
89 Self::Capture(e) => Some(e),
90 _ => None,
91 }
92 }
93}
94
95impl From<protocol::Error> for ReadError {
96 fn from(value: protocol::Error) -> Self {
97 Self::Decode(value)
98 }
99}
100
101fn expected_unit(channel: taf15::Channel<'_>) -> Result<Unit, ReadError> {
102 match channel.unit {
103 "Wh" => Ok(Unit::WH),
104 "varh" => Ok(Unit::VARH),
105 "m³" => Ok(Unit::M3),
106 _ => Err(ReadError::Unit),
107 }
108}
109
110fn coefficient(value: SmlValue<'_>) -> Result<i128, ReadError> {
111 value.as_integer().ok_or(ReadError::Value)
112}
113
114fn status(value: u64) -> Result<u32, ReadError> {
115 u32::try_from(value).map_err(|_| ReadError::Status)
116}
117
118fn bind<const N: usize>(
119 server_id: &[u8],
120 source: &Source<'_>,
121 destination: &taf15::Profile<'_, N>,
122) -> Result<Unit, ReadError> {
123 if server_id != source.server_id || destination.channel() != source.channel {
124 return Err(ReadError::WrongSource);
125 }
126 expected_unit(source.channel)
127}
128
129pub fn read_profile_pack<const N: usize>(
136 response: &GetProfilePackResponse<'_>,
137 source: &Source<'_>,
138 range: RangeInclusive<i64>,
139 destination: &mut taf15::Profile<'_, N>,
140) -> Result<Counts, ReadError> {
141 let unit = bind(response.server_id.as_bytes(), source, destination)?;
142 let window = destination.window();
143 if range.is_empty() || !window.contains(range.start()) || !window.contains(range.end()) {
144 return Err(ReadError::Window);
145 }
146 let mut path = response.tree_path.iter();
147 if !matches!((path.next(), path.next()), (Some(Ok(name)), None) if name == source.profile.0) {
148 return Err(ReadError::Profile);
149 }
150 if i64::from(response.reg_period) != destination.period().seconds() {
151 return Err(ReadError::Period);
152 }
153
154 let register = Obis(source.channel.obis);
155 let mut found = None;
156 for (index, column) in response.columns.iter().enumerate() {
157 let column = column?;
158 if column.obis == register {
159 if found.is_some() {
160 return Err(ReadError::Column);
161 }
162 found = Some((index, column));
163 }
164 }
165 let (index, column) = found.ok_or(ReadError::Column)?;
166 if column.unit != unit {
167 return Err(ReadError::Unit);
168 }
169 if response.periods.len() > N {
170 return Err(ReadError::TooManyRows);
171 }
172
173 destination.capture_batch(|batch| {
174 let mut counts = Counts::default();
175 for period in &response.periods {
176 let period = period?;
177 let utc = i64::from(period.val_time.unix_seconds().ok_or(ReadError::Time)?);
178 if !range.contains(&utc) {
179 return Err(ReadError::OutsideRange);
180 }
181 let value = period.values.iter().nth(index).ok_or(ReadError::Column)??;
183 let record = taf15::Record {
184 reference_utc: utc,
185 measured_utc: utc,
186 coefficient: coefficient(value.value)?,
187 scale: column.scaler,
188 meter_status: Some(status(period.status)?),
189 };
190 match batch
191 .capture(source.channel, record)
192 .map_err(ReadError::Capture)?
193 {
194 taf15::Capture::Inserted => counts.inserted += 1,
195 taf15::Capture::Duplicate => counts.duplicates += 1,
196 }
197 }
198 Ok(counts)
199 })
200}
201
202pub fn capture_reading<const N: usize>(
209 list: &GetListResponse<'_>,
210 source: &Source<'_>,
211 slot: Slot,
212 destination: &mut taf15::Profile<'_, N>,
213) -> Result<taf15::Capture, ReadError> {
214 let unit = bind(list.server_id.as_bytes(), source, destination)?;
215 if !slot.contains_reception(destination.period().seconds()) {
216 return Err(ReadError::Slot);
217 }
218 let register = Obis(source.channel.obis);
219 let mut found: Option<ListEntry<'_>> = None;
220 for entry in &list.entries {
221 let entry = entry?;
222 if entry.obis == register {
223 if found.is_some() {
224 return Err(ReadError::Column);
225 }
226 found = Some(entry);
227 }
228 }
229 let entry = found.ok_or(ReadError::Column)?;
230 let (Some(entry_unit), Some(scale)) = (entry.unit, entry.scaler) else {
231 return Err(ReadError::Unit);
232 };
233 if entry_unit != unit {
234 return Err(ReadError::Unit);
235 }
236 let record = taf15::Record {
237 reference_utc: slot.reference_utc,
238 measured_utc: slot.received_utc,
239 coefficient: coefficient(entry.value)?,
240 scale,
241 meter_status: entry.status.map(status).transpose()?,
242 };
243 destination
244 .capture(source.channel, record)
245 .map_err(ReadError::Capture)
246}
247
248#[cfg(test)]
249mod tests {
250 extern crate std;
251
252 use super::*;
253 use protocol::{
254 NameList, ProfileColumn, ProfileColumns, ProfilePeriod, ProfilePeriods, ProfileValue,
255 ProfileValues, ServerId, Time,
256 };
257 use std::vec::Vec;
258
259 const FIRST: i64 = 1_700_000_100;
260 const SERVER: &[u8] = b"\x0a\x01IMS\x00\x00\x00\x00\x01";
261 const PROFILE: Obis = Obis::new(1, 0, 99, 1, 0, 255);
262 const PATH: [&[u8]; 1] = [&PROFILE.0];
263 const COLUMNS: [ProfileColumn; 2] = [
264 ProfileColumn {
265 obis: Obis::new(1, 0, 2, 8, 0, 255),
266 unit: Unit::WH,
267 scaler: 0,
268 },
269 ProfileColumn {
270 obis: Obis::ENERGY_IMPORT,
271 unit: Unit::WH,
272 scaler: -1,
273 },
274 ];
275
276 fn source() -> Source<'static> {
277 Source {
278 channel: taf15::Channel {
279 meter_id: "meter",
280 obis: Obis::ENERGY_IMPORT.0,
281 unit: "Wh",
282 },
283 server_id: SERVER,
284 profile: PROFILE,
285 }
286 }
287
288 fn profile() -> taf15::Profile<'static, 3> {
289 taf15::Profile::new("p", source().channel, taf15::Period::QuarterHour, FIRST).unwrap()
290 }
291
292 fn values(import: u64) -> [ProfileValue<'static>; 2] {
293 [
294 ProfileValue::new(SmlValue::Uint(7)),
295 ProfileValue::new(SmlValue::Uint(import)),
296 ]
297 }
298
299 fn period<'a>(time: Time, values: &'a [ProfileValue<'a>]) -> ProfilePeriod<'a> {
300 ProfilePeriod {
301 val_time: time,
302 status: 0x0800_0104,
303 values: ProfileValues::from_slice(values),
304 period_signature: None,
305 }
306 }
307
308 fn response<'a>(periods: &'a [ProfilePeriod<'a>]) -> GetProfilePackResponse<'a> {
309 GetProfilePackResponse {
310 server_id: ServerId::new(SERVER),
311 act_time: Time::Timestamp(FIRST as u32 + 2000),
312 reg_period: 900,
313 tree_path: NameList::from_slice(&PATH),
314 columns: ProfileColumns::from_slice(&COLUMNS),
315 periods: ProfilePeriods::from_slice(periods),
316 rawdata: None,
317 profile_signature: None,
318 }
319 }
320
321 fn at(slot: i64) -> Time {
322 Time::Timestamp((FIRST + slot * 900) as u32)
323 }
324
325 const ALL: RangeInclusive<i64> = FIRST..=FIRST + 1800;
326
327 #[test]
328 fn a_packed_profile_keeps_scaler_status_and_counts_repeats() {
329 let (a, b) = (values(123_400), values(123_415));
330 let rows = [period(at(0), &a), period(at(2), &b)];
331 let mut history = profile();
332 let counts = read_profile_pack(&response(&rows), &source(), ALL, &mut history).unwrap();
333 assert_eq!(
334 counts,
335 Counts {
336 inserted: 2,
337 duplicates: 0
338 }
339 );
340 assert_eq!(history.missing().collect::<Vec<_>>(), [FIRST + 900]);
341 assert_eq!(
342 history.records().nth(1),
343 Some(&taf15::Record {
344 reference_utc: FIRST + 1800,
345 measured_utc: FIRST + 1800,
346 coefficient: 123_415,
347 scale: -1,
348 meter_status: Some(0x0800_0104),
349 })
350 );
351 let again = read_profile_pack(&response(&rows), &source(), ALL, &mut history).unwrap();
352 assert_eq!(
353 again,
354 Counts {
355 inserted: 0,
356 duplicates: 2
357 }
358 );
359 }
360
361 #[test]
362 fn a_rejected_last_row_discards_the_whole_answer() {
363 let (v, w) = (values(1), values(2));
364 let local = Time::LocalTimestamp {
365 timestamp: (FIRST + 900) as u32,
366 local_offset_minutes: 60,
367 season_offset_minutes: 0,
368 };
369 let cases: [(&[ProfilePeriod<'_>], ReadError); 3] = [
370 (
371 &[period(at(0), &v), period(local, &v), period(at(3), &v)],
372 ReadError::OutsideRange,
373 ),
374 (
375 &[period(at(0), &v), period(Time::SecIndex(42), &v)],
376 ReadError::Time,
377 ),
378 (
379 &[period(at(0), &v), period(at(1), &v), period(at(1), &w)],
380 ReadError::Capture(taf15::Error::Conflict),
381 ),
382 ];
383 for (rows, expected) in cases {
384 let mut history = profile();
385 assert_eq!(
386 read_profile_pack(&response(rows), &source(), ALL, &mut history),
387 Err(expected)
388 );
389 assert_eq!(history.records().count(), 0);
390 }
391 }
392
393 #[test]
394 fn identity_profile_period_and_unit_bind_the_answer() {
395 let v = values(1);
396 let rows = [period(at(0), &v)];
397 let check = |mutate: &dyn Fn(&mut GetProfilePackResponse<'_>), expected| {
398 let mut answer = response(&rows);
399 mutate(&mut answer);
400 let mut history = profile();
401 assert_eq!(
402 read_profile_pack(&answer, &source(), ALL, &mut history),
403 Err(expected)
404 );
405 assert_eq!(history.records().count(), 0);
406 };
407 check(
408 &|r| r.server_id = ServerId::new(b"other"),
409 ReadError::WrongSource,
410 );
411 check(
412 &|r| r.tree_path = NameList::from_slice(&[]),
413 ReadError::Profile,
414 );
415 const NESTED: [&[u8]; 2] = [&PROFILE.0, &PROFILE.0];
416 check(
417 &|r| r.tree_path = NameList::from_slice(&NESTED),
418 ReadError::Profile,
419 );
420 check(&|r| r.reg_period = 3600, ReadError::Period);
421 check(
422 &|r| r.columns = ProfileColumns::from_slice(&COLUMNS[..1]),
423 ReadError::Column,
424 );
425 const TWICE: [ProfileColumn; 2] = [COLUMNS[1], COLUMNS[1]];
426 check(
427 &|r| r.columns = ProfileColumns::from_slice(&TWICE),
428 ReadError::Column,
429 );
430 const VARH: [ProfileColumn; 2] = [
431 COLUMNS[0],
432 ProfileColumn {
433 unit: Unit::VARH,
434 ..COLUMNS[1]
435 },
436 ];
437 check(
438 &|r| r.columns = ProfileColumns::from_slice(&VARH),
439 ReadError::Unit,
440 );
441
442 let mut history = profile();
443 let answer = response(&rows);
444 assert_eq!(
445 read_profile_pack(&answer, &source(), FIRST..=FIRST + 2700, &mut history),
446 Err(ReadError::Window)
447 );
448 #[allow(clippy::reversed_empty_ranges)]
449 let empty = FIRST + 900..=FIRST;
450 assert_eq!(
451 read_profile_pack(&answer, &source(), empty, &mut history),
452 Err(ReadError::Window)
453 );
454 let gas = Source {
455 channel: taf15::Channel {
456 unit: "kWh",
457 ..source().channel
458 },
459 ..source()
460 };
461 let mut other =
462 taf15::Profile::<3>::new("p", gas.channel, taf15::Period::QuarterHour, FIRST).unwrap();
463 assert_eq!(
464 read_profile_pack(&answer, &gas, ALL, &mut other),
465 Err(ReadError::Unit)
466 );
467 }
468
469 #[test]
470 fn values_status_and_row_count_are_checked() {
471 let text = [values(1)[0], ProfileValue::new(SmlValue::Bytes(b"x"))];
472 let v = values(1);
473 let mut wide = period(at(0), &v);
474 wide.status = u64::from(u32::MAX) + 1;
475 for (rows, expected) in [
476 (&[period(at(0), &text)][..], ReadError::Value),
477 (&[wide][..], ReadError::Status),
478 (
479 &[
480 period(at(0), &v),
481 period(at(1), &v),
482 period(at(2), &v),
483 period(at(2), &v),
484 ][..],
485 ReadError::TooManyRows,
486 ),
487 ] {
488 let mut history = profile();
489 assert_eq!(
490 read_profile_pack(&response(rows), &source(), ALL, &mut history),
491 Err(expected)
492 );
493 assert_eq!(history.records().count(), 0);
494 }
495 }
496
497 fn list<'a>(entries: &'a [ListEntry<'a>]) -> GetListResponse<'a> {
498 GetListResponse {
499 client_id: None,
500 server_id: ServerId::new(SERVER),
501 list_name: None,
502 act_sensor_time: Some(Time::SecIndex(5)),
503 entries: protocol::ListEntries::from_slice(entries),
504 list_signature: None,
505 act_gateway_time: None,
506 }
507 }
508
509 #[test]
510 fn a_push_reading_fills_the_slot_its_reception_falls_in() {
511 let entries = [
512 ListEntry::bytes(Obis::MANUFACTURER, b"IMS"),
513 ListEntry {
514 status: Some(0x0182),
515 ..ListEntry::unsigned(Obis::ENERGY_IMPORT, Unit::WH, -1, 98_765)
516 },
517 ];
518 let mut history = profile();
519 let slot = |received_utc| Slot {
520 reference_utc: FIRST + 900,
521 received_utc,
522 };
523 for received in [FIRST + 899, FIRST + 1800] {
524 assert_eq!(
525 capture_reading(&list(&entries), &source(), slot(received), &mut history),
526 Err(ReadError::Slot)
527 );
528 }
529 assert_eq!(
530 capture_reading(&list(&entries), &source(), slot(FIRST + 1799), &mut history),
531 Ok(taf15::Capture::Inserted)
532 );
533 assert_eq!(
534 history.records().next(),
535 Some(&taf15::Record {
536 reference_utc: FIRST + 900,
537 measured_utc: FIRST + 1799,
538 coefficient: 98_765,
539 scale: -1,
540 meter_status: Some(0x0182),
541 })
542 );
543 assert_eq!(
544 capture_reading(&list(&entries), &source(), slot(FIRST + 1799), &mut history),
545 Ok(taf15::Capture::Duplicate)
546 );
547 }
548
549 #[test]
550 fn a_push_reading_needs_the_commissioned_meter_register_and_unit() {
551 let good = ListEntry::number(Obis::ENERGY_IMPORT, Unit::WH, 0, 1);
552 let slot = Slot {
553 reference_utc: FIRST,
554 received_utc: FIRST,
555 };
556 let cases: [(&[ListEntry<'_>], ReadError); 5] = [
557 (
558 &[ListEntry::number(Obis::ENERGY_EXPORT, Unit::WH, 0, 1)],
559 ReadError::Column,
560 ),
561 (&[good, good], ReadError::Column),
562 (
563 &[ListEntry::number(Obis::ENERGY_IMPORT, Unit::VARH, 0, 1)],
564 ReadError::Unit,
565 ),
566 (
567 &[ListEntry {
568 scaler: None,
569 ..good
570 }],
571 ReadError::Unit,
572 ),
573 (
574 &[ListEntry {
575 value: SmlValue::Bool(true),
576 ..good
577 }],
578 ReadError::Value,
579 ),
580 ];
581 for (entries, expected) in cases {
582 let mut history = profile();
583 assert_eq!(
584 capture_reading(&list(entries), &source(), slot, &mut history),
585 Err(expected)
586 );
587 assert_eq!(history.records().count(), 0);
588 }
589 let only = [good];
590 let mut other = list(&only);
591 other.server_id = ServerId::new(b"\x0a\x01IMS\x00\x00\x00\x00\x02");
592 assert_eq!(
593 capture_reading(&other, &source(), slot, &mut profile()),
594 Err(ReadError::WrongSource)
595 );
596 }
597}