use alloc::borrow::ToOwned;
use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
#[must_use = "a key that was rejected or is not supported left the configuration unchanged, and \
`ChangeConfiguration.conf` has to say so"]
pub enum ConfigurationStatus {
Accepted,
Rejected,
RebootRequired,
NotSupported,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ValueType {
Text,
Integer,
Boolean,
CsvList,
}
impl ValueType {
#[must_use]
pub fn accepts(self, value: &str) -> bool {
match self {
ValueType::Text | ValueType::CsvList => true,
ValueType::Integer => value.parse::<i64>().is_ok(),
ValueType::Boolean => matches!(value, "true" | "false"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Access {
ReadOnly,
ReadWrite,
RebootRequired,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Key {
pub name: &'static str,
pub access: Access,
pub value_type: ValueType,
pub profile: &'static str,
pub value: Option<String>,
}
#[derive(Clone, Debug, Default)]
pub struct ConfigurationKeys {
keys: BTreeMap<&'static str, Key>,
}
impl ConfigurationKeys {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_defaults() -> Self {
let mut keys = BTreeMap::new();
for key in defaults() {
keys.insert(key.name, key);
}
Self { keys }
}
pub fn declare(&mut self, key: Key) {
self.keys.insert(key.name, key);
}
pub fn remove(&mut self, name: &str) {
self.keys.retain(|key, _| *key != name);
}
#[must_use]
pub fn len(&self) -> usize {
self.keys.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.keys.is_empty()
}
#[must_use]
pub fn get(&self, name: &str) -> Option<&Key> {
self.keys.get(name)
}
pub fn set(&mut self, name: &str, value: &str) -> ConfigurationStatus {
let Some(key) = self.keys.get_mut(name) else {
return ConfigurationStatus::NotSupported;
};
if key.access == Access::ReadOnly || !key.value_type.accepts(value) {
return ConfigurationStatus::Rejected;
}
if name == "SecurityProfile" && !self.security_profile_change_allowed(value) {
return ConfigurationStatus::Rejected;
}
let Some(key) = self.keys.get_mut(name) else {
return ConfigurationStatus::NotSupported;
};
key.value = Some(value.to_owned());
if key.access == Access::RebootRequired {
ConfigurationStatus::RebootRequired
} else {
ConfigurationStatus::Accepted
}
}
fn security_profile_change_allowed(&self, value: &str) -> bool {
let Ok(requested) = value.trim().parse::<u8>() else {
return false;
};
if !(1..=3).contains(&requested) {
return false;
}
let current = self
.keys
.get("SecurityProfile")
.and_then(|key| key.value.as_deref())
.and_then(|value| value.trim().parse::<u8>().ok())
.unwrap_or(1);
if requested > current {
let has_key = self
.keys
.get("AuthorizationKey")
.and_then(|key| key.value.as_deref())
.is_some_and(|key| !key.is_empty());
return requested == 3 || has_key;
}
if requested == current {
return requested == 1;
}
let downgrade_allowed = self
.keys
.get("AllowSecurityProfileDowngrade")
.and_then(|key| key.value.as_deref())
.is_some_and(|value| value.eq_ignore_ascii_case("true"));
current == 3 && requested == 2 && downgrade_allowed
}
#[must_use]
pub fn report<'a>(&'a self, requested: &[&str]) -> (Vec<&'a Key>, Vec<String>) {
if requested.is_empty() {
return (self.keys.values().collect(), Vec::new());
}
let mut known = Vec::new();
let mut unknown = Vec::new();
for name in requested {
match self.keys.get(*name) {
Some(key) => known.push(key),
None => unknown.push((*name).to_string()),
}
}
(known, unknown)
}
}
const fn key(
name: &'static str,
access: Access,
value_type: ValueType,
profile: &'static str,
) -> Key {
Key {
name,
access,
value_type,
profile,
value: None,
}
}
fn with(mut key: Key, value: &str) -> Key {
key.value = Some(value.to_owned());
key
}
#[allow(clippy::too_many_lines)]
fn defaults() -> Vec<Key> {
use Access::{ReadOnly, ReadWrite, RebootRequired};
use ValueType::{Boolean, CsvList, Integer, Text};
alloc::vec![
with(key("HeartbeatInterval", ReadWrite, Integer, "Core"), "300"),
with(
key("AllowOfflineTxForUnknownId", ReadWrite, Boolean, "Core"),
"false"
),
with(
key("AuthorizationCacheEnabled", ReadWrite, Boolean, "Core"),
"true"
),
with(
key("AuthorizeRemoteTxRequests", ReadOnly, Boolean, "Core"),
"false"
),
with(
key("ClockAlignedDataInterval", ReadWrite, Integer, "Core"),
"0"
),
with(key("ConnectionTimeOut", ReadWrite, Integer, "Core"), "60"),
with(
key("ConnectorPhaseRotation", ReadWrite, CsvList, "Core"),
"Unknown"
),
with(
key("GetConfigurationMaxKeys", ReadOnly, Integer, "Core"),
"50"
),
with(
key("LocalAuthorizeOffline", ReadWrite, Boolean, "Core"),
"true"
),
with(
key("LocalPreAuthorize", ReadWrite, Boolean, "Core"),
"false"
),
with(
key("MeterValuesAlignedData", ReadWrite, CsvList, "Core"),
""
),
with(
key("MeterValuesSampledData", ReadWrite, CsvList, "Core"),
"Energy.Active.Import.Register",
),
with(
key("MeterValueSampleInterval", ReadWrite, Integer, "Core"),
"60"
),
with(key("NumberOfConnectors", ReadOnly, Integer, "Core"), "1"),
with(key("ResetRetries", ReadWrite, Integer, "Core"), "3"),
with(
key(
"StopTransactionOnEVSideDisconnect",
ReadWrite,
Boolean,
"Core"
),
"true"
),
with(
key("StopTransactionOnInvalidId", ReadWrite, Boolean, "Core"),
"true"
),
with(key("StopTxnAlignedData", ReadWrite, CsvList, "Core"), ""),
with(key("StopTxnSampledData", ReadWrite, CsvList, "Core"), ""),
with(
key("SupportedFeatureProfiles", ReadOnly, CsvList, "Core"),
"Core,FirmwareManagement,LocalAuthListManagement,Reservation,SmartCharging,RemoteTrigger",
),
with(
key("TransactionMessageAttempts", ReadWrite, Integer, "Core"),
"3"
),
with(
key(
"TransactionMessageRetryInterval",
ReadWrite,
Integer,
"Core"
),
"60"
),
with(
key(
"UnlockConnectorOnEVSideDisconnect",
ReadWrite,
Boolean,
"Core"
),
"true"
),
with(
key("WebSocketPingInterval", ReadWrite, Integer, "Core"),
"60"
),
with(
key(
"LocalAuthListEnabled",
ReadWrite,
Boolean,
"LocalAuthListManagement"
),
"true"
),
with(
key(
"LocalAuthListMaxLength",
ReadOnly,
Integer,
"LocalAuthListManagement"
),
"0"
),
with(
key(
"SendLocalListMaxLength",
ReadOnly,
Integer,
"LocalAuthListManagement"
),
"0"
),
with(
key(
"ReserveConnectorZeroSupported",
ReadOnly,
Boolean,
"Reservation"
),
"false"
),
with(
key(
"ChargeProfileMaxStackLevel",
ReadOnly,
Integer,
"SmartCharging"
),
"3"
),
with(
key(
"ChargingScheduleAllowedChargingRateUnit",
ReadOnly,
CsvList,
"SmartCharging"
),
"Current,Power",
),
with(
key(
"ChargingScheduleMaxPeriods",
ReadOnly,
Integer,
"SmartCharging"
),
"10"
),
with(
key(
"MaxChargingProfilesInstalled",
ReadOnly,
Integer,
"SmartCharging"
),
"10"
),
key("AuthorizationKey", ReadWrite, Text, "Security"),
with(key("SecurityProfile", ReadWrite, Integer, "Security"), "1"),
with(
key(
"AllowSecurityProfileDowngrade",
ReadWrite,
Boolean,
"Security"
),
"false"
),
with(
key(
"AdditionalRootCertificateCheck",
ReadOnly,
Boolean,
"Security"
),
"false"
),
with(
key(
"CertificateSignedMaxChainSize",
ReadOnly,
Integer,
"Security"
),
"0"
),
with(
key("CertificateStoreMaxLength", ReadOnly, Integer, "Security"),
"0"
),
key("CpoName", ReadWrite, Text, "Security"),
with(key("ConnectionUrl", RebootRequired, Text, "Core"), ""),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_security_profile_is_never_lowered_except_three_to_two_when_allowed() {
use ConfigurationStatus::{Accepted, Rejected};
let mut config = ConfigurationKeys::with_defaults();
assert_eq!(config.set("SecurityProfile", "2"), Rejected);
assert_eq!(
config.set("AuthorizationKey", "00112233445566778899aabbccddeeff"),
Accepted
);
assert_eq!(config.set("SecurityProfile", "2"), Accepted);
assert_eq!(config.set("SecurityProfile", "2"), Rejected);
assert_eq!(config.set("SecurityProfile", "1"), Rejected);
assert_eq!(config.set("SecurityProfile", "0"), Rejected);
assert_eq!(config.set("SecurityProfile", "3"), Accepted);
assert_eq!(config.set("SecurityProfile", "2"), Rejected);
assert_eq!(
config.set("AllowSecurityProfileDowngrade", "true"),
Accepted
);
assert_eq!(config.set("SecurityProfile", "1"), Rejected);
assert_eq!(config.set("SecurityProfile", "2"), Accepted);
assert_eq!(
config.get("SecurityProfile").unwrap().value.as_deref(),
Some("2")
);
}
#[test]
fn writes_are_checked_against_the_keys_type_and_access() {
let mut config = ConfigurationKeys::with_defaults();
assert_eq!(
config.set("HeartbeatInterval", "600"),
ConfigurationStatus::Accepted
);
assert_eq!(
config.get("HeartbeatInterval").unwrap().value.as_deref(),
Some("600")
);
assert_eq!(
config.set("HeartbeatInterval", "soon"),
ConfigurationStatus::Rejected
);
assert_eq!(
config.set("NumberOfConnectors", "4"),
ConfigurationStatus::Rejected
);
assert_eq!(
config.set("LocalAuthListEnabled", "yes"),
ConfigurationStatus::Rejected
);
assert_eq!(
config.set("LocalAuthListEnabled", "false"),
ConfigurationStatus::Accepted
);
assert_eq!(
config.set("Nonexistent", "1"),
ConfigurationStatus::NotSupported
);
}
#[test]
fn a_reboot_required_key_says_so() {
let mut config = ConfigurationKeys::with_defaults();
assert_eq!(
config.set("ConnectionUrl", "ws://csms.example.com/ocpp"),
ConfigurationStatus::RebootRequired
);
}
#[test]
fn get_configuration_splits_known_from_unknown_keys() {
let config = ConfigurationKeys::with_defaults();
let (known, unknown) = config.report(&["HeartbeatInterval", "Nonexistent"]);
assert_eq!(known.len(), 1);
assert_eq!(known[0].name, "HeartbeatInterval");
assert_eq!(unknown, alloc::vec!["Nonexistent".to_string()]);
let (all, unknown) = config.report(&[]);
assert_eq!(all.len(), config.len());
assert!(unknown.is_empty(), "{unknown:?}");
}
#[test]
fn removing_a_key_makes_the_station_report_it_as_unknown() {
let mut config = ConfigurationKeys::with_defaults();
config.remove("ReserveConnectorZeroSupported");
let (known, unknown) = config.report(&["ReserveConnectorZeroSupported"]);
assert!(known.is_empty(), "{known:?}");
assert_eq!(unknown.len(), 1);
}
}