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