sml_kit/file.rs
1//! A whole SML file: the unit a client sends and a meter answers with.
2
3use crate::message::{Body, Message};
4use crate::tl::Writer;
5use crate::{Error, Result};
6
7/// The most messages a file can hold: each gets a one-byte message number.
8const MAX_MESSAGES: usize = 256;
9
10/// The longest file-ID prefix of a transaction ID.
11const PREFIX: usize = 7;
12
13/// An SML file: an open, the requests (or responses) and a close, sharing one file ID.
14///
15/// [`write`](Self::write) gives every message a transaction ID unique in the file (the
16/// file ID's first seven bytes and the message number) and its own CRC. A meter repeats a
17/// request's transaction ID in its answer, which is how a client matches the two.
18///
19/// ```
20/// use sml_kit::{Body, CloseRequest, GetListRequest, OpenRequest, SmlFile, encode_frame};
21///
22/// let bodies = [
23/// Body::OpenRequest(OpenRequest {
24/// codepage: None,
25/// client_id: b"gw-1",
26/// req_file_id: b"F42",
27/// server_id: None,
28/// username: None,
29/// password: None,
30/// sml_version: None,
31/// }),
32/// Body::GetListRequest(GetListRequest {
33/// client_id: b"gw-1",
34/// server_id: None,
35/// username: None,
36/// password: None,
37/// list_name: None,
38/// }),
39/// Body::CloseRequest(CloseRequest { global_signature: None }),
40/// ];
41/// let mut payload = [0u8; 128];
42/// let n = SmlFile { file_id: b"F42", messages: &bodies }.write(&mut payload)?;
43///
44/// let mut wire = [0u8; 300];
45/// let len = encode_frame(&payload[..n], &mut wire)?; // send &wire[..len]
46/// # assert!(len > n);
47/// # Ok::<(), sml_kit::Error>(())
48/// ```
49///
50/// The shape is checked, not the direction: a file must start with an `OpenRequest` or
51/// `OpenResponse`, end with a `CloseRequest` or `CloseResponse`, and have at most 256
52/// messages; anything else is [`Error::InvalidFile`]. Every message is written with
53/// `group_no` 0 and `abort_on_error` 0; for other values write [`Message`]s one by one.
54///
55/// `Debug` shows each body through its own `Debug`, which prints passwords as
56/// `<redacted>`.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub struct SmlFile<'a> {
59 /// The file ID, also the prefix of every transaction ID.
60 pub file_id: &'a [u8],
61 /// The messages, in order.
62 pub messages: &'a [Body<'a>],
63}
64
65impl SmlFile<'_> {
66 /// Write every message with its CRC into `out`. Returns the number of bytes written:
67 /// the unframed payload for [`encode_frame`](crate::encode_frame).
68 pub fn write(&self, out: &mut [u8]) -> Result<usize> {
69 let opens = matches!(self.messages.first(), Some(Body::OpenRequest(_) | Body::OpenResponse(_)));
70 let closes = matches!(self.messages.last(), Some(Body::CloseRequest(_) | Body::CloseResponse(_)));
71 if !opens || !closes || self.messages.len() > MAX_MESSAGES {
72 return Err(Error::InvalidFile);
73 }
74 let prefix_len = self.file_id.len().min(PREFIX);
75 let mut tx = [0u8; PREFIX + 1];
76 if let (Some(dst), Some(src)) = (tx.get_mut(..prefix_len), self.file_id.get(..prefix_len)) {
77 dst.copy_from_slice(src);
78 }
79 let mut w = Writer::new(out);
80 for (number, &body) in (0..=u8::MAX).zip(self.messages) {
81 if let Some(last) = tx.get_mut(prefix_len) {
82 *last = number;
83 }
84 let transaction_id = tx.get(..=prefix_len).unwrap_or(&[]);
85 Message { transaction_id, group_no: 0, abort_on_error: 0, body }.write(&mut w)?;
86 }
87 Ok(w.position())
88 }
89}