use alloc::borrow::Cow;
use alloc::string::String;
use core::fmt;
use core::ops::Range;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Register {
ActiveEnergyImport,
ActiveEnergyExport,
TotalImportMains,
TotalImportDevice,
TransactionImportMains,
TransactionImportDevice,
TotalExportMains,
TotalExportDevice,
TransactionExportMains,
TransactionExportDevice,
Reserved,
Other,
}
impl Register {
#[must_use]
pub const fn is_import(self) -> Option<bool> {
Some(match self {
Self::ActiveEnergyImport
| Self::TotalImportMains
| Self::TotalImportDevice
| Self::TransactionImportMains
| Self::TransactionImportDevice => true,
Self::ActiveEnergyExport
| Self::TotalExportMains
| Self::TotalExportDevice
| Self::TransactionExportMains
| Self::TransactionExportDevice => false,
Self::Reserved | Self::Other => return None,
})
}
#[must_use]
pub const fn is_device_side(self) -> Option<bool> {
Some(match self {
Self::TotalImportDevice
| Self::TransactionImportDevice
| Self::TotalExportDevice
| Self::TransactionExportDevice => true,
Self::TotalImportMains
| Self::TransactionImportMains
| Self::TotalExportMains
| Self::TransactionExportMains => false,
Self::ActiveEnergyImport | Self::ActiveEnergyExport | Self::Reserved | Self::Other => {
return None;
}
})
}
#[must_use]
pub const fn is_transaction_scoped(self) -> Option<bool> {
Some(match self {
Self::TransactionImportMains
| Self::TransactionImportDevice
| Self::TransactionExportMains
| Self::TransactionExportDevice => true,
Self::TotalImportMains
| Self::TotalImportDevice
| Self::TotalExportMains
| Self::TotalExportDevice => false,
Self::ActiveEnergyImport | Self::ActiveEnergyExport | Self::Reserved | Self::Other => {
return None;
}
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObisCode<'a> {
raw: Cow<'a, str>,
groups: [Range<usize>; 5],
period: Option<Range<usize>>,
}
impl<'a> ObisCode<'a> {
#[must_use]
pub fn as_str(&self) -> &str {
&self.raw
}
#[must_use]
pub fn medium(&self) -> &str {
&self.raw[self.groups[0].clone()]
}
#[must_use]
pub fn channel(&self) -> &str {
&self.raw[self.groups[1].clone()]
}
#[must_use]
pub fn quantity(&self) -> &str {
&self.raw[self.groups[2].clone()]
}
#[must_use]
pub fn processing(&self) -> &str {
&self.raw[self.groups[3].clone()]
}
#[must_use]
pub fn tariff(&self) -> &str {
&self.raw[self.groups[4].clone()]
}
#[must_use]
pub fn billing_period(&self) -> Option<&str> {
self.period.clone().map(|r| &self.raw[r])
}
#[must_use]
pub fn register(&self) -> Register {
let c = trimmed_upper(self.quantity());
match &*c {
"1" => Register::ActiveEnergyImport,
"2" => Register::ActiveEnergyExport,
"B0" => Register::TotalImportMains,
"B1" => Register::TotalImportDevice,
"B2" => Register::TransactionImportMains,
"B3" => Register::TransactionImportDevice,
"C0" => Register::TotalExportMains,
"C1" => Register::TotalExportDevice,
"C2" => Register::TransactionExportMains,
"C3" => Register::TransactionExportDevice,
"B4" | "B5" | "B6" | "B7" | "B8" | "B9" | "BA" | "BB" | "BC" | "BD" | "BE" | "BF"
| "C4" | "C5" | "C6" | "C7" => Register::Reserved,
_ => Register::Other,
}
}
#[must_use]
pub fn is_register(&self) -> bool {
trimmed_upper(self.processing()) == "8"
}
#[must_use]
pub fn canonical(&self) -> String {
let mut s = String::with_capacity(20);
push_group(&mut s, self.medium());
s.push('-');
push_group(&mut s, self.channel());
s.push(':');
push_group(&mut s, self.quantity());
s.push('.');
push_group(&mut s, self.processing());
s.push('.');
push_group(&mut s, self.tariff());
if let Some(period) = self.billing_period() {
s.push('*');
push_group(&mut s, period);
}
s
}
#[must_use]
pub fn is_canonical(&self) -> bool {
fn group(g: &str) -> bool {
g.len() == 2
&& g.bytes()
.all(|c| c.is_ascii_digit() || c.is_ascii_uppercase())
}
[
self.medium(),
self.channel(),
self.quantity(),
self.processing(),
self.tariff(),
]
.iter()
.all(|g| group(g))
&& match self.billing_period() {
None => true,
Some(period) => group(period) && self.raw.contains('*'),
}
}
#[must_use]
pub fn parse(raw: &'a str) -> Option<Self> {
Self::parse_cow(Cow::Borrowed(raw))
}
#[must_use]
pub fn parse_cow(raw: Cow<'a, str>) -> Option<Self> {
let (groups, period) = locate(&raw)?;
Some(Self {
raw,
groups,
period,
})
}
}
type Groups = ([Range<usize>; 5], Option<Range<usize>>);
fn locate(s: &str) -> Option<Groups> {
let dash = s.find('-')?;
let colon = s[dash + 1..].find(':')? + dash + 1;
let rest_at = colon + 1;
let rest = &s[rest_at..];
let (body_end, period) = if let Some(star) = rest.find('*') {
(rest_at + star, Some(rest_at + star + 1..s.len()))
} else if rest.match_indices('.').count() == 3 {
let dot = rest.rfind('.')?;
(rest_at + dot, Some(rest_at + dot + 1..s.len()))
} else {
(s.len(), None)
};
let body = &s[rest_at..body_end];
let first = body.find('.')?;
let second = body[first + 1..].find('.')? + first + 1;
if body[second + 1..].contains('.') {
return None;
}
let groups = [
0..dash,
dash + 1..colon,
rest_at..rest_at + first,
rest_at + first + 1..rest_at + second,
rest_at + second + 1..body_end,
];
if groups.iter().any(|g| !is_group(&s[g.clone()])) {
return None;
}
if period.clone().is_some_and(|p| !is_group(&s[p])) {
return None;
}
Some((groups, period))
}
impl fmt::Display for ObisCode<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.raw)
}
}
fn is_group(g: &str) -> bool {
!g.is_empty() && g.len() <= 4 && g.bytes().all(|c| c.is_ascii_alphanumeric())
}
fn trimmed_upper(g: &str) -> alloc::borrow::Cow<'_, str> {
let t = g.trim_start_matches('0');
let t = if t.is_empty() { "0" } else { t };
if t.bytes().any(|c| c.is_ascii_lowercase()) {
alloc::borrow::Cow::Owned(t.to_ascii_uppercase())
} else {
alloc::borrow::Cow::Borrowed(t)
}
}
fn push_group(s: &mut String, g: &str) {
let t = g.trim_start_matches('0');
let t = if t.is_empty() { "0" } else { t };
if t.len() == 1 {
s.push('0');
}
for c in t.bytes() {
s.push(c.to_ascii_uppercase() as char);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn code(s: &str) -> ObisCode<'_> {
ObisCode::parse(s).expect("parses")
}
#[test]
fn the_form_every_real_record_uses() {
let c = code("1-b:1.8.0");
assert_eq!(c.medium(), "1");
assert_eq!(c.channel(), "b");
assert_eq!(c.register(), Register::ActiveEnergyImport);
assert!(c.is_register());
assert_eq!(c.canonical(), "01-0B:01.08.00");
assert!(
!c.is_canonical(),
"no real record is written the table's way"
);
}
#[test]
fn the_form_the_table_specifies() {
let c = code("01-00:B1.08.00*FF");
assert_eq!(c.register(), Register::TotalImportDevice);
assert_eq!(c.register().is_device_side(), Some(true));
assert_eq!(c.register().is_import(), Some(true));
assert_eq!(c.register().is_transaction_scoped(), Some(false));
assert_eq!(c.canonical(), "01-00:B1.08.00*FF");
assert!(c.is_canonical());
}
#[test]
fn all_three_billing_period_spellings() {
assert_eq!(code("1-0:2.8.0*198").billing_period(), Some("198"));
assert_eq!(code("1-0:2.8.0.FF").billing_period(), Some("FF"));
assert_eq!(code("1-0:2.8.0").billing_period(), None);
}
#[test]
fn codes_that_differ_only_in_spelling_share_a_canonical_form() {
assert_eq!(
code("1-0:1.8.0").canonical(),
code("01-00:01.08.00").canonical()
);
assert_eq!(
code("1-b:1.8.E").canonical(),
code("01-0B:01.08.0e").canonical()
);
}
#[test]
fn transaction_and_total_are_distinguished() {
assert_eq!(
code("01-00:B3.08.00*FF").register(),
Register::TransactionImportDevice
);
assert_eq!(
code("01-00:C2.08.00*FF").register(),
Register::TransactionExportMains
);
assert_eq!(code("01-00:B7.08.00*FF").register(), Register::Reserved);
}
#[test]
fn an_escaped_obis_code_is_read_rather_than_refused() {
let c = ObisCode::parse_cow(Cow::Owned(alloc::string::String::from("1-b:1.8.0")))
.expect("parses");
assert_eq!(c.as_str(), "1-b:1.8.0");
assert_eq!(c.tariff(), "0");
assert_eq!(c.canonical(), "01-0B:01.08.00");
assert_eq!(c.register(), Register::ActiveEnergyImport);
assert_eq!(c, code("1-b:1.8.0"), "the same register, either spelling");
}
#[test]
fn nonsense_is_refused() {
for s in ["", "1.8.0", "1-b:1.8", "1-b:1.8.0.0.0", "1-b:1.8.z z"] {
assert!(ObisCode::parse(s).is_none(), "{s} should not parse");
}
}
}