Skip to main content

mbus_kit/
json.rs

1//! Telegrams as JSON, without allocating: `Display` adapters that write one object.
2//!
3//! ```
4//! use mbus_kit::{json::Json, Application};
5//!
6//! let app = Application::parse(0x78, &[0x0C, 0x13, 0x27, 0x04, 0x85, 0x02])?;
7//! assert_eq!(
8//!     Json::new(&app).to_string(),
9//!     r#"{"meter":null,"ci":"78","authenticity":"none","body":"records","records":[{"name":"volume","function":"instantaneous","storage":0,"tariff":0,"subunit":0,"modifiers":[],"value":2850.427,"unit":"m3","text":"volume — 2850.427 m³"}]}"#
10//! );
11//! # Ok::<(), mbus_kit::Error>(())
12//! ```
13//!
14//! Schema (one object per telegram; fields in this order, absent ones left out):
15//!
16//! | Field | Type | Meaning |
17//! |---|---|---|
18//! | `meter` | object or `null` | `manufacturer` (3 letters), `id` (8 digits, or 8 hex digits when not BCD), `version`, `medium` (name), `medium_code` |
19//! | `ci` | string | the CI field, two hex digits |
20//! | `access`, `status` | number | from the transport header, if it has one |
21//! | `rssi_dbm` | number | when given with [`Json::rssi`] |
22//! | `authenticity` | string | `none`, `encrypted` (decrypted, not integrity-protected) or `authenticated` |
23//! | `counter` | number | the message counter the MAC or tag covers (`authenticated` only) |
24//! | `body` | string | `records`, `encrypted`, `compact`, `format`, `fragment`, `application_error`, `alarm`, `empty` |
25//! | `security` | string | for `encrypted`: `mode5`, `mode7`, `mode10`, `ell`, `mode<n>` |
26//! | `signature` | string | for `compact` and `format`: the format signature, four hex digits |
27//! | `bytes` | string | for `application_error` and `alarm`: the payload in hex |
28//! | `records` | array | for `records`: see below |
29//! | `manufacturer_data` | string | bytes after a `0F`/`1F` DIF, in hex |
30//!
31//! A record is `name`, `function`, `storage`, `tariff`, `subunit`, `modifiers` (strings),
32//! then `value` and `unit`: an exact decimal **number literal** with an ASCII unit code
33//! (`m3`, `Wh`, `degC`, `m3/h`, …) when the record is a quantity; otherwise a string (dates
34//! and times in ISO 8601, text, hex bytes) or `null` (no value, NaN, invalid BCD). Then
35//! `encrypted` (`true` when the record came out of decryption) and `text`, the record's
36//! one-line description. A compact profile has `"value":null` and a `profile` object:
37//! `direction` (`forward`, `backward`, `registers`), `elements_are` (`readings`,
38//! `increments`, `decrements`, `differences`), `spacing` (`{"every":15,"unit":"s"}`,
39//! months as `"mo"`, or `"columns"`) and `elements`, exact numbers in the record's unit
40//! (`null` for the "illegal" preset). A record that does not parse is
41//! `{"error": "…"}`, and the list ends there. Strings are escaped per RFC 8259.
42
43use core::fmt::{self, Write};
44
45use crate::app::{Address, Application, Authenticity, Body, Security};
46use crate::profile::{Increment, Profile, Spacing};
47use crate::record::Record;
48use crate::value::Value;
49use crate::vif::Direction;
50
51/// One telegram as a JSON object.
52#[derive(Clone, Copy, Debug)]
53pub struct Json<'x, 'a> {
54    app: &'x Application<'a>,
55    rssi_dbm: Option<i16>,
56}
57
58impl<'x, 'a> Json<'x, 'a> {
59    /// The JSON of `app`.
60    pub const fn new(app: &'x Application<'a>) -> Self {
61        Self { app, rssi_dbm: None }
62    }
63
64    /// Include the signal strength a receiver reported.
65    #[must_use]
66    pub const fn rssi(mut self, dbm: Option<i16>) -> Self {
67        self.rssi_dbm = dbm;
68        self
69    }
70}
71
72impl fmt::Display for Json<'_, '_> {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        let app = self.app;
75        f.write_str("{\"meter\":")?;
76        match app.meter() {
77            Some(a) => meter(f, a)?,
78            None => f.write_str("null")?,
79        }
80        write!(f, ",\"ci\":\"{:02X}\"", app.ci)?;
81        if let Some(s) = app.header.short() {
82            write!(f, ",\"access\":{},\"status\":{}", s.access_number, s.status)?;
83        }
84        if let Some(dbm) = self.rssi_dbm {
85            write!(f, ",\"rssi_dbm\":{dbm}")?;
86        }
87        match app.authenticity {
88            Authenticity::None => f.write_str(",\"authenticity\":\"none\"")?,
89            Authenticity::Encrypted => f.write_str(",\"authenticity\":\"encrypted\"")?,
90            Authenticity::Authenticated { counter } => {
91                write!(f, ",\"authenticity\":\"authenticated\",\"counter\":{counter}")?;
92            }
93        }
94        match &app.body {
95            Body::Records(records) => {
96                f.write_str(",\"body\":\"records\",\"records\":[")?;
97                let mut records = records.clone();
98                let mut first = true;
99                for r in records.by_ref() {
100                    if !first {
101                        f.write_char(',')?;
102                    }
103                    first = false;
104                    match r {
105                        Ok(r) => JsonRecord(&r).fmt(f)?,
106                        Err(e) => {
107                            f.write_str("{\"error\":")?;
108                            string(f, format_args!("{e}"))?;
109                            f.write_char('}')?;
110                        }
111                    }
112                }
113                f.write_char(']')?;
114                if let Some(m) = records.manufacturer_data().filter(|m| !m.is_empty()) {
115                    f.write_str(",\"manufacturer_data\":\"")?;
116                    hex(f, m)?;
117                    f.write_char('"')?;
118                }
119            }
120            Body::Encrypted(e) => {
121                let security = match e.security {
122                    Security::Mode5 => "mode5",
123                    Security::Mode7 => "mode7",
124                    Security::Mode10 => "mode10",
125                    Security::EllCtr => "ell",
126                    Security::Other(m) => {
127                        return write!(f, ",\"body\":\"encrypted\",\"security\":\"mode{m}\"}}");
128                    }
129                };
130                write!(f, ",\"body\":\"encrypted\",\"security\":\"{security}\"")?;
131            }
132            Body::Compact(c) => write!(f, ",\"body\":\"compact\",\"signature\":\"{:04X}\"", c.signature)?,
133            Body::Format(c) => write!(f, ",\"body\":\"format\",\"signature\":\"{:04X}\"", c.signature)?,
134            Body::Fragment(_) => f.write_str(",\"body\":\"fragment\"")?,
135            Body::Empty => f.write_str(",\"body\":\"empty\"")?,
136            Body::ApplicationError(b) | Body::Alarm(b) => {
137                let kind = if matches!(app.body, Body::Alarm(_)) { "alarm" } else { "application_error" };
138                write!(f, ",\"body\":\"{kind}\",\"bytes\":\"")?;
139                hex(f, b)?;
140                f.write_char('"')?;
141            }
142        }
143        f.write_char('}')
144    }
145}
146
147/// One record as a JSON object (the elements of `records` in [`Json`]).
148#[derive(Clone, Copy, Debug)]
149pub struct JsonRecord<'x, 'a>(pub &'x Record<'a>);
150
151impl fmt::Display for JsonRecord<'_, '_> {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        let r = self.0;
154        f.write_str("{\"name\":")?;
155        string(f, format_args!("{}", r.vib.description().kind))?;
156        f.write_str(",\"function\":")?;
157        string(f, format_args!("{}", r.dib.function))?;
158        write!(
159            f,
160            ",\"storage\":{},\"tariff\":{},\"subunit\":{}",
161            r.dib.storage, r.dib.tariff, r.dib.subunit
162        )?;
163        f.write_str(",\"modifiers\":[")?;
164        for (i, m) in r.vib.modifiers().enumerate() {
165            if i > 0 {
166                f.write_char(',')?;
167            }
168            string(f, format_args!("{m}"))?;
169        }
170        f.write_str("],\"value\":")?;
171        if let Some(p) = r.profile() {
172            return profile(f, r, &p);
173        }
174        match (r.quantity(), r.value) {
175            (Some(q), _) => {
176                // The exact decimal, without the unit (or its prefix).
177                write!(f, "{}", crate::Quantity { unit: None, ..q })?;
178                if let Some(unit) = q.unit {
179                    f.write_str(",\"unit\":\"")?;
180                    ascii_unit(f, unit.symbol())?;
181                    f.write_char('"')?;
182                } else if let Some(text) = r.vib.plain_text() {
183                    f.write_str(",\"unit\":")?;
184                    string(f, format_args!("{}", Reversed(text)))?;
185                }
186            }
187            (None, v) => value(f, &v)?,
188        }
189        if r.from_ciphertext {
190            f.write_str(",\"encrypted\":true")?;
191        }
192        f.write_str(",\"text\":")?;
193        string(f, format_args!("{r}"))?;
194        f.write_char('}')
195    }
196}
197
198/// A meter address as the JSON object used for `meter`.
199#[derive(Clone, Copy, Debug)]
200pub struct JsonAddress<'x>(pub &'x Address);
201
202impl fmt::Display for JsonAddress<'_> {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        meter(f, *self.0)
205    }
206}
207
208/// A compact profile: `"value":null`, the unit, and `profile` with the elements as exact
209/// numbers in the record's unit (`null` for the "illegal" preset).
210fn profile(f: &mut fmt::Formatter<'_>, r: &Record<'_>, p: &Profile<'_>) -> fmt::Result {
211    let d = r.vib.description();
212    f.write_str("null")?;
213    if let Some(unit) = d.unit {
214        f.write_str(",\"unit\":\"")?;
215        ascii_unit(f, unit.symbol())?;
216        f.write_char('"')?;
217    }
218    let direction = match p.direction {
219        Direction::Forward => "forward",
220        Direction::Inverse => "backward",
221        Direction::WithRegisters => "registers",
222    };
223    let increment = match p.increment {
224        Increment::Absolute => "readings",
225        Increment::Positive => "increments",
226        Increment::Negative => "decrements",
227        Increment::Difference => "differences",
228    };
229    write!(f, ",\"profile\":{{\"direction\":\"{direction}\",\"elements_are\":\"{increment}\",\"spacing\":")?;
230    match p.spacing {
231        Spacing::Every(n, unit) => {
232            write!(f, "{{\"every\":{n},\"unit\":\"")?;
233            ascii_unit(f, unit.symbol())?;
234            f.write_str("\"}")?;
235        }
236        Spacing::HalfMonth => f.write_str("{\"every\":0.5,\"unit\":\"mo\"}")?,
237        Spacing::Months(n) => write!(f, "{{\"every\":{n},\"unit\":\"mo\"}}")?,
238        Spacing::Columns => f.write_str("\"columns\"")?,
239        Spacing::Reserved(v) => write!(f, "{{\"reserved\":{v}}}")?,
240    }
241    f.write_str(",\"elements\":[")?;
242    for k in 0..p.len() {
243        if k > 0 {
244            f.write_char(',')?;
245        }
246        match p.element(k) {
247            Some(e) => write!(f, "{}", crate::Quantity { mantissa: e, exponent: d.exponent, unit: None })?,
248            None => f.write_str("null")?,
249        }
250    }
251    f.write_str("]}")?;
252    if r.from_ciphertext {
253        f.write_str(",\"encrypted\":true")?;
254    }
255    f.write_str(",\"text\":")?;
256    string(f, format_args!("{r}"))?;
257    f.write_char('}')
258}
259
260/// A string as a JSON string literal, quotes included.
261#[derive(Clone, Copy, Debug)]
262pub struct JsonString<'s>(pub &'s str);
263
264impl fmt::Display for JsonString<'_> {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        string(f, format_args!("{}", self.0))
267    }
268}
269
270fn meter(f: &mut fmt::Formatter<'_>, a: Address) -> fmt::Result {
271    // A crafted address decodes to any of `@`, `[`, `\`, … : escape it too.
272    f.write_str("{\"manufacturer\":")?;
273    string(f, format_args!("{}", a.manufacturer))?;
274    f.write_str(",\"id\":\"")?;
275    if let Some(n) = a.id_number() {
276        write!(f, "{n:08}")?;
277    } else {
278        let [x, y, z, w] = a.id;
279        write!(f, "{w:02X}{z:02X}{y:02X}{x:02X}")?;
280    }
281
282    write!(f, "\",\"version\":{},\"medium\":", a.version)?;
283    string(f, format_args!("{}", a.medium))?;
284    write!(f, ",\"medium_code\":{}}}", a.medium.0)
285}
286
287/// A value that is not a quantity: integers as numbers, everything else as a string.
288fn value(f: &mut fmt::Formatter<'_>, v: &Value<'_>) -> fmt::Result {
289    match *v {
290        Value::Int(n) | Value::Bcd(n) => write!(f, "{n}"),
291        Value::UInt(n) => write!(f, "{n}"),
292        Value::None | Value::InvalidBcd(_) | Value::Real32(_) => f.write_str("null"),
293        Value::Date(d) => write!(f, "\"{d}\""),
294        Value::Time(t) => write!(f, "\"{t}\""),
295        Value::DateTime(t) => {
296            let (d, tm) = (t.date, t.time);
297            write!(f, "\"{:04}-{:02}-{:02}T{:02}:{:02}", d.year, d.month, d.day, tm.hour, tm.minute)?;
298            if t.has_seconds {
299                write!(f, ":{:02}", tm.second)?;
300            }
301            f.write_char('"')
302        }
303        Value::Text(_) | Value::Bytes(_) | Value::Duration(_) => string(f, format_args!("{v}")),
304    }
305}
306
307/// A JSON string: quotes, backslashes and control characters escaped (RFC 8259 §7).
308fn string(f: &mut fmt::Formatter<'_>, args: fmt::Arguments<'_>) -> fmt::Result {
309    f.write_char('"')?;
310    Escape(f).write_fmt(args)?;
311    f.write_char('"')
312}
313
314struct Escape<'f, 'g>(&'f mut fmt::Formatter<'g>);
315
316impl Write for Escape<'_, '_> {
317    fn write_str(&mut self, s: &str) -> fmt::Result {
318        for c in s.chars() {
319            match c {
320                '"' => self.0.write_str("\\\"")?,
321                '\\' => self.0.write_str("\\\\")?,
322                c if (c as u32) < 0x20 => write!(self.0, "\\u{:04x}", c as u32)?,
323                c => self.0.write_char(c)?,
324            }
325        }
326        Ok(())
327    }
328}
329
330/// `m³` → `m3`, `°C` → `degC`, `µg/m³` → `ug/m3`: unit codes a program can match on.
331fn ascii_unit(f: &mut fmt::Formatter<'_>, symbol: &str) -> fmt::Result {
332    for c in symbol.chars() {
333        match c {
334            '³' => f.write_char('3')?,
335            '²' => f.write_char('2')?,
336            'µ' => f.write_char('u')?,
337            '°' => f.write_str("deg")?,
338            c if c.is_ascii() => f.write_char(c)?,
339            _ => f.write_char('?')?,
340        }
341    }
342    Ok(())
343}
344
345fn hex(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
346    bytes.iter().try_for_each(|b| write!(f, "{b:02X}"))
347}
348
349/// A plain-text unit, stored reversed on the wire, in reading order with `\xNN` escapes.
350struct Reversed<'a>(&'a [u8]);
351
352impl fmt::Display for Reversed<'_> {
353    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354        crate::value::escaped(f, self.0.iter().rev())
355    }
356}