use serde::{Deserialize, Serialize};
use super::builder::strict_builder;
use super::datetime::HourMinute;
use super::extensions::Extensions;
use super::number::Number;
use super::text::Text;
use super::validate::{Validate, Validator, ViolationCode, validate_fields};
use crate::{oicp_enum, oicp_open_enum};
oicp_open_enum! {
pub enum Accessibility {
FreePubliclyAccessible = "Free publicly accessible",
RestrictedAccess = "Restricted access",
PayingPubliclyAccessible = "Paying publicly accessible",
TestStation = "Test Station",
}
}
oicp_open_enum! {
pub enum AccessibilityLocation {
OnStreet = "OnStreet",
ParkingLot = "ParkingLot",
ParkingGarage = "ParkingGarage",
UndergroundParkingGarage = "UndergroundParkingGarage",
}
}
oicp_open_enum! {
pub enum AuthenticationMode {
NfcRfidClassic = "NFC RFID Classic",
NfcRfidDesFire = "NFC RFID DESFire",
PnC = "PnC",
Remote = "REMOTE",
DirectPayment = "Direct Payment",
NoAuthenticationRequired = "No Authentication Required",
}
}
oicp_open_enum! {
pub enum PaymentOption {
NoPayment = "No Payment",
Direct = "Direct",
Contract = "Contract",
}
}
oicp_open_enum! {
pub enum Plug {
SmallPaddleInductive = "Small Paddle Inductive",
LargePaddleInductive = "Large Paddle Inductive",
AvconConnector = "AVCON Connector",
TeslaConnector = "Tesla Connector",
Nema520 = "NEMA 5-20",
TypeEFrenchStandard = "Type E French Standard",
TypeFSchuko = "Type F Schuko",
TypeGBritishStandard = "Type G British Standard",
TypeJSwissStandard = "Type J Swiss Standard",
Type1ConnectorCableAttached = "Type 1 Connector (Cable Attached)",
Type2Outlet = "Type 2 Outlet",
Type2ConnectorCableAttached = "Type 2 Connector (Cable Attached)",
Type3Outlet = "Type 3 Outlet",
Iec60309SinglePhase = "IEC 60309 Single Phase",
Iec60309ThreePhase = "IEC 60309 Three Phase",
CcsCombo2PlugCableAttached = "CCS Combo 2 Plug (Cable Attached)",
CcsCombo1PlugCableAttached = "CCS Combo 1 Plug (Cable Attached)",
ChaDeMo = "CHAdeMO",
}
}
oicp_open_enum! {
pub enum ValueAddedService {
Reservation = "Reservation",
DynamicPricing = "DynamicPricing",
ParkingSensors = "ParkingSensors",
MaximumPowerCharging = "MaximumPowerCharging",
PredictiveChargePointUsage = "PredictiveChargePointUsage",
ChargingPlans = "ChargingPlans",
RoofProvided = "RoofProvided",
None = "None",
}
}
oicp_open_enum! {
pub enum PowerType {
Ac1Phase = "AC_1_PHASE",
Ac3Phase = "AC_3_PHASE",
Dc = "DC",
}
}
oicp_open_enum! {
pub enum ChargingMode {
Mode1 = "Mode_1",
Mode2 = "Mode_2",
Mode3 = "Mode_3",
Mode4 = "Mode_4",
ChaDeMo = "CHAdeMO",
}
}
oicp_open_enum! {
pub enum EnergyType {
Solar = "Solar",
Wind = "Wind",
HydroPower = "HydroPower",
GeothermalEnergy = "GeothermalEnergy",
Biomass = "Biomass",
Coal = "Coal",
NuclearEnergy = "NuclearEnergy",
Petroleum = "Petroleum",
NaturalGas = "NaturalGas",
}
}
oicp_open_enum! {
pub enum CalibrationLawDataAvailability {
Local = "Local",
External = "External",
NotAvailable = "Not Available",
}
}
oicp_open_enum! {
pub enum DaySelection {
Everyday = "Everyday",
Workdays = "Workdays",
Weekend = "Weekend",
Monday = "Monday",
Tuesday = "Tuesday",
Wednesday = "Wednesday",
Thursday = "Thursday",
Friday = "Friday",
Saturday = "Saturday",
Sunday = "Sunday",
}
}
oicp_open_enum! {
pub enum DynamicInfoAvailable {
True = "true",
False = "false",
Auto = "auto",
}
}
oicp_enum! {
pub enum ActionType {
FullLoad = "fullLoad",
Update = "update",
Insert = "insert",
Delete = "delete",
}
}
impl ActionType {
#[must_use]
pub const fn is_destructive_replace(self) -> bool {
matches!(self, Self::FullLoad)
}
}
oicp_open_enum! {
pub enum ReferenceUnit {
Hour = "HOUR",
KilowattHour = "KILOWATT_HOUR",
Minute = "MINUTE",
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, bon::Builder)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[builder(finish_fn = build_unchecked)]
pub struct Address {
#[serde(rename = "Country")]
#[builder(into)]
pub country: Text<3>,
#[serde(rename = "City")]
#[builder(into)]
pub city: Text<50>,
#[serde(rename = "Street")]
#[builder(into)]
pub street: Text<100>,
#[serde(rename = "PostalCode")]
#[builder(into)]
pub postal_code: Text<10>,
#[serde(rename = "HouseNum")]
#[builder(into)]
pub house_num: Text<10>,
#[serde(rename = "Floor", default, skip_serializing_if = "Option::is_none")]
#[builder(into)]
pub floor: Option<Text<5>>,
#[serde(rename = "Region", default, skip_serializing_if = "Option::is_none")]
#[builder(into)]
pub region: Option<Text<50>>,
#[serde(rename = "ParkingFacility", default, skip_serializing_if = "Option::is_none")]
pub parking_facility: Option<bool>,
#[serde(rename = "ParkingSpot", default, skip_serializing_if = "Option::is_none")]
#[builder(into)]
pub parking_spot: Option<Text<5>>,
#[serde(rename = "TimeZone", default, skip_serializing_if = "Option::is_none")]
#[builder(into)]
pub time_zone: Option<String>,
#[serde(flatten, default, skip_serializing_if = "Extensions::is_empty")]
#[builder(default)]
pub extensions: Extensions,
}
impl Address {
#[must_use]
pub fn time_zone_is_well_formed(&self) -> bool {
let Some(tz) = &self.time_zone else { return true };
let b = tz.as_bytes();
b.len() == 9
&& &b[..3] == b"UTC"
&& (b[3] == b'+' || b[3] == b'-')
&& b[4].is_ascii_digit()
&& b[5].is_ascii_digit()
&& b[6] == b':'
&& b[7].is_ascii_digit()
&& b[8].is_ascii_digit()
}
}
impl Validate for Address {
fn validate_in(&self, v: &mut Validator) {
if self.country.len() != 3 || !self.country.as_str().bytes().all(|c| c.is_ascii_alphabetic()) {
v.report_at(
"Country",
ViolationCode::PatternMismatch,
format!(
"{:?} is not an alpha-3 country code; OICP 2.2 and 2.3 allow only alpha-3 (ISO 3166-1)",
self.country.as_str()
),
);
}
if self.city.is_empty() {
v.report_at(
"City",
ViolationCode::TooShort,
"the city is required and has a minimum length of 1",
);
}
if self.street.len() < 2 && !self.street.is_empty() {
v.report_at("Street", ViolationCode::TooShort, "the street has a minimum length of 2");
}
if !self.time_zone_is_well_formed() {
v.report_at(
"TimeZone",
ViolationCode::PatternMismatch,
format!(
"{:?} is not of the form UTC+HH:MM or UTC-HH:MM",
self.time_zone.as_deref().unwrap_or("")
),
);
}
validate_fields!(
self,
v,
country as "Country",
city as "City",
street as "Street",
postal_code as "PostalCode",
house_num as "HouseNum",
floor as "Floor",
region as "Region",
parking_spot as "ParkingSpot",
);
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, bon::Builder)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[builder(finish_fn = build_unchecked)]
pub struct ChargingFacility {
#[serde(rename = "PowerType")]
pub power_type: PowerType,
#[serde(rename = "Voltage", default, skip_serializing_if = "Option::is_none")]
pub voltage: Option<Number>,
#[serde(rename = "Amperage", default, skip_serializing_if = "Option::is_none")]
pub amperage: Option<Number>,
#[serde(rename = "Power")]
pub power: Number,
#[serde(rename = "ChargingModes", default, skip_serializing_if = "Option::is_none")]
pub charging_modes: Option<Vec<ChargingMode>>,
#[serde(flatten, default, skip_serializing_if = "Extensions::is_empty")]
#[builder(default)]
pub extensions: Extensions,
}
impl Validate for ChargingFacility {
fn validate_in(&self, v: &mut Validator) {
v.enter("Power");
self.power.validate_in(v);
self.power.validate_range(v, 0, 999);
if !self.power.is_integer() {
v.report(
ViolationCode::Inconsistent,
format!(
"the leading OICP 2.3 document types Power as an Integer of at most three digits, \
but this facility reports {}; see erratum OICP23-E003",
self.power
),
);
}
v.leave();
if let Some(voltage) = self.voltage {
v.enter("Voltage");
voltage.validate_range_with_defect(v, 0, 999, "OICP23-D002");
v.leave();
}
if let Some(amperage) = self.amperage {
v.enter("Amperage");
amperage.validate_range_with_defect(v, 0, 99, "OICP23-D001");
v.leave();
}
validate_fields!(self, v, power_type as "PowerType", charging_modes as "ChargingModes");
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, bon::Builder)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[builder(finish_fn = build_unchecked)]
pub struct EnergySource {
#[serde(rename = "Energy", default, skip_serializing_if = "Option::is_none")]
pub energy: Option<EnergyType>,
#[serde(rename = "Percentage", default, skip_serializing_if = "Option::is_none")]
pub percentage: Option<Number>,
#[serde(flatten, default, skip_serializing_if = "Extensions::is_empty")]
#[builder(default)]
pub extensions: Extensions,
}
impl Validate for EnergySource {
fn validate_in(&self, v: &mut Validator) {
if let Some(pct) = self.percentage {
v.enter("Percentage");
pct.validate_range(v, 0, 99);
v.leave();
}
validate_fields!(self, v, energy as "Energy");
}
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize, bon::Builder)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[builder(finish_fn = build_unchecked)]
pub struct EnvironmentalImpact {
#[serde(rename = "CO2Emission", default, skip_serializing_if = "Option::is_none")]
pub co2_emission: Option<Number>,
#[serde(rename = "NuclearWaste", default, skip_serializing_if = "Option::is_none")]
pub nuclear_waste: Option<Number>,
#[serde(flatten, default, skip_serializing_if = "Extensions::is_empty")]
#[builder(default)]
pub extensions: Extensions,
}
impl Validate for EnvironmentalImpact {
fn validate_in(&self, v: &mut Validator) {
for (name, value) in [("CO2Emission", self.co2_emission), ("NuclearWaste", self.nuclear_waste)] {
if let Some(value) = value {
v.enter(name);
value.validate_range(v, 0, 99_999);
v.leave();
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[builder(finish_fn = build_unchecked)]
pub struct Period {
#[serde(rename = "begin")]
pub begin: HourMinute,
#[serde(rename = "end")]
pub end: HourMinute,
}
impl Validate for Period {
fn validate_in(&self, v: &mut Validator) {
validate_fields!(self, v, begin as "begin", end as "end");
if let (Some(b), Some(e)) = (self.begin.minutes_of_day(), self.end.minutes_of_day()) {
if b == e {
v.report(ViolationCode::Inconsistent, "the period begins and ends at the same time");
}
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, bon::Builder)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[builder(finish_fn = build_unchecked)]
pub struct OpeningTimes {
#[serde(rename = "Period")]
pub period: Vec<Period>,
#[serde(rename = "on")]
pub on: DaySelection,
#[serde(flatten, default, skip_serializing_if = "Extensions::is_empty")]
#[builder(default)]
pub extensions: Extensions,
}
impl Validate for OpeningTimes {
fn validate_in(&self, v: &mut Validator) {
if self.period.is_empty() {
v.report_at("Period", ViolationCode::EmptyRequiredList, "opening times need at least one period");
}
validate_fields!(self, v, period as "Period", on as "on");
}
}
strict_builder!(Address, AddressBuilder, address_builder);
strict_builder!(ChargingFacility, ChargingFacilityBuilder, charging_facility_builder);
strict_builder!(EnergySource, EnergySourceBuilder, energy_source_builder);
strict_builder!(EnvironmentalImpact, EnvironmentalImpactBuilder, environmental_impact_builder);
strict_builder!(Period, PeriodBuilder, period_builder);
strict_builder!(OpeningTimes, OpeningTimesBuilder, opening_times_builder);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn action_type_is_closed_because_guessing_would_delete_a_fleet() {
assert!(serde_json::from_str::<ActionType>(r#""replace""#).is_err());
assert!(ActionType::FullLoad.is_destructive_replace());
assert!(!ActionType::Update.is_destructive_replace());
}
#[test]
fn dynamic_info_available_is_a_string_enum_not_a_bool() {
let value: DynamicInfoAvailable = serde_json::from_str(r#""auto""#).unwrap();
assert_eq!(value, DynamicInfoAvailable::Auto);
assert_eq!(serde_json::to_string(&DynamicInfoAvailable::True).unwrap(), r#""true""#);
}
#[test]
fn a_plug_hubject_adds_later_is_kept() {
let plug: Plug = serde_json::from_str(r#""MCS""#).unwrap();
assert!(!plug.is_known());
assert_eq!(serde_json::to_string(&plug).unwrap(), r#""MCS""#);
}
#[test]
fn charging_facility_accepts_a_fractional_power_and_reports_it() {
let json = r#"{"PowerType":"AC_3_PHASE","Power":22.5}"#;
let facility: ChargingFacility = serde_json::from_str(json).unwrap();
assert_eq!(facility.power.to_string(), "22.5");
assert_eq!(serde_json::to_string(&facility).unwrap(), json);
let err = facility.validate().unwrap_err();
assert_eq!(err.as_slice()[0].code, ViolationCode::Inconsistent);
assert!(err.as_slice()[0].message.contains("OICP23-E003"));
}
#[test]
fn an_integral_power_within_range_is_clean() {
let facility: ChargingFacility =
serde_json::from_str(r#"{"PowerType":"AC_3_PHASE","Power":22,"Voltage":480,"Amperage":32}"#)
.unwrap();
assert!(facility.validate().is_ok());
}
#[test]
fn out_of_range_power_is_reported() {
let facility: ChargingFacility = serde_json::from_str(r#"{"PowerType":"DC","Power":1500}"#).unwrap();
let err = facility.validate().unwrap_err();
assert!(err.iter().any(|x| x.code == ViolationCode::OutOfRange));
}
#[test]
fn addresses_require_an_alpha_3_country_code() {
let address = Address::builder()
.country("DEU")
.city("Berlin")
.street("EUREF CAMPUS")
.postal_code("10829")
.house_num("22")
.time_zone("UTC+01:00")
.build()
.expect("a conformant address builds");
assert!(address.validate().is_ok());
let err = Address::builder()
.country("DE")
.city("Berlin")
.street("EUREF CAMPUS")
.postal_code("10829")
.house_num("22")
.build()
.unwrap_err();
assert_eq!(err.as_slice()[0].pointer, "/Country");
}
#[test]
fn a_malformed_time_zone_is_reported() {
let err = Address::builder()
.country("DEU")
.city("Berlin")
.street("Somewhere")
.postal_code("10829")
.house_num("22")
.time_zone("Europe/Berlin")
.build()
.unwrap_err();
assert_eq!(err.as_slice()[0].pointer, "/TimeZone");
}
#[test]
fn build_unchecked_lets_a_nonconformant_object_exist_for_tests() {
let address = Address::builder()
.country("DE")
.city("Berlin")
.street("Somewhere")
.postal_code("10829")
.house_num("22")
.build_unchecked();
assert!(address.validate().is_err());
}
}