1use 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#[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 pub const fn new(app: &'x Application<'a>) -> Self {
62 Self { app, rssi_dbm: None }
63 }
64
65 #[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
146fn 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#[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 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#[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
220fn 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#[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 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
297fn 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
317fn 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
340fn 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
359struct 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}