# MQTT

A device holds one long-lived MQTT session with the gateway for its zone. The device SDK opens and
keeps that session for you. This page is for when you connect with your own MQTT client.

Before you start, [claim](https://docs.qualithm.com/http.md#claim-a-device) the device. The claim response gives you its device
ID, its token and the gateway to connect to.

## Find your gateway

Each [zone](https://docs.qualithm.com/zones.md) has its own gateway. A device connects to the gateway of the zone its
[scope](https://docs.qualithm.com/scopes.md) is in.

_This part shows live data. See it at https://docs.qualithm.com/mqtt._

This table is read from the [zones endpoint](https://docs.qualithm.com/api/zones.md) in this environment. Your device doesn't
need to copy a host from it: the claim response names the gateway for the device's zone in its
`broker` field.

## Connect a device

Every connection uses TLS on the port above. The gateway accepts no unencrypted connection.

Use MQTT 5. Set the client ID to the device ID (`dev_…`). The gateway refuses any other client ID.

A device proves who it is with its token while you develop, and with a certificate in production:

- **Token** (start here) — set the username to the device ID and the password to the device's token.
  The gateway checks the password.
- **Certificate** (production devices) — present the device's client certificate in the TLS
  handshake (mutual TLS). Send no username or password. The certificate's subject `CN` is the device
  ID. Its key stays in the device's protected hardware, where it can't be read out.

The gateway keeps no session between connections. Connect with Clean Start set: the CONNACK always
reports no session present. The gateway honours the keep-alive you send, and closes a connection
that stays silent for one and a half keep-alive intervals.

The CONNACK carries the largest payload the gateway accepts as its Maximum Packet Size. Read it from
there rather than hard-coding it. [Devices](https://docs.qualithm.com/devices.md#stay-under-the-event-limit) explains the limit.

### When the gateway refuses a connection

The CONNACK reason code says why:

| Code   | Name                        | Cause                                                                                                                                                                        |
| ------ | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `0x85` | Client Identifier not valid | The client ID is not a device ID.                                                                                                                                            |
| `0x87` | Not authorized              | The device is unknown, a member parked it, or its token or certificate is wrong, revoked or expired. A device parked for being idle gets it from a gateway outside its zone. |
| `0x97` | Quota exceeded              | The team has as many devices connected as its plan allows. Reconnect later with backoff, or move the team to a paid plan.                                                    |
| `0x9F` | Connection rate exceeded    | Too many connection attempts from your address. Wait and reconnect with backoff.                                                                                             |
| `0x9D` | Server moved                | Another gateway serves the device's zone. Reconnect to the gateway the CONNACK names.                                                                                        |
| `0x80` | Unspecified error           | The gateway failed to check the credential. Reconnect with backoff.                                                                                                          |

`0x87` never says which check failed, so the gateway doesn't reveal which device IDs exist. When a
credential is revoked, the gateway sends a DISCONNECT and closes the live session.

A device parked for being idle unparks when it connects to the gateway for its zone with a valid
token or certificate. A connection the free plan's connected-device limit refuses leaves it parked.
Any other gateway answers `0x87`, not `0x9D`, so connect the device to
[its zone's gateway](#find-your-gateway) directly. [Park a device](https://docs.qualithm.com/devices.md#park-a-device) explains
both parks.

A `0x97` CONNACK carries a reason string that names the limit:
`team has reached its plan's limit of <limit> connected devices: move to a paid plan to connect more`.
On the free plan, `<limit>` is 100. Paid plans set no limit.
Devices already connected stay connected. A reconnect counts as a new connection, so a device that
drops can be refused when it comes back.
[Billing and usage](https://docs.qualithm.com/billing-and-usage.md#connect-more-devices) says how to connect more.

An MQTT 3.1.1 client reads this refusal as return code 5, Not authorized: the same code as a refused
credential or a parked device. When a device gets code 5, check the team's
[Usage](https://docs.qualithm.com/billing-and-usage.md#read-your-usage) before you replace its credential.

A `0x9D` CONNACK carries the device's gateway as its Server Reference, as `host:port`. Store it in
place of the gateway you connected to, and connect there from then on. An MQTT 3.1.1 client reads
`0x9D` as return code 3, Server unavailable. [Renew the credential](https://docs.qualithm.com/http.md#renew-a-credential) at the
device's [`apiUrl`](https://docs.qualithm.com/http.md#find-your-api-url): the renewal response names the gateway in `broker`.

## Use device topics

Topics are relative to the device. Publish to `telemetry`, not to a path with your team or scope in
it. The gateway adds the device's team, scope and device ID from the credential it connected with,
so a device can only ever publish as itself.

Three topics carry meaning:

| Topic           | Direction         | Carries                                                             |
| --------------- | ----------------- | ------------------------------------------------------------------- |
| `telemetry`     | device to gateway | [Readings](#publish-a-reading)                                      |
| `capabilities`  | device to gateway | The [capability manifest](#declare-capabilities)                    |
| `command/<key>` | both              | A [command](#receive-commands) for one capability, and its response |

The gateway refuses a publish on any other topic: a QoS 1 publish gets a PUBACK with `0x90` Topic
Name invalid, and a QoS 0 publish is dropped. Neither is stored or counted. The gateway keeps no
retained messages and never publishes a Will message.

## Publish a reading

Publish readings to the `telemetry` topic as JSON:

```json
{ "ts": 1767225600000, "metrics": { "temperature": 21.4 } }
```

`ts` is the reading time in epoch milliseconds, as an integer. `metrics` maps each metric name to a
number. A reading needs at least one metric and holds at most 64, and every value must be a finite
number.

Publish at QoS 1. The gateway sends the PUBACK once it has stored the reading:

- `0x00` — stored.
- `0x83` Implementation specific error, with the reason string `broker busy` — not stored. Publish
  it again with backoff.
- `0x83` Implementation specific error, with the reason string
  `capability manifest missing: publish it to capabilities first` — the session hasn't
  [declared its capabilities](#declare-capabilities), so the reading isn't stored. Publish the
  manifest, then publish the reading again.
- `0x97` Quota exceeded, with the reason string `quota exceeded` — over the device's publish budget,
  not stored. Publish it again with backoff.
- `0x97` Quota exceeded, with the reason string `team's monthly events used` — the team has used the
  month's events on its plan, not stored. The gateway refuses readings until the month resets on the
  1st, UTC, or until the team moves to a plan that includes more. Don't retry before then.
- `0x99` Payload format invalid, with the reason string `too many metrics` — more than 64 metrics,
  not stored. Split the reading into smaller ones instead of publishing it again.

The gateway checks the reading's shape after it acknowledges it. It drops a reading that isn't the
shape above. It also drops a reading it accepted shortly before it learned the team had used the
month's events. To make a retry safe, set a `msg-id` user property on the publish: a repeat with the
same `msg-id` soon after is stored once.

### Send buffered readings in one publish

A device that was offline can send the readings it buffered in one publish. Wrap them in a
`readings` list on the same `telemetry` topic:

```json
{
  "readings": [
    { "ts": 1767225600000, "metrics": { "temperature": 21.4 } },
    { "ts": 1767225660000, "metrics": { "temperature": 21.6 } }
  ]
}
```

A batch holds 1 to 100 readings, and each one follows the rules for a single reading. The gateway
stores each reading on its own, in the order you send them. Each reading counts as one event, the
same as if you had published it alone. A batch spends one publish from the device's budget.

The gateway accepts or refuses a batch whole. A QoS 1 batch gets one PUBACK, with the codes above. A
batch with no readings, more than 100, or a reading without a `metrics` object gets `0x99` Payload
format invalid, with the reason string
`invalid batch: send 1 to 100 readings, each with a metrics object`. Set a `msg-id` on a batch to
make a retry safe: the gateway stores each reading of a repeated batch once.

### Stay under the limits

- **Topic** — a reading goes to `telemetry`. A publish on a topic outside the table above is
  dropped. A QoS 1 publish gets a PUBACK with `0x90` Topic Name invalid, and a QoS 0 publish gets no
  reply.
- **Size** — a payload over the Maximum Packet Size gets a DISCONNECT with reason `0x95` Packet too
  large, and the gateway closes the connection.
- **Metrics** — a reading holds at most 64 metrics. A reading with more is dropped, and so is a
  batch that contains one. A QoS 1 publish gets a PUBACK with `0x99` Payload format invalid, and a
  QoS 0 publish gets no reply.
- **Capabilities** — a reading or command response before the session's manifest is dropped. A QoS 1
  publish gets a PUBACK with `0x83`, and a QoS 0 publish gets no reply. The connection stays up, and
  the gateway always accepts the manifest.
- **Rate** — each device has a publish budget that refills every second. A publish over it is
  dropped. A QoS 1 publish gets a PUBACK with `0x97` Quota exceeded, and a QoS 0 publish gets no
  reply. Spread readings out rather than sending them in bursts.
- **Plan** — the team's plan includes a number of events a month. Once the team has used them, the
  gateway drops every reading until the month resets or the team moves to a plan that includes more.
  A QoS 1 publish gets a PUBACK with `0x97` and the reason string `team's monthly events used`, and
  a QoS 0 publish gets no reply. [Billing and usage](https://docs.qualithm.com/billing-and-usage.md#raise-a-monthly-limit) says
  how to raise the limit.

## Declare capabilities

A capability is something a device can do or report, such as a relay you switch or a sensor you
read. Publish the device's capabilities to the `capabilities` topic on every connect, before any
reading. The gateway refuses a session's readings until its manifest arrives:

```json
{
  "capabilities": [
    { "key": "power", "type": "onoff", "config": {} },
    { "key": "brightness", "type": "range", "config": { "min": 0, "max": 100, "unit": "%" } },
    { "key": "mode", "type": "enum", "config": { "options": ["eco", "boost"] } },
    { "key": "restart", "type": "trigger", "config": {} },
    { "key": "temperature", "type": "sensor", "config": { "metric": "temperature", "unit": "°C" } }
  ]
}
```

`key` names the capability. It is 1 to 64 letters, digits, `_` or `-`, starts with a letter or
digit, and is unique on the device. `type` sets what `config` holds:

| `type`    | `config`                                                            | Command `value`              |
| --------- | ------------------------------------------------------------------- | ---------------------------- |
| `onoff`   | nothing                                                             | `true` or `false`            |
| `range`   | `min` and `max` (`min` below `max`), and optional `step` and `unit` | A number from `min` to `max` |
| `enum`    | `options`: one or more non-empty strings                            | One of `options`             |
| `trigger` | nothing                                                             | None                         |
| `sensor`  | `metric`: the `telemetry` metric it reports, and optional `unit`    | Takes no commands            |

The manifest replaces the last one. A key it leaves out is removed from the device, and a key it
keeps holds the name and tags your team gave it. Keep the manifest under 16 KiB. A manifest that is
invalid or too large is dropped, and the device keeps its last capabilities.

## Receive commands

The gateway delivers each command on `command/<key>`, where `<key>` is the capability's key.
Subscribe to `command/#` to receive every command. The gateway also grants `command/+` and
`command/<key>`. It refuses any other filter with SUBACK `0x87` Not authorized, because it never
delivers anything else.

Each command's payload:

- An `onoff`, `range` or `enum` command carries `{"value": <value>}`, such as `{"value": true}`.
- A `trigger` command carries `{}`.

The gateway delivers commands at QoS 0, while the device is connected. A command sent while the
device is offline is not queued: it fails. The device's [command list](https://docs.qualithm.com/api/commands.md) shows each
command as `sent` once the gateway has written it to the connection, or `failed`. The device sends
no reply. To report the result, publish a reading.

## See also

- [Devices guide](https://docs.qualithm.com/devices.md)
- [HTTP](https://docs.qualithm.com/http.md)
