pybluecurrent 0.4.1__tar.gz → 0.5.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.
Files changed (60) hide show
  1. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/.github/workflows/test.yaml +4 -2
  2. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/CHANGELOG.md +12 -0
  3. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/PKG-INFO +98 -3
  4. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/README.md +93 -2
  5. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/pyproject.toml +3 -1
  6. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent/_version.py +3 -3
  7. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent/cli/__init__.py +2 -0
  8. pybluecurrent-0.5.0/src/pybluecurrent/cli/relay.py +96 -0
  9. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent/client.py +74 -3
  10. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent/models.py +33 -3
  11. pybluecurrent-0.5.0/src/pybluecurrent/relay/__init__.py +10 -0
  12. pybluecurrent-0.5.0/src/pybluecurrent/relay/commands.py +55 -0
  13. pybluecurrent-0.5.0/src/pybluecurrent/relay/relay.py +435 -0
  14. pybluecurrent-0.5.0/src/pybluecurrent/relay/serialize.py +28 -0
  15. pybluecurrent-0.5.0/src/pybluecurrent/relay/settings.py +54 -0
  16. pybluecurrent-0.5.0/src/pybluecurrent/relay/state.py +87 -0
  17. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent/utilities.py +23 -6
  18. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent.egg-info/PKG-INFO +98 -3
  19. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent.egg-info/SOURCES.txt +11 -0
  20. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent.egg-info/requires.txt +5 -0
  21. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent.egg-info/scm_file_list.json +11 -0
  22. pybluecurrent-0.5.0/src/pybluecurrent.egg-info/scm_version.json +8 -0
  23. pybluecurrent-0.5.0/tests/fake_mqtt.py +94 -0
  24. pybluecurrent-0.5.0/tests/fixtures/ch_status.json +25 -0
  25. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fixtures/charge_point_settings.json +1 -0
  26. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fixtures/charge_point_status.json +1 -0
  27. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fixtures/charge_point_status_socket_two.json +1 -0
  28. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fixtures/charge_point_statuses.json +5 -3
  29. pybluecurrent-0.5.0/tests/fixtures/grid_current.json +7 -0
  30. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/test_client.py +7 -4
  31. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/test_offline.py +219 -7
  32. pybluecurrent-0.5.0/tests/test_relay.py +880 -0
  33. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/test_utilities.py +19 -2
  34. pybluecurrent-0.4.1/src/pybluecurrent.egg-info/scm_version.json +0 -8
  35. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/.github/workflows/publish.yaml +0 -0
  36. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/.gitignore +0 -0
  37. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/.pre-commit-config.yaml +0 -0
  38. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/LICENSE +0 -0
  39. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/setup.cfg +0 -0
  40. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent/__init__.py +0 -0
  41. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent/cli/transactions.py +0 -0
  42. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent/enums.py +0 -0
  43. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent/exceptions.py +0 -0
  44. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent/py.typed +0 -0
  45. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent.egg-info/dependency_links.txt +0 -0
  46. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent.egg-info/entry_points.txt +0 -0
  47. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/src/pybluecurrent.egg-info/top_level.txt +0 -0
  48. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/conftest.py +0 -0
  49. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fake_rest.py +0 -0
  50. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fake_socket.py +0 -0
  51. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fixtures/account.json +0 -0
  52. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fixtures/charge_cards.json +0 -0
  53. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fixtures/charge_points.json +0 -0
  54. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fixtures/error_forbidden.json +0 -0
  55. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fixtures/grid_status.json +0 -0
  56. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fixtures/sustainability_status.json +0 -0
  57. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/fixtures/transactions.json +0 -0
  58. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/models_check.py +0 -0
  59. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/test_cli.py +0 -0
  60. {pybluecurrent-0.4.1 → pybluecurrent-0.5.0}/tests/test_enums.py +0 -0
@@ -21,11 +21,13 @@ jobs:
21
21
  python-version: "3.x"
22
22
 
23
23
  - name: Install Dependencies
24
+ # A venv: ty resolves imports from the project's environment, and finds none on a bare interpreter.
24
25
  run: |
25
- pip3 install -e ".[dev]"
26
+ python3 -m venv .venv
27
+ .venv/bin/pip install -e ".[dev,mqtt]"
26
28
 
27
29
  - name: Run pre-commit
28
- run: pre-commit run --all-files
30
+ run: .venv/bin/pre-commit run --all-files
29
31
 
30
32
  test:
31
33
  runs-on: ubuntu-latest
@@ -5,6 +5,17 @@ All notable changes to this project are documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
6
  This project is pre-1.0: breaking changes may land in minor releases.
7
7
 
8
+ ## [0.5.0] - 2026-11-29
9
+
10
+ ### Added
11
+
12
+ - An MQTT relay, `pybluecurrent relay`, behind the new `mqtt` extra (`pip install pybluecurrent[mqtt]`). It publishes the live status of every socket, each charge point's settings (smart-charging profiles included), the grid current and a health topic to an MQTT broker, and optionally every charging transaction. It also takes commands on a command topic, starting with `set_card` to set the plug-and-charge card, and answers each one on an ack topic. Configure it with options or environment variables (`BLUECURRENT_MQTT_HOST`, `BLUECURRENT_POLL_INTERVAL`, `BLUECURRENT_SYNC_TRANSACTIONS`, …). The client library keeps its own dependencies: the extra is only needed to run the relay.
13
+
14
+ - `live_updates()` yields the messages the backend sends by itself, such as the grid current and a charge point's live status, as an async generator that survives reconnects. Name the message types you want (`live_updates("GRID_CURRENT")`) or take everything. The login messages are never yielded, since they carry the session token.
15
+ - `connected`, telling you whether the websocket is up right now.
16
+ - `smart_current_heartbeat_timeout` on `ChargePointStatus` and on the `delayed_charging` setting. It is positive while a smart-charging profile is holding a session back — with `vehicle_status` `"C"` the state the BlueCurrent app shows as "Scheduled", and the one `boost()` overrides.
17
+ - `GridCurrent`, the response model for a pushed grid-current message.
18
+
8
19
  ## [0.4.1] - 2026-09-12
9
20
 
10
21
  ### Fixed
@@ -93,6 +104,7 @@ This project is pre-1.0: breaking changes may land in minor releases.
93
104
  - `get_account` returns `first_login_app` as a `datetime` (previously a `date`).
94
105
  - Internal: switched tooling to Ruff and ty, added a Python 3.10–3.13 CI matrix, and moved to PyPI trusted publishing (OIDC).
95
106
 
107
+ [0.5.0]: https://github.com/rogiervandergeer/pybluecurrent/compare/0.4.1...0.5.0
96
108
  [0.4.1]: https://github.com/rogiervandergeer/pybluecurrent/compare/0.4.0...0.4.1
97
109
  [0.4.0]: https://github.com/rogiervandergeer/pybluecurrent/compare/0.3.0...0.4.0
98
110
  [0.3.0]: https://github.com/rogiervandergeer/pybluecurrent/compare/0.2.0...0.3.0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pybluecurrent
3
- Version: 0.4.1
3
+ Version: 0.5.0
4
4
  Summary: Python client for BlueCurrent charge points.
5
5
  Author-email: Rogier van der Geer <rogier@vander-geer.nl>
6
6
  License: MIT
@@ -25,10 +25,14 @@ Requires-Dist: sjcl>=0.2.1
25
25
  Requires-Dist: typer>=0.12
26
26
  Requires-Dist: websockets>=14.0
27
27
  Provides-Extra: dev
28
+ Requires-Dist: pybluecurrent[mqtt]; extra == "dev"
28
29
  Requires-Dist: pre-commit>=3.3.3; extra == "dev"
29
30
  Requires-Dist: pytest==8.4.2; extra == "dev"
30
31
  Requires-Dist: pytest-asyncio==1.2.0; extra == "dev"
31
32
  Requires-Dist: typeguard>=4.0; extra == "dev"
33
+ Provides-Extra: mqtt
34
+ Requires-Dist: aiomqtt<3,>=2.0; extra == "mqtt"
35
+ Requires-Dist: tzdata; extra == "mqtt"
32
36
  Dynamic: license-file
33
37
 
34
38
  # pybluecurrent
@@ -98,6 +102,33 @@ client = BlueCurrentClient(api_token="your_api_token")
98
102
  Retrieve or rotate the token with [`get_api_token`](#get_api_token) and
99
103
  [`generate_api_token`](#generate_api_token), or from the [BlueCurrent website](https://my.bluecurrent.nl).
100
104
 
105
+ A long-lived client reconnects by itself when the connection drops. `client.connected` tells you whether
106
+ the websocket is up right now; calls made while it is reconnecting wait for the connection to return.
107
+
108
+ ### Live updates
109
+
110
+ Besides answering your calls, the backend sends messages of its own accord: the grid current, and the
111
+ status of a socket while it charges. `live_updates` yields them as they arrive, across reconnects:
112
+
113
+ ```python
114
+ async with client:
115
+ async for message in client.live_updates("GRID_CURRENT"):
116
+ print(message["evse_id"], message["grid_actual_p1"])
117
+ ```
118
+
119
+ Name the message types you want, or omit them to receive everything — including the replies to your own
120
+ calls. Messages sent while the connection is down are lost, as are messages arriving before your first
121
+ read. The loop ends when the client is closed, and raises if the client stops reconnecting:
122
+ `ConnectionLost`, or `AuthenticationFailed` when the credentials are rejected.
123
+
124
+ | Type | When | Contents |
125
+ |---|---|---|
126
+ | `GRID_CURRENT` | several times an hour, in bursts, around the clock | `evse_id` and the current per phase, `grid_actual_p1` to `grid_actual_p3`, as integers |
127
+ | `CH_STATUS` | only during a charging session: a few at the start, one at each switch between charging and paused, a few at the unplug, and one every two minutes in between | `evse_id` and `socket_id`, and under `data` the fields of [`get_charge_point_status`](#get_charge_point_status), without `smart_current_heartbeat_timeout` and with `start_datetime` and `stop_datetime` always `""` |
128
+
129
+ The backend can stop sending these for hours, with no error, while your calls still get answers. Don't
130
+ rely on them alone: read the full status now and then too.
131
+
101
132
  ## Command line
102
133
 
103
134
  Installing the package also installs a `pybluecurrent` command, which exports your transactions:
@@ -121,9 +152,72 @@ or from the matching `--username` / `--password` / `--api-token` options.
121
152
  - `-o`, `--output`: Write to a file instead of stdout.
122
153
  - `--newest-first` / `--oldest-first`: Output order, newest first by default.
123
154
 
155
+ ### MQTT relay
156
+
157
+ `pybluecurrent relay` publishes what your charge points report to an MQTT broker, for a dashboard or
158
+ a home automation system to read, and runs the commands it receives there. It needs the `mqtt` extra:
159
+
160
+ ```shell
161
+ pip install "pybluecurrent[mqtt]"
162
+
163
+ export BLUECURRENT_USERNAME="your_username"
164
+ export BLUECURRENT_PASSWORD="your_secret_password"
165
+ export BLUECURRENT_MQTT_HOST="broker.example.com"
166
+
167
+ pybluecurrent relay
168
+ ```
169
+
170
+ It publishes, retained, as JSON with a UTC `timestamp`:
171
+
172
+ | Topic | Contents |
173
+ |---|---|
174
+ | `bluecurrent/{evse_id}/{socket_id}/status` | the live status of one socket, every `--poll-interval` seconds (30; at least 15), right after a command (at most once a second), and on each status message the backend pushes |
175
+ | `bluecurrent/{evse_id}/settings` | the charge point's settings, including its smart-charging profiles; read again when a socket's activity changes and after every successful command (at most once a poll interval), and every `--settings-interval` seconds (an hour; at least two minutes) for changes made in the app |
176
+ | `bluecurrent/{evse_id}/grid` | the grid current, kept up to date from the backend's own messages, and read in full with the settings |
177
+ | `bluecurrent/{evse_id}/transactions` | one message per finished charging session (not retained), with `--sync-transactions`. Without `--transaction-state-file`, a restart publishes the last `--transaction-lookback-days` again, so set one if you add them up |
178
+ | `bluecurrent/backend_health` | `up`, or `down` with the error; repeated every minute so its `timestamp` shows the relay is alive |
179
+
180
+ Every option can also be set through an environment variable: its name in capitals, after
181
+ `BLUECURRENT_`, such as `BLUECURRENT_MQTT_HOST` for `--mqtt-host`. Run `pybluecurrent relay --help`
182
+ for the details.
183
+
184
+ To change a setting, publish a JSON command to `bluecurrent/command`. The answer comes on
185
+ `bluecurrent/command/ack` (not retained), with the `id`, `command` and `evse_id` you sent, `status`
186
+ `ok` or `error`, and the `error` when there is one. Commands run one at a time, in the order they
187
+ arrive, so a command that waits for the backend (up to two minutes during an outage) holds back the
188
+ next one. A command sent while the relay is down is lost and gets no answer, so give anything that
189
+ waits for the answer a timeout. Don't publish commands with retain: the relay ignores a retained
190
+ command after a reconnect.
191
+
192
+ | Command | Arguments | Effect |
193
+ |---|---|---|
194
+ | `set_card` | `uid`: a card's UID, or `null` for no card | sets the plug-and-charge card; refused unless the charge point is available |
195
+
196
+ ```shell
197
+ mosquitto_pub -h broker.example.com -t bluecurrent/command \
198
+ -m '{"command": "set_card", "evse_id": "BCU123456", "uid": null, "id": "1"}'
199
+ ```
200
+
201
+ Anyone who can publish to `bluecurrent/command` can change your charge point, so limit that with
202
+ your broker's access control. Limit who can read too: the retained settings hold your address and
203
+ your cards.
204
+
205
+ The backend reports times without a timezone; the relay reads them as Dutch time (Europe/Amsterdam)
206
+ and publishes them in UTC, whatever timezone it runs in.
207
+
208
+ The relay reconnects to the broker by itself, and keeps one backend session across those reconnects.
209
+ On a reconnect it publishes the settings and grid status it already has again, and reads the status;
210
+ it asks the backend for the rest only when those reads are due. It stops on `SIGTERM` after saying
211
+ it is down, and the broker says so on its behalf if the relay is killed instead (that message has no
212
+ `timestamp`). It does exit when the login fails or the backend connection is given up for good,
213
+ after waiting five minutes — rather than logging in over and over, which BlueCurrent would refuse —
214
+ so give it a restart policy that backs off. A charge point that leaves your account keeps its last
215
+ retained messages, so watch their `timestamp`. The relay runs on Linux and macOS, not on Windows.
216
+
124
217
  ## Methods
125
218
 
126
- Every method is a coroutine on `BlueCurrentClient`; call them inside the async context (see
219
+ Every method is a coroutine on `BlueCurrentClient`, except `iterate_transactions` and `live_updates`,
220
+ which are async generators to iterate with `async for`. Call them inside the async context (see
127
221
  [Connection](#connection)). Charge points are addressed by their `evse_id`.
128
222
 
129
223
  - **Account & authentication** — [`get_account`](#get_account), [`get_api_token`](#get_api_token), [`generate_api_token`](#generate_api_token), [`get_contracts`](#get_contracts)
@@ -132,6 +226,7 @@ Every method is a coroutine on `BlueCurrentClient`; call them inside the async c
132
226
  - **Settings & control** — [`set_plug_and_charge_charge_card`](#set_plug_and_charge_charge_card), [`set_status`](#set_status), [`set_capacity_tariff`](#set_capacity_tariff), [`unlock_connector`](#unlock_connector), [`soft_reset`](#soft_reset), [`reboot`](#reboot)
133
227
  - **Smart charging** — [`set_delayed_charging`](#set_delayed_charging), [`set_delayed_charging_schedule`](#set_delayed_charging_schedule), [`set_price_based_charging`](#set_price_based_charging), [`set_price_based_charging_settings`](#set_price_based_charging_settings), [`boost`](#boost)
134
228
  - **Transactions** — [`get_transactions`](#get_transactions), [`iterate_transactions`](#iterate_transactions)
229
+ - **Live updates** — [`live_updates`](#live-updates)
135
230
 
136
231
  ### Response models
137
232
 
@@ -147,7 +242,7 @@ from pybluecurrent.models import ChargePoint, Transaction
147
242
 
148
243
  **The model definitions are the field-level reference** — each field, its type, and any parsing
149
244
  notes live there. The response types are `Account`, `ChargeCard`, `ChargePoint`,
150
- `ChargePointSettings`, `ChargePointStatus`, `GridStatus`, `Grid`, `SustainabilityStatus`,
245
+ `ChargePointSettings`, `ChargePointStatus`, `GridStatus`, `GridCurrent`, `Grid`, `SustainabilityStatus`,
151
246
  `Contract`, `TransactionsPage` and `Transaction`, built from the nested shapes `Tariff`,
152
247
  `Location`, `Address`, `DelayedCharging`, `PriceBasedCharging`, `CapacityTariff`, `CardRef`,
153
248
  `BoolSetting` and `IntSetting`. Dates and times are parsed for you: `date`/`datetime` fields are Python objects, and
@@ -65,6 +65,33 @@ client = BlueCurrentClient(api_token="your_api_token")
65
65
  Retrieve or rotate the token with [`get_api_token`](#get_api_token) and
66
66
  [`generate_api_token`](#generate_api_token), or from the [BlueCurrent website](https://my.bluecurrent.nl).
67
67
 
68
+ A long-lived client reconnects by itself when the connection drops. `client.connected` tells you whether
69
+ the websocket is up right now; calls made while it is reconnecting wait for the connection to return.
70
+
71
+ ### Live updates
72
+
73
+ Besides answering your calls, the backend sends messages of its own accord: the grid current, and the
74
+ status of a socket while it charges. `live_updates` yields them as they arrive, across reconnects:
75
+
76
+ ```python
77
+ async with client:
78
+ async for message in client.live_updates("GRID_CURRENT"):
79
+ print(message["evse_id"], message["grid_actual_p1"])
80
+ ```
81
+
82
+ Name the message types you want, or omit them to receive everything — including the replies to your own
83
+ calls. Messages sent while the connection is down are lost, as are messages arriving before your first
84
+ read. The loop ends when the client is closed, and raises if the client stops reconnecting:
85
+ `ConnectionLost`, or `AuthenticationFailed` when the credentials are rejected.
86
+
87
+ | Type | When | Contents |
88
+ |---|---|---|
89
+ | `GRID_CURRENT` | several times an hour, in bursts, around the clock | `evse_id` and the current per phase, `grid_actual_p1` to `grid_actual_p3`, as integers |
90
+ | `CH_STATUS` | only during a charging session: a few at the start, one at each switch between charging and paused, a few at the unplug, and one every two minutes in between | `evse_id` and `socket_id`, and under `data` the fields of [`get_charge_point_status`](#get_charge_point_status), without `smart_current_heartbeat_timeout` and with `start_datetime` and `stop_datetime` always `""` |
91
+
92
+ The backend can stop sending these for hours, with no error, while your calls still get answers. Don't
93
+ rely on them alone: read the full status now and then too.
94
+
68
95
  ## Command line
69
96
 
70
97
  Installing the package also installs a `pybluecurrent` command, which exports your transactions:
@@ -88,9 +115,72 @@ or from the matching `--username` / `--password` / `--api-token` options.
88
115
  - `-o`, `--output`: Write to a file instead of stdout.
89
116
  - `--newest-first` / `--oldest-first`: Output order, newest first by default.
90
117
 
118
+ ### MQTT relay
119
+
120
+ `pybluecurrent relay` publishes what your charge points report to an MQTT broker, for a dashboard or
121
+ a home automation system to read, and runs the commands it receives there. It needs the `mqtt` extra:
122
+
123
+ ```shell
124
+ pip install "pybluecurrent[mqtt]"
125
+
126
+ export BLUECURRENT_USERNAME="your_username"
127
+ export BLUECURRENT_PASSWORD="your_secret_password"
128
+ export BLUECURRENT_MQTT_HOST="broker.example.com"
129
+
130
+ pybluecurrent relay
131
+ ```
132
+
133
+ It publishes, retained, as JSON with a UTC `timestamp`:
134
+
135
+ | Topic | Contents |
136
+ |---|---|
137
+ | `bluecurrent/{evse_id}/{socket_id}/status` | the live status of one socket, every `--poll-interval` seconds (30; at least 15), right after a command (at most once a second), and on each status message the backend pushes |
138
+ | `bluecurrent/{evse_id}/settings` | the charge point's settings, including its smart-charging profiles; read again when a socket's activity changes and after every successful command (at most once a poll interval), and every `--settings-interval` seconds (an hour; at least two minutes) for changes made in the app |
139
+ | `bluecurrent/{evse_id}/grid` | the grid current, kept up to date from the backend's own messages, and read in full with the settings |
140
+ | `bluecurrent/{evse_id}/transactions` | one message per finished charging session (not retained), with `--sync-transactions`. Without `--transaction-state-file`, a restart publishes the last `--transaction-lookback-days` again, so set one if you add them up |
141
+ | `bluecurrent/backend_health` | `up`, or `down` with the error; repeated every minute so its `timestamp` shows the relay is alive |
142
+
143
+ Every option can also be set through an environment variable: its name in capitals, after
144
+ `BLUECURRENT_`, such as `BLUECURRENT_MQTT_HOST` for `--mqtt-host`. Run `pybluecurrent relay --help`
145
+ for the details.
146
+
147
+ To change a setting, publish a JSON command to `bluecurrent/command`. The answer comes on
148
+ `bluecurrent/command/ack` (not retained), with the `id`, `command` and `evse_id` you sent, `status`
149
+ `ok` or `error`, and the `error` when there is one. Commands run one at a time, in the order they
150
+ arrive, so a command that waits for the backend (up to two minutes during an outage) holds back the
151
+ next one. A command sent while the relay is down is lost and gets no answer, so give anything that
152
+ waits for the answer a timeout. Don't publish commands with retain: the relay ignores a retained
153
+ command after a reconnect.
154
+
155
+ | Command | Arguments | Effect |
156
+ |---|---|---|
157
+ | `set_card` | `uid`: a card's UID, or `null` for no card | sets the plug-and-charge card; refused unless the charge point is available |
158
+
159
+ ```shell
160
+ mosquitto_pub -h broker.example.com -t bluecurrent/command \
161
+ -m '{"command": "set_card", "evse_id": "BCU123456", "uid": null, "id": "1"}'
162
+ ```
163
+
164
+ Anyone who can publish to `bluecurrent/command` can change your charge point, so limit that with
165
+ your broker's access control. Limit who can read too: the retained settings hold your address and
166
+ your cards.
167
+
168
+ The backend reports times without a timezone; the relay reads them as Dutch time (Europe/Amsterdam)
169
+ and publishes them in UTC, whatever timezone it runs in.
170
+
171
+ The relay reconnects to the broker by itself, and keeps one backend session across those reconnects.
172
+ On a reconnect it publishes the settings and grid status it already has again, and reads the status;
173
+ it asks the backend for the rest only when those reads are due. It stops on `SIGTERM` after saying
174
+ it is down, and the broker says so on its behalf if the relay is killed instead (that message has no
175
+ `timestamp`). It does exit when the login fails or the backend connection is given up for good,
176
+ after waiting five minutes — rather than logging in over and over, which BlueCurrent would refuse —
177
+ so give it a restart policy that backs off. A charge point that leaves your account keeps its last
178
+ retained messages, so watch their `timestamp`. The relay runs on Linux and macOS, not on Windows.
179
+
91
180
  ## Methods
92
181
 
93
- Every method is a coroutine on `BlueCurrentClient`; call them inside the async context (see
182
+ Every method is a coroutine on `BlueCurrentClient`, except `iterate_transactions` and `live_updates`,
183
+ which are async generators to iterate with `async for`. Call them inside the async context (see
94
184
  [Connection](#connection)). Charge points are addressed by their `evse_id`.
95
185
 
96
186
  - **Account & authentication** — [`get_account`](#get_account), [`get_api_token`](#get_api_token), [`generate_api_token`](#generate_api_token), [`get_contracts`](#get_contracts)
@@ -99,6 +189,7 @@ Every method is a coroutine on `BlueCurrentClient`; call them inside the async c
99
189
  - **Settings & control** — [`set_plug_and_charge_charge_card`](#set_plug_and_charge_charge_card), [`set_status`](#set_status), [`set_capacity_tariff`](#set_capacity_tariff), [`unlock_connector`](#unlock_connector), [`soft_reset`](#soft_reset), [`reboot`](#reboot)
100
190
  - **Smart charging** — [`set_delayed_charging`](#set_delayed_charging), [`set_delayed_charging_schedule`](#set_delayed_charging_schedule), [`set_price_based_charging`](#set_price_based_charging), [`set_price_based_charging_settings`](#set_price_based_charging_settings), [`boost`](#boost)
101
191
  - **Transactions** — [`get_transactions`](#get_transactions), [`iterate_transactions`](#iterate_transactions)
192
+ - **Live updates** — [`live_updates`](#live-updates)
102
193
 
103
194
  ### Response models
104
195
 
@@ -114,7 +205,7 @@ from pybluecurrent.models import ChargePoint, Transaction
114
205
 
115
206
  **The model definitions are the field-level reference** — each field, its type, and any parsing
116
207
  notes live there. The response types are `Account`, `ChargeCard`, `ChargePoint`,
117
- `ChargePointSettings`, `ChargePointStatus`, `GridStatus`, `Grid`, `SustainabilityStatus`,
208
+ `ChargePointSettings`, `ChargePointStatus`, `GridStatus`, `GridCurrent`, `Grid`, `SustainabilityStatus`,
118
209
  `Contract`, `TransactionsPage` and `Transaction`, built from the nested shapes `Tariff`,
119
210
  `Location`, `Address`, `DelayedCharging`, `PriceBasedCharging`, `CapacityTariff`, `CardRef`,
120
211
  `BoolSetting` and `IntSetting`. Dates and times are parsed for you: `date`/`datetime` fields are Python objects, and
@@ -38,7 +38,9 @@ dependencies = [
38
38
  dynamic = ["version"]
39
39
 
40
40
  [project.optional-dependencies]
41
- dev = ["pre-commit>=3.3.3", "pytest==8.4.2", "pytest-asyncio==1.2.0", "typeguard>=4.0"]
41
+ dev = ["pybluecurrent[mqtt]", "pre-commit>=3.3.3", "pytest==8.4.2", "pytest-asyncio==1.2.0", "typeguard>=4.0"]
42
+ # The MQTT relay (pybluecurrent relay); the client library itself needs none of this.
43
+ mqtt = ["aiomqtt>=2.0,<3", "tzdata"]
42
44
 
43
45
  [project.scripts]
44
46
  pybluecurrent = "pybluecurrent.cli:main"
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.4.1'
22
- __version_tuple__ = version_tuple = (0, 4, 1)
21
+ __version__ = version = '0.5.0'
22
+ __version_tuple__ = version_tuple = (0, 5, 0)
23
23
 
24
- __commit_id__ = commit_id = 'g94f4b103b'
24
+ __commit_id__ = commit_id = 'gf7dba7de9'
@@ -2,6 +2,7 @@
2
2
 
3
3
  from typer import Typer
4
4
 
5
+ from pybluecurrent.cli.relay import relay
5
6
  from pybluecurrent.cli.transactions import transactions
6
7
 
7
8
  app = Typer(no_args_is_help=True, add_completion=False, help="Command-line access to your BlueCurrent account.")
@@ -13,6 +14,7 @@ def _root() -> None:
13
14
 
14
15
 
15
16
  app.command()(transactions)
17
+ app.command()(relay)
16
18
 
17
19
  main = app
18
20
 
@@ -0,0 +1,96 @@
1
+ """The ``relay`` command: publish what your charge points report to an MQTT broker."""
2
+
3
+ from asyncio import run as run_async
4
+ from logging import DEBUG, INFO, basicConfig, getLogger
5
+ from pathlib import Path
6
+ from typing import Annotated
7
+
8
+ from typer import BadParameter, Exit, Option, echo
9
+
10
+
11
+ def relay(
12
+ mqtt_host: Annotated[str, Option(envvar="BLUECURRENT_MQTT_HOST", help="Broker to publish to.")] = "localhost",
13
+ mqtt_port: Annotated[int, Option(envvar="BLUECURRENT_MQTT_PORT", help="Broker port.")] = 1883,
14
+ mqtt_username: Annotated[str | None, Option(envvar="BLUECURRENT_MQTT_USERNAME")] = None,
15
+ mqtt_password: Annotated[str | None, Option(envvar="BLUECURRENT_MQTT_PASSWORD")] = None,
16
+ mqtt_client_id: Annotated[
17
+ str, Option(envvar="BLUECURRENT_MQTT_CLIENT_ID", help="Client identifier to connect with.")
18
+ ] = "pybluecurrent-relay",
19
+ mqtt_qos: Annotated[
20
+ int, Option(envvar="BLUECURRENT_MQTT_QOS", min=0, max=2, help="Quality of service to publish with.")
21
+ ] = 1,
22
+ topic_prefix: Annotated[
23
+ str, Option(envvar="BLUECURRENT_TOPIC_PREFIX", help="Root of every topic.")
24
+ ] = "bluecurrent",
25
+ poll_interval: Annotated[
26
+ float, Option(envvar="BLUECURRENT_POLL_INTERVAL", min=15, help="Seconds between status polls.")
27
+ ] = 30.0,
28
+ settings_interval: Annotated[
29
+ float,
30
+ Option(
31
+ envvar="BLUECURRENT_SETTINGS_INTERVAL",
32
+ min=120, # the backend blocks an account that asks too often
33
+ help="Seconds between settings and transaction polls; both also run after a change and a command.",
34
+ ),
35
+ ] = 3600.0,
36
+ sync_transactions: Annotated[
37
+ bool, Option(envvar="BLUECURRENT_SYNC_TRANSACTIONS", help="Also publish charging transactions.")
38
+ ] = False,
39
+ transaction_lookback_days: Annotated[
40
+ int,
41
+ Option(
42
+ envvar="BLUECURRENT_TRANSACTION_LOOKBACK_DAYS",
43
+ min=0,
44
+ help="How far the first sync looks back; 0 for all history.",
45
+ ),
46
+ ] = 28,
47
+ transaction_rescan_days: Annotated[
48
+ int, Option(envvar="BLUECURRENT_TRANSACTION_RESCAN_DAYS", min=0, help="How far each later sync looks back.")
49
+ ] = 2,
50
+ transaction_state_file: Annotated[
51
+ Path | None,
52
+ Option(
53
+ envvar="BLUECURRENT_TRANSACTION_STATE_FILE",
54
+ help="Where to remember published transactions across restarts.",
55
+ ),
56
+ ] = None,
57
+ username: Annotated[str | None, Option(envvar="BLUECURRENT_USERNAME")] = None,
58
+ password: Annotated[str | None, Option(envvar="BLUECURRENT_PASSWORD")] = None,
59
+ api_token: Annotated[str | None, Option(envvar="BLUECURRENT_API_TOKEN")] = None,
60
+ debug: Annotated[bool, Option(envvar="BLUECURRENT_DEBUG", help="Log every message exchanged.")] = False,
61
+ ) -> None:
62
+ """Publish charge point status, settings and grid current to MQTT, and take commands, until stopped."""
63
+ try:
64
+ from pybluecurrent.relay import Settings, run
65
+ except ImportError as error:
66
+ raise BadParameter(f"The relay needs its extra: pip install pybluecurrent[mqtt] ({error}).")
67
+ if api_token is None and (username is None or password is None):
68
+ raise BadParameter("Set BLUECURRENT_USERNAME and BLUECURRENT_PASSWORD, or BLUECURRENT_API_TOKEN.")
69
+
70
+ basicConfig(format="%(asctime)s %(levelname)s %(message)s", level=INFO)
71
+ if debug:
72
+ getLogger("pybluecurrent").setLevel(DEBUG)
73
+ settings = Settings(
74
+ username=username,
75
+ password=password,
76
+ api_token=api_token,
77
+ mqtt_host=mqtt_host,
78
+ mqtt_port=mqtt_port,
79
+ mqtt_username=mqtt_username,
80
+ mqtt_password=mqtt_password,
81
+ mqtt_client_id=mqtt_client_id,
82
+ mqtt_qos=mqtt_qos,
83
+ topic_prefix=topic_prefix,
84
+ poll_interval=poll_interval,
85
+ settings_interval=settings_interval,
86
+ sync_transactions=sync_transactions,
87
+ transaction_lookback_days=transaction_lookback_days,
88
+ transaction_rescan_days=transaction_rescan_days,
89
+ transaction_state_file=transaction_state_file,
90
+ )
91
+ try:
92
+ run_async(run(settings))
93
+ except Exception as error:
94
+ # Login rejected, no network, or backend given up: print one line, not a traceback.
95
+ echo(f"error: {str(error) or type(error).__name__}", err=True)
96
+ raise Exit(code=1)
@@ -2,11 +2,12 @@ from asyncio import Event, Lock, Queue, Task, create_task, get_running_loop, sle
2
2
  from asyncio import TimeoutError as AsyncTimeoutError
3
3
  from collections import defaultdict, deque
4
4
  from contextlib import asynccontextmanager
5
+ from copy import deepcopy
5
6
  from datetime import date, time
6
7
  from json import JSONDecodeError, dumps, loads
7
8
  from logging import getLogger
8
9
  from random import uniform
9
- from typing import Any, AsyncIterable, AsyncIterator, Iterable, cast
10
+ from typing import Any, AsyncGenerator, AsyncIterable, AsyncIterator, Iterable, cast
10
11
  from uuid import uuid4
11
12
 
12
13
  from asyncio_multisubscriber_queue import MultisubscriberQueue
@@ -102,9 +103,12 @@ _CONNECTION_CLOSED = object()
102
103
  # Frame fields masked before a received message is logged, so a token never reaches the logs.
103
104
  _SENSITIVE_KEYS = ("token", "Authorization")
104
105
 
106
+ # The login verdicts, which carry the session token: never yielded by live_updates.
107
+ _LOGIN_OBJECTS = ("STATUS_PASSWORD", "STATUS_API_TOKEN")
108
+
105
109
 
106
110
  def _redact(message):
107
- """Return the message with any sensitive fields masked, for safe logging."""
111
+ """Return the message with any sensitive fields masked, for safe logging and for live_updates."""
108
112
  if isinstance(message, dict) and any(key in message for key in _SENSITIVE_KEYS):
109
113
  return {key: ("***" if key in _SENSITIVE_KEYS else value) for key, value in message.items()}
110
114
  return message
@@ -196,6 +200,70 @@ class BlueCurrentClient:
196
200
  self._supervisor = None
197
201
  await self._teardown(exc_type, exc_val, exc_tb)
198
202
 
203
+ @property
204
+ def connected(self) -> bool:
205
+ """Whether the websocket is up and usable right now.
206
+
207
+ False before the client is entered, while it reconnects after a drop, and once it has closed
208
+ or given up. A silent network drop still reads True until the keepalive notices it, which
209
+ takes about 40 seconds.
210
+ """
211
+ return self._closed is None and self._drop_reason is None and self._connected.is_set()
212
+
213
+ async def live_updates(self, *objects: str) -> AsyncGenerator[dict[str, Any], None]:
214
+ """Yield messages from the backend as they arrive, for as long as the client lives.
215
+
216
+ The backend pushes messages of its own accord — the grid current, and the status of a socket
217
+ while it charges. It can stop for hours without an error, so do not rely on them alone.
218
+ Subscribing survives reconnects: messages sent while the connection was down are lost, but
219
+ the generator carries on once it is back.
220
+
221
+ Args:
222
+ objects: The message types to yield, such as "GRID_CURRENT". Every message is yielded
223
+ when no type is given — including the replies to your own calls and the handshake of
224
+ each (re)connect, so it is usually worth naming the types you want.
225
+
226
+ Yields:
227
+ Each message as a dictionary, with its type under "object".
228
+
229
+ Raises:
230
+ RuntimeError: If the client was never connected.
231
+ ConnectionLost: If the client stops reconnecting, or the connection drops while
232
+ auto_reconnect is off.
233
+ AuthenticationFailed: If the credentials are rejected while reconnecting.
234
+
235
+ The generator ends when the client is closed. It starts receiving at the first read, not
236
+ when you call it, so a message that arrives in between is missed. Messages queue up while
237
+ you are not reading them, so consume promptly, and close the generator
238
+ (``contextlib.aclosing``, or by letting the loop end) to stop the queueing. An ``ERROR`` the
239
+ backend broadcasts is yielded as a message like any other, not raised.
240
+ """
241
+ with self.queue.queue() as q:
242
+ # Check after subscribing, never before: a client that is already gone would otherwise
243
+ # block here forever instead of saying so.
244
+ if self._closed is not None:
245
+ raise self._closed
246
+ if self.socket is None and self._supervisor is None:
247
+ raise RuntimeError(f"{self.__class__.__name__} is not connected.")
248
+ if self._supervisor is None and self._drop_reason is not None:
249
+ raise self._drop_reason # dropped with no supervisor to reconnect (auto_reconnect off)
250
+ session = self._connected # a fresh Event per __aenter__, so it identifies this session
251
+ while True:
252
+ message = await q.get()
253
+ if message is _CONNECTION_CLOSED:
254
+ if self._shutting_down or self._connected is not session:
255
+ return # this generator's session is over, even if the client was re-entered
256
+ if self._closed is None and self._supervisor is not None:
257
+ continue # a drop the supervisor is about to reconnect
258
+ raise self._closed or self._drop_reason or ConnectionLost("The connection was closed.")
259
+ if message.get("object") in _LOGIN_OBJECTS:
260
+ continue # never hand out the frames carrying the session token
261
+ if objects and message.get("object") not in objects:
262
+ continue
263
+ # A copy per consumer: the same dictionary reaches every subscriber, and the calls
264
+ # awaiting a reply of their own parse and rename its fields in place.
265
+ yield deepcopy(_redact(message))
266
+
199
267
  def _now(self) -> float:
200
268
  """The running loop's clock, behind a seam so tests can drive reconnect timing."""
201
269
  return get_running_loop().time()
@@ -690,6 +758,7 @@ class BlueCurrentClient:
690
758
  "smartcharging_max_usage": 6,
691
759
  "max_offline": 10,
692
760
  "offline_since": "",
761
+ "smart_current_heartbeat_timeout": 0,
693
762
  "start_datetime": datetime(2023, 7, 24, 15, 25, 33),
694
763
  "stop_datetime": datetime(2023, 7, 26, 7, 48, 40),
695
764
  "total_cost": 9.93,
@@ -1186,7 +1255,9 @@ class BlueCurrentClient:
1186
1255
  message_flow_id = message.get("flow_id")
1187
1256
  if flow_id is not None and message_flow_id is not None and message_flow_id != flow_id:
1188
1257
  continue # another call's confirmation for the same object
1189
- return message
1258
+ # A copy, because every subscriber received this same dictionary and the caller goes
1259
+ # on to parse and rename its fields in place.
1260
+ return deepcopy(message)
1190
1261
 
1191
1262
  async def _send(self, data: dict[str, Any], token: bool = False):
1192
1263
  terminal = self._closed or self._drop_reason
@@ -34,11 +34,15 @@ class DelayedCharging(BoolSetting, total=False):
34
34
  vocabulary as ``set_delayed_charging_schedule(days=...)``; the backend's own read key
35
35
  (``selected_days``) is normalized to ``days`` before you see it. ``start_time``/``end_time``
36
36
  are parsed from the backend's "HH:MM" strings into ``time`` objects.
37
+
38
+ ``smart_current_heartbeat_timeout`` is positive while this profile is holding a session back,
39
+ and ``0`` otherwise; see ``ChargePointStatus``, which carries the same field per socket.
37
40
  """
38
41
 
39
42
  start_time: time
40
43
  end_time: time
41
44
  days: list[int]
45
+ smart_current_heartbeat_timeout: int
42
46
 
43
47
 
44
48
  class PriceBasedCharging(BoolSetting, total=False):
@@ -221,6 +225,20 @@ class GridStatus(TypedDict):
221
225
  grid_max_reserved: float # maximum grid current the charge point(s) may use together
222
226
 
223
227
 
228
+ class GridCurrent(TypedDict):
229
+ """A grid-current message, as the backend pushes it to ``live_updates`` (currents in amps).
230
+
231
+ Unlike ``GridStatus``, which ``get_grid_status`` returns, this carries only the actual currents
232
+ of the grid connection a charge point is on, without its maximums.
233
+ """
234
+
235
+ object: str
236
+ evse_id: str
237
+ grid_actual_p1: float # actual current on grid phase L1
238
+ grid_actual_p2: float # actual current on grid phase L2
239
+ grid_actual_p3: float # actual current on grid phase L3
240
+
241
+
224
242
  class SustainabilityStatus(TypedDict):
225
243
  """Sustainability statistics, as returned by ``get_sustainability_status``."""
226
244
 
@@ -228,9 +246,7 @@ class SustainabilityStatus(TypedDict):
228
246
  co2: float
229
247
 
230
248
 
231
- class ChargePointStatus(TypedDict):
232
- """The live status of a charge point, as returned by ``get_charge_point_status``."""
233
-
249
+ class _ChargePointStatusBase(TypedDict):
234
250
  actual_p1: float
235
251
  actual_p2: float
236
252
  actual_p3: float
@@ -252,6 +268,20 @@ class ChargePointStatus(TypedDict):
252
268
  socket_id: int
253
269
 
254
270
 
271
+ class ChargePointStatus(_ChargePointStatusBase, total=False):
272
+ """The live status of a charge point, as returned by ``get_charge_point_status``.
273
+
274
+ ``smart_current_heartbeat_timeout`` is positive while a smart-charging profile is holding this
275
+ session back, and ``0`` when it is not. A positive value together with ``vehicle_status`` "C" (a
276
+ car that is ready to charge) is what the BlueCurrent app shows as "Scheduled", and the state
277
+ ``boost`` overrides. The app guards against it being absent or ``None`` here and falls back to
278
+ the copy in the ``delayed_charging`` setting, so treat both as "no information". The unit is
279
+ undocumented.
280
+ """
281
+
282
+ smart_current_heartbeat_timeout: int | None
283
+
284
+
255
285
  class Contract(TypedDict):
256
286
  """A contract, as returned by ``get_contracts``."""
257
287
 
@@ -0,0 +1,10 @@
1
+ """The MQTT relay: publish what your charge points report to an MQTT broker, and run its commands.
2
+
3
+ Install it with the ``mqtt`` extra (``pip install pybluecurrent[mqtt]``) and run it as
4
+ ``pybluecurrent relay``. The client library itself does not depend on any of this.
5
+ """
6
+
7
+ from pybluecurrent.relay.relay import run
8
+ from pybluecurrent.relay.settings import Settings
9
+
10
+ __all__ = ["Settings", "run"]