1use core::fmt;
18
19use crate::codec::{Decode, Encode, Error, ErrorKind, Reader, Result, Writer};
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
23#[non_exhaustive]
24pub enum Medium {
25 Abstract,
27 Electricity,
29 ElectricityDc,
31 HeatCostAllocator,
33 Cooling,
35 Heat,
37 Gas,
39 ColdWater,
41 HotWater,
43 Other,
45 Reserved(u8),
47}
48
49impl Medium {
50 #[must_use]
52 pub const fn as_u8(self) -> u8 {
53 match self {
54 Self::Abstract => 0,
55 Self::Electricity => 1,
56 Self::ElectricityDc => 2,
57 Self::HeatCostAllocator => 4,
58 Self::Cooling => 5,
59 Self::Heat => 6,
60 Self::Gas => 7,
61 Self::ColdWater => 8,
62 Self::HotWater => 9,
63 Self::Other => 15,
64 Self::Reserved(v) => v,
65 }
66 }
67
68 #[must_use]
70 pub const fn from_u8(v: u8) -> Self {
71 match v {
72 0 => Self::Abstract,
73 1 => Self::Electricity,
74 2 => Self::ElectricityDc,
75 4 => Self::HeatCostAllocator,
76 5 => Self::Cooling,
77 6 => Self::Heat,
78 7 => Self::Gas,
79 8 => Self::ColdWater,
80 9 => Self::HotWater,
81 15 => Self::Other,
82 other => Self::Reserved(other),
83 }
84 }
85}
86
87#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
92pub struct Obis(pub [u8; 6]);
93
94impl Obis {
95 #[must_use]
97 pub const fn new(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> Self {
98 Self([a, b, c, d, e, f])
99 }
100
101 #[must_use]
103 pub const fn from_bytes(b: [u8; 6]) -> Self {
104 Self(b)
105 }
106
107 #[must_use]
109 pub const fn as_bytes(&self) -> &[u8; 6] {
110 &self.0
111 }
112
113 #[must_use]
115 pub const fn a(&self) -> u8 {
116 self.0[0]
117 }
118
119 #[must_use]
121 pub const fn b(&self) -> u8 {
122 self.0[1]
123 }
124
125 #[must_use]
127 pub const fn c(&self) -> u8 {
128 self.0[2]
129 }
130
131 #[must_use]
133 pub const fn d(&self) -> u8 {
134 self.0[3]
135 }
136
137 #[must_use]
139 pub const fn e(&self) -> u8 {
140 self.0[4]
141 }
142
143 #[must_use]
145 pub const fn f(&self) -> u8 {
146 self.0[5]
147 }
148
149 #[must_use]
151 pub const fn medium(&self) -> Medium {
152 Medium::from_u8(self.0[0])
153 }
154
155 #[must_use]
160 pub const fn is_manufacturer_specific(&self) -> bool {
161 (self.0[2] >= 128 && self.0[2] <= 199)
162 || (self.0[3] >= 128 && self.0[3] <= 254)
163 || (self.0[4] >= 128 && self.0[4] <= 254)
164 }
165
166 pub fn parse(s: &str) -> core::result::Result<Self, ObisParseError> {
174 let mut groups = [0u16; 6];
175 let mut n = 0usize;
176 let mut have_digit = false;
177 let mut cur: u16 = 0;
178 for ch in s.bytes() {
179 match ch {
180 b'0'..=b'9' => {
181 if !have_digit {
182 cur = 0;
183 }
184 have_digit = true;
185 cur = cur
186 .checked_mul(10)
187 .and_then(|v| v.checked_add(u16::from(ch - b'0')))
188 .ok_or(ObisParseError)?;
189 if cur > 255 {
190 return Err(ObisParseError);
191 }
192 }
193 b'-' | b':' | b'.' | b'*' | b'&' => {
194 if !have_digit || n >= 6 {
195 return Err(ObisParseError);
196 }
197 groups[n] = cur;
198 n += 1;
199 have_digit = false;
200 }
201 _ => return Err(ObisParseError),
202 }
203 }
204 if !have_digit || n >= 6 {
205 return Err(ObisParseError);
206 }
207 groups[n] = cur;
208 n += 1;
209
210 let g = |i: usize| groups.get(i).copied().unwrap_or(0) as u8;
213 match n {
214 3 => Ok(Self::new(1, 0, g(0), g(1), g(2), 255)),
215 5 => Ok(Self::new(g(0), g(1), g(2), g(3), g(4), 255)),
216 6 => Ok(Self::new(g(0), g(1), g(2), g(3), g(4), g(5))),
217 _ => Err(ObisParseError),
218 }
219 }
220}
221
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
224pub struct ObisParseError;
225
226impl fmt::Display for ObisParseError {
227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228 f.write_str("not an OBIS code")
229 }
230}
231
232#[cfg(feature = "std")]
233impl std::error::Error for ObisParseError {}
234
235impl core::str::FromStr for Obis {
236 type Err = ObisParseError;
237
238 fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
239 Self::parse(s)
240 }
241}
242
243impl fmt::Display for Obis {
244 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245 let [a, b, c, d, e, g] = self.0;
246 write!(f, "{a}-{b}:{c}.{d}.{e}*{g}")
247 }
248}
249
250impl fmt::Debug for Obis {
251 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252 write!(f, "Obis({self})")
253 }
254}
255
256impl From<[u8; 6]> for Obis {
257 fn from(v: [u8; 6]) -> Self {
258 Self(v)
259 }
260}
261
262impl From<Obis> for [u8; 6] {
263 fn from(v: Obis) -> Self {
264 v.0
265 }
266}
267
268impl Encode for Obis {
269 fn encode(&self, w: &mut dyn Writer) -> Result<()> {
270 w.write_bytes(&self.0)
271 }
272
273 fn encoded_len(&self) -> usize {
274 6
275 }
276}
277
278impl<'a> Decode<'a> for Obis {
279 fn decode(r: &mut Reader<'a>) -> Result<Self> {
280 Ok(Self(r.array::<6>()?))
281 }
282}
283
284impl Obis {
285 pub fn from_octet_string(bytes: &[u8], offset: usize) -> Result<Self> {
287 let arr: [u8; 6] = bytes.try_into().map_err(|_| Error::new(ErrorKind::InvalidLength, offset))?;
288 Ok(Self(arr))
289 }
290}
291
292#[cfg(feature = "obis-names")]
297pub mod names {
298 use super::Obis;
299
300 pub const CLOCK: Obis = Obis::new(0, 0, 1, 0, 0, 255);
302 pub const LOGICAL_DEVICE_NAME: Obis = Obis::new(0, 0, 42, 0, 0, 255);
304 pub const CURRENT_ASSOCIATION: Obis = Obis::new(0, 0, 40, 0, 0, 255);
306 pub const SECURITY_SETUP: Obis = Obis::new(0, 0, 43, 0, 0, 255);
308 pub const SAP_ASSIGNMENT: Obis = Obis::new(0, 0, 41, 0, 0, 255);
310 pub const DEVICE_ID_1: Obis = Obis::new(0, 0, 96, 1, 0, 255);
312 pub const ERROR_REGISTER: Obis = Obis::new(0, 0, 97, 97, 0, 255);
314 pub const EVENT_LOG: Obis = Obis::new(0, 0, 99, 98, 0, 255);
316 pub const HDLC_SETUP: Obis = Obis::new(0, 0, 22, 0, 0, 255);
318 pub const DISCONNECT_CONTROL: Obis = Obis::new(0, 0, 96, 3, 10, 255);
320 pub const PUSH_SETUP: Obis = Obis::new(0, 0, 25, 9, 0, 255);
322 pub const IMAGE_TRANSFER: Obis = Obis::new(0, 0, 44, 0, 0, 255);
324
325 pub const ACTIVE_ENERGY_IMPORT_TOTAL: Obis = Obis::new(1, 0, 1, 8, 0, 255);
327 pub const ACTIVE_ENERGY_IMPORT_T1: Obis = Obis::new(1, 0, 1, 8, 1, 255);
329 pub const ACTIVE_ENERGY_IMPORT_T2: Obis = Obis::new(1, 0, 1, 8, 2, 255);
331 pub const ACTIVE_ENERGY_EXPORT_TOTAL: Obis = Obis::new(1, 0, 2, 8, 0, 255);
333 pub const REACTIVE_ENERGY_IMPORT_TOTAL: Obis = Obis::new(1, 0, 3, 8, 0, 255);
335 pub const REACTIVE_ENERGY_EXPORT_TOTAL: Obis = Obis::new(1, 0, 4, 8, 0, 255);
337 pub const ACTIVE_POWER_IMPORT: Obis = Obis::new(1, 0, 1, 7, 0, 255);
339 pub const ACTIVE_POWER_EXPORT: Obis = Obis::new(1, 0, 2, 7, 0, 255);
341 pub const VOLTAGE_L1: Obis = Obis::new(1, 0, 32, 7, 0, 255);
343 pub const VOLTAGE_L2: Obis = Obis::new(1, 0, 52, 7, 0, 255);
345 pub const VOLTAGE_L3: Obis = Obis::new(1, 0, 72, 7, 0, 255);
347 pub const CURRENT_L1: Obis = Obis::new(1, 0, 31, 7, 0, 255);
349 pub const CURRENT_L2: Obis = Obis::new(1, 0, 51, 7, 0, 255);
351 pub const CURRENT_L3: Obis = Obis::new(1, 0, 71, 7, 0, 255);
353 pub const LOAD_PROFILE_1: Obis = Obis::new(1, 0, 99, 1, 0, 255);
355 pub const LOAD_PROFILE_2: Obis = Obis::new(1, 0, 99, 2, 0, 255);
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362 use crate::codec::SliceWriter;
363
364 #[test]
365 fn textual_notation_round_trips() {
366 #[cfg(feature = "std")]
367 {
368 use std::string::ToString;
369 let o = Obis::new(1, 0, 1, 8, 0, 255);
370 assert_eq!(o.to_string(), "1-0:1.8.0*255");
371 assert_eq!(Obis::parse(&o.to_string()).unwrap(), o);
372 }
373 }
374
375 #[test]
376 fn the_three_accepted_shapes() {
377 assert_eq!(Obis::parse("1-0:1.8.0*255").unwrap(), Obis::new(1, 0, 1, 8, 0, 255));
378 assert_eq!(Obis::parse("1-0:1.8.0").unwrap(), Obis::new(1, 0, 1, 8, 0, 255));
379 assert_eq!(Obis::parse("1.8.0").unwrap(), Obis::new(1, 0, 1, 8, 0, 255));
380 }
381
382 #[test]
383 fn a_group_count_that_is_not_three_five_or_six_is_refused() {
384 assert!(Obis::parse("1.8").is_err());
385 assert!(Obis::parse("1-0:1.8").is_err());
386 assert!(Obis::parse("1-0:1.8.0*255*1").is_err());
387 }
388
389 #[test]
390 fn a_group_above_255_is_refused_rather_than_truncated() {
391 assert!(Obis::parse("1-0:1.8.256").is_err());
392 assert!(Obis::parse("1-0:1.8.99999").is_err());
393 }
394
395 #[test]
396 fn junk_is_refused() {
397 for s in ["", "-", "1-0:1.8.x", "1--0:1.8.0", "1-0:1.8.", "abc"] {
398 assert!(Obis::parse(s).is_err(), "{s:?} should not parse");
399 }
400 }
401
402 #[test]
403 fn wire_form_is_six_bytes_in_order() {
404 let o = Obis::new(1, 0, 1, 8, 0, 255);
405 let mut buf = [0u8; 6];
406 let mut w = SliceWriter::new(&mut buf);
407 o.encode(&mut w).unwrap();
408 assert_eq!(buf, [1, 0, 1, 8, 0, 255]);
409 assert_eq!(Obis::from_bytes(buf), o);
410 }
411
412 #[test]
413 fn manufacturer_ranges_are_recognised() {
414 assert!(Obis::new(1, 0, 128, 8, 0, 255).is_manufacturer_specific());
415 assert!(!Obis::new(1, 0, 1, 8, 0, 255).is_manufacturer_specific());
416 }
417
418 #[test]
419 fn media_classify() {
420 assert_eq!(Obis::new(0, 0, 1, 0, 0, 255).medium(), Medium::Abstract);
421 assert_eq!(Obis::new(7, 0, 3, 0, 0, 255).medium(), Medium::Gas);
422 assert_eq!(Obis::new(3, 0, 3, 0, 0, 255).medium(), Medium::Reserved(3));
423 }
424}