sme-ocpp-sim 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. sme_ocpp_sim/__init__.py +3 -0
  2. sme_ocpp_sim/__main__.py +65 -0
  3. sme_ocpp_sim/charging/__init__.py +5 -0
  4. sme_ocpp_sim/charging/composite.py +293 -0
  5. sme_ocpp_sim/charging/ev.py +99 -0
  6. sme_ocpp_sim/charging/power.py +143 -0
  7. sme_ocpp_sim/charging/profiles.py +216 -0
  8. sme_ocpp_sim/config.py +314 -0
  9. sme_ocpp_sim/configs/demo-site.yaml +46 -0
  10. sme_ocpp_sim/engine.py +485 -0
  11. sme_ocpp_sim/framelog.py +92 -0
  12. sme_ocpp_sim/protocol/__init__.py +1 -0
  13. sme_ocpp_sim/protocol/base.py +439 -0
  14. sme_ocpp_sim/protocol/registry.py +50 -0
  15. sme_ocpp_sim/protocol/v16/__init__.py +1 -0
  16. sme_ocpp_sim/protocol/v16/adapter.py +322 -0
  17. sme_ocpp_sim/protocol/v16/codec.py +171 -0
  18. sme_ocpp_sim/protocol/v16/config_keys.py +98 -0
  19. sme_ocpp_sim/protocol/v16/enums.py +255 -0
  20. sme_ocpp_sim/protocol/v16/models.py +398 -0
  21. sme_ocpp_sim/rpc/__init__.py +11 -0
  22. sme_ocpp_sim/rpc/connection.py +222 -0
  23. sme_ocpp_sim/rpc/errors.py +58 -0
  24. sme_ocpp_sim/rpc/framer.py +102 -0
  25. sme_ocpp_sim/rpc/transport.py +216 -0
  26. sme_ocpp_sim/runtime/__init__.py +1 -0
  27. sme_ocpp_sim/runtime/charger.py +1234 -0
  28. sme_ocpp_sim/runtime/config_store.py +128 -0
  29. sme_ocpp_sim/runtime/state.py +107 -0
  30. sme_ocpp_sim/static/app.js +967 -0
  31. sme_ocpp_sim/static/favicon.svg +5 -0
  32. sme_ocpp_sim/static/i18n/en.js +147 -0
  33. sme_ocpp_sim/static/i18n/ja.js +147 -0
  34. sme_ocpp_sim/static/i18n/zh.js +147 -0
  35. sme_ocpp_sim/static/index.html +237 -0
  36. sme_ocpp_sim/static/style.css +118 -0
  37. sme_ocpp_sim/web.py +573 -0
  38. sme_ocpp_sim-0.1.0.dist-info/METADATA +147 -0
  39. sme_ocpp_sim-0.1.0.dist-info/RECORD +44 -0
  40. sme_ocpp_sim-0.1.0.dist-info/WHEEL +5 -0
  41. sme_ocpp_sim-0.1.0.dist-info/entry_points.txt +2 -0
  42. sme_ocpp_sim-0.1.0.dist-info/licenses/LICENSE +21 -0
  43. sme_ocpp_sim-0.1.0.dist-info/licenses/THIRD-PARTY-NOTICES +68 -0
  44. sme_ocpp_sim-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3 @@
1
+ """SME OCPPSim: OCPP charging station simulator with a web UI."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,65 @@
1
+ """Command line entry point.
2
+
3
+ sme-ocpp-sim [run] [-c CONFIG] [--host 127.0.0.1] [--http-port 8082] [--no-browser]
4
+ sme-ocpp-sim --version
5
+
6
+ The common options and the web server start come from ``sme_sim_common.cli``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import logging
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ from sme_sim_common.cli import add_common_args, run_web
17
+
18
+ from . import __version__
19
+
20
+ APP_NAME = "sme-ocpp-sim"
21
+ DEFAULT_HTTP_PORT = 8082 # series port table (sme-sim-common README)
22
+ _PKG = Path(__file__).resolve().parent
23
+ # Default config when started without -c (as sme-modbus-sim / sme-bac-sim).
24
+ # Installed wheel: sme_ocpp_sim/configs; source tree, Docker image and Windows exe (PyInstaller puts the
25
+ # package under sys._MEIPASS, so __file__ resolves there): configs/ beside the package.
26
+ DEFAULT_CONFIG = next((p for p in (_PKG / "configs" / "demo-site.yaml", _PKG.parent / "configs" / "demo-site.yaml")
27
+ if p.exists()), _PKG.parent / "configs" / "demo-site.yaml")
28
+
29
+
30
+ def main(argv=None) -> int:
31
+ rest = sys.argv[1:] if argv is None else list(argv)
32
+ if rest[:1] == ["run"]:
33
+ rest = rest[1:]
34
+ ap = argparse.ArgumentParser(prog=APP_NAME,
35
+ description="OCPP charging station simulator with a web UI; "
36
+ "default config: the bundled configs/demo-site.yaml")
37
+ add_common_args(ap, default_http_port=DEFAULT_HTTP_PORT, app_name=APP_NAME, version=__version__,
38
+ templates=False)
39
+ args = ap.parse_args(rest)
40
+
41
+ logging.basicConfig(stream=sys.stdout, level=logging.DEBUG if args.verbose else logging.INFO,
42
+ format="%(asctime)s %(levelname)s %(name)s: %(message)s")
43
+
44
+ from .config import SimConfig, load_file
45
+ from .engine import OcppEngine
46
+
47
+ path = args.config
48
+ if path is None and DEFAULT_CONFIG.exists():
49
+ path = str(DEFAULT_CONFIG)
50
+ try:
51
+ cfg = load_file(path) if path else SimConfig()
52
+ text = Path(path).read_text(encoding="utf-8") if path else None
53
+ engine = OcppEngine(cfg, config_text=text, config_path=path)
54
+ except Exception as e: # noqa: BLE001
55
+ print(f"config error: {e}", file=sys.stderr)
56
+ return 2
57
+
58
+ from .web import create_app
59
+
60
+ run_web(create_app(engine, path), args, name=f"SME OCPPSim v{__version__}")
61
+ return 0
62
+
63
+
64
+ if __name__ == "__main__":
65
+ sys.exit(main())
@@ -0,0 +1,5 @@
1
+ """Version-neutral smart charging and power model (plan §5 M4).
2
+
3
+ ``profiles`` holds installed charging profiles, ``composite`` evaluates them into a composite schedule and the
4
+ live power limit. Nothing here imports a protocol package; version adapters convert into these domain types.
5
+ """
@@ -0,0 +1,293 @@
1
+ """Composite charging schedule and live power limit from one evaluator (design §3.3, plan §6.1).
2
+
3
+ :func:`composite_schedule` answers GetCompositeSchedule; :func:`limit_at` is the limit the power model applies
4
+ each tick and is literally the first period of a one-second composite schedule, so the schedule reported to the
5
+ CSMS and the power actually drawn cannot diverge (C12).
6
+
7
+ Rules implemented from OCPP 1.6 edition 2 (and its errata sheet v4.0):
8
+
9
+ - 3.13.2: per purpose, the prevailing profile is the valid one (validFrom/validTo) with the highest stackLevel;
10
+ when its schedule is not running (not started, ``duration`` elapsed) the next lower stackLevel applies
11
+ (errata 3.43); without any profile there is no limit.
12
+ - 3.13.1 / 3.13.3: TxProfile overrules TxDefaultProfile for the current transaction; the result is the minimum
13
+ of that and ChargePointMaxProfile. A connector-specific TxDefaultProfile replaces the connector-0 one with
14
+ the same stackLevel for that connector only.
15
+ - 7.9 / 7.13: Absolute starts at ``startSchedule``; Relative and Absolute without ``startSchedule`` start at the
16
+ transaction start; Recurring restarts every day/week; a ``duration`` longer than the recurrence is cut to
17
+ the recurrence (errata 3.43/3.44).
18
+ - 7.12 / 7.14: W = A x line voltage x phases, phases = ``numberPhases`` or 3 if absent; errata 3.34: a profile
19
+ with more phases than the charger has applies its limit to the phases actually available.
20
+ - 5.7: the schedule covers [start, start + duration); connectorId 0 reports the whole charger's grid draw.
21
+
22
+ Interpretations (not defined by the spec)
23
+ -----------------------------------------
24
+ - Relative schedules (and Absolute without startSchedule) with no transaction on the connector use the start
25
+ of the requested window as origin (5.7, 7.13 checked). ChargePointMaxProfiles always use the window start.
26
+ Hence :func:`limit_at` without a transaction always sees the first period of a Relative schedule.
27
+ - Recurring without ``startSchedule`` is anchored at 00:00 UTC (Daily) or Monday 00:00 UTC (Weekly); the
28
+ recurrence also extends before ``startSchedule`` (which only fixes the time of day / week; 7.8, 7.9 checked).
29
+ - validFrom is inclusive, validTo is exclusive (7.8 checked).
30
+ - connectorId 0 = min(ChargePointMax, sum over connectors 1..N of their TxProfile/TxDefault limit); if any
31
+ connector is unconstrained the sum is unconstrained (5.7, 3.13.3 checked). Idle connectors (no transaction)
32
+ are included: they contribute their TxDefault limit, or make the sum unconstrained if they have none, so the
33
+ value is the most the charger *may* draw, not what it draws now. A single connector gets the full
34
+ ChargePointMax value (no sharing between connectors is modelled here).
35
+ - ``minChargingRate`` does not alter the limit; refusing to charge below it is the EV model's job (7.13 checked).
36
+ - An unconstrained interval is reported as ``limit=None``; the adapter decides how to encode it. No unit given
37
+ -> W. Limits are returned unrounded except for float noise (6 decimals); 1-decimal rounding is the adapter's.
38
+ - Period boundaries falling between whole seconds start at the next whole second (startPeriod is an integer).
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import math
44
+ from dataclasses import dataclass, field
45
+ from datetime import datetime, timedelta, timezone
46
+ from typing import Iterator, List, Mapping, Optional, Sequence, Tuple, cast
47
+
48
+ from sme_ocpp_sim.charging.profiles import (
49
+ ChargingProfile,
50
+ ChargingProfileKind,
51
+ ChargingProfilePurpose,
52
+ ChargingRateUnit,
53
+ ProfileStore,
54
+ RecurrencyKind,
55
+ SchedulePeriod,
56
+ )
57
+
58
+ DEFAULT_VOLTAGE = 230.0 # set line-to-neutral voltage (7.12 example)
59
+ DEFAULT_PHASES = 3 # numberPhases absent -> 3 (7.12, 7.14)
60
+
61
+ _ZERO = timedelta(0)
62
+ _RECURRENCE = {RecurrencyKind.DAILY: timedelta(days=1), RecurrencyKind.WEEKLY: timedelta(weeks=1)}
63
+ _ANCHOR = {
64
+ RecurrencyKind.DAILY: datetime(1970, 1, 1, tzinfo=timezone.utc),
65
+ RecurrencyKind.WEEKLY: datetime(1970, 1, 5, tzinfo=timezone.utc), # a Monday
66
+ }
67
+
68
+ _Limit = Tuple[float, int] # (watts, effective phases)
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class ActiveTransaction:
73
+ transaction_id: int
74
+ start: datetime
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class CompositePeriod:
79
+ start_period: int # seconds from CompositeSchedule.start
80
+ limit: Optional[float] # None = unconstrained
81
+ number_phases: Optional[int] = None # set for unit A only
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class CompositeSchedule:
86
+ connector_id: int
87
+ start: datetime
88
+ duration: int
89
+ unit: ChargingRateUnit
90
+ periods: Tuple[CompositePeriod, ...]
91
+
92
+
93
+ def convert(value: float, src: ChargingRateUnit, dst: ChargingRateUnit, phases: int, voltage: float) -> float:
94
+ """A (per phase) <-> W: P = U x I x phases."""
95
+ if src is dst:
96
+ return value
97
+ if src is ChargingRateUnit.A:
98
+ return value * voltage * phases
99
+ return value / (voltage * phases)
100
+
101
+
102
+ @dataclass
103
+ class _Context:
104
+ store: ProfileStore
105
+ transactions: Mapping[int, ActiveTransaction]
106
+ phases: int
107
+ voltage: float
108
+ window_start: datetime
109
+ _cache: dict = field(default_factory=dict)
110
+
111
+ def relative_origin(self, connector_id: int) -> datetime:
112
+ tx = self.transactions.get(connector_id)
113
+ return tx.start if tx else self.window_start
114
+
115
+ def candidates(self, connector_id: int, purpose: ChargingProfilePurpose) -> List[ChargingProfile]:
116
+ key = (connector_id, purpose)
117
+ if key not in self._cache:
118
+ own = [ip.profile for ip in self.store.profiles(connector_id) if ip.profile.purpose is purpose]
119
+ if purpose is ChargingProfilePurpose.TX:
120
+ tx = self.transactions.get(connector_id)
121
+ own = [p for p in own if tx and p.transaction_id in (None, tx.transaction_id)]
122
+ elif purpose is ChargingProfilePurpose.TX_DEFAULT and connector_id != 0:
123
+ levels = {p.stack_level for p in own}
124
+ own += [
125
+ ip.profile
126
+ for ip in self.store.profiles(0)
127
+ if ip.profile.purpose is purpose and ip.profile.stack_level not in levels
128
+ ]
129
+ self._cache[key] = sorted(own, key=lambda p: p.stack_level, reverse=True)
130
+ return self._cache[key]
131
+
132
+
133
+ def _origin(profile: ChargingProfile, t: datetime, rel_origin: datetime) -> Tuple[datetime, Optional[timedelta]]:
134
+ """Schedule origin in force at ``t`` and the effective schedule duration."""
135
+ sched = profile.schedule
136
+ duration = timedelta(seconds=sched.duration) if sched.duration is not None else None
137
+ if profile.kind is ChargingProfileKind.RECURRING:
138
+ kind = profile.recurrency_kind or RecurrencyKind.DAILY
139
+ period = _RECURRENCE[kind]
140
+ anchor = sched.start_schedule or _ANCHOR[kind]
141
+ origin = anchor + ((t - anchor) // period) * period
142
+ return origin, min(duration, period) if duration is not None else period
143
+ if profile.kind is ChargingProfileKind.ABSOLUTE and sched.start_schedule is not None:
144
+ return sched.start_schedule, duration
145
+ return rel_origin, duration
146
+
147
+
148
+ def _period_at(profile: ChargingProfile, t: datetime, rel_origin: datetime) -> Optional[SchedulePeriod]:
149
+ if (profile.valid_from and t < profile.valid_from) or (profile.valid_to and t >= profile.valid_to):
150
+ return None
151
+ origin, duration = _origin(profile, t, rel_origin)
152
+ offset = t - origin
153
+ if offset < _ZERO or (duration is not None and offset >= duration):
154
+ return None
155
+ seconds = offset.total_seconds()
156
+ current = None
157
+ for period in profile.schedule.periods:
158
+ if period.start_period > seconds:
159
+ break
160
+ current = period
161
+ return current
162
+
163
+
164
+ def _prevailing(ctx: _Context, profiles: Sequence[ChargingProfile], t: datetime, rel: datetime) -> Optional[_Limit]:
165
+ for profile in profiles:
166
+ period = _period_at(profile, t, rel)
167
+ if period is not None:
168
+ phases = min(period.number_phases or DEFAULT_PHASES, ctx.phases)
169
+ watts = convert(period.limit, profile.schedule.unit, ChargingRateUnit.W, phases, ctx.voltage)
170
+ return watts, phases
171
+ return None
172
+
173
+
174
+ def _min(a: Optional[_Limit], b: Optional[_Limit]) -> Optional[_Limit]:
175
+ if a is None or b is None:
176
+ return a if b is None else b
177
+ return a if a[0] <= b[0] else b
178
+
179
+
180
+ def _tx_limit(ctx: _Context, connector_id: int, t: datetime) -> Optional[_Limit]:
181
+ rel = ctx.relative_origin(connector_id)
182
+ tx = _prevailing(ctx, ctx.candidates(connector_id, ChargingProfilePurpose.TX), t, rel)
183
+ if tx is not None:
184
+ return tx
185
+ return _prevailing(ctx, ctx.candidates(connector_id, ChargingProfilePurpose.TX_DEFAULT), t, rel)
186
+
187
+
188
+ def _limit(ctx: _Context, connector_id: int, t: datetime) -> Optional[_Limit]:
189
+ cp_max = _prevailing(ctx, ctx.candidates(0, ChargingProfilePurpose.CHARGE_POINT_MAX), t, ctx.window_start)
190
+ if connector_id != 0:
191
+ return _min(cp_max, _tx_limit(ctx, connector_id, t))
192
+ parts = [_tx_limit(ctx, c, t) for c in range(1, ctx.store.connector_count + 1)]
193
+ if not parts or any(p is None for p in parts):
194
+ return cp_max # no connectors, or one is unconstrained
195
+ return _min(cp_max, (sum(cast(_Limit, p)[0] for p in parts), ctx.phases))
196
+
197
+
198
+ def _boundaries(
199
+ profile: ChargingProfile, rel_origins: Sequence[datetime], start: datetime, end: datetime
200
+ ) -> Iterator[datetime]:
201
+ """Every instant at which ``profile`` may start, stop or change period (superset is fine)."""
202
+ for t in (profile.valid_from, profile.valid_to):
203
+ if t is not None:
204
+ yield t
205
+ offsets = [timedelta(seconds=p.start_period) for p in profile.schedule.periods]
206
+ if profile.kind is ChargingProfileKind.RECURRING:
207
+ origin, duration = _origin(profile, start, start)
208
+ recurrence = _RECURRENCE[profile.recurrency_kind or RecurrencyKind.DAILY]
209
+ while origin < end:
210
+ yield from (origin + o for o in offsets if duration is None or o < duration)
211
+ if duration is not None:
212
+ yield origin + duration
213
+ origin += recurrence
214
+ return
215
+ origins = {_origin(profile, start, r)[0] for r in rel_origins}
216
+ duration = _origin(profile, start, start)[1]
217
+ for origin in origins:
218
+ yield from (origin + o for o in offsets)
219
+ if duration is not None:
220
+ yield origin + duration
221
+
222
+
223
+ def composite_schedule(
224
+ store: ProfileStore,
225
+ connector_id: int,
226
+ start: datetime,
227
+ duration: int,
228
+ unit: Optional[ChargingRateUnit] = None,
229
+ *,
230
+ transactions: Optional[Mapping[int, ActiveTransaction]] = None,
231
+ number_phases: int = DEFAULT_PHASES,
232
+ voltage: float = DEFAULT_VOLTAGE,
233
+ ) -> CompositeSchedule:
234
+ """Composite schedule over [start, start + duration) seconds.
235
+
236
+ ``transactions`` maps connectorId -> its active transaction; ``number_phases`` / ``voltage`` describe the
237
+ charger's supply. Raises ``ValueError`` for an unknown connector (adapter -> Rejected), a non-positive
238
+ duration or a naive ``start``.
239
+ """
240
+ if start.tzinfo is None:
241
+ raise ValueError("start must be timezone-aware")
242
+ if duration < 1:
243
+ raise ValueError("duration must be >= 1 s")
244
+ if not 0 <= connector_id <= store.connector_count:
245
+ raise ValueError(f"unknown connector {connector_id}")
246
+ out_unit = unit or ChargingRateUnit.W
247
+ txs = transactions or {}
248
+ ctx = _Context(store, txs, number_phases, voltage, start)
249
+ end = start + timedelta(seconds=duration)
250
+ rel_origins = [start, *(tx.start for tx in txs.values())]
251
+
252
+ offsets = {0}
253
+ for ip in store.profiles():
254
+ for b in _boundaries(ip.profile, rel_origins, start, end):
255
+ if start < b < end:
256
+ offsets.add(math.ceil((b - start).total_seconds()))
257
+
258
+ periods: List[CompositePeriod] = []
259
+ for offset in sorted(o for o in offsets if o < duration):
260
+ lim = _limit(ctx, connector_id, start + timedelta(seconds=offset))
261
+ if lim is None:
262
+ period = CompositePeriod(offset, None)
263
+ else:
264
+ value = round(convert(lim[0], ChargingRateUnit.W, out_unit, lim[1], voltage), 6)
265
+ phases = lim[1] if out_unit is ChargingRateUnit.A else None
266
+ period = CompositePeriod(offset, value, phases)
267
+ if periods and (periods[-1].limit, periods[-1].number_phases) == (period.limit, period.number_phases):
268
+ continue
269
+ periods.append(period)
270
+ return CompositeSchedule(connector_id, start, duration, out_unit, tuple(periods))
271
+
272
+
273
+ def limit_at(
274
+ store: ProfileStore,
275
+ connector_id: int,
276
+ now: datetime,
277
+ *,
278
+ transactions: Optional[Mapping[int, ActiveTransaction]] = None,
279
+ number_phases: int = DEFAULT_PHASES,
280
+ voltage: float = DEFAULT_VOLTAGE,
281
+ ) -> Optional[float]:
282
+ """Limit in W in force at ``now`` (None = unconstrained); the first period of a 1 s composite schedule."""
283
+ schedule = composite_schedule(
284
+ store,
285
+ connector_id,
286
+ now,
287
+ 1,
288
+ ChargingRateUnit.W,
289
+ transactions=transactions,
290
+ number_phases=number_phases,
291
+ voltage=voltage,
292
+ )
293
+ return schedule.periods[0].limit
@@ -0,0 +1,99 @@
1
+ """EV model: battery, AC acceptance limits and a CC-CV-like SoC taper (pure data + functions).
2
+
3
+ Modelling choices (simulator conventions, not defined by OCPP):
4
+
5
+ - The taper is a piecewise-linear table ``SoC% -> fraction of max AC power`` (design §3.2/§7, e.g.
6
+ ``[[0, 1.0], [80, 1.0], [100, 0.1]]`` = constant power to 80 %, then linear convergence). SoC outside the
7
+ table is clamped to the first / last point.
8
+ - AC acceptance is ``min(max_ac_w * fraction, max_current_a * V_phase * phases_used)`` where
9
+ ``phases_used = min(ev.phases, supply phases)``; the EV accepts 0 W once ``soc_pct >= target_soc_pct``.
10
+ - ``min_current_a`` (default 6 A, the lowest current an IEC 61851-1 control pilot can signal) is the least
11
+ per-phase current the on-board charger can run on; :mod:`.power` treats a lower EVSE offer as no offer.
12
+ - ``efficiency`` is the grid-to-battery efficiency used to convert metered energy into SoC.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Dict, Tuple
19
+
20
+ Curve = Tuple[Tuple[float, float], ...]
21
+
22
+ #: Constant power up to 80 % SoC, then linear down to 10 % of max at 100 % (design §7 example).
23
+ DEFAULT_CURVE: Curve = ((0.0, 1.0), (80.0, 1.0), (100.0, 0.1))
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class EvModel:
28
+ id: str
29
+ capacity_kwh: float
30
+ max_ac_w: float
31
+ max_current_a: float
32
+ phases: int = 1
33
+ min_current_a: float = 6.0
34
+ efficiency: float = 0.9
35
+ curve: Curve = DEFAULT_CURVE
36
+
37
+ def __post_init__(self) -> None:
38
+ if self.capacity_kwh <= 0 or self.max_ac_w <= 0 or self.max_current_a <= 0:
39
+ raise ValueError("capacity_kwh, max_ac_w and max_current_a must be > 0")
40
+ if self.phases not in (1, 2, 3):
41
+ raise ValueError("phases must be 1, 2 or 3")
42
+ if not 0 <= self.min_current_a <= self.max_current_a:
43
+ raise ValueError("min_current_a must be within [0, max_current_a]")
44
+ if not 0 < self.efficiency <= 1:
45
+ raise ValueError("efficiency must be in (0, 1]")
46
+ validate_curve(self.curve)
47
+
48
+
49
+ def validate_curve(curve: Curve) -> None:
50
+ """Require >= 1 point, strictly increasing SoC within [0, 100] and fractions within [0, 1]."""
51
+ if not curve:
52
+ raise ValueError("curve needs at least one point")
53
+ prev = -1.0
54
+ for soc, frac in curve:
55
+ if not 0 <= soc <= 100 or not 0 <= frac <= 1:
56
+ raise ValueError(f"curve point out of range: ({soc}, {frac})")
57
+ if soc <= prev:
58
+ raise ValueError("curve SoC values must be strictly increasing")
59
+ prev = soc
60
+
61
+
62
+ def curve_fraction(curve: Curve, soc_pct: float) -> float:
63
+ """Linear interpolation of the taper table at ``soc_pct`` (clamped to the table ends)."""
64
+ if soc_pct <= curve[0][0]:
65
+ return curve[0][1]
66
+ for (s0, f0), (s1, f1) in zip(curve, curve[1:]):
67
+ if soc_pct <= s1:
68
+ return f0 + (f1 - f0) * (soc_pct - s0) / (s1 - s0)
69
+ return curve[-1][1]
70
+
71
+
72
+ def ev_max_power_w(ev: EvModel, soc_pct: float, phase_voltage_v: float, phases_used: int) -> float:
73
+ """Power the EV can take at ``soc_pct`` (taper and current limit; ignores the target SoC)."""
74
+ by_current = ev.max_current_a * phase_voltage_v * phases_used
75
+ return min(ev.max_ac_w * curve_fraction(ev.curve, soc_pct), by_current)
76
+
77
+
78
+ def ev_accept_w(ev: EvModel, soc_pct: float, target_soc_pct: float,
79
+ phase_voltage_v: float, phases_used: int) -> float:
80
+ """EV acceptance: 0 once the target SoC is reached, otherwise :func:`ev_max_power_w`."""
81
+ if soc_pct >= target_soc_pct:
82
+ return 0.0
83
+ return ev_max_power_w(ev, soc_pct, phase_voltage_v, phases_used)
84
+
85
+
86
+ def ev_min_power_w(ev: EvModel, phase_voltage_v: float, phases_used: int) -> float:
87
+ """Lowest power the on-board charger can run at (``min_current_a`` on every used phase)."""
88
+ return ev.min_current_a * phase_voltage_v * phases_used
89
+
90
+
91
+ #: Illustrative presets (not specific vehicles). ``compact-40kwh`` mirrors the design §7 example.
92
+ PRESETS: Dict[str, EvModel] = {
93
+ m.id: m
94
+ for m in (
95
+ EvModel("kei-20kwh", capacity_kwh=20, max_ac_w=3000, max_current_a=15, phases=1),
96
+ EvModel("compact-40kwh", capacity_kwh=40, max_ac_w=6000, max_current_a=30, phases=1),
97
+ EvModel("midsize-60kwh", capacity_kwh=60, max_ac_w=11000, max_current_a=16, phases=3),
98
+ )
99
+ }
@@ -0,0 +1,143 @@
1
+ """Power model step (design §3.2): EVSE limit + EV acceptance -> delivered power, energy register, SoC.
2
+
3
+ Pure and deterministic: the caller owns :class:`PowerState` and feeds it back each tick.
4
+
5
+ Modelling choices (simulator conventions, not defined by OCPP):
6
+
7
+ - ``target = min(evse_max_w, evse_limit_w, ev_accept_w)``; ``evse_limit_w=None`` means "no schedule limit".
8
+ - Suspension (the cause, reported independently of the ramp):
9
+ ``SuspendedEV`` if the EV accepts 0 W (target SoC reached, or a zero taper) or its acceptance has tapered
10
+ below its own minimum usable power (``ev.min_current_a`` per used phase; end-of-charge taper), checked first;
11
+ otherwise ``SuspendedEVSE`` if the EVSE offer is 0 W or below that minimum -- the EV cannot run on it.
12
+ Either way the target becomes 0 W.
13
+ - Ramp: power moves toward the target at ``ramp_up_w_per_s`` / ``ramp_down_w_per_s`` (``None`` = step
14
+ change). Default ramp-down is a step change, so a lowered limit is honoured within the same tick.
15
+ - ``time_scale`` multiplies the caller's elapsed ``dt_s`` into simulated seconds; *everything* time-based
16
+ in this module (ramp, energy, SoC) advances by ``dt_s * time_scale``.
17
+ - Energy uses the trapezoid of the previous and new power over the step; the register only grows.
18
+ SoC += energy * efficiency / capacity; it is not clipped at the target, so it may overshoot it by at
19
+ most one step's worth (then the EV accepts 0 W).
20
+ - Electrical: ``P = V_phase * I * phases``. ``AcSupply.voltage_v`` is the nominal supply voltage; with
21
+ ``line_to_line=True`` (e.g. Japanese 3-phase 200 V delta) the per-phase voltage on a 3-phase supply is
22
+ ``voltage_v / sqrt(3)``, so ``P = sqrt(3) * V_LL * I``. Single-phase always uses ``voltage_v``.
23
+ Phases in use = ``min(ev.phases, supply.phases)``; current is balanced across them.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import math
29
+ from dataclasses import dataclass, replace
30
+ from typing import Literal, Optional
31
+
32
+ from .ev import EvModel, ev_accept_w, ev_min_power_w
33
+
34
+ Suspension = Literal["SuspendedEV", "SuspendedEVSE"]
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class AcSupply:
39
+ voltage_v: float = 200.0
40
+ phases: int = 1
41
+ line_to_line: bool = False
42
+
43
+ def __post_init__(self) -> None:
44
+ if self.voltage_v <= 0:
45
+ raise ValueError("voltage_v must be > 0")
46
+ if self.phases not in (1, 2, 3):
47
+ raise ValueError("phases must be 1, 2 or 3")
48
+
49
+ def phase_voltage_v(self) -> float:
50
+ """Voltage across each phase load used in ``P = V_phase * I * phases``."""
51
+ if self.line_to_line and self.phases == 3:
52
+ return self.voltage_v / math.sqrt(3)
53
+ return self.voltage_v
54
+
55
+ def phases_used(self, ev: EvModel) -> int:
56
+ return min(ev.phases, self.phases)
57
+
58
+
59
+ def amps_to_watts(current_a: float, supply: AcSupply, phases: int) -> float:
60
+ """Per-phase current limit (e.g. a profile in A) -> active power over ``phases`` phases."""
61
+ return current_a * supply.phase_voltage_v() * phases
62
+
63
+
64
+ def watts_to_amps(power_w: float, supply: AcSupply, phases: int) -> float:
65
+ """Active power -> balanced per-phase current over ``phases`` phases."""
66
+ return power_w / (supply.phase_voltage_v() * phases)
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class PowerState:
71
+ soc_pct: float
72
+ power_w: float = 0.0
73
+ energy_wh: float = 0.0 # Energy.Active.Import.Register, monotonic
74
+ target_w: float = 0.0 # power the step was heading for (before the ramp)
75
+ suspension: Optional[Suspension] = None
76
+
77
+
78
+ def _ramp(current_w: float, target_w: float, sim_dt_s: float,
79
+ up_w_per_s: Optional[float], down_w_per_s: Optional[float]) -> float:
80
+ rate = up_w_per_s if target_w > current_w else down_w_per_s
81
+ if rate is None:
82
+ return target_w
83
+ max_delta = rate * sim_dt_s
84
+ return current_w + max(-max_delta, min(max_delta, target_w - current_w))
85
+
86
+
87
+ def step(state: PowerState, *, dt_s: float, ev: EvModel, target_soc_pct: float,
88
+ evse_limit_w: Optional[float], evse_max_w: float, supply: AcSupply,
89
+ ramp_up_w_per_s: Optional[float] = None, ramp_down_w_per_s: Optional[float] = None,
90
+ time_scale: float = 1.0) -> PowerState:
91
+ """Advance one tick of ``dt_s`` caller seconds (``dt_s * time_scale`` simulated seconds)."""
92
+ if dt_s < 0 or time_scale <= 0:
93
+ raise ValueError("dt_s must be >= 0 and time_scale > 0")
94
+ for rate in (ramp_up_w_per_s, ramp_down_w_per_s):
95
+ if rate is not None and rate <= 0:
96
+ raise ValueError("ramp rates must be > 0 or None")
97
+ sim_dt_s = dt_s * time_scale
98
+ v_phase = supply.phase_voltage_v()
99
+ n = supply.phases_used(ev)
100
+
101
+ offer_w = evse_max_w if evse_limit_w is None else min(evse_max_w, evse_limit_w)
102
+ offer_w = max(0.0, offer_w)
103
+ accept_w = ev_accept_w(ev, state.soc_pct, target_soc_pct, v_phase, n)
104
+
105
+ min_w = ev_min_power_w(ev, v_phase, n)
106
+ suspension: Optional[Suspension] = None
107
+ if accept_w <= 0 or accept_w < min_w:
108
+ suspension, target_w = "SuspendedEV", 0.0
109
+ elif offer_w <= 0 or offer_w < min_w:
110
+ suspension, target_w = "SuspendedEVSE", 0.0
111
+ else:
112
+ target_w = min(offer_w, accept_w)
113
+
114
+ power_w = _ramp(state.power_w, target_w, sim_dt_s, ramp_up_w_per_s, ramp_down_w_per_s)
115
+ delta_wh = (state.power_w + power_w) / 2 * sim_dt_s / 3600.0
116
+ soc_pct = min(100.0, state.soc_pct + delta_wh * ev.efficiency / (ev.capacity_kwh * 10.0))
117
+ return replace(state, soc_pct=soc_pct, power_w=power_w, energy_wh=state.energy_wh + delta_wh,
118
+ target_w=target_w, suspension=suspension)
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class MeterReading:
123
+ """Values for the 1.6 measurands Power.Active.Import (W), Current.Import (A, per phase),
124
+ Voltage (V), Energy.Active.Import.Register (Wh) and SoC (Percent)."""
125
+
126
+ power_active_import_w: float
127
+ current_import_a: float # per phase, balanced over ``phases``
128
+ voltage_v: float # nominal supply voltage as configured
129
+ energy_active_import_register_wh: float
130
+ soc_pct: float
131
+ phases: int
132
+
133
+
134
+ def meter_reading(state: PowerState, ev: EvModel, supply: AcSupply) -> MeterReading:
135
+ n = supply.phases_used(ev)
136
+ return MeterReading(
137
+ power_active_import_w=state.power_w,
138
+ current_import_a=watts_to_amps(state.power_w, supply, n),
139
+ voltage_v=supply.voltage_v,
140
+ energy_active_import_register_wh=state.energy_wh,
141
+ soc_pct=state.soc_pct,
142
+ phases=n,
143
+ )