use alloc::borrow::ToOwned;
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::string::String;
use alloc::vec::Vec;
use crate::types::Decimal;
use core::fmt;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Attribute {
#[default]
Actual,
Target,
MinSet,
MaxSet,
}
impl Attribute {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Attribute::Actual => "Actual",
Attribute::Target => "Target",
Attribute::MinSet => "MinSet",
Attribute::MaxSet => "MaxSet",
}
}
#[must_use]
pub fn from_wire(value: &str) -> Option<Self> {
Some(match value {
"Actual" => Attribute::Actual,
"Target" => Attribute::Target,
"MinSet" => Attribute::MinSet,
"MaxSet" => Attribute::MaxSet,
_ => return None,
})
}
}
impl fmt::Display for Attribute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Mutability {
#[default]
ReadOnly,
WriteOnly,
ReadWrite,
}
impl Mutability {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Mutability::ReadOnly => "ReadOnly",
Mutability::WriteOnly => "WriteOnly",
Mutability::ReadWrite => "ReadWrite",
}
}
#[must_use]
pub const fn readable(self) -> bool {
!matches!(self, Mutability::WriteOnly)
}
#[must_use]
pub const fn writable(self) -> bool {
!matches!(self, Mutability::ReadOnly)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DataType {
#[default]
String,
Decimal,
Integer,
DateTime,
Boolean,
OptionList,
SequenceList,
MemberList,
}
impl DataType {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
DataType::String => "string",
DataType::Decimal => "decimal",
DataType::Integer => "integer",
DataType::DateTime => "dateTime",
DataType::Boolean => "boolean",
DataType::OptionList => "OptionList",
DataType::SequenceList => "SequenceList",
DataType::MemberList => "MemberList",
}
}
#[must_use]
pub fn from_wire(value: &str) -> Option<Self> {
Some(match value {
"string" => DataType::String,
"decimal" => DataType::Decimal,
"integer" => DataType::Integer,
"dateTime" => DataType::DateTime,
"boolean" => DataType::Boolean,
"OptionList" => DataType::OptionList,
"SequenceList" => DataType::SequenceList,
"MemberList" => DataType::MemberList,
_ => return None,
})
}
#[must_use]
pub fn accepts(self, value: &str, values_list: &[String]) -> bool {
match self {
DataType::String => true,
DataType::Boolean => matches!(value, "true" | "false"),
DataType::Integer => value.parse::<i64>().is_ok(),
DataType::Decimal => value.parse::<Decimal>().is_ok(),
DataType::DateTime => crate::types::DateTime::parse(value).is_ok(),
DataType::OptionList => {
values_list.is_empty() || values_list.iter().any(|v| v == value)
}
DataType::SequenceList | DataType::MemberList => {
values_list.is_empty()
|| value
.split(',')
.map(str::trim)
.all(|item| values_list.iter().any(|v| v == item))
}
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ComponentKey {
pub name: String,
pub instance: Option<String>,
pub evse: Option<u32>,
pub connector: Option<u32>,
}
impl ComponentKey {
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
instance: None,
evse: None,
connector: None,
}
}
#[must_use]
pub fn instance(mut self, instance: impl Into<String>) -> Self {
self.instance = Some(instance.into());
self
}
#[must_use]
pub fn evse(mut self, evse: u32, connector: Option<u32>) -> Self {
self.evse = Some(evse);
self.connector = connector;
self
}
}
impl ComponentKey {
#[must_use]
pub fn matches(&self, criterion: &ComponentKey) -> bool {
self.name == criterion.name
&& criterion
.instance
.as_ref()
.is_none_or(|instance| self.instance.as_ref() == Some(instance))
&& criterion.evse.is_none_or(|evse| self.evse == Some(evse))
&& criterion
.connector
.is_none_or(|connector| self.connector == Some(connector))
}
}
impl From<&str> for ComponentKey {
fn from(name: &str) -> Self {
ComponentKey::new(name)
}
}
impl fmt::Display for ComponentKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.name)?;
if let Some(instance) = &self.instance {
write!(f, "({instance})")?;
}
if let Some(evse) = self.evse {
write!(f, "@evse{evse}")?;
if let Some(connector) = self.connector {
write!(f, ".{connector}")?;
}
}
Ok(())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VariableKey {
pub name: String,
pub instance: Option<String>,
}
impl VariableKey {
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
instance: None,
}
}
#[must_use]
pub fn instance(mut self, instance: impl Into<String>) -> Self {
self.instance = Some(instance.into());
self
}
}
impl From<&str> for VariableKey {
fn from(name: &str) -> Self {
VariableKey::new(name)
}
}
impl fmt::Display for VariableKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.name)?;
if let Some(instance) = &self.instance {
write!(f, "[{instance}]")?;
}
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct VariableSpec {
key: VariableKey,
data_type: DataType,
mutability: Mutability,
unit: Option<String>,
values_list: Vec<String>,
min_limit: Option<Decimal>,
max_limit: Option<Decimal>,
persistent: bool,
constant: bool,
reboot_required: bool,
supported: BTreeSet<Attribute>,
values: BTreeMap<Attribute, String>,
}
impl VariableSpec {
#[must_use]
pub fn new(name: impl Into<String>, data_type: DataType) -> Self {
Self {
key: VariableKey::new(name),
data_type,
mutability: Mutability::ReadOnly,
unit: None,
values_list: Vec::new(),
min_limit: None,
max_limit: None,
persistent: true,
constant: false,
reboot_required: false,
supported: BTreeSet::from([Attribute::Actual]),
values: BTreeMap::new(),
}
}
#[must_use]
pub fn instance(mut self, instance: impl Into<String>) -> Self {
self.key.instance = Some(instance.into());
self
}
#[must_use]
pub fn mutability(mut self, mutability: Mutability) -> Self {
self.mutability = mutability;
self
}
#[must_use]
pub fn unit(mut self, unit: impl Into<String>) -> Self {
self.unit = Some(unit.into());
self
}
#[must_use]
pub fn values(mut self, values: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.values_list = values.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn limits(mut self, min: Option<Decimal>, max: Option<Decimal>) -> Self {
self.min_limit = min;
self.max_limit = max;
self
}
#[must_use]
pub fn reboot_required(mut self) -> Self {
self.reboot_required = true;
self
}
#[must_use]
pub fn constant(mut self) -> Self {
self.constant = true;
self.mutability = Mutability::ReadOnly;
self
}
#[must_use]
pub fn value(mut self, value: impl Into<String>) -> Self {
self.values.insert(Attribute::Actual, value.into());
self
}
#[must_use]
pub fn attribute(mut self, attribute: Attribute, value: impl Into<String>) -> Self {
self.supported.insert(attribute);
self.values.insert(attribute, value.into());
self
}
#[must_use]
pub fn supports(mut self, attribute: Attribute) -> Self {
self.supported.insert(attribute);
self
}
pub fn supported(&self) -> impl Iterator<Item = Attribute> + '_ {
self.supported.iter().copied()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum GetStatus {
Accepted,
UnknownComponent,
UnknownVariable,
NotSupportedAttributeType,
Rejected,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
#[must_use = "a rejected write left the variable unchanged; the CSMS has to be told which \
status it got, not `Accepted`"]
pub enum SetStatus {
Accepted,
RebootRequired,
UnknownComponent,
UnknownVariable,
NotSupportedAttributeType,
Rejected,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ReportDatum {
pub component: ComponentKey,
pub variable: VariableKey,
pub attributes: Vec<(Attribute, Mutability, Option<String>)>,
pub mutability: Mutability,
pub data_type: DataType,
pub unit: Option<String>,
pub values_list: Vec<String>,
pub min_limit: Option<Decimal>,
pub max_limit: Option<Decimal>,
pub persistent: bool,
pub constant: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReportBase {
FullInventory,
ConfigurationInventory,
SummaryInventory,
}
#[derive(Clone, Debug, Default)]
pub struct DeviceModel {
components: BTreeMap<ComponentKey, BTreeMap<VariableKey, VariableSpec>>,
}
impl DeviceModel {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_defaults() -> Self {
let mut model = Self::new();
for (component, spec) in defaults() {
model.declare(component, spec);
}
model
}
pub fn declare_standard(&mut self, component: &str) -> Option<usize> {
let standard = crate::standard::components::component(component)?;
let key = ComponentKey::new(standard.name);
let mut declared = 0;
for variable in standard.variables {
let data_type = variable
.data_type
.and_then(DataType::from_wire)
.unwrap_or(DataType::String);
let mut spec = VariableSpec::new(variable.name, data_type);
if let Some(instance) = variable.instance {
spec = spec.instance(instance);
}
if let Some(unit) = variable.unit {
spec = spec.unit(unit);
}
match variable.attribute.and_then(Attribute::from_wire) {
Some(attribute) if attribute != Attribute::Actual => {
if let Some(existing) = self
.components
.get_mut(&key)
.and_then(|variables| variables.get_mut(&spec.key))
{
existing.supported.insert(attribute);
continue;
}
spec = spec.supports(attribute);
}
_ => {}
}
self.declare(key.clone(), spec);
declared += 1;
}
Some(declared)
}
pub fn declare(&mut self, component: impl Into<ComponentKey>, spec: VariableSpec) {
self.components
.entry(component.into())
.or_default()
.insert(spec.key.clone(), spec);
}
#[must_use]
pub fn len(&self) -> usize {
self.components.values().map(BTreeMap::len).sum()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn components(&self) -> impl Iterator<Item = &ComponentKey> {
self.components.keys()
}
pub fn get(
&self,
component: impl Into<ComponentKey>,
variable: impl Into<VariableKey>,
attribute: Attribute,
) -> Result<String, GetStatus> {
let component = component.into();
let variable = variable.into();
let Some(variables) = self.components.get(&component) else {
return Err(GetStatus::UnknownComponent);
};
let Some(spec) = variables.get(&variable) else {
return Err(GetStatus::UnknownVariable);
};
if !spec.mutability.readable() {
return Err(GetStatus::Rejected);
}
if !spec.supported.contains(&attribute) {
return Err(GetStatus::NotSupportedAttributeType);
}
Ok(spec.values.get(&attribute).cloned().unwrap_or_default())
}
pub fn set(
&mut self,
component: impl Into<ComponentKey>,
variable: impl Into<VariableKey>,
attribute: Attribute,
value: &str,
) -> SetStatus {
let component = component.into();
let variable = variable.into();
let Some(variables) = self.components.get_mut(&component) else {
return SetStatus::UnknownComponent;
};
let Some(spec) = variables.get_mut(&variable) else {
return SetStatus::UnknownVariable;
};
if !spec.mutability.writable() || spec.constant {
return SetStatus::Rejected;
}
if !spec.supported.contains(&attribute) {
return SetStatus::NotSupportedAttributeType;
}
if !spec.data_type.accepts(value, &spec.values_list) {
return SetStatus::Rejected;
}
if matches!(spec.data_type, DataType::Integer | DataType::Decimal) {
if let Ok(number) = value.parse::<Decimal>() {
if spec.min_limit.is_some_and(|min| number < min)
|| spec.max_limit.is_some_and(|max| number > max)
{
return SetStatus::Rejected;
}
}
}
spec.values.insert(attribute, value.to_owned());
if spec.reboot_required {
SetStatus::RebootRequired
} else {
SetStatus::Accepted
}
}
#[must_use]
pub fn report(
&self,
base: ReportBase,
component_filter: Option<&str>,
variable_filter: Option<&str>,
) -> Vec<ReportDatum> {
let criterion = component_filter.map(ComponentKey::new);
self.report_matching(base, criterion.as_ref(), variable_filter)
}
#[must_use]
pub fn report_matching(
&self,
base: ReportBase,
component_filter: Option<&ComponentKey>,
variable_filter: Option<&str>,
) -> Vec<ReportDatum> {
let mut out = Vec::new();
for (component, variables) in &self.components {
if component_filter.is_some_and(|criterion| !component.matches(criterion)) {
continue;
}
for (variable, spec) in variables {
if variable_filter.is_some_and(|name| name != variable.name) {
continue;
}
let include = match base {
ReportBase::FullInventory => true,
ReportBase::ConfigurationInventory => spec.mutability.writable(),
ReportBase::SummaryInventory => is_summary_variable(&variable.name),
};
if !include {
continue;
}
out.push(ReportDatum {
component: component.clone(),
variable: variable.clone(),
attributes: spec
.supported
.iter()
.map(|attribute| {
let value = spec
.mutability
.readable()
.then(|| spec.values.get(attribute).cloned())
.flatten();
(*attribute, spec.mutability, value)
})
.collect(),
mutability: spec.mutability,
data_type: spec.data_type,
unit: spec.unit.clone(),
values_list: spec.values_list.clone(),
min_limit: spec.min_limit,
max_limit: spec.max_limit,
persistent: spec.persistent,
constant: spec.constant,
});
}
}
out
}
#[must_use]
pub fn paginate(data: &[ReportDatum], per_page: usize) -> Vec<(i32, bool, Vec<ReportDatum>)> {
let per_page = per_page.max(1);
let total = data.len().div_ceil(per_page).max(1);
let mut pages = Vec::with_capacity(total);
let mut chunks = data.chunks(per_page).peekable();
let mut seq = 0;
if chunks.peek().is_none() {
return alloc::vec![(0, false, Vec::new())];
}
while let Some(chunk) = chunks.next() {
pages.push((seq, chunks.peek().is_some(), chunk.to_vec()));
seq += 1;
}
pages
}
}
fn is_summary_variable(name: &str) -> bool {
matches!(
name,
"AvailabilityState" | "Active" | "Problem" | "Tripped" | "Overload" | "Fallback"
)
}
#[allow(clippy::too_many_lines)]
fn defaults() -> Vec<(ComponentKey, VariableSpec)> {
use DataType::{Boolean, Integer, String as Str};
let seconds = |name: &str| VariableSpec::new(name, Integer).unit("s");
alloc::vec![
(
ComponentKey::new("OCPPCommCtrlr"),
seconds("HeartbeatInterval")
.mutability(Mutability::ReadWrite)
.value("300"),
),
(
ComponentKey::new("OCPPCommCtrlr"),
seconds("MessageTimeout").instance("Default").value("30"),
),
(
ComponentKey::new("OCPPCommCtrlr"),
VariableSpec::new("MessageAttempts", Integer)
.instance("TransactionEvent")
.mutability(Mutability::ReadWrite)
.value("3"),
),
(
ComponentKey::new("OCPPCommCtrlr"),
seconds("MessageAttemptInterval")
.instance("TransactionEvent")
.mutability(Mutability::ReadWrite)
.value("60"),
),
(
ComponentKey::new("OCPPCommCtrlr"),
seconds("WebSocketPingInterval")
.mutability(Mutability::ReadWrite)
.value("60"),
),
(
ComponentKey::new("OCPPCommCtrlr"),
seconds("RetryBackOffWaitMinimum")
.mutability(Mutability::ReadWrite)
.value("10"),
),
(
ComponentKey::new("OCPPCommCtrlr"),
seconds("RetryBackOffRandomRange")
.mutability(Mutability::ReadWrite)
.value("10"),
),
(
ComponentKey::new("OCPPCommCtrlr"),
VariableSpec::new("RetryBackOffRepeatTimes", Integer)
.mutability(Mutability::ReadWrite)
.value("3"),
),
(
ComponentKey::new("OCPPCommCtrlr"),
seconds("OfflineThreshold")
.mutability(Mutability::ReadWrite)
.value("600"),
),
(
ComponentKey::new("OCPPCommCtrlr"),
VariableSpec::new("QueueAllMessages", Boolean)
.mutability(Mutability::ReadWrite)
.value("false"),
),
(
ComponentKey::new("OCPPCommCtrlr"),
VariableSpec::new("NetworkConfigurationPriority", Str)
.mutability(Mutability::ReadWrite)
.value("0"),
),
(
ComponentKey::new("OCPPCommCtrlr"),
VariableSpec::new("NetworkProfileConnectionAttempts", Integer)
.mutability(Mutability::ReadWrite)
.value("3"),
),
(
ComponentKey::new("SecurityCtrlr"),
VariableSpec::new("SecurityProfile", Integer)
.limits(Some(Decimal::from(1)), Some(Decimal::from(3)))
.value("1"),
),
(
ComponentKey::new("SecurityCtrlr"),
VariableSpec::new("BasicAuthPassword", Str).mutability(Mutability::WriteOnly),
),
(
ComponentKey::new("SecurityCtrlr"),
VariableSpec::new("Identity", Str).constant(),
),
(
ComponentKey::new("SecurityCtrlr"),
VariableSpec::new("OrganizationName", Str).mutability(Mutability::ReadWrite),
),
(
ComponentKey::new("TxCtrlr"),
VariableSpec::new("TxStartPoint", DataType::MemberList)
.mutability(Mutability::ReadWrite)
.values([
"ParkingBayOccupancy",
"EVConnected",
"Authorized",
"DataSigned",
"PowerPathClosed",
"EnergyTransfer"
])
.value("PowerPathClosed"),
),
(
ComponentKey::new("TxCtrlr"),
VariableSpec::new("TxStopPoint", DataType::MemberList)
.mutability(Mutability::ReadWrite)
.values([
"ParkingBayOccupancy",
"EVConnected",
"Authorized",
"DataSigned",
"PowerPathClosed",
"EnergyTransfer"
])
.value("EVConnected"),
),
(
ComponentKey::new("TxCtrlr"),
VariableSpec::new("StopTxOnInvalidId", Boolean)
.mutability(Mutability::ReadWrite)
.value("true"),
),
(
ComponentKey::new("AuthCtrlr"),
VariableSpec::new("AuthorizeRemoteStart", Boolean)
.mutability(Mutability::ReadWrite)
.value("false"),
),
(
ComponentKey::new("AuthCtrlr"),
VariableSpec::new("LocalPreAuthorize", Boolean)
.mutability(Mutability::ReadWrite)
.value("false"),
),
(
ComponentKey::new("AuthCacheCtrlr"),
VariableSpec::new("Enabled", Boolean)
.mutability(Mutability::ReadWrite)
.value("true"),
),
(
ComponentKey::new("LocalAuthListCtrlr"),
VariableSpec::new("Enabled", Boolean)
.mutability(Mutability::ReadWrite)
.value("true"),
),
(
ComponentKey::new("LocalAuthListCtrlr"),
VariableSpec::new("Entries", Integer).value("0"),
),
(
ComponentKey::new("ClockCtrlr"),
VariableSpec::new("TimeSource", DataType::SequenceList)
.mutability(Mutability::ReadWrite)
.values([
"Heartbeat",
"NTP",
"GPS",
"RealTimeClock",
"MobileNetwork",
"RadioTimeTransmitter"
])
.value("Heartbeat"),
),
(
ComponentKey::new("ClockCtrlr"),
VariableSpec::new("DateTime", DataType::DateTime),
),
(
ComponentKey::new("DeviceDataCtrlr"),
VariableSpec::new("ItemsPerMessage", Integer)
.instance("GetReport")
.value("25"),
),
(
ComponentKey::new("DeviceDataCtrlr"),
VariableSpec::new("BytesPerMessage", Integer)
.instance("GetReport")
.value("65536"),
),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mutability_and_type_are_enforced_on_write() {
let mut model = DeviceModel::with_defaults();
assert_eq!(
model.set(
"OCPPCommCtrlr",
"HeartbeatInterval",
Attribute::Actual,
"600"
),
SetStatus::Accepted
);
assert_eq!(
model
.get("OCPPCommCtrlr", "HeartbeatInterval", Attribute::Actual)
.unwrap(),
"600"
);
assert_eq!(
model.set(
"OCPPCommCtrlr",
"HeartbeatInterval",
Attribute::Actual,
"soon"
),
SetStatus::Rejected
);
assert_eq!(
model.set("SecurityCtrlr", "Identity", Attribute::Actual, "CS-1"),
SetStatus::Rejected
);
assert_eq!(
model.set("SecurityCtrlr", "SecurityProfile", Attribute::Actual, "9"),
SetStatus::Rejected
);
assert_eq!(
model.set("Nope", "Whatever", Attribute::Actual, "1"),
SetStatus::UnknownComponent
);
assert_eq!(
model.set("SecurityCtrlr", "Whatever", Attribute::Actual, "1"),
SetStatus::UnknownVariable
);
}
#[test]
fn a_supported_attribute_with_no_value_is_readable_and_writable_b06_fr_13() {
let mut model = DeviceModel::new();
model.declare(
"OCPPCommCtrlr",
VariableSpec::new("HeartbeatInterval", DataType::Integer)
.mutability(Mutability::ReadWrite)
.value("300")
.supports(Attribute::Target),
);
let data = model.report(ReportBase::FullInventory, None, None);
let entry = data
.iter()
.find(|d| d.variable.name == "HeartbeatInterval")
.expect("declared");
let target = entry
.attributes
.iter()
.find(|(attribute, _, _)| *attribute == Attribute::Target)
.expect("B07.FR.11: a supported attribute is reported even when unset");
assert_eq!(target.2, None, "…and it is reported without a value");
assert_eq!(
model.get("OCPPCommCtrlr", "HeartbeatInterval", Attribute::Target),
Ok(String::new())
);
assert_eq!(
model.set(
"OCPPCommCtrlr",
"HeartbeatInterval",
Attribute::Target,
"60"
),
SetStatus::Accepted
);
assert_eq!(
model.get("OCPPCommCtrlr", "HeartbeatInterval", Attribute::Target),
Ok("60".to_owned())
);
assert_eq!(
model.get("OCPPCommCtrlr", "HeartbeatInterval", Attribute::MinSet),
Err(GetStatus::NotSupportedAttributeType)
);
assert_eq!(
model.set("OCPPCommCtrlr", "HeartbeatInterval", Attribute::MinSet, "1"),
SetStatus::NotSupportedAttributeType
);
}
#[test]
fn a_write_only_variable_is_never_read_back() {
let mut model = DeviceModel::with_defaults();
assert_eq!(
model.set(
"SecurityCtrlr",
"BasicAuthPassword",
Attribute::Actual,
"0123456789abcdef"
),
SetStatus::Accepted
);
assert_eq!(
model.get("SecurityCtrlr", "BasicAuthPassword", Attribute::Actual),
Err(GetStatus::Rejected)
);
let report = model.report(
ReportBase::FullInventory,
Some("SecurityCtrlr"),
Some("BasicAuthPassword"),
);
assert_eq!(
report[0].attributes[0].2, None,
"the value is withheld from reports too"
);
}
#[test]
fn a_report_criterion_matches_instance_evse_and_connector_where_given() {
let station = ComponentKey::new("Connector");
let evse1 = ComponentKey::new("Connector").evse(1, Some(1));
let evse2 = ComponentKey::new("Connector").evse(2, Some(1));
let named = ComponentKey::new("Connector")
.instance("A")
.evse(1, Some(2));
let any = ComponentKey::new("Connector");
assert!(station.matches(&any) && evse1.matches(&any) && named.matches(&any));
let on_evse1 = ComponentKey::new("Connector").evse(1, None); assert!(evse1.matches(&on_evse1) && named.matches(&on_evse1));
assert!(!evse2.matches(&on_evse1) && !station.matches(&on_evse1));
let instance_a = ComponentKey::new("Connector").instance("A"); assert!(named.matches(&instance_a) && !evse1.matches(&instance_a));
assert!(!ComponentKey::new("EVSE").matches(&any));
}
#[test]
fn instances_distinguish_variables_of_the_same_name() {
let model = DeviceModel::with_defaults();
let attempts = model
.get(
"OCPPCommCtrlr",
VariableKey::new("MessageAttempts").instance("TransactionEvent"),
Attribute::Actual,
)
.unwrap();
assert_eq!(attempts, "3");
assert_eq!(
model.get("OCPPCommCtrlr", "MessageAttempts", Attribute::Actual),
Err(GetStatus::UnknownVariable)
);
}
#[test]
fn a_configuration_inventory_reports_only_writable_variables() {
let model = DeviceModel::with_defaults();
let full = model.report(ReportBase::FullInventory, None, None);
let config = model.report(ReportBase::ConfigurationInventory, None, None);
assert!(config.len() < full.len());
assert!(config.iter().all(|datum| datum.mutability.writable()));
}
#[test]
fn the_standard_catalogue_declares_a_component_with_its_types_and_units() {
let mut model = DeviceModel::new();
let declared = model
.declare_standard("OCPPCommCtrlr")
.expect("a standard component");
assert!(
declared >= 15,
"the appendix lists at least 15 OCPPCommCtrlr variables"
);
let report = model.report(
ReportBase::FullInventory,
Some("OCPPCommCtrlr"),
Some("HeartbeatInterval"),
);
assert_eq!(report[0].data_type, DataType::Integer);
assert_eq!(report[0].unit.as_deref(), Some("s"));
assert!(model.declare_standard("NotAComponent").is_none());
}
#[test]
fn a_physical_component_gets_its_types_from_the_standardized_variable_list() {
let mut model = DeviceModel::new();
model
.declare_standard("EVSE")
.expect("EVSE is standardized");
let report = model.report(ReportBase::FullInventory, Some("EVSE"), Some("ACVoltage"));
assert_eq!(report[0].data_type, DataType::Decimal);
assert_eq!(report[0].unit.as_deref(), Some("V"));
}
#[test]
fn a_summary_inventory_reports_availability_and_condition_b07_fr_09() {
let mut model = DeviceModel::new();
model.declare(
ComponentKey::new("ChargingStation"),
VariableSpec::new("AvailabilityState", DataType::OptionList).value("Available"),
);
model.declare(
ComponentKey::new("Connector").evse(1, Some(1)),
VariableSpec::new("Problem", DataType::Boolean).value("false"),
);
model.declare(
ComponentKey::new("OCPPCommCtrlr"),
VariableSpec::new("HeartbeatInterval", DataType::Integer)
.mutability(Mutability::ReadWrite)
.value("300"),
);
let summary = model.report(ReportBase::SummaryInventory, None, None);
let names: Vec<&str> = summary
.iter()
.map(|datum| datum.variable.name.as_str())
.collect();
assert!(names.contains(&"AvailabilityState"), "{names:?}");
assert!(names.contains(&"Problem"), "{names:?}");
assert!(
!names.contains(&"HeartbeatInterval"),
"a configuration variable is not a summary: {names:?}"
);
let full = model.report(ReportBase::FullInventory, None, None);
assert_eq!(full.len(), 3);
}
#[test]
fn a_supported_but_unset_attribute_is_still_reported_b07_fr_11() {
let mut model = DeviceModel::new();
model.declare(
ComponentKey::new("SmartChargingCtrlr"),
VariableSpec::new("Entries", DataType::Integer)
.mutability(Mutability::ReadWrite)
.value("10")
.supports(Attribute::MaxSet),
);
let report = model.report(ReportBase::FullInventory, None, None);
let attributes = &report[0].attributes;
let max_set = attributes
.iter()
.find(|(attribute, _, _)| *attribute == Attribute::MaxSet)
.expect("MaxSet is supported, so it is reported");
assert_eq!(max_set.2, None, "…with no value, which is the point");
assert!(
attributes
.iter()
.any(|(attribute, _, value)| *attribute == Attribute::Actual
&& value.as_deref() == Some("10"))
);
}
#[test]
fn reports_are_paginated_with_a_to_be_continued_flag() {
let model = DeviceModel::with_defaults();
let pages = DeviceModel::paginate(&model.report(ReportBase::FullInventory, None, None), 10);
assert!(pages.len() > 1);
assert_eq!(pages[0].0, 0);
assert!(pages[0].1, "every page but the last is `tbc`");
assert!(!pages.last().unwrap().1);
let total: usize = pages.iter().map(|(_, _, data)| data.len()).sum();
assert_eq!(
total,
model.report(ReportBase::FullInventory, None, None).len()
);
}
}