ocpp-sdk 1.0.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.
- ocpp_sdk/__init__.py +35 -0
- ocpp_sdk/_internal/__init__.py +1 -0
- ocpp_sdk/_internal/dispatch.py +46 -0
- ocpp_sdk/_internal/lifecycle.py +284 -0
- ocpp_sdk/datetime.py +67 -0
- ocpp_sdk/errors.py +129 -0
- ocpp_sdk/model.py +210 -0
- ocpp_sdk/ocppj/__init__.py +15 -0
- ocpp_sdk/ocppj/endpoint.py +321 -0
- ocpp_sdk/ocppj/frames.py +237 -0
- ocpp_sdk/ocppj/registry.py +166 -0
- ocpp_sdk/py.typed +0 -0
- ocpp_sdk/transport/__init__.py +7 -0
- ocpp_sdk/transport/auth.py +179 -0
- ocpp_sdk/transport/client.py +242 -0
- ocpp_sdk/transport/connection.py +54 -0
- ocpp_sdk/transport/server.py +293 -0
- ocpp_sdk/v16/__init__.py +35 -0
- ocpp_sdk/v16/charge_point.py +174 -0
- ocpp_sdk/v16/charge_point_handlers.py +974 -0
- ocpp_sdk/v16/core.py +751 -0
- ocpp_sdk/v16/csms.py +210 -0
- ocpp_sdk/v16/csms_handlers.py +1786 -0
- ocpp_sdk/v16/firmware.py +176 -0
- ocpp_sdk/v16/localauth.py +113 -0
- ocpp_sdk/v16/remotetrigger.py +58 -0
- ocpp_sdk/v16/reservation.py +112 -0
- ocpp_sdk/v16/security.py +605 -0
- ocpp_sdk/v16/smartcharging.py +179 -0
- ocpp_sdk/v16/transaction_queue.py +384 -0
- ocpp_sdk/v16/types.py +1085 -0
- ocpp_sdk/v201/__init__.py +61 -0
- ocpp_sdk/v201/appendices.py +1926 -0
- ocpp_sdk/v201/authorization.py +123 -0
- ocpp_sdk/v201/availability.py +169 -0
- ocpp_sdk/v201/charging_station.py +190 -0
- ocpp_sdk/v201/charging_station_handlers.py +1687 -0
- ocpp_sdk/v201/csms.py +230 -0
- ocpp_sdk/v201/csms_handlers.py +2974 -0
- ocpp_sdk/v201/datatransfer.py +69 -0
- ocpp_sdk/v201/diagnostics.py +653 -0
- ocpp_sdk/v201/displaymessage.py +227 -0
- ocpp_sdk/v201/firmware.py +299 -0
- ocpp_sdk/v201/iso15118.py +305 -0
- ocpp_sdk/v201/localauthlist.py +129 -0
- ocpp_sdk/v201/metervalues.py +66 -0
- ocpp_sdk/v201/provisioning.py +466 -0
- ocpp_sdk/v201/remotecontrol.py +252 -0
- ocpp_sdk/v201/reservation.py +176 -0
- ocpp_sdk/v201/security.py +177 -0
- ocpp_sdk/v201/smartcharging.py +540 -0
- ocpp_sdk/v201/tariffandcost.py +62 -0
- ocpp_sdk/v201/transactions.py +170 -0
- ocpp_sdk/v201/types.py +3375 -0
- ocpp_sdk/versions.py +18 -0
- ocpp_sdk-1.0.0.dist-info/METADATA +57 -0
- ocpp_sdk-1.0.0.dist-info/RECORD +59 -0
- ocpp_sdk-1.0.0.dist-info/WHEEL +4 -0
- ocpp_sdk-1.0.0.dist-info/licenses/LICENSE +21 -0
ocpp_sdk/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Async Python SDK for OCPP-J (OCPP 1.6J, 2.0.1 and 2.1).
|
|
2
|
+
|
|
3
|
+
The everyday names are re-exported here; the messages live in ``ocpp_sdk.v16`` and
|
|
4
|
+
``ocpp_sdk.v201``, the WebSocket transport in ``ocpp_sdk.transport``.
|
|
5
|
+
|
|
6
|
+
Example:
|
|
7
|
+
>>> import ocpp_sdk
|
|
8
|
+
>>> isinstance(ocpp_sdk.__version__, str)
|
|
9
|
+
True
|
|
10
|
+
>>> issubclass(ocpp_sdk.NotConnectedError, ocpp_sdk.OCPPError)
|
|
11
|
+
True
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from ocpp_sdk.errors import (
|
|
15
|
+
CallError,
|
|
16
|
+
CallTimeoutError,
|
|
17
|
+
NotConnectedError,
|
|
18
|
+
OCPPError,
|
|
19
|
+
QueueFullError,
|
|
20
|
+
ValidationError,
|
|
21
|
+
)
|
|
22
|
+
from ocpp_sdk.versions import Version
|
|
23
|
+
|
|
24
|
+
__version__ = "1.0.0"
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"CallError",
|
|
28
|
+
"CallTimeoutError",
|
|
29
|
+
"NotConnectedError",
|
|
30
|
+
"OCPPError",
|
|
31
|
+
"QueueFullError",
|
|
32
|
+
"ValidationError",
|
|
33
|
+
"Version",
|
|
34
|
+
"__version__",
|
|
35
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Helpers shared by the versions' high-level classes; not part of the public API."""
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Turns a ``Config`` of handlers and a generated dispatch table into an endpoint handler."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import logging
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel
|
|
11
|
+
|
|
12
|
+
from ocpp_sdk.errors import CallError
|
|
13
|
+
from ocpp_sdk.ocppj.endpoint import Handler
|
|
14
|
+
|
|
15
|
+
__all__ = ["make_handler"]
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger("ocpp_sdk.dispatch")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def make_handler(
|
|
21
|
+
config: object,
|
|
22
|
+
table: Mapping[str, tuple[str, str]],
|
|
23
|
+
*leading: Any,
|
|
24
|
+
) -> Handler:
|
|
25
|
+
"""Build the ``handler(action, request)`` of an ``Endpoint``.
|
|
26
|
+
|
|
27
|
+
``table`` maps an action to the ``Config`` field and the handler method that serve it. A
|
|
28
|
+
missing field (``None``) or an action that is not in the table is answered ``NotSupported``.
|
|
29
|
+
``leading`` arguments (the CSMS passes its session) go before the request. Handlers may be
|
|
30
|
+
sync or async.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
async def handle(action: str, request: BaseModel) -> BaseModel:
|
|
34
|
+
entry = table.get(action)
|
|
35
|
+
handler = getattr(config, entry[0]) if entry is not None else None
|
|
36
|
+
if entry is None or handler is None:
|
|
37
|
+
raise CallError("NotSupported", f"{action} is not supported")
|
|
38
|
+
result = getattr(handler, entry[1])(*leading, request)
|
|
39
|
+
if inspect.isawaitable(result):
|
|
40
|
+
result = await result
|
|
41
|
+
if not isinstance(result, BaseModel):
|
|
42
|
+
logger.error("the handler of %s returned %r, not a response model", action, result)
|
|
43
|
+
raise TypeError(f"the handler of {action} returned no response")
|
|
44
|
+
return result
|
|
45
|
+
|
|
46
|
+
return handle
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""Connection lifecycle shared by the high-level station and CSMS classes of every version.
|
|
2
|
+
|
|
3
|
+
The public classes (``v16.ChargePoint``, ``v201.ChargingStation``, the CSMS classes and their
|
|
4
|
+
session objects) hold one of these and forward to it, so no internal type is exposed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import inspect
|
|
11
|
+
import ssl
|
|
12
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
13
|
+
from typing import Any, Generic, TypeVar
|
|
14
|
+
|
|
15
|
+
from pydantic import BaseModel
|
|
16
|
+
|
|
17
|
+
from ocpp_sdk._internal.dispatch import make_handler
|
|
18
|
+
from ocpp_sdk.errors import NotConnectedError
|
|
19
|
+
from ocpp_sdk.ocppj.endpoint import Endpoint
|
|
20
|
+
from ocpp_sdk.ocppj.registry import Registry
|
|
21
|
+
from ocpp_sdk.transport.client import Client, Reconnect
|
|
22
|
+
from ocpp_sdk.transport.connection import Connection, FrameSink
|
|
23
|
+
from ocpp_sdk.transport.server import Server
|
|
24
|
+
from ocpp_sdk.versions import Version
|
|
25
|
+
|
|
26
|
+
__all__ = ["CSMSCore", "SessionCore", "StationCore"]
|
|
27
|
+
|
|
28
|
+
Dispatch = Mapping[str, tuple[str, str]]
|
|
29
|
+
_MaybeAwaitable = Awaitable[object] | object
|
|
30
|
+
S = TypeVar("S")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def resolve(value: object) -> None:
|
|
34
|
+
"""Await ``value`` if it is awaitable (hooks may be sync or async)."""
|
|
35
|
+
if inspect.isawaitable(value):
|
|
36
|
+
await value
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _OnlineSink:
|
|
40
|
+
"""Wraps the endpoint to clear the online flag when its connection ends."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, endpoint: Endpoint, online: asyncio.Event) -> None:
|
|
43
|
+
self._endpoint = endpoint
|
|
44
|
+
self._online = online
|
|
45
|
+
|
|
46
|
+
def feed(self, raw: str) -> None:
|
|
47
|
+
self._endpoint.feed(raw)
|
|
48
|
+
|
|
49
|
+
async def close(self) -> None:
|
|
50
|
+
self._online.clear()
|
|
51
|
+
await self._endpoint.close()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class StationCore:
|
|
55
|
+
"""The client side: one reconnecting connection to a CSMS."""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
url: str,
|
|
60
|
+
*,
|
|
61
|
+
version: Version,
|
|
62
|
+
registry: Registry,
|
|
63
|
+
config: object,
|
|
64
|
+
dispatch: Dispatch,
|
|
65
|
+
response_timeout: float,
|
|
66
|
+
queue_size: int,
|
|
67
|
+
password: str | None,
|
|
68
|
+
ssl_context: ssl.SSLContext | None,
|
|
69
|
+
reconnect: Reconnect | None,
|
|
70
|
+
ping_interval: float | None,
|
|
71
|
+
ping_timeout: float | None,
|
|
72
|
+
max_message_size: int,
|
|
73
|
+
open_timeout: float,
|
|
74
|
+
close_timeout: float,
|
|
75
|
+
) -> None:
|
|
76
|
+
self._registry = registry
|
|
77
|
+
self._config = config
|
|
78
|
+
self._dispatch = dispatch
|
|
79
|
+
self._response_timeout = response_timeout
|
|
80
|
+
self._queue_size = queue_size
|
|
81
|
+
self._endpoint: Endpoint | None = None
|
|
82
|
+
self._online = asyncio.Event()
|
|
83
|
+
self._client = Client(
|
|
84
|
+
url,
|
|
85
|
+
self._on_connect,
|
|
86
|
+
versions=(version,),
|
|
87
|
+
password=password,
|
|
88
|
+
ssl_context=ssl_context,
|
|
89
|
+
reconnect=reconnect,
|
|
90
|
+
ping_interval=ping_interval,
|
|
91
|
+
ping_timeout=ping_timeout,
|
|
92
|
+
max_message_size=max_message_size,
|
|
93
|
+
open_timeout=open_timeout,
|
|
94
|
+
close_timeout=close_timeout,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def connected(self) -> bool:
|
|
99
|
+
return self._endpoint is not None and not self._endpoint.closed
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def connection(self) -> Connection | None:
|
|
103
|
+
return self._client.connection
|
|
104
|
+
|
|
105
|
+
async def wait_online(self) -> None:
|
|
106
|
+
await self._online.wait()
|
|
107
|
+
|
|
108
|
+
def start(self) -> None:
|
|
109
|
+
self._client.start()
|
|
110
|
+
|
|
111
|
+
async def wait_connected(self, timeout: float | None) -> Connection: # noqa: ASYNC109
|
|
112
|
+
return await self._client.wait_connected(timeout)
|
|
113
|
+
|
|
114
|
+
async def enter(self) -> None:
|
|
115
|
+
await self._client.__aenter__()
|
|
116
|
+
|
|
117
|
+
async def close(self) -> None:
|
|
118
|
+
await self._client.close()
|
|
119
|
+
|
|
120
|
+
async def _on_connect(self, connection: Connection) -> FrameSink:
|
|
121
|
+
endpoint = Endpoint(
|
|
122
|
+
self._registry,
|
|
123
|
+
connection.send,
|
|
124
|
+
handler=make_handler(self._config, self._dispatch),
|
|
125
|
+
response_timeout=self._response_timeout,
|
|
126
|
+
queue_size=self._queue_size,
|
|
127
|
+
)
|
|
128
|
+
self._endpoint = endpoint
|
|
129
|
+
self._online.set()
|
|
130
|
+
return _OnlineSink(endpoint, self._online)
|
|
131
|
+
|
|
132
|
+
async def call(
|
|
133
|
+
self,
|
|
134
|
+
request: BaseModel,
|
|
135
|
+
timeout: float | None, # noqa: ASYNC109
|
|
136
|
+
) -> BaseModel:
|
|
137
|
+
endpoint = self._endpoint
|
|
138
|
+
if endpoint is None or endpoint.closed:
|
|
139
|
+
raise NotConnectedError("not connected to the Central System")
|
|
140
|
+
return await endpoint.call(request, timeout=timeout)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class SessionCore:
|
|
144
|
+
"""One connected station, as seen by the CSMS."""
|
|
145
|
+
|
|
146
|
+
def __init__(self, connection: Connection) -> None:
|
|
147
|
+
self.connection = connection
|
|
148
|
+
self.endpoint: Endpoint | None = None
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def charge_point_id(self) -> str:
|
|
152
|
+
return self.connection.charge_point_id
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def connected(self) -> bool:
|
|
156
|
+
return self.endpoint is not None and not self.endpoint.closed
|
|
157
|
+
|
|
158
|
+
async def call(
|
|
159
|
+
self,
|
|
160
|
+
request: BaseModel,
|
|
161
|
+
timeout: float | None, # noqa: ASYNC109
|
|
162
|
+
) -> BaseModel:
|
|
163
|
+
endpoint = self.endpoint
|
|
164
|
+
if endpoint is None or endpoint.closed:
|
|
165
|
+
raise NotConnectedError(f"{self.charge_point_id} is not connected")
|
|
166
|
+
return await endpoint.call(request, timeout=timeout)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class CSMSCore(Generic[S]):
|
|
170
|
+
"""The server side: accepts stations and keeps one session object per connection.
|
|
171
|
+
|
|
172
|
+
``wrap`` turns a :class:`SessionCore` into the version's public session object, which is
|
|
173
|
+
what handlers and hooks receive.
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
def __init__(
|
|
177
|
+
self,
|
|
178
|
+
*,
|
|
179
|
+
version: Version,
|
|
180
|
+
registry: Registry,
|
|
181
|
+
config: object,
|
|
182
|
+
dispatch: Dispatch,
|
|
183
|
+
wrap: Callable[[SessionCore], S],
|
|
184
|
+
on_connect: Callable[[S], _MaybeAwaitable] | None,
|
|
185
|
+
on_disconnect: Callable[[S], _MaybeAwaitable] | None,
|
|
186
|
+
response_timeout: float,
|
|
187
|
+
queue_size: int,
|
|
188
|
+
host: str,
|
|
189
|
+
port: int,
|
|
190
|
+
ssl_context: ssl.SSLContext | None,
|
|
191
|
+
known_id: Callable[[str], _MaybeAwaitable] | None,
|
|
192
|
+
authenticate: Callable[[str, str], _MaybeAwaitable] | None,
|
|
193
|
+
check_certificate_identity: bool,
|
|
194
|
+
operator_name: str | None,
|
|
195
|
+
ping_interval: float | None,
|
|
196
|
+
ping_timeout: float | None,
|
|
197
|
+
max_message_size: int,
|
|
198
|
+
open_timeout: float,
|
|
199
|
+
close_timeout: float,
|
|
200
|
+
) -> None:
|
|
201
|
+
self._registry = registry
|
|
202
|
+
self._config = config
|
|
203
|
+
self._dispatch = dispatch
|
|
204
|
+
self._wrap = wrap
|
|
205
|
+
self._on_connect_hook = on_connect
|
|
206
|
+
self._on_disconnect_hook = on_disconnect
|
|
207
|
+
self._response_timeout = response_timeout
|
|
208
|
+
self._queue_size = queue_size
|
|
209
|
+
self._sessions: dict[str, tuple[S, SessionCore]] = {}
|
|
210
|
+
self._server = Server(
|
|
211
|
+
self._on_connect,
|
|
212
|
+
on_disconnect=self._on_disconnect,
|
|
213
|
+
host=host,
|
|
214
|
+
port=port,
|
|
215
|
+
versions=(version,),
|
|
216
|
+
ssl_context=ssl_context,
|
|
217
|
+
known_id=known_id,
|
|
218
|
+
authenticate=authenticate,
|
|
219
|
+
check_certificate_identity=check_certificate_identity,
|
|
220
|
+
operator_name=operator_name,
|
|
221
|
+
ping_interval=ping_interval,
|
|
222
|
+
ping_timeout=ping_timeout,
|
|
223
|
+
max_message_size=max_message_size,
|
|
224
|
+
open_timeout=open_timeout,
|
|
225
|
+
close_timeout=close_timeout,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
async def start(self) -> None:
|
|
229
|
+
await self._server.start()
|
|
230
|
+
|
|
231
|
+
@property
|
|
232
|
+
def port(self) -> int:
|
|
233
|
+
return self._server.port
|
|
234
|
+
|
|
235
|
+
def ids(self) -> list[str]:
|
|
236
|
+
return sorted(self._sessions)
|
|
237
|
+
|
|
238
|
+
def session(self, charge_point_id: str) -> S | None:
|
|
239
|
+
entry = self._sessions.get(charge_point_id)
|
|
240
|
+
return entry[0] if entry else None
|
|
241
|
+
|
|
242
|
+
async def for_each(self, fn: Callable[[S], _MaybeAwaitable]) -> None:
|
|
243
|
+
for charge_point_id in self.ids():
|
|
244
|
+
entry = self._sessions.get(charge_point_id)
|
|
245
|
+
if entry is not None:
|
|
246
|
+
await resolve(fn(entry[0]))
|
|
247
|
+
|
|
248
|
+
async def shutdown(self, timeout: float) -> None: # noqa: ASYNC109
|
|
249
|
+
await self._server.shutdown(timeout)
|
|
250
|
+
|
|
251
|
+
async def call(
|
|
252
|
+
self,
|
|
253
|
+
charge_point_id: str,
|
|
254
|
+
request: BaseModel,
|
|
255
|
+
timeout: float | None, # noqa: ASYNC109
|
|
256
|
+
) -> BaseModel:
|
|
257
|
+
entry = self._sessions.get(charge_point_id)
|
|
258
|
+
if entry is None:
|
|
259
|
+
raise NotConnectedError(f"{charge_point_id} is not connected")
|
|
260
|
+
return await entry[1].call(request, timeout)
|
|
261
|
+
|
|
262
|
+
async def _on_connect(self, connection: Connection) -> FrameSink:
|
|
263
|
+
core = SessionCore(connection)
|
|
264
|
+
session = self._wrap(core)
|
|
265
|
+
endpoint = Endpoint(
|
|
266
|
+
self._registry,
|
|
267
|
+
connection.send,
|
|
268
|
+
handler=make_handler(self._config, self._dispatch, session),
|
|
269
|
+
response_timeout=self._response_timeout,
|
|
270
|
+
queue_size=self._queue_size,
|
|
271
|
+
)
|
|
272
|
+
core.endpoint = endpoint
|
|
273
|
+
self._sessions[connection.charge_point_id] = (session, core)
|
|
274
|
+
if self._on_connect_hook is not None:
|
|
275
|
+
await resolve(self._on_connect_hook(session))
|
|
276
|
+
return endpoint
|
|
277
|
+
|
|
278
|
+
async def _on_disconnect(self, connection: Connection) -> None:
|
|
279
|
+
entry: Any = self._sessions.get(connection.charge_point_id)
|
|
280
|
+
if entry is None or entry[1].connection is not connection:
|
|
281
|
+
return # a newer connection of the same station replaced this one
|
|
282
|
+
del self._sessions[connection.charge_point_id]
|
|
283
|
+
if self._on_disconnect_hook is not None:
|
|
284
|
+
await resolve(self._on_disconnect_hook(entry[0]))
|
ocpp_sdk/datetime.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""The one date-time parser and formatter, shared by every OCPP version.
|
|
2
|
+
|
|
3
|
+
Sending: UTC with ``Z``, whole seconds, or milliseconds when the value has a
|
|
4
|
+
fraction. Receiving: RFC 3339 with or without fractional seconds, ``Z`` or an
|
|
5
|
+
offset, or no zone at all (taken as UTC).
|
|
6
|
+
|
|
7
|
+
Example:
|
|
8
|
+
>>> from ocpp_sdk import datetime as ocpp_datetime
|
|
9
|
+
>>> ocpp_datetime.format(ocpp_datetime.parse("2025-01-02T03:04:05+01:00"))
|
|
10
|
+
'2025-01-02T02:04:05Z'
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from datetime import UTC, datetime, timedelta, timezone
|
|
17
|
+
|
|
18
|
+
from ocpp_sdk.errors import ValidationError
|
|
19
|
+
|
|
20
|
+
__all__ = ["format", "parse"]
|
|
21
|
+
|
|
22
|
+
_PATTERN = re.compile(
|
|
23
|
+
r"([0-9]{4})-([0-9]{2})-([0-9]{2})[Tt]([0-9]{2}):([0-9]{2}):([0-9]{2})"
|
|
24
|
+
r"(?:\.([0-9]+))?(?:([Zz])|([+-])([0-9]{2}):([0-9]{2}))?"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def parse(value: str) -> datetime:
|
|
29
|
+
"""Parse an OCPP date-time into an aware UTC ``datetime``.
|
|
30
|
+
|
|
31
|
+
Raises:
|
|
32
|
+
ValidationError: ``value`` is not an RFC 3339 date-time.
|
|
33
|
+
"""
|
|
34
|
+
match = _PATTERN.fullmatch(value) if isinstance(value, str) else None
|
|
35
|
+
if match is None:
|
|
36
|
+
raise ValidationError(f"invalid date-time {value!r}")
|
|
37
|
+
year, month, day, hour, minute, second, frac, _z, sign, off_h, off_m = match.groups()
|
|
38
|
+
try:
|
|
39
|
+
micro = int((frac + "000000")[:6]) if frac else 0
|
|
40
|
+
tz = UTC
|
|
41
|
+
if sign:
|
|
42
|
+
if int(off_h) > 23 or int(off_m) > 59:
|
|
43
|
+
raise ValueError("offset out of range")
|
|
44
|
+
delta = timedelta(hours=int(off_h), minutes=int(off_m))
|
|
45
|
+
tz = timezone(-delta if sign == "-" else delta)
|
|
46
|
+
parsed = datetime(
|
|
47
|
+
int(year), int(month), int(day), int(hour), int(minute), int(second), micro, tz
|
|
48
|
+
)
|
|
49
|
+
return parsed.astimezone(UTC)
|
|
50
|
+
except (ValueError, OverflowError) as exc:
|
|
51
|
+
raise ValidationError(f"invalid date-time {value!r}") from exc
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def format(value: datetime) -> str:
|
|
55
|
+
"""Format an aware ``datetime`` as UTC, with milliseconds only if it has a fraction.
|
|
56
|
+
|
|
57
|
+
Raises:
|
|
58
|
+
ValidationError: ``value`` is a naive ``datetime`` (no time zone).
|
|
59
|
+
"""
|
|
60
|
+
if value.tzinfo is None or value.utcoffset() is None:
|
|
61
|
+
raise ValidationError("naive datetime rejected: attach a time zone (e.g. tzinfo=UTC)")
|
|
62
|
+
utc = value.astimezone(UTC)
|
|
63
|
+
text = utc.strftime("%Y-%m-%dT%H:%M:%S")
|
|
64
|
+
millis = utc.microsecond // 1000
|
|
65
|
+
if millis:
|
|
66
|
+
text += f".{millis:03d}"
|
|
67
|
+
return text + "Z"
|
ocpp_sdk/errors.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Exception hierarchy and CALLERROR code sets.
|
|
2
|
+
|
|
3
|
+
Example:
|
|
4
|
+
>>> from ocpp_sdk.errors import CallError, ErrorCodeV2
|
|
5
|
+
>>> raise CallError(ErrorCodeV2.NOT_SUPPORTED, "no such feature") # doctest: +SKIP
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping, Sequence
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from ocpp_sdk.versions import Version
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class OCPPError(Exception):
|
|
18
|
+
"""Base class of every exception raised by this SDK."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CallTimeoutError(OCPPError):
|
|
22
|
+
"""No response arrived within the response timeout."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class NotConnectedError(OCPPError):
|
|
26
|
+
"""The connection is closed or was lost; nothing is queued or retried."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class QueueFullError(OCPPError):
|
|
30
|
+
"""The outgoing call queue is full."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ValidationError(OCPPError):
|
|
34
|
+
"""A message failed validation, on send or on receive.
|
|
35
|
+
|
|
36
|
+
Attributes:
|
|
37
|
+
issues: One ``{"field": ..., "type": ...}`` entry per problem found.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, message: str, *, issues: Sequence[Mapping[str, Any]] | None = None) -> None:
|
|
41
|
+
super().__init__(message)
|
|
42
|
+
self.issues: list[dict[str, Any]] = [dict(i) for i in issues or ()]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class CallError(OCPPError):
|
|
46
|
+
"""A CALLERROR, received from the peer or raised by a handler to send one.
|
|
47
|
+
|
|
48
|
+
Example:
|
|
49
|
+
>>> err = CallError("NotSupported", "no such feature")
|
|
50
|
+
>>> str(err)
|
|
51
|
+
'NotSupported: no such feature'
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
code: str,
|
|
57
|
+
description: str = "",
|
|
58
|
+
details: Mapping[str, Any] | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
super().__init__(f"{code}: {description}" if description else code)
|
|
61
|
+
self.code = str(code)
|
|
62
|
+
self.description = description
|
|
63
|
+
self.details: dict[str, Any] = dict(details or {})
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ErrorCodeV16(StrEnum):
|
|
67
|
+
"""CALLERROR codes of OCPP 1.6 (note the spec's spelling of ``Occurence``)."""
|
|
68
|
+
|
|
69
|
+
NOT_IMPLEMENTED = "NotImplemented"
|
|
70
|
+
NOT_SUPPORTED = "NotSupported"
|
|
71
|
+
INTERNAL_ERROR = "InternalError"
|
|
72
|
+
PROTOCOL_ERROR = "ProtocolError"
|
|
73
|
+
SECURITY_ERROR = "SecurityError"
|
|
74
|
+
FORMATION_VIOLATION = "FormationViolation"
|
|
75
|
+
PROPERTY_CONSTRAINT_VIOLATION = "PropertyConstraintViolation"
|
|
76
|
+
OCCURENCE_CONSTRAINT_VIOLATION = "OccurenceConstraintViolation"
|
|
77
|
+
TYPE_CONSTRAINT_VIOLATION = "TypeConstraintViolation"
|
|
78
|
+
GENERIC_ERROR = "GenericError"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class ErrorCodeV2(StrEnum):
|
|
82
|
+
"""CALLERROR codes of OCPP 2.0.1 and 2.1."""
|
|
83
|
+
|
|
84
|
+
FORMAT_VIOLATION = "FormatViolation"
|
|
85
|
+
GENERIC_ERROR = "GenericError"
|
|
86
|
+
INTERNAL_ERROR = "InternalError"
|
|
87
|
+
MESSAGE_TYPE_NOT_SUPPORTED = "MessageTypeNotSupported"
|
|
88
|
+
NOT_IMPLEMENTED = "NotImplemented"
|
|
89
|
+
NOT_SUPPORTED = "NotSupported"
|
|
90
|
+
OCCURRENCE_CONSTRAINT_VIOLATION = "OccurrenceConstraintViolation"
|
|
91
|
+
PROPERTY_CONSTRAINT_VIOLATION = "PropertyConstraintViolation"
|
|
92
|
+
PROTOCOL_ERROR = "ProtocolError"
|
|
93
|
+
RPC_FRAMEWORK_ERROR = "RpcFrameworkError"
|
|
94
|
+
SECURITY_ERROR = "SecurityError"
|
|
95
|
+
TYPE_CONSTRAINT_VIOLATION = "TypeConstraintViolation"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
V16_ERROR_CODES: frozenset[str] = frozenset(c.value for c in ErrorCodeV16)
|
|
99
|
+
V2_ERROR_CODES: frozenset[str] = frozenset(c.value for c in ErrorCodeV2)
|
|
100
|
+
|
|
101
|
+
_TO_V16 = {
|
|
102
|
+
ErrorCodeV2.FORMAT_VIOLATION.value: ErrorCodeV16.FORMATION_VIOLATION.value,
|
|
103
|
+
ErrorCodeV2.OCCURRENCE_CONSTRAINT_VIOLATION.value: (
|
|
104
|
+
ErrorCodeV16.OCCURENCE_CONSTRAINT_VIOLATION.value
|
|
105
|
+
),
|
|
106
|
+
}
|
|
107
|
+
_TO_V2 = {v: k for k, v in _TO_V16.items()}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def error_codes(version: Version) -> frozenset[str]:
|
|
111
|
+
"""Return the CALLERROR codes valid for ``version``."""
|
|
112
|
+
return V16_ERROR_CODES if version is Version.OCPP16 else V2_ERROR_CODES
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def code_for_version(code: str, version: Version) -> str:
|
|
116
|
+
"""Return ``code`` spelled as ``version`` spells it.
|
|
117
|
+
|
|
118
|
+
The 1.6 and 2.x spellings of the two renamed codes are translated either
|
|
119
|
+
way; a code the version does not have becomes ``GenericError``.
|
|
120
|
+
|
|
121
|
+
Example:
|
|
122
|
+
>>> code_for_version("FormatViolation", Version.OCPP16)
|
|
123
|
+
'FormationViolation'
|
|
124
|
+
>>> code_for_version("RpcFrameworkError", Version.OCPP16)
|
|
125
|
+
'GenericError'
|
|
126
|
+
"""
|
|
127
|
+
mapping = _TO_V16 if version is Version.OCPP16 else _TO_V2
|
|
128
|
+
code = mapping.get(code, code)
|
|
129
|
+
return code if code in error_codes(version) else "GenericError"
|