ocpp-sdk 1.0.0__tar.gz
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-1.0.0/.gitignore +15 -0
- ocpp_sdk-1.0.0/LICENSE +21 -0
- ocpp_sdk-1.0.0/PKG-INFO +57 -0
- ocpp_sdk-1.0.0/README.md +34 -0
- ocpp_sdk-1.0.0/pyproject.toml +90 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/__init__.py +35 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/_internal/__init__.py +1 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/_internal/dispatch.py +46 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/_internal/lifecycle.py +284 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/datetime.py +67 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/errors.py +129 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/model.py +210 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/ocppj/__init__.py +15 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/ocppj/endpoint.py +321 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/ocppj/frames.py +237 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/ocppj/registry.py +166 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/py.typed +0 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/transport/__init__.py +7 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/transport/auth.py +179 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/transport/client.py +242 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/transport/connection.py +54 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/transport/server.py +293 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/__init__.py +35 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/charge_point.py +174 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/charge_point_handlers.py +974 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/core.py +751 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/csms.py +210 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/csms_handlers.py +1786 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/firmware.py +176 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/localauth.py +113 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/remotetrigger.py +58 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/reservation.py +112 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/security.py +605 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/smartcharging.py +179 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/transaction_queue.py +384 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v16/types.py +1085 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/__init__.py +61 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/appendices.py +1926 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/authorization.py +123 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/availability.py +169 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/charging_station.py +190 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/charging_station_handlers.py +1687 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/csms.py +230 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/csms_handlers.py +2974 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/datatransfer.py +69 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/diagnostics.py +653 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/displaymessage.py +227 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/firmware.py +299 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/iso15118.py +305 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/localauthlist.py +129 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/metervalues.py +66 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/provisioning.py +466 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/remotecontrol.py +252 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/reservation.py +176 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/security.py +177 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/smartcharging.py +540 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/tariffandcost.py +62 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/transactions.py +170 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/v201/types.py +3375 -0
- ocpp_sdk-1.0.0/src/ocpp_sdk/versions.py +18 -0
ocpp_sdk-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fauz Ecum
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
ocpp_sdk-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ocpp-sdk
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Async Python SDK for OCPP-J (1.6J, 2.0.1, 2.1): charge point and central system roles.
|
|
5
|
+
Project-URL: Repository, https://github.com/foecum/python-ocpp-sdk
|
|
6
|
+
Author: Fauz Ecum
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: asyncio,charging,ev,ocpp,websocket
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Requires-Dist: pydantic<3,>=2
|
|
21
|
+
Requires-Dist: websockets>=14
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# python-ocpp-sdk
|
|
25
|
+
|
|
26
|
+
Async Python SDK for **OCPP-J** (OCPP over JSON/WebSocket), covering the Charge
|
|
27
|
+
Point / Charging Station and Central System / CSMS roles.
|
|
28
|
+
|
|
29
|
+
**Status: 1.0 for OCPP 1.6J and 2.0.1; OCPP 2.1 is planned.** The core (errors, date-times, OCPP-J
|
|
30
|
+
framing, endpoint), the WebSocket transport (server, client with reconnect,
|
|
31
|
+
security profiles 1-3) and the OCPP 1.6 message models (generated from the official
|
|
32
|
+
schemas) and the high-level OCPP 1.6 `ChargePoint` and `CSMS` classes (typed calls,
|
|
33
|
+
handlers per feature profile) are done, so 1.6 stations and Central Systems can be
|
|
34
|
+
built, with an opt-in transaction message queue (in-memory or file-backed) and
|
|
35
|
+
examples in `examples/v16`. The 1.6 security extension messages and AuthorizationKey helpers are in too. OCPP 2.0.1 is done too (`ocpp_sdk.v201`, examples in `examples/v201`). 2.1 is not done. See the documentation site (`site/index.html`).
|
|
36
|
+
|
|
37
|
+
| Version | Status |
|
|
38
|
+
|-----------|---------|
|
|
39
|
+
| OCPP 1.6J | models, high-level API, transaction queue, examples, go-ocpp-sdk interop tests and the security extension done |
|
|
40
|
+
| OCPP 2.0.1 | done: 64 messages, appendices constants, `ChargingStation` and `CSMS` |
|
|
41
|
+
| OCPP 2.1 | planned |
|
|
42
|
+
|
|
43
|
+
## Quick start
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
python examples/v16/csms.py --port 9000 # Central System
|
|
47
|
+
python examples/v16/charge_point.py --url ws://127.0.0.1:9000/CP-1 # Charge Point
|
|
48
|
+
python examples/v201/csms.py --port 9001 # OCPP 2.0.1 CSMS
|
|
49
|
+
python examples/v201/charging_station.py --url ws://127.0.0.1:9001/CS-1 # 2.0.1 station
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
See `site/index.html` for the API: typed calls, handlers per feature profile, security
|
|
53
|
+
profiles 1-3, the transaction queue, logging and error handling.
|
|
54
|
+
|
|
55
|
+
- PyPI name: `ocpp-sdk` (import `ocpp_sdk`), Python 3.11+
|
|
56
|
+
- Sister project: [go-ocpp-sdk](https://github.com/foecum/go-ocpp-sdk)
|
|
57
|
+
- Licence: MIT
|
ocpp_sdk-1.0.0/README.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# python-ocpp-sdk
|
|
2
|
+
|
|
3
|
+
Async Python SDK for **OCPP-J** (OCPP over JSON/WebSocket), covering the Charge
|
|
4
|
+
Point / Charging Station and Central System / CSMS roles.
|
|
5
|
+
|
|
6
|
+
**Status: 1.0 for OCPP 1.6J and 2.0.1; OCPP 2.1 is planned.** The core (errors, date-times, OCPP-J
|
|
7
|
+
framing, endpoint), the WebSocket transport (server, client with reconnect,
|
|
8
|
+
security profiles 1-3) and the OCPP 1.6 message models (generated from the official
|
|
9
|
+
schemas) and the high-level OCPP 1.6 `ChargePoint` and `CSMS` classes (typed calls,
|
|
10
|
+
handlers per feature profile) are done, so 1.6 stations and Central Systems can be
|
|
11
|
+
built, with an opt-in transaction message queue (in-memory or file-backed) and
|
|
12
|
+
examples in `examples/v16`. The 1.6 security extension messages and AuthorizationKey helpers are in too. OCPP 2.0.1 is done too (`ocpp_sdk.v201`, examples in `examples/v201`). 2.1 is not done. See the documentation site (`site/index.html`).
|
|
13
|
+
|
|
14
|
+
| Version | Status |
|
|
15
|
+
|-----------|---------|
|
|
16
|
+
| OCPP 1.6J | models, high-level API, transaction queue, examples, go-ocpp-sdk interop tests and the security extension done |
|
|
17
|
+
| OCPP 2.0.1 | done: 64 messages, appendices constants, `ChargingStation` and `CSMS` |
|
|
18
|
+
| OCPP 2.1 | planned |
|
|
19
|
+
|
|
20
|
+
## Quick start
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
python examples/v16/csms.py --port 9000 # Central System
|
|
24
|
+
python examples/v16/charge_point.py --url ws://127.0.0.1:9000/CP-1 # Charge Point
|
|
25
|
+
python examples/v201/csms.py --port 9001 # OCPP 2.0.1 CSMS
|
|
26
|
+
python examples/v201/charging_station.py --url ws://127.0.0.1:9001/CS-1 # 2.0.1 station
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
See `site/index.html` for the API: typed calls, handlers per feature profile, security
|
|
30
|
+
profiles 1-3, the transaction queue, logging and error handling.
|
|
31
|
+
|
|
32
|
+
- PyPI name: `ocpp-sdk` (import `ocpp_sdk`), Python 3.11+
|
|
33
|
+
- Sister project: [go-ocpp-sdk](https://github.com/foecum/go-ocpp-sdk)
|
|
34
|
+
- Licence: MIT
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ocpp-sdk"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Async Python SDK for OCPP-J (1.6J, 2.0.1, 2.1): charge point and central system roles."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Fauz Ecum" }]
|
|
14
|
+
keywords = ["ocpp", "ev", "charging", "websocket", "asyncio"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 5 - Production/Stable",
|
|
17
|
+
"Framework :: AsyncIO",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Programming Language :: Python :: 3.14",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
dependencies = [
|
|
27
|
+
"pydantic>=2,<3",
|
|
28
|
+
"websockets>=14",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Repository = "https://github.com/foecum/python-ocpp-sdk"
|
|
33
|
+
|
|
34
|
+
[dependency-groups]
|
|
35
|
+
dev = [
|
|
36
|
+
"ruff",
|
|
37
|
+
"mypy",
|
|
38
|
+
"pytest",
|
|
39
|
+
"pytest-asyncio",
|
|
40
|
+
"pytest-cov",
|
|
41
|
+
"hypothesis",
|
|
42
|
+
"pytest-benchmark",
|
|
43
|
+
"jsonschema",
|
|
44
|
+
"types-jsonschema",
|
|
45
|
+
"trustme>=1.2.1",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
[tool.hatch.version]
|
|
49
|
+
path = "src/ocpp_sdk/__init__.py"
|
|
50
|
+
|
|
51
|
+
[tool.hatch.build.targets.sdist]
|
|
52
|
+
include = ["src/ocpp_sdk", "README.md", "LICENSE", "pyproject.toml"]
|
|
53
|
+
exclude = ["docs/spec"]
|
|
54
|
+
|
|
55
|
+
[tool.hatch.build.targets.wheel]
|
|
56
|
+
packages = ["src/ocpp_sdk"]
|
|
57
|
+
exclude = ["docs/spec"]
|
|
58
|
+
|
|
59
|
+
[tool.ruff]
|
|
60
|
+
line-length = 100
|
|
61
|
+
target-version = "py311"
|
|
62
|
+
src = ["src", "tests", "tools"]
|
|
63
|
+
|
|
64
|
+
[tool.ruff.lint]
|
|
65
|
+
select = ["E", "F", "W", "I", "B", "UP", "ASYNC", "SIM", "RUF"]
|
|
66
|
+
|
|
67
|
+
[tool.ruff.lint.per-file-ignores]
|
|
68
|
+
"tests/**" = ["SIM117", "ASYNC109", "ASYNC110"]
|
|
69
|
+
"src/ocpp_sdk/v*/*_handlers.py" = ["ASYNC109"]
|
|
70
|
+
"src/ocpp_sdk/v*/appendices.py" = ["E501"] # data tables with long descriptions
|
|
71
|
+
|
|
72
|
+
[tool.mypy]
|
|
73
|
+
strict = true
|
|
74
|
+
python_version = "3.11"
|
|
75
|
+
mypy_path = "src"
|
|
76
|
+
plugins = ["pydantic.mypy"]
|
|
77
|
+
|
|
78
|
+
[tool.pytest.ini_options]
|
|
79
|
+
testpaths = ["tests", "src"]
|
|
80
|
+
addopts = "--doctest-modules --benchmark-disable"
|
|
81
|
+
asyncio_mode = "auto"
|
|
82
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
83
|
+
markers = ["slow: builds and runs examples or opens many connections"]
|
|
84
|
+
|
|
85
|
+
[tool.coverage.run]
|
|
86
|
+
branch = true
|
|
87
|
+
source = ["ocpp_sdk"]
|
|
88
|
+
|
|
89
|
+
[tool.coverage.report]
|
|
90
|
+
show_missing = true
|
|
@@ -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]))
|
|
@@ -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"
|