|
| 1 | +# License: MIT |
| 2 | +# Copyright © 2022 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +"""Interactions with pools of ev chargers.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import asyncio |
| 9 | +import logging |
| 10 | +from collections.abc import Iterator |
| 11 | +from dataclasses import dataclass |
| 12 | +from enum import Enum |
| 13 | +from typing import Optional |
| 14 | + |
| 15 | +from frequenz.channels import Broadcast, Receiver |
| 16 | +from frequenz.channels.util import Merge |
| 17 | + |
| 18 | +from ... import microgrid |
| 19 | +from ..._internal.asyncio import cancel_and_await |
| 20 | +from ...microgrid.component import ( |
| 21 | + ComponentCategory, |
| 22 | + EVChargerCableState, |
| 23 | + EVChargerComponentState, |
| 24 | + EVChargerData, |
| 25 | +) |
| 26 | + |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
| 29 | + |
| 30 | +class EVChargerState(Enum): |
| 31 | + """State of individual ev charger.""" |
| 32 | + |
| 33 | + UNSPECIFIED = "UNSPECIFIED" |
| 34 | + IDLE = "IDLE" |
| 35 | + EV_PLUGGED = "EV_PLUGGED" |
| 36 | + EV_LOCKED = "EV_LOCKED" |
| 37 | + ERROR = "ERROR" |
| 38 | + |
| 39 | + @classmethod |
| 40 | + def from_ev_charger_data(cls, data: EVChargerData) -> EVChargerState: |
| 41 | + """Create an `EVChargerState` instance from component data. |
| 42 | +
|
| 43 | + Args: |
| 44 | + data: ev charger data coming from microgrid. |
| 45 | +
|
| 46 | + Returns: |
| 47 | + An `EVChargerState` instance. |
| 48 | + """ |
| 49 | + if data.component_state in ( |
| 50 | + EVChargerComponentState.AUTHORIZATION_REJECTED, |
| 51 | + EVChargerComponentState.ERROR, |
| 52 | + ): |
| 53 | + return EVChargerState.ERROR |
| 54 | + if data.cable_state == EVChargerCableState.EV_LOCKED: |
| 55 | + return EVChargerState.EV_LOCKED |
| 56 | + if data.cable_state == EVChargerCableState.EV_PLUGGED: |
| 57 | + return EVChargerState.EV_PLUGGED |
| 58 | + return EVChargerState.IDLE |
| 59 | + |
| 60 | + |
| 61 | +@dataclass(frozen=True) |
| 62 | +class EVChargerPoolStates: |
| 63 | + """States of all ev chargers in the pool.""" |
| 64 | + |
| 65 | + _states: dict[int, EVChargerState] |
| 66 | + _changed_component: Optional[int] = None |
| 67 | + |
| 68 | + def __iter__(self) -> Iterator[tuple[int, EVChargerState]]: |
| 69 | + """Iterate over states of all ev chargers. |
| 70 | +
|
| 71 | + Returns: |
| 72 | + An iterator over all ev charger states. |
| 73 | + """ |
| 74 | + return iter(self._states.items()) |
| 75 | + |
| 76 | + def latest_change(self) -> Optional[tuple[int, EVChargerState]]: |
| 77 | + """Return the most recent ev charger state change. |
| 78 | +
|
| 79 | + Returns: |
| 80 | + A tuple with the component ID of an ev charger that just had a state |
| 81 | + change, and its new state. |
| 82 | + """ |
| 83 | + if self._changed_component is None: |
| 84 | + return None |
| 85 | + return ( |
| 86 | + self._changed_component, |
| 87 | + self._states.setdefault( |
| 88 | + self._changed_component, EVChargerState.UNSPECIFIED |
| 89 | + ), |
| 90 | + ) |
| 91 | + |
| 92 | + |
| 93 | +class _StateTracker: |
| 94 | + """A class for keeping track of the states of all ev chargers in a pool.""" |
| 95 | + |
| 96 | + def __init__(self, comp_states: dict[int, EVChargerState]) -> None: |
| 97 | + """Create a `_StateTracker` instance. |
| 98 | +
|
| 99 | + Args: |
| 100 | + comp_states: initial states of all ev chargers in the pool. |
| 101 | + """ |
| 102 | + self._states = comp_states |
| 103 | + |
| 104 | + def get(self) -> EVChargerPoolStates: |
| 105 | + """Get a representation of the current states of all ev chargers. |
| 106 | +
|
| 107 | + Returns: |
| 108 | + An `EVChargerPoolStates` instance. |
| 109 | + """ |
| 110 | + return EVChargerPoolStates(self._states) |
| 111 | + |
| 112 | + def update( |
| 113 | + self, |
| 114 | + data: EVChargerData, |
| 115 | + ) -> Optional[EVChargerPoolStates]: |
| 116 | + """Update the state of an ev charger, from a new data point. |
| 117 | +
|
| 118 | + Args: |
| 119 | + data: component data from the microgrid, for an ev charger in the pool. |
| 120 | +
|
| 121 | + Returns: |
| 122 | + A new `EVChargerPoolStates` instance representing all the ev chargers in |
| 123 | + the pool, in case there has been a state change for any of the ev |
| 124 | + chargers, or `None` otherwise. |
| 125 | + """ |
| 126 | + evc_id = data.component_id |
| 127 | + new_state = EVChargerState.from_ev_charger_data(data) |
| 128 | + if evc_id not in self._states or self._states[evc_id] != new_state: |
| 129 | + self._states[evc_id] = new_state |
| 130 | + return EVChargerPoolStates(self._states, evc_id) |
| 131 | + return None |
| 132 | + |
| 133 | + |
| 134 | +class EVChargerPool: |
| 135 | + """Interactions with EV Chargers.""" |
| 136 | + |
| 137 | + def __init__( |
| 138 | + self, |
| 139 | + component_ids: Optional[set[int]] = None, |
| 140 | + ) -> None: |
| 141 | + """Create an `EVChargerPool` instance. |
| 142 | +
|
| 143 | + Args: |
| 144 | + component_ids: An optional list of component_ids belonging to this pool. If |
| 145 | + not specified, IDs of all ev chargers in the microgrid will be fetched |
| 146 | + from the component graph. |
| 147 | + """ |
| 148 | + self._component_ids = set() |
| 149 | + if component_ids is not None: |
| 150 | + self._component_ids = component_ids |
| 151 | + else: |
| 152 | + graph = microgrid.get().component_graph |
| 153 | + self._component_ids = { |
| 154 | + evc.component_id |
| 155 | + for evc in graph.components( |
| 156 | + component_category={ComponentCategory.EV_CHARGER} |
| 157 | + ) |
| 158 | + } |
| 159 | + self._channel = Broadcast[EVChargerPoolStates]( |
| 160 | + "EVCharger States", resend_latest=True |
| 161 | + ) |
| 162 | + self._task: Optional[asyncio.Task[None]] = None |
| 163 | + self._merged_stream: Optional[Merge] = None |
| 164 | + |
| 165 | + async def _run(self) -> None: |
| 166 | + logger.debug("Starting EVChargerPool for components: %s", self._component_ids) |
| 167 | + api_client = microgrid.get().api_client |
| 168 | + streams: list[Receiver[EVChargerData]] = await asyncio.gather( |
| 169 | + *[api_client.ev_charger_data(cid) for cid in self._component_ids] |
| 170 | + ) |
| 171 | + |
| 172 | + latest_messages: list[EVChargerData] = await asyncio.gather( |
| 173 | + *[stream.receive() for stream in streams] |
| 174 | + ) |
| 175 | + states = { |
| 176 | + msg.component_id: EVChargerState.from_ev_charger_data(msg) |
| 177 | + for msg in latest_messages |
| 178 | + } |
| 179 | + state_tracker = _StateTracker(states) |
| 180 | + self._merged_stream = Merge(*streams) |
| 181 | + sender = self._channel.new_sender() |
| 182 | + await sender.send(state_tracker.get()) |
| 183 | + async for data in self._merged_stream: |
| 184 | + if updated_states := state_tracker.update(data): |
| 185 | + await sender.send(updated_states) |
| 186 | + |
| 187 | + async def _stop(self) -> None: |
| 188 | + if self._task: |
| 189 | + await cancel_and_await(self._task) |
| 190 | + if self._merged_stream: |
| 191 | + await self._merged_stream.stop() |
| 192 | + |
| 193 | + def states(self) -> Receiver[EVChargerPoolStates]: |
| 194 | + """Return a receiver that streams ev charger states. |
| 195 | +
|
| 196 | + Returns: |
| 197 | + A receiver that streams the states of all ev chargers in the pool, every |
| 198 | + time the states of any of them change. |
| 199 | + """ |
| 200 | + if self._task is None or self._task.done(): |
| 201 | + self._task = asyncio.create_task(self._run()) |
| 202 | + return self._channel.new_receiver() |
0 commit comments