Metadata-Version: 2.4
Name: pybluecurrent
Version: 0.5.0rc1
Summary: Python client for BlueCurrent charge points.
Author-email: Rogier van der Geer <rogier@vander-geer.nl>
License: MIT
Project-URL: Repository, https://github.com/rogiervandergeer/pybluecurrent
Keywords: api,blue current,electric vehicle,ev
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: asyncio-multisubscriber-queue>=0.4.1
Requires-Dist: httpx>=0.28
Requires-Dist: sjcl>=0.2.1
Requires-Dist: typer>=0.12
Requires-Dist: websockets>=14.0
Provides-Extra: dev
Requires-Dist: pybluecurrent[mqtt]; extra == "dev"
Requires-Dist: pre-commit>=3.3.3; extra == "dev"
Requires-Dist: pytest==8.4.2; extra == "dev"
Requires-Dist: pytest-asyncio==1.2.0; extra == "dev"
Requires-Dist: typeguard>=4.0; extra == "dev"
Provides-Extra: mqtt
Requires-Dist: aiomqtt<3,>=2.0; extra == "mqtt"
Requires-Dist: tzdata; extra == "mqtt"
Dynamic: license-file

# pybluecurrent

Python client for [BlueCurrent](https://www.bluecurrent.nl) charge points.

![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/rogiervandergeer/pybluecurrent/test.yaml) 
![PyPI](https://img.shields.io/pypi/v/pybluecurrent)
![PyPI - License](https://img.shields.io/pypi/l/pybluecurrent)
![PyPI - Downloads](https://img.shields.io/pypi/dm/pybluecurrent) 

`pybluecurrent` is an **unofficial, third-party async client** — it is not affiliated with
BlueCurrent.

Compared to BlueCurrent's official [`bluecurrent-api`](https://github.com/bluecurrent/HomeAssistantAPI):

- **Per-call `async`/`await`** — each method awaits its own response, rather than a single callback
  receiver that routes every server message.
- **Typed responses** — getters return `TypedDict`-annotated dictionaries; the official client
  hands back untyped dicts.
- **Instance-scoped state** — no process-global mutable state.
- **Username/password *or* API token** — the official client is API-token only.

## Installation

Requires Python 3.10 or newer. Install with pip:

```shell
pip install pybluecurrent
```

or with [uv](https://docs.astral.sh/uv/):

```shell
uv add pybluecurrent
```

This also installs the [`pybluecurrent` command](#command-line) — no extra needed.

## Usage

Using the client is as simple as:
```python
from pybluecurrent import BlueCurrentClient

client = BlueCurrentClient("your_username", "your_secret_password")

async with client:
    charge_points = await client.get_charge_points()
    transactions = await client.get_transactions(charge_points[0]["evse_id"])
```

### Connection

The client can only be used while its websocket is connected. For example:
```python
client = BlueCurrentClient("your_username", "your_secret_password")
async with client:
    result = await client.get_account()
```
Entering the async context automatically logs in.

Instead of a username and password, you can authenticate with an API token:
```python
client = BlueCurrentClient(api_token="your_api_token")
```
Retrieve or rotate the token with [`get_api_token`](#get_api_token) and
[`generate_api_token`](#generate_api_token), or from the [BlueCurrent website](https://my.bluecurrent.nl).

A long-lived client reconnects by itself when the connection drops. `client.connected` tells you whether
the websocket is up right now; calls made while it is reconnecting wait for the connection to return.

### Live updates

Besides answering your calls, the backend sends messages of its own accord: the grid current, and the
status of a socket while it charges. `live_updates` yields them as they arrive, across reconnects:

```python
async with client:
    async for message in client.live_updates("GRID_CURRENT"):
        print(message["evse_id"], message["grid_actual_p1"])
```

Name the message types you want, or omit them to receive everything — including the replies to your own
calls. Messages sent while the connection is down are lost, as are messages arriving before your first
read. The loop ends when the client is closed, and raises if the client stops reconnecting:
`ConnectionLost`, or `AuthenticationFailed` when the credentials are rejected.

| Type | When | Contents |
|---|---|---|
| `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 |
| `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 `""` |

The backend can stop sending these for hours, with no error, while your calls still get answers. Don't
rely on them alone: read the full status now and then too.

## Command line

Installing the package also installs a `pybluecurrent` command, which exports your transactions:

```shell
export BLUECURRENT_USERNAME="your_username"
export BLUECURRENT_PASSWORD="your_secret_password"

pybluecurrent transactions --format csv -o transactions.csv
pybluecurrent transactions --format json --days 30
pybluecurrent transactions --format jsonl --evse-id BCU123456
```

Credentials come from `BLUECURRENT_USERNAME` / `BLUECURRENT_PASSWORD` (or `BLUECURRENT_API_TOKEN`),
or from the matching `--username` / `--password` / `--api-token` options.

**Options**
- `--format`: `csv` (default), `json` (one array) or `jsonl` (one object per line).
- `--evse-id`: Charge point to export, repeatable. Defaults to all of your charge points.
- `--days`: Only export the last N days. Defaults to your whole history.
- `-o`, `--output`: Write to a file instead of stdout.
- `--newest-first` / `--oldest-first`: Output order, newest first by default.

### MQTT relay

`pybluecurrent relay` publishes what your charge points report to an MQTT broker, for a dashboard or
a home automation system to read, and runs the commands it receives there. It needs the `mqtt` extra:

```shell
pip install "pybluecurrent[mqtt]"

export BLUECURRENT_USERNAME="your_username"
export BLUECURRENT_PASSWORD="your_secret_password"
export BLUECURRENT_MQTT_HOST="broker.example.com"

pybluecurrent relay
```

It publishes, retained, as JSON with a UTC `timestamp`:

| Topic | Contents |
|---|---|
| `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 |
| `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 |
| `bluecurrent/{evse_id}/grid` | the grid current, kept up to date from the backend's own messages, and read in full with the settings |
| `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 |
| `bluecurrent/backend_health` | `up`, or `down` with the error; repeated every minute so its `timestamp` shows the relay is alive |

Every option can also be set through an environment variable: its name in capitals, after
`BLUECURRENT_`, such as `BLUECURRENT_MQTT_HOST` for `--mqtt-host`. Run `pybluecurrent relay --help`
for the details.

To change a setting, publish a JSON command to `bluecurrent/command`. The answer comes on
`bluecurrent/command/ack` (not retained), with the `id`, `command` and `evse_id` you sent, `status`
`ok` or `error`, and the `error` when there is one. Commands run one at a time, in the order they
arrive, so a command that waits for the backend (up to two minutes during an outage) holds back the
next one. A command sent while the relay is down is lost and gets no answer, so give anything that
waits for the answer a timeout. Don't publish commands with retain: the relay ignores a retained
command after a reconnect.

| Command | Arguments | Effect |
|---|---|---|
| `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 |

```shell
mosquitto_pub -h broker.example.com -t bluecurrent/command \
  -m '{"command": "set_card", "evse_id": "BCU123456", "uid": null, "id": "1"}'
```

Anyone who can publish to `bluecurrent/command` can change your charge point, so limit that with
your broker's access control. Limit who can read too: the retained settings hold your address and
your cards.

The backend reports times without a timezone; the relay reads them as Dutch time (Europe/Amsterdam)
and publishes them in UTC, whatever timezone it runs in.

The relay reconnects to the broker by itself, and keeps one backend session across those reconnects.
On a reconnect it publishes the settings and grid status it already has again, and reads the status;
it asks the backend for the rest only when those reads are due. It stops on `SIGTERM` after saying
it is down, and the broker says so on its behalf if the relay is killed instead (that message has no
`timestamp`). It does exit when the login fails or the backend connection is given up for good,
after waiting five minutes — rather than logging in over and over, which BlueCurrent would refuse —
so give it a restart policy that backs off. A charge point that leaves your account keeps its last
retained messages, so watch their `timestamp`. The relay runs on Linux and macOS, not on Windows.

## Methods

Every method is a coroutine on `BlueCurrentClient`, except `iterate_transactions` and `live_updates`,
which are async generators to iterate with `async for`. Call them inside the async context (see
[Connection](#connection)). Charge points are addressed by their `evse_id`.

- **Account & authentication** — [`get_account`](#get_account), [`get_api_token`](#get_api_token), [`generate_api_token`](#generate_api_token), [`get_contracts`](#get_contracts)
- **Charge points & cards** — [`get_charge_points`](#get_charge_points), [`get_charge_point_settings`](#get_charge_point_settings), [`get_charge_point_status`](#get_charge_point_status), [`get_charge_point_statuses`](#get_charge_point_statuses), [`get_charge_cards`](#get_charge_cards)
- **Grid & sustainability** — [`get_grid_status`](#get_grid_status), [`get_grids`](#get_grids), [`get_sustainability_status`](#get_sustainability_status)
- **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)
- **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)
- **Transactions** — [`get_transactions`](#get_transactions), [`iterate_transactions`](#iterate_transactions)
- **Live updates** — [`live_updates`](#live-updates)

### Response models

The getters return plain dictionaries annotated with `TypedDict`s from
[`pybluecurrent.models`](https://github.com/rogiervandergeer/pybluecurrent/blob/main/src/pybluecurrent/models.py).
Access is unchanged — `response["key"]`, `.get()`, `**response` and `json.dumps` all keep working —
and an unexpected field the backend adds simply rides along; the types just add autocomplete and
static checking:

```python
from pybluecurrent.models import ChargePoint, Transaction
```

**The model definitions are the field-level reference** — each field, its type, and any parsing
notes live there. The response types are `Account`, `ChargeCard`, `ChargePoint`,
`ChargePointSettings`, `ChargePointStatus`, `GridStatus`, `GridCurrent`, `Grid`, `SustainabilityStatus`,
`Contract`, `TransactionsPage` and `Transaction`, built from the nested shapes `Tariff`,
`Location`, `Address`, `DelayedCharging`, `PriceBasedCharging`, `CapacityTariff`, `CardRef`,
`BoolSetting` and `IntSetting`. Dates and times are parsed for you: `date`/`datetime` fields are Python objects, and
schedule times (`start_time`, `end_time`, `expected_departure_time`) are `datetime.time`.

### Account & authentication

#### get_account

```python
async def get_account(self) -> Account
```

Returns your account information as an [`Account`](#response-models).

#### get_api_token

```python
async def get_api_token(self) -> str
```

Returns the API token (home automation key) for your account. It can be used to authenticate
instead of a username and password, by constructing the client with `BlueCurrentClient(api_token=...)`.

#### generate_api_token

```python
async def generate_api_token(self) -> str
```

Generates a new API token and returns it. **Warning:** this rotates the token — any previously
issued token is invalidated, which will break anything still using the old one.

#### get_contracts

```python
async def get_contracts(self) -> list[Contract]
```

Returns your contracts, each a [`Contract`](#response-models).

### Charge points & cards

#### get_charge_points

```python
async def get_charge_points(self) -> list[ChargePoint]
```

Returns your charge points, each a [`ChargePoint`](#response-models). A disabled smart-charging
profile is still present as its `{value, permission}` wrapper; its schedule/settings fields appear
only while the profile is enabled.

#### get_charge_point_settings

```python
async def get_charge_point_settings(self, evse_id: str) -> ChargePointSettings
```

Returns the settings of a charge point as a [`ChargePointSettings`](#response-models). All of this
is already included in the response of [`get_charge_points`](#get_charge_points).

**Arguments**
- `evse_id`: The ID of the charge point.

#### get_charge_point_status

```python
async def get_charge_point_status(self, evse_id: str, socket_id: int | None = None) -> ChargePointStatus
```

Returns the live status of a single socket as a [`ChargePointStatus`](#response-models). Most charge
points have a single socket, and omitting `socket_id` returns it whatever its number. Dual-socket
models (such as the NanoXL) have a socket per side, and there is no sensible default between them:
name the `socket_id` you want, or use
[`get_charge_point_statuses`](#get_charge_point_statuses) to fetch them all. Raises `ValueError` if
the charge point has no socket with the given `socket_id`, or if `socket_id` is omitted for a
multi-socket charge point.

**Arguments**
- `evse_id`: The ID of the charge point.
- `socket_id`: The socket to fetch. May be omitted for a single-socket charge point.

#### get_charge_point_statuses

```python
async def get_charge_point_statuses(self, evse_id: str) -> list[ChargePointStatus]
```

Returns the live status of every socket of a charge point, each a
[`ChargePointStatus`](#response-models). Single-socket charge points return a one-element list;
dual-socket models return one entry per socket, each tagged with its `socket_id`.

**Arguments**
- `evse_id`: The ID of the charge point.

#### get_charge_cards

```python
async def get_charge_cards(self) -> list[ChargeCard]
```

Returns your charge cards, each a [`ChargeCard`](#response-models).

### Grid & sustainability

#### get_grid_status

```python
async def get_grid_status(self, evse_id: str) -> GridStatus
```

Returns the grid status associated with a charge point (currents in amps) as a
[`GridStatus`](#response-models).

**Arguments**
- `evse_id`: The ID of the charge point.

#### get_grids

```python
async def get_grids(self) -> list[Grid]
```

Returns your grid connections, each a [`Grid`](#response-models).

#### get_sustainability_status

```python
async def get_sustainability_status(self) -> SustainabilityStatus
```

Returns sustainability statistics for all your charge points as a
[`SustainabilityStatus`](#response-models) — `{"trees": ..., "co2": ...}`.

### Settings & control

#### set_plug_and_charge_charge_card

```python
async def set_plug_and_charge_charge_card(self, evse_id: str, uid: str | None = None) -> None
```

Sets the plug-and-charge card for the charge point. `uid` must be the `uid` of one of your
[charge cards](#get_charge_cards), or `None` to charge without a card. Raises `BlueCurrentException`
if the command fails.

**Arguments**
- `evse_id`: The ID of the charge point.
- `uid`: A charge card UID, or `None` (the default) to use no charge card.

#### set_status

```python
async def set_status(self, evse_id: str, enabled: bool, socket_id: int | None = None) -> None
```

Enables or disables a socket of a charge point. The call returns once the backend confirms the
change, and raises `BlueCurrentException` if it fails — for example when the charge point does not
respond.

**Arguments**
- `evse_id`: The ID of the charge point.
- `enabled`: Boolean that indicates the desired status.
- `socket_id`: The socket to enable or disable. May be omitted for a single-socket charge point.

#### unlock_connector

```python
async def unlock_connector(self, evse_id: str, socket_id: int | None = None) -> None
```

Unlocks the connector of a charge point. Raises `BlueCurrentException` if the command fails, and
`NotImplementedError` for portable (UMOVE) charge points, which are not supported.

**Arguments**
- `evse_id`: The ID of the charge point.
- `socket_id`: The socket to unlock. May be omitted for a single-socket charge point.

#### soft_reset

```python
async def soft_reset(self, evse_id: str) -> None
```

Soft-resets a charge point. Raises `BlueCurrentException` if the command fails.

**Arguments**
- `evse_id`: The ID of the charge point.

#### reboot

```python
async def reboot(self, evse_id: str) -> None
```

Reboots a charge point — a full reboot, as opposed to the software reset of
[`soft_reset`](#soft_reset). Raises `BlueCurrentException` if the command fails.

**Arguments**
- `evse_id`: The ID of the charge point.

#### set_capacity_tariff

```python
async def set_capacity_tariff(self, evse_id: str, enabled: bool, max_kwh: float | None = None) -> None
```

Enables, updates or disables the capacity-tariff setting of a charge point: an on/off toggle
with a maximum energy value in kWh, applied by the backend. The configured state is read back
from the `capacity_tariff` field of the charge point settings, where the value appears as
`max_kwh`.

**Arguments**
- `evse_id`: The ID of the charge point.
- `enabled`: Whether the capacity tariff should be enabled.
- `max_kwh`: The maximum energy value in kWh, from `0.01` to `80` inclusive. Required when
  enabling; must be omitted when disabling.

### Smart charging

#### set_delayed_charging

```python
async def set_delayed_charging(self, evse_id: str, enabled: bool) -> None
```

Enables or disables delayed charging. While enabled, the charge point only charges within the window
configured with [`set_delayed_charging_schedule`](#set_delayed_charging_schedule), and delays
charging outside of it. A charge point has at most one smart-charging profile active, so enabling
this disables any other profile.

**Arguments**
- `evse_id`: The ID of the charge point.
- `enabled`: Whether delayed charging should be enabled.

#### set_delayed_charging_schedule

```python
async def set_delayed_charging_schedule(
    self,
    evse_id: str,
    start_time: time | str,
    end_time: time | str,
    days: Iterable[Weekday | int | str],
) -> None
```

Sets the window in which the charge point may charge on the selected days. The window may span
midnight. It is applied only while delayed charging is enabled with
[`set_delayed_charging`](#set_delayed_charging).

```python
from datetime import time
from pybluecurrent import Weekday

await client.set_delayed_charging_schedule(
    "BCU123456", start_time=time(23, 0), end_time=time(7, 0), days=[Weekday.MONDAY, "tu", 3]
)
```

**Arguments**
- `evse_id`: The ID of the charge point.
- `start_time`: The time at which charging may start, as a `time` or a `"HH:MM"` string.
- `end_time`: The time at which charging must stop, as a `time` or a `"HH:MM"` string.
- `days`: The days on which the schedule applies. Each day may be a `pybluecurrent.Weekday`, an
  isoweekday number (1 for Monday through 7 for Sunday), or a name such as `"monday"` or `"mo"`.

The schedule is read back from the `delayed_charging` key of
[`get_charge_point_settings`](#get_charge_point_settings).

#### set_price_based_charging

```python
async def set_price_based_charging(self, evse_id: str, enabled: bool) -> None
```

Enables or disables price-based charging. While enabled, the charge point charges during the
cheapest hours before the expected departure time, as configured with
[`set_price_based_charging_settings`](#set_price_based_charging_settings). A charge point has at most
one smart-charging profile active, so enabling this disables any other profile.

**Arguments**
- `evse_id`: The ID of the charge point.
- `enabled`: Whether price-based charging should be enabled.

#### set_price_based_charging_settings

```python
async def set_price_based_charging_settings(
    self,
    evse_id: str,
    expected_departure_time: time | str,
    expected_kwh: float,
    minimum_kwh: float,
) -> None
```

Configures how much energy to charge before departure. Applied only while price-based charging is
enabled with [`set_price_based_charging`](#set_price_based_charging).

**Arguments**
- `evse_id`: The ID of the charge point.
- `expected_departure_time`: The time the vehicle is expected to leave, as a `time` or a `"HH:MM"`
  string.
- `expected_kwh`: The amount of energy, in kWh, expected to be charged before departure.
- `minimum_kwh`: The amount of energy, in kWh, to charge immediately regardless of price.

The settings are read back from the `price_based_charging` key of
[`get_charge_point_settings`](#get_charge_point_settings).

#### boost

```python
async def boost(self, evse_id: str) -> None
```

Starts charging immediately, overriding whichever smart-charging profile is currently delaying
charging — delayed charging or price-based charging — for the ongoing session. The override cannot
be undone. While it is active, [`get_charge_point_status`](#get_charge_point_status) reports
`"boosting": True`. Raises `ValueError` if no smart-charging profile is active.

**Arguments**
- `evse_id`: The ID of the charge point.

### Transactions

#### get_transactions

```python
async def get_transactions(
    self,
    evse_id: str,
    newest_first: bool = True,
    page: int = 1,
    start_date: date | None = None,
    end_date: date | None = None,
) -> TransactionsPage
```

Returns a single page of transactions as a [`TransactionsPage`](#response-models); its
`transactions` key holds a list of [`Transaction`](#response-models).

**Arguments**
- `evse_id`: The ID of the charge point.
- `newest_first`: If `True`, start with the most recent transaction. Defaults to `True`.
- `page`: Page number to get. Defaults to `1`.
- `start_date`: Only return transactions from this date onwards. Omitted by default.
- `end_date`: Only return transactions up to this date. Omitted by default.

#### iterate_transactions

```python
async def iterate_transactions(
    self,
    evse_id: str,
    newest_first: bool = True,
    start_date: date | None = None,
    end_date: date | None = None,
) -> AsyncIterable[Transaction]
```

Iterates over all your transactions, fetching further pages as needed. Yields
[`Transaction`](#response-models) dictionaries.

**Arguments**
- `evse_id`: The ID of the charge point.
- `newest_first`: If `True`, start with the most recent transaction. Defaults to `True`.
- `start_date`: Only return transactions from this date onwards. Omitted by default.
- `end_date`: Only return transactions up to this date. Omitted by default.

## Development

- **Install** (editable, with dev extras): `uv sync --extra dev` (or `pip install -e ".[dev]"`).
- **Pre-commit**: the repo ships a `.pre-commit-config.yaml`, but git installs no hooks on clone, so
  it is a one-time manual step — run `uvx pre-commit install`.
- **Contributions** and feature requests are welcome.

## Changelog

See [CHANGELOG.md](https://github.com/rogiervandergeer/pybluecurrent/blob/main/CHANGELOG.md).
