> ## Documentation Index
> Fetch the complete documentation index at: https://developer.plugchoice.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Live updates

> Follow chargers' live state over a WebSocket: the state now, then each change as it happens.

The WebSocket at `wss://api.plugchoice.com/v4/websocket` sends you the live state of chargers as it changes. You subscribe once, get each charger's state now, then its whole state again after each change. A charger's state is the JSON that [`GET /v4/chargers/{charger}/live`](https://developer.plugchoice.com/v4/api/get-charger-live) answers, so one parser reads both.

## Poll or subscribe

Poll [`GET /v4/chargers/{charger}/live`](https://developer.plugchoice.com/v4/api/get-charger-live), or [`GET /v4/chargers/live`](https://developer.plugchoice.com/v4/api/list-chargers-live) for several chargers, when you need the state now and then: a script that runs every few minutes, a page that shows the state when it opens, or code that can't keep a connection open.

Subscribe when you act on changes as they happen, such as on a dashboard that stays open, in Home Assistant or in evcc. A change reaches you without waiting for your next poll.

The WebSocket only reads. To change something, such as [an EVSE's limit](https://developer.plugchoice.com/v4/api/update-evse.md), send an HTTP request.

## Connect

Open a WebSocket to `wss://api.plugchoice.com/v4/websocket`, with nothing in the URL. Your token goes in the first message, never in the URL: proxies along the way log URLs, and browsers keep them in their history. A browser's `WebSocket` can't send an `Authorization` header, so a first message works the same for every client. The API doesn't read an `Authorization` header on the upgrade.

The API may refuse the upgrade with a [problem](https://developer.plugchoice.com/v4/errors.md):

| Status | When |
| - | - |
| `400` [`bad-request`](https://developer.plugchoice.com/api/errors/bad-request) | The URL has a query string, or the request isn't a WebSocket upgrade. |
| `403` [`forbidden`](https://developer.plugchoice.com/api/errors/forbidden) | A browser page on an origin the API doesn't allow. Only a request with an `Origin` header is checked, and browsers send one. |
| `503` [`unavailable`](https://developer.plugchoice.com/api/errors/unavailable) | The server is full or stopping. [Reconnect](#reconnect) with backoff. |

Every message, both ways, is a JSON object in a text frame:

| Field | |
| - | - |
| `type` | What the message is, such as `subscribe` or `live`. |
| `id` | Your id for a request, 1 to 64 characters. The answer carries it, and so does every message of a subscription. |
| `data` | The content. Absent when there is none. |

A message with another field gets [`validation-failed`](https://developer.plugchoice.com/api/errors/validation-failed). A binary frame, or text that isn't a JSON object with a `type`, closes the connection with `4000`. Ignore fields, message types and reasons you don't know: like the rest of v4, the protocol only adds.

Right after the upgrade, the server sends `hello`:

```json theme={null}
{"type": "hello", "data": {"connection_id": "6f1c2d3e-8a4b-4c5d-9e6f-7a8b9c0d1e2f", "heartbeat_interval_s": 25, "authenticate_within_s": 10}}
```

Give the `connection_id` when you ask support about a connection.

## Authenticate

Within 10 seconds of `hello`, and before any other message, send `authenticate` with an access token. It's the token you send to the HTTP API: see [authentication](https://developer.plugchoice.com/v4/authentication.md).

```json theme={null}
{"type": "authenticate", "id": "1", "data": {"token": "YOUR_ACCESS_TOKEN"}}
```

```json theme={null}
{"type": "authenticated", "id": "1", "data": {"expires_at": "2026-11-24T10:20:00Z", "scopes": ["chargers:read", "chargers:control"]}}
```

`expires_at` is when the connection's authentication ends: the token's expiry, or the end of a personal API token when that comes first. `scopes` are the token's scopes. The `id` is optional.

* A token the API doesn't accept gets an `error` with [`unauthenticated`](https://developer.plugchoice.com/api/errors/unauthenticated), and the connection closes with `4002`. So does a client's own token, which belongs to your OAuth client and not to a person. Every HTTP endpoint except [`GET /token`](https://developer.plugchoice.com/v4/api/get-token) refuses it too.
* No `authenticate` within 10 seconds, or another message first, closes the connection with `4001`.

## Subscribe

Send `subscribe` with an `id` of your own. The id names the subscription: every message of it carries the id.

```json theme={null}
{"type": "subscribe", "id": "garage", "data": {"topic": "chargers/live", "filter": {"location_id": "5620bf8d-88e0-4d6f-9153-4a3b97e5ae30"}}}
```

```json theme={null}
{"type": "subscribed", "id": "garage", "data": {"topic": "chargers/live", "count": 2}}
```

```json theme={null}
{
  "type": "live",
  "id": "garage",
  "data": {
    "charger_id": "0f8d4c1e-7b5e-4a5e-9a51-3c1f0e8b2d47",
    "connection": {
      "status": "online",
      "last_seen_at": "2026-11-24T09:00:00Z"
    },
    "evses": [
      {
        "id": 1,
        "status": "charging",
        "status_changed_at": "2026-11-24T09:30:00Z",
        "measurements": {
          "power_w": 11040.0,
          "current_a": {
            "l1": 16.0,
            "l2": 16.1,
            "l3": 15.9
          },
          "voltage_v": null,
          "energy_register_wh": 1523400.0,
          "soc_percent": null,
          "measured_at": "2026-11-24T10:15:30Z"
        },
        "transaction": {
          "id": "8d3c2a90-51f7-4c1e-b7d2-6f0e9a4c3b18",
          "started_at": "2026-11-24T09:30:00Z",
          "energy_wh": 5300
        },
        "limit": {
          "current_a": 16,
          "power_w": null,
          "set_by": "api"
        },
        "allocation": null
      }
    ]
  }
}
```

The topic `chargers/live` follows the chargers that [`GET /v4/chargers/live`](https://developer.plugchoice.com/v4/api/list-chargers-live) lists, with its scope (`chargers:read`), access and reach. Its filter takes the list's filters that say where:

| Filter | |
| - | - |
| `charger_id` | These chargers, as a list of up to 100 ids. |
| `location_id` | The chargers at this location. |
| `team_id` | The chargers of this team. It must be one of your teams. |

Filters narrow each other. Without a filter, the subscription follows every charger your token reaches, when that is at most 100. The list's other filters, such as `status`, aren't taken: they change with the state the subscription sends.

Instead of `subscribed`, you get an `error` with the subscription's id when:

| Code | When |
| - | - |
| [`insufficient-scope`](https://developer.plugchoice.com/api/errors/insufficient-scope) | The token lacks `chargers:read`. |
| [`not-found`](https://developer.plugchoice.com/api/errors/not-found) | The filter names a charger, location or team you can't reach. |
| [`too-broad`](https://developer.plugchoice.com/api/errors/too-broad) | The filter gives more than 100 chargers, or the connection would follow more than 500. |
| [`validation-failed`](https://developer.plugchoice.com/api/errors/validation-failed) | The message has no `id` or names an unknown topic, or the filter has a field the topic doesn't take or a value that isn't an id. |
| [`too-many-subscriptions`](https://developer.plugchoice.com/api/errors/too-many-subscriptions) | The connection has 20 subscriptions. |
| [`duplicate-id`](https://developer.plugchoice.com/api/errors/duplicate-id) | An open subscription has this id. |
| [`unavailable`](https://developer.plugchoice.com/api/errors/unavailable) | The server follows as many chargers as it can. Try again later. |

To end a subscription, send `unsubscribe` with its id:

```json theme={null}
{"type": "unsubscribe", "id": "garage"}
```

```json theme={null}
{"type": "unsubscribed", "id": "garage", "data": {"reason": "requested"}}
```

An id that names no open subscription gets [`not-found`](https://developer.plugchoice.com/api/errors/not-found). After `unsubscribed`, you can use the id again.

## What a subscription sends

* `subscribed`, with `count`: how many chargers it follows.
* A `live` per charger with its state now, in the list's order.
* A `live` after each change, with the charger's whole state. Replace what you had with it.
* At most one `live` per charger a second. A charger that changes more often sends its newest state at the end of the second. A change that undoes itself within the second sends nothing.
* `removed` with a `charger_id` when a charger leaves a location's or a team's subscription, and a `live` when a charger comes in. The API checks this every 60 seconds.
* `unsubscribed` with a `reason` when the subscription ends. No message of the subscription comes after it.

| `reason` | |
| - | - |
| `requested` | You sent `unsubscribe`. |
| `insufficient_scope` | Your token lost `chargers:read`, at a renewal with fewer scopes. |
| `not_found` | Something the filter names is out of your reach now. |
| `too_broad` | The filter gives more than 100 chargers now, or the connection would follow more than 500. |

Messages arrive in the order the server sent them. Between subscriptions there is no order beyond that: compare the times in the state, such as `measured_at` and `status_changed_at`.

Chargers you name with `charger_id` stay watched while the subscription is open: while they charge, they send their meter values every 60 seconds, so their power and current change more often. A subscription of a location or a team keeps no charger watched.

There is no resume. On a new connection, subscribe again: the first messages are the state now. Changes in between aren't sent, and a charger missing from the new first messages is no longer in the subscription. A session that started and ended while you were away is in no `live` message. Read those with [`GET /v4/transactions`](https://developer.plugchoice.com/v4/api/list-transactions) and `updated_since`.

## Renew the token

60 seconds before `expires_at`, the server sends `token_expiring`. Send `authenticate` again with a fresh access token. The connection and its subscriptions go on.

```json theme={null}
{"type": "token_expiring", "data": {"expires_at": "2026-11-24T10:20:00Z"}}
```

```json theme={null}
{"type": "authenticate", "id": "2", "data": {"token": "YOUR_FRESH_ACCESS_TOKEN"}}
```

```json theme={null}
{"type": "authenticated", "id": "2", "data": {"expires_at": "2026-11-24T10:25:00Z", "scopes": ["chargers:read", "chargers:control"]}}
```

You may renew at any time before `expires_at`.

* The fresh token must be for the same person and the same OAuth client. Another token gets [`forbidden`](https://developer.plugchoice.com/api/errors/forbidden), and the connection keeps its old one. To change users, open a new connection.
* A fresh token the API doesn't accept gets [`unauthenticated`](https://developer.plugchoice.com/api/errors/unauthenticated). The connection goes on with its old token until `expires_at`.
* Without a fresh token, the connection closes with `4100` at `expires_at`. A renewal can't take a connection past the end of a personal API token.
* Don't give `authenticate` the id of an open subscription: it gets [`duplicate-id`](https://developer.plugchoice.com/api/errors/duplicate-id), and the token isn't renewed.

The API checks your access again every 60 seconds, and at once when a fresh token has other scopes or another reach. What you can no longer reach ends with `removed` or `unsubscribed`.

## Heartbeats

* The server sends `heartbeat` after 25 seconds without another message (`heartbeat_interval_s` in `hello`).
* Nothing from the server for 60 seconds, not even a `heartbeat`, means the connection is gone, even when your socket doesn't say so. Close it and [reconnect](#reconnect).
* The server sends a WebSocket Ping frame every 25 seconds. Browsers and WebSocket libraries answer it by themselves. A connection the server hears nothing from for 60 seconds, not even that answer, closes with `4102`.
* Read messages as they come. A connection that takes no message for 60 seconds closes with `4103`.

To check a connection yourself, such as when your app comes back from the background, send `ping`. A `pong` comes back with the same `data` and `id`:

```json theme={null}
{"type": "ping", "data": 42}
```

```json theme={null}
{"type": "pong", "data": 42}
```

## Reconnect

Before the server closes a connection, it sends `reconnect`: when the server stops, such as for a release, or when the connection reaches its maximum age, after 50 to 60 minutes.

```json theme={null}
{"type": "reconnect", "data": {"reason": "server_stopping", "close_in_s": 10}}
```

1. Open a new connection, authenticate and subscribe, as at the start.
2. Once the new subscriptions are made, close the old connection with code `1000`. Until then both may send the same state: keep the new connection's.
3. The server closes the old connection after `close_in_s` seconds, with `4200` or `4201`.

Other closes tell you what to do by their code:

| Code | What to do |
| - | - |
| `4000` to `4099` | Change something first. Connecting again as before fails again. |
| `4100` to `4199` | Reconnect with backoff. |
| `4200` to `4299` | Reconnect after a random wait of 0 to 5 seconds. |
| Any other, such as `1001`, `1006` or `1011` | Reconnect with backoff. |

Backoff means a random wait before each attempt, up to 2 seconds before the first, then up to 4, 8 and so on, at most 60. Start counting again once a connection has been authenticated for a minute.

| Code | Reason | When |
| - | - | - |
| `1000` | `normal` | You closed the connection, such as the old one after `reconnect`. |
| `1002` | `protocol_error` | A frame that breaks the WebSocket protocol (RFC 6455). |
| `1007` | `invalid_data` | A text frame that isn't UTF-8. |
| `4000` | `bad_message` | A binary frame, or text that isn't a JSON object with a `type`. |
| `4001` | `not_authenticated` | No `authenticate` within 10 seconds, or another message first. |
| `4002` | `authentication_failed` | The first token isn't accepted, or is a client's own token. Get one that works. |
| `4003` | `message_too_big` | A message over 16 KiB. |
| `4004` | `too_many_connections` | Your OAuth client has 10 connections open for this person already, or the person has 20 over all their clients. |
| `4100` | `token_expired` | No fresh token by `expires_at`. |
| `4101` | `rate_limited` | More than 60 messages a minute. |
| `4102` | `heartbeat_timeout` | Nothing from you for 60 seconds, not even the answer to a Ping. |
| `4103` | `too_slow` | You took no message for 60 seconds. You may not get this close and see the connection drop instead (`1006`). |
| `4104` | `unavailable` | The server is full, or a service it needs doesn't answer. |
| `4105` | `server_error` | A fault on our side. |
| `4200` | `server_stopping` | The server stops. A `reconnect` came first. |
| `4201` | `max_age` | The connection reached its maximum age. A `reconnect` came first. |

## Limits

| What | Limit | Past it |
| - | - | - |
| A message from you | 16 KiB | Close `4003` |
| Messages from you | 20 at once, then 1 a second: 60 a minute | Close `4101` |
| Subscriptions per connection | 20 | [`too-many-subscriptions`](https://developer.plugchoice.com/api/errors/too-many-subscriptions) |
| Chargers per subscription | 100 | [`too-broad`](https://developer.plugchoice.com/api/errors/too-broad) |
| Chargers per connection, each counted once | 500 | [`too-broad`](https://developer.plugchoice.com/api/errors/too-broad) |
| Connections per OAuth client and person | 10 | Close `4004` |
| Connections per person, over all clients | 20 | Close `4004` |

Each personal API token counts as an OAuth client of its own. A connection that was sent `reconnect` doesn't count toward the connection limits, so the new one you open in its place fits.

## Try it

[websocat](https://github.com/vi/websocat) sends each line you give it as a message, and prints each message it gets. This sends `authenticate` with the token in `$ACCESS_TOKEN`, then `subscribe`, then each line you type:

```bash theme={null}
{ jq -nc --arg token "$ACCESS_TOKEN" '{type: "authenticate", data: {token: $token}}'
  jq -nc '{type: "subscribe", id: "garage", data: {topic: "chargers/live", filter: {location_id: "YOUR_LOCATION_ID"}}}'
  cat; } | websocat wss://api.plugchoice.com/v4/websocket
```

The connection closes with `4100` when the token runs out.

## Examples

Both examples follow the chargers at one location and print each EVSE's status and power. They renew the token on `token_expiring`, move to a new connection on `reconnect`, reconnect with backoff by the close code, and give up on a connection that sends nothing for 60 seconds. They get their token with a personal API token's client ID and secret: see [authentication](https://developer.plugchoice.com/guides/authentication.md).

The JavaScript example uses the standard `WebSocket`, so it runs in Node.js 22 or later and in a browser on an origin the API allows. In a browser, make `accessToken()` return the access token of your app's sign-in: a client secret never goes in code that runs in a browser.

The Python example needs Python 3.11 or later and the [websockets](https://websockets.readthedocs.io) library, version 14 or later (`pip install websockets`).

```javascript JavaScript theme={null}
const SOCKET_URL = "wss://api.plugchoice.com/v4/websocket";
const TOKEN_URL = "https://accounts.plugchoice.com/realms/accounts/protocol/openid-connect/token";
const SUBSCRIPTION = { topic: "chargers/live", filter: { location_id: "YOUR_LOCATION_ID" } };

// A fresh access token for a personal API token's client ID and secret.
async function accessToken() {
  const response = await fetch(TOKEN_URL, {
    method: "POST",
    body: new URLSearchParams({
      grant_type: "client_credentials",
      client_id: "YOUR_CLIENT_ID",
      client_secret: "YOUR_CLIENT_SECRET",
    }),
  });
  if (!response.ok) throw new Error(`token: ${response.status}`);
  return (await response.json()).access_token;
}

const chargers = new Map(); // each charger's live state, by its id
let attempt = 0;

function show(state) {
  for (const evse of state.evses) {
    console.log(state.charger_id, evse.id, evse.status, evse.measurements?.power_w);
  }
}

// One connection, from hello to its close. After a `reconnect`, `previous` is the connection
// this one takes over from: it closes once this one's subscription is made.
function connect(previous) {
  const socket = new WebSocket(SOCKET_URL);
  let done = false; // given up, or a newer connection took over
  let authenticatedAt = null;
  let silence;

  const send = (message) => socket.send(JSON.stringify(message));

  async function authenticate() {
    try {
      send({ type: "authenticate", data: { token: await accessToken() } });
    } catch (error) {
      socket.close();
      ended(1006, error.message);
    }
  }

  // Nothing from the server for 60 seconds: the connection is gone.
  function listen() {
    clearTimeout(silence);
    silence = setTimeout(() => {
      socket.close();
      ended(1006, "nothing for 60 seconds");
    }, 60_000);
  }

  // What comes after this connection, from its close code.
  function ended(code, reason) {
    if (done) return;
    done = true;
    clearTimeout(silence);
    previous?.close(1000);
    if (authenticatedAt !== null && Date.now() - authenticatedAt >= 60_000) attempt = 0;
    if (code >= 4000 && code < 4100) {
      console.error(`closed with ${code} ${reason}: change something before you connect again`);
      return;
    }
    const wait =
      code >= 4200 && code < 4300
        ? Math.random() * 5_000
        : Math.random() * Math.min(60_000, 1_000 * 2 ** ++attempt);
    console.warn(`closed with ${code} ${reason}, connecting again in ${Math.round(wait)} ms`);
    setTimeout(() => connect(), wait);
  }

  socket.onopen = listen;
  socket.onclose = (event) => ended(event.code, event.reason);
  socket.onmessage = async (event) => {
    if (done) return;
    listen();
    const message = JSON.parse(event.data);
    switch (message.type) {
      case "hello":
        await authenticate();
        break;
      case "authenticated":
        if (authenticatedAt === null) {
          authenticatedAt = Date.now();
          send({ type: "subscribe", id: "chargers", data: SUBSCRIPTION });
        }
        break;
      case "subscribed":
        chargers.clear(); // the live messages that follow are the state now of every charger it follows
        previous?.close(1000);
        previous = null;
        break;
      case "live":
        chargers.set(message.data.charger_id, message.data);
        show(message.data);
        break;
      case "removed":
        chargers.delete(message.data.charger_id);
        break;
      case "token_expiring":
        await authenticate();
        break;
      case "reconnect":
        done = true;
        clearTimeout(silence);
        connect(socket);
        break;
      case "error":
      case "unsubscribed":
        console.warn(message);
        break;
    }
  };
}

connect();
```

```python Python theme={null}
import asyncio
import json
import random
import time
import urllib.parse
import urllib.request

from websockets.asyncio.client import connect
from websockets.exceptions import ConnectionClosed, InvalidStatus

SOCKET_URL = "wss://api.plugchoice.com/v4/websocket"
TOKEN_URL = "https://accounts.plugchoice.com/realms/accounts/protocol/openid-connect/token"
SUBSCRIPTION = {"topic": "chargers/live", "filter": {"location_id": "YOUR_LOCATION_ID"}}


def access_token():
    """A fresh access token for a personal API token's client ID and secret."""
    body = urllib.parse.urlencode({
        "grant_type": "client_credentials",
        "client_id": "YOUR_CLIENT_ID",
        "client_secret": "YOUR_CLIENT_SECRET",
    }).encode()
    with urllib.request.urlopen(TOKEN_URL, data=body, timeout=10) as response:
        return json.load(response)["access_token"]


def show(state):
    for evse in state["evses"]:
        power = (evse.get("measurements") or {}).get("power_w")
        print(state["charger_id"], evse["id"], evse.get("status"), power)


class Stop(Exception):
    """Connecting again as before would fail again: change something first."""


class Client:
    def __init__(self):
        self.chargers = {}  # each charger's live state, by its id
        self.attempt = 0
        self.authenticated_at = None

    async def authenticate(self, socket):
        token = await asyncio.to_thread(access_token)
        await socket.send(json.dumps({"type": "authenticate", "data": {"token": token}}))

    async def follow(self, previous):
        """One connection, until the server sends `reconnect`: then it returns the connection, still
        open. `previous` is the connection this one takes over from: it closes once this one's
        subscription is made."""
        socket = await connect(SOCKET_URL)
        try:
            while True:
                # Nothing from the server for 60 seconds: the connection is gone.
                message = json.loads(await asyncio.wait_for(socket.recv(), 60))
                kind, data = message["type"], message.get("data")
                if kind == "hello":
                    await self.authenticate(socket)
                elif kind == "authenticated" and self.authenticated_at is None:
                    self.authenticated_at = time.monotonic()
                    subscribe = {"type": "subscribe", "id": "chargers", "data": SUBSCRIPTION}
                    await socket.send(json.dumps(subscribe))
                elif kind == "subscribed":
                    self.chargers.clear()  # the live messages that follow are the state now of every charger it follows
                    if previous:
                        await previous.close()  # code 1000
                        previous = None
                elif kind == "live":
                    self.chargers[data["charger_id"]] = data
                    show(data)
                elif kind == "removed":
                    self.chargers.pop(data["charger_id"], None)
                elif kind == "token_expiring":
                    await self.authenticate(socket)
                elif kind == "reconnect":
                    return socket
                elif kind in ("error", "unsubscribed"):
                    print(kind, message.get("id"), data)
        except BaseException:
            await socket.close()
            raise

    async def run(self):
        previous = None
        while True:
            self.authenticated_at = None
            try:
                previous = await self.follow(previous)
                continue  # the server asked for a new connection: open it now
            except ConnectionClosed as closed:
                code = closed.rcvd.code if closed.rcvd else 1006
                reason = closed.rcvd.reason if closed.rcvd else ""
            except InvalidStatus as refused:  # refused before the upgrade
                code, reason = refused.response.status_code, ""
            except OSError as error:  # no connection, no token, or nothing for 60 seconds
                code, reason = 1006, repr(error)
            if previous:
                await previous.close()
                previous = None
            if self.authenticated_at and time.monotonic() - self.authenticated_at >= 60:
                self.attempt = 0
            if 4000 <= code < 4100 or code in (400, 403):
                raise Stop(f"closed with {code} {reason}")
            if 4200 <= code < 4300:
                wait = random.uniform(0, 5)
            else:
                self.attempt += 1
                wait = random.uniform(0, min(60, 2 ** self.attempt))
            print(f"closed with {code} {reason}, connecting again in {wait:.1f} s")
            await asyncio.sleep(wait)


asyncio.run(Client().run())
```

## Integrations that run all day

An integration for Home Assistant, evcc or another server keeps one connection open and does what the examples do.

* Put your subscriptions on one connection, up to 20, rather than a connection per charger. Connections are limited per OAuth client and person.
* On `token_expiring`, get a fresh token the way you get one for HTTP: with the refresh token of the user's sign-in, or with your personal API token's client ID and secret.
* Name the chargers with `charger_id` when you need their power every minute while they charge. A subscription of a location or a team keeps no charger watched.
* On a close from `4000` to `4099`, stop reconnecting and tell the user what to fix, such as signing in again.
* To record sessions, read [`GET /v4/transactions`](https://developer.plugchoice.com/v4/api/list-transactions) with `updated_since` after each reconnect. A session that started and ended while you were away is in no `live` message.
* Log the `connection_id` from `hello`, and give it when you ask support about a connection.

The [WebSocket reference](https://developer.plugchoice.com/v4/api/websocket.md) lists every message and its fields.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.