sml_kit/sim.rs
1//! Write meter telegrams: for tests, simulators and fixtures.
2//!
3//! [`Telegram`] writes what a basic meter pushes on its optical interface: an
4//! `OpenResponse`, one `GetListResponse` with the entries, and a `CloseResponse`, each
5//! with a correct message CRC, through the same [`SmlFile`] a client uses. Frame the result with [`encode_frame`](crate::encode_frame).
6//!
7//! ```
8//! use sml_kit::{ListEntry, Obis, Unit, encode_frame, readout, sim::Telegram};
9//!
10//! let entries = [
11//! ListEntry::bytes(Obis::MANUFACTURER, b"SIM"),
12//! ListEntry::number(Obis::ENERGY_IMPORT, Unit::WH, -1, 123_456_789),
13//! ];
14//! let telegram = Telegram { server_id: b"\x0a\x01SIM\x00\x00\x00\x00\x01", file_id: b"F1", entries: &entries };
15//! let mut payload = [0u8; 256];
16//! let n = telegram.write(&mut payload)?;
17//! assert_eq!(readout(&payload[..n])?.quantity(Obis::ENERGY_IMPORT).unwrap().to_string(), "12345678.9 Wh");
18//! # Ok::<(), sml_kit::Error>(())
19//! ```
20//!
21//! This is a simulator, not a model of any particular meter. Agreement between it and
22//! the decoder proves consistency only; the real-meter corpus (`tests/corpus/`) is the
23//! evidence that real meters decode.
24
25use crate::message::{Body, CloseResponse, GetListResponse, OpenResponse};
26use crate::value::Time;
27use crate::{ListEntries, ListEntry, Result, ServerId, SmlFile};
28
29/// The list name basic meters use: `1-0:98.10.255*255`.
30const LIST_NAME: [u8; 6] = [1, 0, 98, 10, 255, 255];
31
32/// A simulated meter telegram.
33#[derive(Clone, Copy, Debug)]
34pub struct Telegram<'a> {
35 /// The meter's server ID (10 bytes on German meters).
36 pub server_id: &'a [u8],
37 /// The file ID shared by the three messages.
38 pub file_id: &'a [u8],
39 /// The entries of the `GetListResponse`.
40 pub entries: &'a [ListEntry<'a>],
41}
42
43impl Telegram<'_> {
44 /// Write the three messages into `out`. Returns the number of bytes written: the
45 /// unframed payload.
46 pub fn write(&self, out: &mut [u8]) -> Result<usize> {
47 let server_id = ServerId::new(self.server_id);
48 let bodies = [
49 Body::OpenResponse(OpenResponse {
50 codepage: None,
51 client_id: None,
52 req_file_id: self.file_id,
53 server_id,
54 ref_time: None,
55 sml_version: None,
56 }),
57 Body::GetListResponse(GetListResponse {
58 client_id: None,
59 server_id,
60 list_name: Some(&LIST_NAME),
61 act_sensor_time: Some(Time::SecIndex(0x0001_0203)),
62 entries: ListEntries::from_slice(self.entries),
63 list_signature: None,
64 act_gateway_time: None,
65 }),
66 Body::CloseResponse(CloseResponse { global_signature: None }),
67 ];
68 SmlFile { file_id: self.file_id, messages: &bodies }.write(out)
69 }
70}