matter_kit/clusters/energy_evse.rs
1//! Energy EVSE, cluster `0x0099` (Application Cluster §9.3).
2//!
3//! > Electric Vehicle Supply Equipment (EVSE) is equipment used to charge an Electric Vehicle
4//! > (EV) or Plug-In Hybrid Electric Vehicle.
5//!
6//! A car is the largest controllable load in most houses, and almost the only one that does
7//! not care *when* it runs so long as it is full by morning. That is what this cluster is for:
8//! a client says how much current the EVSE may pass and until when, and the user says what the
9//! car needs and by what time; something else decides the hours in between.
10//!
11//! # Enabled until a moment, not enabled
12//!
13//! §9.3.8.4: `ChargingEnabledUntil` is a timestamp, and "a value in the past or 0x0 indicates
14//! that EVSE charging SHALL be disabled". So *every* enable has an end, and the ordinary
15//! failure mode of a home energy manager — it crashes, or the Wi-Fi drops — leaves the car
16//! charging until the window it was given runs out rather than for ever. §9.3.8.4 also makes
17//! the attribute persistent, "for example a temporary power failure should not stop the
18//! vehicle from being charged".
19//!
20//! The timestamps are `epoch-s`, in UTC. A monotonic clock cannot compare them, so
21//! [`EvseHooks::utc`] is where they come from; an EVSE whose clock has not been set reports
22//! `None` and this cluster then never expires a window on its own, because guessing would
23//! either cut a charge short or run one past its end.
24//!
25//! # Charging and discharging are two axes, not three states
26//!
27//! §9.3.9.2.4 and §9.3.9.3.3 spell out a small state table: enabling charging from `Disabled`
28//! gives `ChargingEnabled`, enabling it from `DischargingEnabled` gives `Enabled`, and each
29//! window expiring drops back to whatever the other one still allows. A device that treated
30//! `SupplyState` as a single mode would turn V2H off every time a charge window ended.
31//!
32//! # The EVSE may refuse, and says why with the state it is in
33//!
34//! §9.3.9.2.4: "If there is currently an error present on the EVSE, or Diagnostics are
35//! currently active, then the command SHALL be ignored and a response with a status of FAILURE
36//! SHALL be returned." Fault clearing is deliberately outside the network's reach — §9.3 notes
37//! that some J1772 faults "may require clearing by an operator by, for example, pressing a
38//! button on the equipment or breaker panel".
39
40use core::cell::{Cell, RefCell};
41
42use crate::clusters::generated::energy_evse as spec_evse;
43use crate::dm::spec::{Conforming, Optional};
44use crate::dm::{Resolved, ResolvedCommand};
45use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
46use crate::tlv::{Tag, TlvWriter, ToTlv};
47
48use super::Cluster;
49
50pub use spec_evse::attribute::{
51 APPROXIMATE_EV_EFFICIENCY, BATTERY_CAPACITY, CHARGING_ENABLED_UNTIL, CIRCUIT_CAPACITY,
52 DISCHARGING_ENABLED_UNTIL, FAULT_STATE, MAXIMUM_CHARGE_CURRENT, MAXIMUM_DISCHARGE_CURRENT,
53 MINIMUM_CHARGE_CURRENT, NEXT_CHARGE_REQUIRED_ENERGY, NEXT_CHARGE_START_TIME,
54 NEXT_CHARGE_TARGET_SO_C, NEXT_CHARGE_TARGET_TIME, RANDOMIZATION_DELAY_WINDOW, SESSION_DURATION,
55 SESSION_ENERGY_CHARGED, SESSION_ENERGY_DISCHARGED, SESSION_ID, STATE, STATE_OF_CHARGE,
56 SUPPLY_STATE, USER_MAXIMUM_CHARGE_CURRENT, VEHICLE_ID,
57};
58pub use spec_evse::command::{
59 CLEAR_TARGETS, DISABLE, ENABLE_CHARGING, ENABLE_DISCHARGING, GET_TARGETS, GET_TARGETS_RESPONSE,
60 SET_TARGETS, START_DIAGNOSTICS,
61};
62pub use spec_evse::event::{
63 ENERGY_TRANSFER_STARTED, ENERGY_TRANSFER_STOPPED, EV_CONNECTED, EV_NOT_DETECTED, FAULT, RFID,
64};
65pub use spec_evse::{
66 ChargingTargetScheduleStruct, ChargingTargetStruct, EnergyTransferStoppedReasonEnum,
67 FaultStateEnum, ID, PICS, REVISION, StateEnum, SupplyStateEnum, TargetDayOfWeekBitmap, feature,
68};
69
70/// §9.3.9.5's constraint: "a list of up to 7 sets of daily charging targets".
71pub const SCHEDULES_MAX: usize = 7;
72
73/// §9.3.7.6's constraint on `TargetTimeMinutesPastMidnight`: "max 1439" — one minute short of
74/// twenty-four hours, because 1440 is midnight the *next* day.
75pub const MINUTES_MAX: u16 = 1439;
76
77/// The days of the week, in `TargetDayOfWeekBitmap`'s bit order (§9.3.7.1).
78const DAYS: [TargetDayOfWeekBitmap; 7] = [
79 TargetDayOfWeekBitmap::SUNDAY,
80 TargetDayOfWeekBitmap::MONDAY,
81 TargetDayOfWeekBitmap::TUESDAY,
82 TargetDayOfWeekBitmap::WEDNESDAY,
83 TargetDayOfWeekBitmap::THURSDAY,
84 TargetDayOfWeekBitmap::FRIDAY,
85 TargetDayOfWeekBitmap::SATURDAY,
86];
87
88/// What the EVSE hardware knows and decides.
89pub trait EvseHooks {
90 /// `State` (§9.3.8.1) — what the pilot signal says. `None` when it cannot be determined.
91 fn state(&self) -> Option<StateEnum>;
92
93 /// `FaultState` (§9.3.8.3).
94 ///
95 /// §9.3.8.3 ties this to `SupplyState`: "For all values of SupplyState other than
96 /// DisabledError, the FaultState attribute SHALL be NoError" — so an EVSE that reports a
97 /// fault here is also telling this cluster to refuse every enable.
98 fn fault(&self) -> FaultStateEnum {
99 FaultStateEnum::NoError
100 }
101
102 /// The current time as `epoch-s` in UTC, or `None` if the clock has never been set.
103 ///
104 /// Every enable window is a UTC timestamp (§9.3.8.4), and a monotonic clock cannot say
105 /// whether one has passed. An EVSE with no clock never expires a window here, which is the
106 /// cautious half of the choice: the alternative is guessing, and a wrong guess either cuts
107 /// a charge short or runs one past the hour the user was quoted.
108 fn utc(&self) -> Option<u32> {
109 None
110 }
111
112 /// `CircuitCapacity` (§9.3.8.6), in mA — what the supply circuit can carry.
113 fn circuit_capacity(&self) -> i64;
114
115 /// `UserMaximumChargeCurrent` (§9.3.8.10), in mA.
116 fn user_maximum_charge_current(&self) -> i64 {
117 0
118 }
119
120 /// `RandomizationDelayWindow` (§9.3.8.11), in seconds.
121 ///
122 /// A fleet of EVSEs that all started on the stroke of a cheap-rate boundary would be a
123 /// step change on the local transformer; this is the window each spreads itself over.
124 fn randomization_delay_window(&self) -> u32 {
125 0
126 }
127
128 /// `SessionID` (§9.3.8.20.1) — increments once per plug-in.
129 fn session_id(&self) -> Option<u32>;
130
131 /// `SessionDuration` (§9.3.8.20.2), in seconds.
132 fn session_duration(&self) -> Option<u32>;
133
134 /// `SessionEnergyCharged` (§9.3.8.20.3), in mWh.
135 fn session_energy_charged(&self) -> Option<i64>;
136
137 /// `SessionEnergyDischarged` — the `V2X` feature's counterpart.
138 fn session_energy_discharged(&self) -> Option<i64> {
139 None
140 }
141
142 /// `StateOfCharge` (`SOC` feature) — what the vehicle reports, if it reports anything.
143 fn state_of_charge(&self) -> Option<u8> {
144 None
145 }
146
147 /// `BatteryCapacity` (`SOC` feature), in mWh.
148 fn battery_capacity(&self) -> Option<i64> {
149 None
150 }
151
152 /// `VehicleID` (`PNC` feature) — the identity a Plug-and-Charge session established.
153 fn vehicle_id(&self) -> Option<&str> {
154 None
155 }
156
157 /// `NextChargeStartTime`, `NextChargeTargetTime`, `NextChargeRequiredEnergy` and
158 /// `NextChargeTargetSoC` (§9.3.8.12–§9.3.8.15), the `CHARGING_PREFERENCES` feature's
159 /// answer to "when will you next charge, and to what".
160 ///
161 /// §9.3.9.5.2 puts the computation firmly on the EVSE: "The EVSE SHALL be responsible for
162 /// updating the NextChargeEndTime, NextChargeRequiredEnergy and/or NextChargeTargetSoC
163 /// attributes as it runs through its internal schedule."
164 fn next_charge(&self) -> NextCharge {
165 NextCharge::default()
166 }
167
168 /// `ApproximateEVEfficiency` (§9.3.8.16), in tenths of a mile per kWh.
169 fn approximate_ev_efficiency(&self) -> Option<u16> {
170 None
171 }
172
173 /// §9.3.9.1: stop any power flow. `false` becomes `FAILURE`.
174 fn disable(&self) -> bool {
175 true
176 }
177
178 /// §9.3.9.2: pass up to `maximum_ma`, down to `minimum_ma` in trickle. `false` is
179 /// `FAILURE`.
180 fn enable_charging(&self, minimum_ma: i64, maximum_ma: i64) -> bool;
181
182 /// §9.3.9.3: accept up to `maximum_ma` back from the vehicle. `false` is `FAILURE`.
183 fn enable_discharging(&self, maximum_ma: i64) -> bool {
184 let _ = maximum_ma;
185 false
186 }
187
188 /// §9.3.9.4: run self-diagnostics. `false` is `FAILURE`.
189 ///
190 /// "The diagnostics are at the discretion of the manufacturer and usually include internal
191 /// checks. Upon completion of the diagnostics, the EVSE SHALL restore SupplyState to the
192 /// Disabled state" — so the EVSE calls [`EnergyEvse::diagnostics_complete`] when it is
193 /// done, and nothing here guesses how long that takes.
194 fn start_diagnostics(&self) -> bool {
195 false
196 }
197
198 /// The user's charging targets changed (§9.3.9.5.2).
199 ///
200 /// The schedule is stored by this cluster; acting on it is the EVSE's, and §9.3.9.5.2 is
201 /// explicit that it may not do the arithmetic itself: "the EVSE may not be able to compute
202 /// the schedules by itself, or may rely upon an EMS or other optimizer to do this."
203 fn targets_changed(&self) {}
204}
205
206/// The four `CHARGING_PREFERENCES` attributes the EVSE computes (§9.3.8.12–§9.3.8.15).
207#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
208pub struct NextCharge {
209 /// `NextChargeStartTime` — `epoch-s`, or `None` for "no charge planned".
210 pub start_time: Option<u32>,
211 /// `NextChargeTargetTime` — `epoch-s`.
212 pub target_time: Option<u32>,
213 /// `NextChargeRequiredEnergy` — mWh.
214 pub required_energy: Option<i64>,
215 /// `NextChargeTargetSoC` — percent.
216 pub target_soc: Option<u8>,
217}
218
219/// An event this cluster produced, for the device to record in its own store (§7.14).
220#[derive(Debug, Clone, Copy, PartialEq, Eq)]
221pub enum Event {
222 /// §9.3.10.1 — a vehicle was plugged in, carrying the new `SessionID`.
223 EvConnected(u32),
224 /// §9.3.10.2 — the vehicle is gone.
225 EvNotDetected,
226 /// §9.3.10.3 — current started flowing.
227 EnergyTransferStarted,
228 /// §9.3.10.4 — current stopped, and why.
229 EnergyTransferStopped(EnergyTransferStoppedReasonEnum),
230 /// §9.3.10.5 — the fault state changed.
231 Fault(FaultStateEnum),
232}
233
234/// One day's charging targets.
235type DayTargets<const T: usize> = heapless::Vec<ChargingTargetStruct, T>;
236
237/// Energy EVSE over one piece of supply equipment.
238///
239/// `T` is how many charging targets *one day* may hold. §9.3.9.5.2's resource rule is about
240/// the total the device supports, and a per-day bound is the shape that makes "replace
241/// Saturday and leave every other day alone" a local edit.
242#[derive(Debug)]
243pub struct EnergyEvse<'a, H: EvseHooks, const T: usize = 10> {
244 hooks: &'a H,
245 feature_map: u32,
246 supply: Cell<SupplyStateEnum>,
247 charging_until: Cell<Option<u32>>,
248 discharging_until: Cell<Option<u32>>,
249 minimum_charge_current: Cell<i64>,
250 maximum_charge_current: Cell<i64>,
251 maximum_discharge_current: Cell<i64>,
252 /// One entry per day, in [`DAYS`] order.
253 targets: RefCell<[DayTargets<T>; 7]>,
254 events: RefCell<heapless::Vec<Event, 8>>,
255}
256
257impl<'a, H: EvseHooks, const T: usize> EnergyEvse<'a, H, T> {
258 /// A cluster over `hooks`, starting `Disabled`.
259 ///
260 /// §9.3.8.2's starting point is the safe one: an EVSE that came up enabled would start
261 /// passing current after a power cut without anybody asking it to.
262 #[must_use]
263 pub fn new(hooks: &'a H, feature_map: u32) -> Self {
264 Self {
265 hooks,
266 feature_map,
267 supply: Cell::new(SupplyStateEnum::Disabled),
268 charging_until: Cell::new(Some(0)),
269 discharging_until: Cell::new(Some(0)),
270 minimum_charge_current: Cell::new(0),
271 maximum_charge_current: Cell::new(0),
272 maximum_discharge_current: Cell::new(0),
273 targets: RefCell::new(core::array::from_fn(|_| heapless::Vec::new())),
274 events: RefCell::new(heapless::Vec::new()),
275 }
276 }
277
278 /// The descriptor for an instance, derived from the specification's tables.
279 pub fn conforming(
280 feature_map: u32,
281 optional: &Optional<'_>,
282 ) -> crate::error::Result<Conforming<23, 8, 1, 6>> {
283 Conforming::new(&spec_evse::CLUSTER, feature_map, optional)
284 }
285
286 /// Everything §9.3 leaves to the product.
287 pub const WITH_ALL_OPTIONAL: Optional<'static> = Optional {
288 attributes: &[USER_MAXIMUM_CHARGE_CURRENT, RANDOMIZATION_DELAY_WINDOW],
289 commands: &[START_DIAGNOSTICS],
290 events: &[],
291 };
292
293 /// Restores the enable windows a reboot interrupted (§9.3.8.4).
294 ///
295 /// > This attribute SHALL be persisted, for example a temporary power failure should not
296 /// > stop the vehicle from being charged.
297 ///
298 /// So the device hands back what it stored, and this cluster puts `SupplyState` where the
299 /// two windows say it belongs rather than assuming `Disabled`.
300 pub fn start(&self, charging_until: Option<u32>, discharging_until: Option<u32>) {
301 self.charging_until.set(charging_until);
302 self.discharging_until.set(discharging_until);
303 self.resupply();
304 }
305
306 /// `SupplyState` (§9.3.8.2).
307 #[must_use]
308 pub fn supply_state(&self) -> SupplyStateEnum {
309 // §9.3.8.3: a fault outranks everything the client asked for.
310 if self.hooks.fault() != FaultStateEnum::NoError {
311 return SupplyStateEnum::DisabledError;
312 }
313 self.supply.get()
314 }
315
316 /// `ChargingEnabledUntil` (§9.3.8.4) — `None` is null, "always enabled".
317 #[must_use]
318 pub fn charging_enabled_until(&self) -> Option<u32> {
319 self.charging_until.get()
320 }
321
322 /// `DischargingEnabledUntil` (§9.3.8.5).
323 #[must_use]
324 pub fn discharging_enabled_until(&self) -> Option<u32> {
325 self.discharging_until.get()
326 }
327
328 /// `MaximumChargeCurrent` (§9.3.8.8), in mA.
329 ///
330 /// §9.3.9.2.3: the command's value is the ceiling, and `UserMaximumChargeCurrent` may only
331 /// lower it — "if the UserMaximumChargeCurrent attribute is adjusted below then this
332 /// value, and then later adjusted above this value, the resulting MaximumChargeCurrent
333 /// attribute will be limited to this value". The user cannot raise the limit an installer
334 /// or a client set.
335 #[must_use]
336 pub fn maximum_charge_current(&self) -> i64 {
337 let user = self.hooks.user_maximum_charge_current();
338 let commanded = self.maximum_charge_current.get();
339 if user > 0 {
340 user.min(commanded)
341 } else {
342 commanded
343 }
344 }
345
346 /// Whether current is flowing either way right now.
347 #[must_use]
348 pub fn transferring(&self) -> bool {
349 matches!(
350 self.hooks.state(),
351 Some(StateEnum::PluggedInCharging | StateEnum::PluggedInDischarging)
352 )
353 }
354
355 /// The charging targets stored for one day (§9.3.9.5).
356 #[must_use]
357 pub fn targets_for(
358 &self,
359 day: TargetDayOfWeekBitmap,
360 ) -> heapless::Vec<ChargingTargetStruct, T> {
361 let index = DAYS.iter().position(|d| *d == day);
362 match index.and_then(|index| self.targets.borrow().get(index).cloned()) {
363 Some(targets) => targets,
364 None => heapless::Vec::new(),
365 }
366 }
367
368 /// §9.3.9.4: the EVSE finished its self-diagnostics.
369 ///
370 /// > Upon completion of the diagnostics, the EVSE SHALL restore SupplyState to the Disabled
371 /// > state.
372 pub fn diagnostics_complete(&self) {
373 if self.supply.get() == SupplyStateEnum::DisabledDiagnostics {
374 self.supply.set(SupplyStateEnum::Disabled);
375 }
376 }
377
378 /// Expires whichever enable windows have passed (§9.3.9.2.4, §9.3.9.3.3).
379 ///
380 /// > If the ChargingEnabledUntil time is not null, then when this time expires then the
381 /// > EVSE SHALL stop charging ... and SHALL update the SupplyState attribute to Disabled
382 /// > (if DischargingEnabledUntil is also in the past) or DischargingEnabled.
383 pub fn poll(&self) {
384 let before = self.supply.get();
385 self.resupply();
386 // The window ran out while current was flowing, so §9.3.9.1.1's rule applies just as
387 // it does to an explicit Disable: the transfer stopped, and a client watching the
388 // event log must be able to see that it was the EVSE's decision.
389 if before != self.supply.get() && self.transferring() {
390 self.record(Event::EnergyTransferStopped(
391 EnergyTransferStoppedReasonEnum::EVSEStopped,
392 ));
393 }
394 }
395
396 /// Recomputes `SupplyState` from the two windows.
397 fn resupply(&self) {
398 // Diagnostics and a fault are not the windows' to override.
399 if matches!(
400 self.supply.get(),
401 SupplyStateEnum::DisabledDiagnostics | SupplyStateEnum::DisabledError
402 ) {
403 return;
404 }
405 let charging = self.window_open(self.charging_until.get());
406 let discharging = self.window_open(self.discharging_until.get()) && self.has(feature::V2_X);
407 self.supply.set(match (charging, discharging) {
408 (true, true) => SupplyStateEnum::Enabled,
409 (true, false) => SupplyStateEnum::ChargingEnabled,
410 (false, true) => SupplyStateEnum::DischargingEnabled,
411 (false, false) => SupplyStateEnum::Disabled,
412 });
413 }
414
415 /// Whether an `epoch-s` window is still open.
416 ///
417 /// `None` is null — §9.3.8.4's "always enabled". Zero, or a moment already past, is
418 /// disabled. And when the EVSE has no clock, an open-ended reading is the only honest one:
419 /// the window was opened by a client and nothing here can say it has closed.
420 fn window_open(&self, until: Option<u32>) -> bool {
421 match until {
422 None => true,
423 Some(0) => false,
424 Some(until) => match self.hooks.utc() {
425 Some(now) => until > now,
426 None => true,
427 },
428 }
429 }
430
431 const fn has(&self, bit: u32) -> bool {
432 self.feature_map & bit != 0
433 }
434
435 /// Records an event for the device's own store.
436 ///
437 /// Public because most of §9.3.10's events are the *hardware's* to notice — a vehicle
438 /// plugged in, a fault detected — and only `EnergyTransferStopped` is ever this cluster's.
439 pub fn record(&self, event: Event) {
440 let mut events = self.events.borrow_mut();
441 if events.is_full() {
442 events.remove(0);
443 }
444 let _ = events.push(event);
445 }
446
447 /// Takes the event records the cluster has collected.
448 pub fn take_events(&self) -> heapless::Vec<Event, 8> {
449 core::mem::take(&mut self.events.borrow_mut())
450 }
451
452 /// §9.3.9.2.4 and §9.3.9.3.3's shared precondition.
453 fn refuses_commands(&self) -> bool {
454 self.hooks.fault() != FaultStateEnum::NoError
455 || self.supply.get() == SupplyStateEnum::DisabledDiagnostics
456 }
457
458 /// §9.3.9.5.2's validation and store.
459 fn set_targets(
460 &self,
461 schedules: crate::tlv::TlvList<'_, ChargingTargetScheduleStruct<'_>>,
462 ) -> Status {
463 let mut seen = TargetDayOfWeekBitmap::empty();
464 let mut staged: [Option<DayTargets<T>>; 7] = core::array::from_fn(|_| None);
465 let mut count = 0usize;
466 for schedule in schedules.iter() {
467 let Ok(schedule) = schedule else {
468 return Status::ConstraintError;
469 };
470 count = count.saturating_add(1);
471 if count > SCHEDULES_MAX {
472 // §9.3.9.5's constraint is "max 7", which is also exactly the number of days:
473 // an eighth schedule could only repeat one.
474 return Status::ConstraintError;
475 }
476 // "each day of the week is included in at most one of the ChargingTargetSchedule,
477 // if they are not then the response SHALL be CONSTRAINT_ERROR" — two schedules
478 // claiming Tuesday is a request with no single meaning.
479 if schedule.day_of_week_for_sequence.intersects(seen) {
480 return Status::ConstraintError;
481 }
482 seen |= schedule.day_of_week_for_sequence;
483
484 let mut targets: DayTargets<T> = heapless::Vec::new();
485 for target in schedule.charging_targets.iter() {
486 let Ok(target) = target else {
487 return Status::ConstraintError;
488 };
489 // §9.3.7.6's constraints: "max 1439" minutes, a percent, and "min 0" energy.
490 if target.target_time_minutes_past_midnight > MINUTES_MAX
491 || target.target_so_c.is_some_and(|soc| soc > 100)
492 || target.added_energy.is_some_and(|energy| energy < 0)
493 {
494 return Status::ConstraintError;
495 }
496 if targets.push(target).is_err() {
497 // §9.3.9.5.2: "When a command is received that requires a total number of
498 // charging targets greater than the device supports, the status of the
499 // response SHALL be RESOURCE_EXHAUSTED."
500 return Status::ResourceExhausted;
501 }
502 }
503 for (index, day) in DAYS.iter().enumerate() {
504 if schedule.day_of_week_for_sequence.contains(*day)
505 && let Some(slot) = staged.get_mut(index)
506 {
507 *slot = Some(targets.clone());
508 }
509 }
510 }
511 // Staged first, applied second: a schedule that fails validation half way through must
512 // not leave the user with three days of the new plan and four of the old.
513 let mut stored = self.targets.borrow_mut();
514 for (index, staged) in staged.into_iter().enumerate() {
515 if let (Some(staged), Some(slot)) = (staged, stored.get_mut(index)) {
516 *slot = staged;
517 }
518 }
519 drop(stored);
520 self.hooks.targets_changed();
521 Status::Success
522 }
523}
524
525impl<H: EvseHooks, const T: usize> ClusterHandler for EnergyEvse<'_, H, T> {
526 #[allow(clippy::too_many_lines)]
527 fn read(
528 &self,
529 resolved: &Resolved<'_>,
530 _ctx: &InteractionContext<'_>,
531 w: &mut TlvWriter<'_>,
532 tag: Tag,
533 ) -> Result<(), Status> {
534 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
535 let epoch = |w: &mut TlvWriter<'_>, value: Option<u32>| match value {
536 Some(value) => full(w.unsigned(tag, u64::from(value))),
537 None => full(w.null(tag)),
538 };
539 let energy = |w: &mut TlvWriter<'_>, value: Option<i64>| match value {
540 Some(value) => full(w.signed(tag, value)),
541 None => full(w.null(tag)),
542 };
543 let next = self.hooks.next_charge();
544 match resolved.attribute {
545 STATE => match self.hooks.state() {
546 Some(state) => full(w.unsigned(tag, u64::from(state.value()))),
547 None => full(w.null(tag)),
548 },
549 SUPPLY_STATE => full(w.unsigned(tag, u64::from(self.supply_state().value()))),
550 FAULT_STATE => full(w.unsigned(tag, u64::from(self.hooks.fault().value()))),
551 CHARGING_ENABLED_UNTIL => epoch(w, self.charging_until.get()),
552 DISCHARGING_ENABLED_UNTIL => epoch(w, self.discharging_until.get()),
553 CIRCUIT_CAPACITY => full(w.signed(tag, self.hooks.circuit_capacity())),
554 MINIMUM_CHARGE_CURRENT => full(w.signed(tag, self.minimum_charge_current.get())),
555 MAXIMUM_CHARGE_CURRENT => full(w.signed(tag, self.maximum_charge_current())),
556 MAXIMUM_DISCHARGE_CURRENT => full(w.signed(tag, self.maximum_discharge_current.get())),
557 USER_MAXIMUM_CHARGE_CURRENT => {
558 full(w.signed(tag, self.hooks.user_maximum_charge_current()))
559 }
560 RANDOMIZATION_DELAY_WINDOW => {
561 full(w.unsigned(tag, u64::from(self.hooks.randomization_delay_window())))
562 }
563 NEXT_CHARGE_START_TIME => epoch(w, next.start_time),
564 NEXT_CHARGE_TARGET_TIME => epoch(w, next.target_time),
565 NEXT_CHARGE_REQUIRED_ENERGY => energy(w, next.required_energy),
566 NEXT_CHARGE_TARGET_SO_C => match next.target_soc {
567 Some(soc) => full(w.unsigned(tag, u64::from(soc))),
568 None => full(w.null(tag)),
569 },
570 APPROXIMATE_EV_EFFICIENCY => match self.hooks.approximate_ev_efficiency() {
571 Some(value) => full(w.unsigned(tag, u64::from(value))),
572 None => full(w.null(tag)),
573 },
574 STATE_OF_CHARGE => match self.hooks.state_of_charge() {
575 Some(soc) => full(w.unsigned(tag, u64::from(soc))),
576 None => full(w.null(tag)),
577 },
578 BATTERY_CAPACITY => energy(w, self.hooks.battery_capacity()),
579 VEHICLE_ID => match self.hooks.vehicle_id() {
580 Some(id) => full(w.utf8(tag, id)),
581 None => full(w.null(tag)),
582 },
583 SESSION_ID => epoch(w, self.hooks.session_id()),
584 SESSION_DURATION => epoch(w, self.hooks.session_duration()),
585 SESSION_ENERGY_CHARGED => energy(w, self.hooks.session_energy_charged()),
586 SESSION_ENERGY_DISCHARGED => energy(w, self.hooks.session_energy_discharged()),
587 _ => Err(Status::UnsupportedAttribute),
588 }
589 }
590
591 fn invoke(
592 &self,
593 resolved: &ResolvedCommand<'_>,
594 fields: Option<&[u8]>,
595 _ctx: &InteractionContext<'_>,
596 w: &mut TlvWriter<'_>,
597 tag: Tag,
598 ) -> Result<Option<CommandId>, StatusIb> {
599 let payload = || fields.ok_or(StatusIb::from(Status::InvalidCommand));
600 match resolved.command.id {
601 DISABLE => {
602 // §9.3.9.1.1: "If the SupplyState attribute is already Disabled, a response
603 // with status of SUCCESS SHALL be returned." Not an error — the client asked
604 // for a state it is already in.
605 let transferring = self.transferring();
606 if !self.hooks.disable() {
607 return Err(Status::Failure.into());
608 }
609 // "the ChargingEnabledUntil and DischargingEnabledUntil attributes SHALL be
610 // set to 0x0" — zero, not null, because null means *always* enabled.
611 self.charging_until.set(Some(0));
612 self.discharging_until.set(Some(0));
613 if self.supply.get() != SupplyStateEnum::DisabledDiagnostics {
614 self.supply.set(SupplyStateEnum::Disabled);
615 }
616 if transferring {
617 self.record(Event::EnergyTransferStopped(
618 EnergyTransferStoppedReasonEnum::EVSEStopped,
619 ));
620 }
621 Ok(None)
622 }
623 ENABLE_CHARGING => {
624 let decoded: spec_evse::EnableChargingFields = super::decode_fields(payload()?)?;
625 if self.refuses_commands() {
626 return Err(Status::Failure.into());
627 }
628 // §9.3.9.2's constraint on both currents is "min 0": an EVSE cannot pass a
629 // negative current towards the vehicle, and a minimum above the maximum is a
630 // window with nothing in it.
631 if decoded.minimum_charge_current < 0
632 || decoded.maximum_charge_current < 0
633 || decoded.minimum_charge_current > decoded.maximum_charge_current
634 {
635 return Err(Status::ConstraintError.into());
636 }
637 let minimum = i64::from(decoded.minimum_charge_current);
638 let maximum = i64::from(decoded.maximum_charge_current);
639 if !self.hooks.enable_charging(minimum, maximum) {
640 return Err(Status::Failure.into());
641 }
642 self.minimum_charge_current.set(minimum);
643 self.maximum_charge_current.set(maximum);
644 self.charging_until.set(decoded.charging_enabled_until.0);
645 self.resupply();
646 Ok(None)
647 }
648 ENABLE_DISCHARGING => {
649 let decoded: spec_evse::EnableDischargingFields = super::decode_fields(payload()?)?;
650 if self.refuses_commands() {
651 return Err(Status::Failure.into());
652 }
653 if decoded.maximum_discharge_current < 0 {
654 return Err(Status::ConstraintError.into());
655 }
656 let maximum = i64::from(decoded.maximum_discharge_current);
657 if !self.hooks.enable_discharging(maximum) {
658 return Err(Status::Failure.into());
659 }
660 self.maximum_discharge_current.set(maximum);
661 self.discharging_until
662 .set(decoded.discharging_enabled_until.0);
663 self.resupply();
664 Ok(None)
665 }
666 START_DIAGNOSTICS => {
667 // §9.3.9.4.1: "the EVSE SHALL enter a Diagnostics state only if the SupplyState
668 // attribute is in the Disabled state" — running self-checks on a circuit that
669 // is passing current to a car is not a thing to do.
670 if self.supply_state() != SupplyStateEnum::Disabled
671 || !self.hooks.start_diagnostics()
672 {
673 return Err(Status::Failure.into());
674 }
675 self.supply.set(SupplyStateEnum::DisabledDiagnostics);
676 Ok(None)
677 }
678 SET_TARGETS => {
679 let decoded: spec_evse::SetTargetsFields<'_> = super::decode_fields(payload()?)?;
680 match self.set_targets(decoded.charging_target_schedules) {
681 Status::Success => Ok(None),
682 other => Err(other.into()),
683 }
684 }
685 GET_TARGETS => {
686 // §9.3.9.7: one schedule per day that has targets. Days with none are omitted
687 // rather than sent empty — an empty schedule is how `SetTargets` *clears* a
688 // day, so echoing one back would read as an instruction.
689 let full =
690 |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
691 let targets = self.targets.borrow();
692 full(w.start_structure(tag))?;
693 full(w.start_array(Tag::Context(0)))?;
694 for (index, day) in DAYS.iter().enumerate() {
695 let Some(day_targets) = targets.get(index) else {
696 continue;
697 };
698 if day_targets.is_empty() {
699 continue;
700 }
701 full(w.start_structure(Tag::Anonymous))?;
702 full(w.unsigned(Tag::Context(0), u64::from(day.bits())))?;
703 full(w.start_array(Tag::Context(1)))?;
704 for target in day_targets {
705 full(target.to_tlv(w, Tag::Anonymous))?;
706 }
707 full(w.end_container())?;
708 full(w.end_container())?;
709 }
710 full(w.end_container())?;
711 full(w.end_container())?;
712 Ok(Some(GET_TARGETS_RESPONSE))
713 }
714 CLEAR_TARGETS => {
715 for day in self.targets.borrow_mut().iter_mut() {
716 day.clear();
717 }
718 self.hooks.targets_changed();
719 Ok(None)
720 }
721 _ => Err(Status::UnsupportedCommand.into()),
722 }
723 }
724}
725
726/// So a tuple of clusters can dispatch to it by id.
727impl<H: EvseHooks, const T: usize> Cluster for EnergyEvse<'_, H, T> {
728 const ID: ClusterId = ID;
729}