1use 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#[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 pub const fn new(app: &'x Application<'a>) -> Self {
61 Self { app, rssi_dbm: None }
62 }
63
64 #[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#[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 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#[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
208fn 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#[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 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
287fn 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
307fn 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
330fn 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
349struct 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}