1use super::{ClockRange, Counts, Source, clock};
4use core::fmt;
5use dlms_cosem_kit::{
6 Obis,
7 axdr::{Data, Unit},
8 codec::{self, ErrorKind},
9 cosem::{CaptureObject, MAX_COLUMNS, ProfileBuffer},
10};
11use smgw_core::taf15;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum RowError {
16 Codec(codec::Error),
18 CaptureObjects,
20 ColumnMapping,
22 ScalerUnit,
24 TooManyRows,
26 RowWidth,
28 RegisterValue,
30 MeterStatus,
32 Clock(clock::ClockError),
34 OutsideRange,
36 Capture(taf15::Error),
38}
39
40impl fmt::Display for RowError {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 match self {
43 Self::Codec(e) => e.fmt(f),
44 Self::Clock(e) => e.fmt(f),
45 Self::Capture(e) => e.fmt(f),
46 Self::CaptureObjects => f.write_str("expected a bounded list of unique, typed capture objects"),
47 Self::ColumnMapping => f.write_str("the commissioned clock, register and optional columns must be present and distinct"),
48 Self::ScalerUnit => f.write_str("expected a signed scaler and the commissioned COSEM unit"),
49 Self::TooManyRows => f.write_str("the page has more rows than the commissioned window"),
50 Self::RowWidth => f.write_str("a profile row has columns beyond the capture list"),
51 Self::RegisterValue => f.write_str("expected a signed or unsigned integer register value"),
52 Self::MeterStatus => f.write_str("expected an unsigned meter status that fits in 32 bits"),
53 Self::OutsideRange => f.write_str("a reference timestamp is outside the requested clock range"),
54 }
55 }
56}
57
58impl core::error::Error for RowError {}
59
60impl From<codec::Error> for RowError {
61 fn from(value: codec::Error) -> Self {
62 Self::Codec(value)
63 }
64}
65
66pub(super) fn scaler_unit(channel: taf15::Channel<'_>, data: &Data<'_>) -> Result<i8, RowError> {
67 let expected = match channel.unit {
68 "Wh" => Unit::WATT_HOUR,
69 "varh" => Unit::VAR_HOUR,
70 "m³" => Unit::CUBIC_METRE,
71 _ => return Err(RowError::ScalerUnit),
72 };
73 let fields = data
74 .as_structure()
75 .filter(|v| v.len() == 2)
76 .ok_or(RowError::ScalerUnit)?;
77 match (fields.get(0)?, fields.get(1)?) {
78 (Data::Integer(scale), Data::Enum(unit)) if Unit(unit) == expected => Ok(scale),
79 _ => Err(RowError::ScalerUnit),
80 }
81}
82
83fn capture_object(encoded: Data<'_>) -> Result<CaptureObject, RowError> {
84 let fields = encoded
85 .as_structure()
86 .filter(|v| v.len() == 4)
87 .ok_or(RowError::CaptureObjects)?;
88 let (
89 Data::LongUnsigned(class),
90 Data::OctetString(name),
91 Data::Integer(attribute),
92 Data::LongUnsigned(index),
93 ) = (
94 fields.get(0)?,
95 fields.get(1)?,
96 fields.get(2)?,
97 fields.get(3)?,
98 )
99 else {
100 return Err(RowError::CaptureObjects);
101 };
102 let name = Obis::from_bytes(name.try_into().map_err(|_| RowError::CaptureObjects)?);
103 Ok(CaptureObject::new(class, name, attribute, index))
104}
105
106#[derive(Debug, PartialEq, Eq)]
108pub(super) struct Layout {
109 objects: [CaptureObject; MAX_COLUMNS],
110 width: usize,
111 clock: usize,
112 value: usize,
113 measured: Option<usize>,
114 status: Option<usize>,
115}
116
117impl Layout {
118 pub(super) fn resolve(source: &Source<'_>, data: &Data<'_>) -> Result<Self, RowError> {
119 let list = data
120 .as_array()
121 .filter(|v| v.len() <= MAX_COLUMNS)
122 .ok_or(RowError::CaptureObjects)?;
123 let mut objects = [CaptureObject::clock(); MAX_COLUMNS];
124 for (index, item) in list.iter().enumerate() {
125 let object = capture_object(item?)?;
126 if objects[..index].contains(&object) {
127 return Err(RowError::CaptureObjects);
128 }
129 objects[index] = object;
130 }
131
132 let position = |object: CaptureObject| {
133 objects[..list.len()]
134 .iter()
135 .position(|item| *item == object)
136 .ok_or(RowError::ColumnMapping)
137 };
138 let clock = position(CaptureObject::clock())?;
139 let value = position(CaptureObject::new(3, source.channel.obis.into(), 2, 0))?;
140 let measured = source.measured_time.map(position).transpose()?;
141 let status = source.status.map(position).transpose()?;
142 if [measured, status]
143 .into_iter()
144 .flatten()
145 .any(|col| col == clock || col == value)
146 || (status.is_some() && status == measured)
147 {
148 return Err(RowError::ColumnMapping);
149 }
150 Ok(Self {
151 objects,
152 width: list.len(),
153 clock,
154 value,
155 measured,
156 status,
157 })
158 }
159
160 pub(super) fn capture<const N: usize>(
162 &self,
163 source: &Source<'_>,
164 profile: &mut taf15::CaptureBatch<'_, '_, N>,
165 range: ClockRange,
166 scale: i8,
167 rows: &Data<'_>,
168 ) -> Result<Counts, RowError> {
169 let buffer = ProfileBuffer::new(rows)?;
170 if buffer.len() > N {
171 return Err(RowError::TooManyRows);
172 }
173 let mut cells = Cells::default();
174 let mut counts = Counts {
175 inserted: 0,
176 duplicates: 0,
177 };
178 let mut domain_error = None;
179 let decoded = buffer.for_each_cell(self.width, |_, column, data| {
180 if column == self.clock {
181 cells.clock = Some(data);
182 } else if column == self.value {
183 cells.value = Some(data);
184 } else if Some(column) == self.measured {
185 cells.measured = Some(data);
186 } else if Some(column) == self.status {
187 cells.status = Some(data);
188 }
189 if column + 1 == self.width {
190 let outcome = cells.record(scale, range).and_then(|record| {
191 profile
192 .capture(source.channel, record)
193 .map_err(RowError::Capture)
194 });
195 match outcome {
196 Ok(taf15::Capture::Inserted) => counts.inserted += 1,
197 Ok(taf15::Capture::Duplicate) => counts.duplicates += 1,
198 Err(error) => {
199 domain_error = Some(error);
201 return Err(codec::Error::new(ErrorKind::InvalidValue, 0));
202 }
203 }
204 }
205 Ok(())
206 });
207 if let Err(wire) = decoded {
208 if let Some(error) = domain_error {
209 return Err(error);
210 }
211 if wire.kind == ErrorKind::InvalidValue
214 && buffer
215 .raw_rows()
216 .nth(counts.inserted + counts.duplicates)
217 .is_some_and(|row| row.is_ok_and(|cells| cells.len() > self.width))
218 {
219 return Err(RowError::RowWidth);
220 }
221 return Err(RowError::Codec(wire));
222 }
223 Ok(counts)
224 }
225}
226
227#[derive(Default)]
228struct Cells<'a> {
229 clock: Option<Data<'a>>,
230 value: Option<Data<'a>>,
231 measured: Option<Data<'a>>,
232 status: Option<Data<'a>>,
233}
234
235impl Cells<'_> {
236 fn record(&self, scale: i8, range: ClockRange) -> Result<taf15::Record, RowError> {
237 let reference_utc = clock::utc_seconds(self.clock.as_ref().ok_or(RowError::ColumnMapping)?)
238 .map_err(RowError::Clock)?;
239 if !range.contains(reference_utc) {
240 return Err(RowError::OutsideRange);
241 }
242 let measured_utc = self
243 .measured
244 .as_ref()
245 .map(clock::utc_seconds)
246 .transpose()
247 .map_err(RowError::Clock)?
248 .unwrap_or(reference_utc);
249 let value = self.value.as_ref().ok_or(RowError::ColumnMapping)?;
250 Ok(taf15::Record {
251 reference_utc,
252 measured_utc,
253 coefficient: coefficient(value)?,
254 scale,
255 meter_status: self.status.as_ref().map(meter_status).transpose()?,
256 })
257 }
258}
259
260fn coefficient(value: &Data<'_>) -> Result<i128, RowError> {
261 Ok(match *value {
262 Data::Integer(n) => i128::from(n),
263 Data::Long(n) => i128::from(n),
264 Data::DoubleLong(n) => i128::from(n),
265 Data::Long64(n) => i128::from(n),
266 Data::Unsigned(n) => i128::from(n),
267 Data::LongUnsigned(n) => i128::from(n),
268 Data::DoubleLongUnsigned(n) => i128::from(n),
269 Data::Long64Unsigned(n) => i128::from(n),
270 _ => return Err(RowError::RegisterValue),
271 })
272}
273
274fn meter_status(value: &Data<'_>) -> Result<u32, RowError> {
275 match *value {
276 Data::Unsigned(n) => Ok(u32::from(n)),
277 Data::LongUnsigned(n) => Ok(u32::from(n)),
278 Data::DoubleLongUnsigned(n) => Ok(n),
279 Data::Long64Unsigned(n) => u32::try_from(n).map_err(|_| RowError::MeterStatus),
280 _ => Err(RowError::MeterStatus),
281 }
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287 use dlms_cosem_kit::{
288 axdr::DateTime,
289 codec::{Encode, SliceWriter, Writer},
290 };
291
292 const FIRST: i64 = 946_684_800;
293 const REGISTER: CaptureObject = CaptureObject::new(3, Obis::new(1, 0, 1, 8, 0, 255), 2, 0);
294 const MEASURED: CaptureObject = CaptureObject::new(1, Obis::new(0, 0, 96, 7, 0, 255), 2, 0);
295 const STATUS: CaptureObject = CaptureObject::new(1, Obis::new(0, 0, 96, 5, 0, 255), 2, 0);
296
297 fn source() -> Source<'static> {
298 Source {
299 channel: taf15::Channel {
300 meter_id: "meter",
301 obis: REGISTER.logical_name.into(),
302 unit: "Wh",
303 },
304 profile: Obis::new(1, 0, 99, 1, 0, 255),
305 measured_time: None,
306 status: None,
307 }
308 }
309
310 fn descriptors(source: &Source<'_>, objects: &[CaptureObject]) -> Result<Layout, RowError> {
311 let mut bytes = [0; 512];
312 let mut out = SliceWriter::new(&mut bytes);
313 out.write_bytes(&[1, objects.len() as u8])?;
314 for object in objects {
315 object.encode(&mut out)?;
316 }
317 Layout::resolve(source, &Data::from_bytes_in(out.as_slice())?)
318 }
319
320 fn sample(minute: u8, second: u8) -> Data<'static> {
321 Data::DateTime(DateTime::from_civil(2000, 1, 1, 0, minute, second, 0).unwrap())
322 }
323
324 fn test_page<'buf>(buf: &'buf mut [u8], rows: &[&[Data<'_>]]) -> Data<'buf> {
325 let mut writer = SliceWriter::new(buf);
326 writer.write_bytes(&[1, rows.len() as u8]).unwrap();
327 for row in rows {
328 writer.write_bytes(&[2, row.len() as u8]).unwrap();
329 for cell in *row {
330 cell.encode(&mut writer).unwrap();
331 }
332 }
333 Data::from_bytes_in(writer.finish()).unwrap()
334 }
335
336 #[test]
337 fn reordered_compressed_columns_preserve_both_clocks_and_raw_status() {
338 let source = Source {
339 measured_time: Some(MEASURED),
340 status: Some(STATUS),
341 ..source()
342 };
343 let layout = descriptors(
344 &source,
345 &[REGISTER, MEASURED, CaptureObject::clock(), STATUS],
346 )
347 .unwrap();
348 let mut profile =
349 taf15::Profile::<3>::new("history", source.channel, taf15::Period::QuarterHour, FIRST)
350 .unwrap();
351 let range = ClockRange::from_unix(FIRST, FIRST + 1800).unwrap();
352 let mut storage = [0; 256];
353 let rows = test_page(
354 &mut storage,
355 &[
356 &[
357 Data::Long(200),
358 sample(0, 1),
359 sample(0, 0),
360 Data::DoubleLongUnsigned(0x80ff),
361 ],
362 &[Data::DeltaLong(-3), sample(15, 1), sample(15, 0)],
364 &[Data::Null, sample(30, 1), sample(30, 0), Data::Null],
366 ],
367 );
368 let result = profile
369 .capture_batch(|batch| layout.capture(&source, batch, range, -3, &rows))
370 .unwrap();
371 assert_eq!((result.inserted, result.duplicates), (3, 0));
372 for (i, record) in profile.records().enumerate() {
373 let reference = FIRST + i as i64 * 900;
374 assert_eq!(
375 *record,
376 taf15::Record {
377 reference_utc: reference,
378 measured_utc: reference + 1,
379 coefficient: [200, 197, 197][i],
380 scale: -3,
381 meter_status: Some(0x80ff),
382 }
383 );
384 }
385 let repeat = profile
386 .capture_batch(|batch| layout.capture(&source, batch, range, -3, &rows))
387 .unwrap();
388 assert_eq!((repeat.inserted, repeat.duplicates), (0, 3));
389 }
390
391 #[test]
392 fn minimal_profile_preserves_unsigned_64_bit_energy_and_absent_status() {
393 let source = source();
394 let layout = descriptors(&source, &[CaptureObject::clock(), REGISTER]).unwrap();
395 let mut profile =
396 taf15::Profile::<1>::new("p", source.channel, taf15::Period::QuarterHour, FIRST)
397 .unwrap();
398 let range = ClockRange::from_unix(FIRST, FIRST).unwrap();
399 let mut storage = [0; 64];
400 let rows = test_page(
401 &mut storage,
402 &[&[sample(0, 0), Data::Long64Unsigned(u64::MAX)]],
403 );
404 profile
405 .capture_batch(|batch| layout.capture(&source, batch, range, 0, &rows))
406 .unwrap();
407 assert_eq!(
408 profile.records().next(),
409 Some(&taf15::Record {
410 reference_utc: FIRST,
411 measured_utc: FIRST,
412 coefficient: i128::from(u64::MAX),
413 scale: 0,
414 meter_status: None,
415 })
416 );
417 }
418
419 #[test]
420 fn numeric_columns_keep_full_integer_width_and_reject_other_wire_types() {
421 assert_eq!(
422 coefficient(&Data::Long64(i64::MIN)),
423 Ok(i128::from(i64::MIN))
424 );
425 assert_eq!(
426 coefficient(&Data::Long64Unsigned(u64::MAX)),
427 Ok(i128::from(u64::MAX))
428 );
429 for bad in [Data::Enum(42), Data::Float32(42.0), Data::Bcd(42)] {
430 assert_eq!(coefficient(&bad), Err(RowError::RegisterValue));
431 }
432 assert_eq!(
433 meter_status(&Data::DoubleLongUnsigned(u32::MAX)),
434 Ok(u32::MAX)
435 );
436 assert_eq!(
437 meter_status(&Data::Long64Unsigned(u64::MAX)),
438 Err(RowError::MeterStatus)
439 );
440 assert_eq!(meter_status(&Data::Integer(-1)), Err(RowError::MeterStatus));
441 }
442
443 #[test]
444 fn scaler_units_and_capture_definitions_require_the_commissioned_wire_types() {
445 let channel = source().channel;
446 let scaler = |bytes: &[u8]| scaler_unit(channel, &Data::from_bytes_in(bytes).unwrap());
447 assert_eq!(scaler(&[2, 2, 15, 0x80, 22, 30]), Ok(-128));
448 assert_eq!(scaler(&[2, 2, 15, 0, 17, 30]), Err(RowError::ScalerUnit));
449 assert_eq!(scaler(&[2, 2, 15, 0, 22, 27]), Err(RowError::ScalerUnit));
450 assert_eq!(scaler(&[2, 3, 15, 0, 22, 30, 0]), Err(RowError::ScalerUnit));
451 let gas = taf15::Channel {
452 unit: "m³",
453 ..channel
454 };
455 let corrected = Data::from_bytes_in(&[2, 2, 15, 0, 22, 14]).unwrap();
456 assert_eq!(scaler_unit(gas, &corrected), Err(RowError::ScalerUnit));
457 let ordinary = Data::from_bytes_in(&[2, 2, 15, 0, 22, 13]).unwrap();
458 assert_eq!(scaler_unit(gas, &ordinary), Ok(0));
459
460 let source = source();
461 assert_eq!(
462 descriptors(&source, &[CaptureObject::clock()]),
463 Err(RowError::ColumnMapping)
464 );
465 assert_eq!(
466 descriptors(&source, &[CaptureObject::clock(), REGISTER, REGISTER]),
467 Err(RowError::CaptureObjects)
468 );
469 assert_eq!(
470 descriptors(
471 &Source {
472 status: Some(REGISTER),
473 ..source
474 },
475 &[CaptureObject::clock(), REGISTER]
476 ),
477 Err(RowError::ColumnMapping)
478 );
479 let mut bytes = [0; 32];
480 let mut out = SliceWriter::new(&mut bytes);
481 REGISTER.encode(&mut out).unwrap();
482 let encoded = out.finish();
483 encoded[2] = 16;
485 assert_eq!(
486 capture_object(Data::from_bytes_in(encoded).unwrap()),
487 Err(RowError::CaptureObjects)
488 );
489 }
490
491 #[test]
492 fn invalid_page_shape_base_and_selected_range_leave_first_slot_empty() {
493 let source = source();
494 let layout = descriptors(&source, &[CaptureObject::clock(), REGISTER]).unwrap();
495 let range = ClockRange::from_unix(FIRST, FIRST).unwrap();
496 let mut profile =
497 taf15::Profile::<1>::new("p", source.channel, taf15::Period::QuarterHour, FIRST)
498 .unwrap();
499 let mut storage = [0; 128];
500 for (rows, expected) in [
501 (
502 &[&[sample(0, 0), Data::Unsigned(1), Data::Null][..]][..],
503 RowError::RowWidth,
504 ),
505 (
506 &[&[sample(15, 0), Data::Unsigned(1)][..]][..],
507 RowError::OutsideRange,
508 ),
509 (
510 &[&[sample(0, 0), Data::Unsigned(1)][..], &[][..]][..],
511 RowError::TooManyRows,
512 ),
513 ] {
514 let page = test_page(&mut storage, rows);
515 let outcome =
516 profile.capture_batch(|batch| layout.capture(&source, batch, range, 0, &page));
517 assert_eq!(outcome.unwrap_err(), expected);
518 }
519 let delta = test_page(&mut storage, &[&[sample(0, 0), Data::DeltaInteger(1)]]);
520 assert!(matches!(
521 profile.capture_batch(|batch| layout.capture(&source, batch, range, 0, &delta)),
522 Err(RowError::Codec(_))
523 ));
524 assert_eq!(profile.missing().next(), Some(FIRST));
525 }
526}