# MQTT requests

> Connect to MQTT 3.1.1 and 5.0 brokers over TCP, TLS or WebSockets, subscribe with wildcards, publish with QoS and retain, and test messages in Cloak Proxy.

Source: https://docs.subcloak.com/cloak-proxy/api-client/protocols/mqtt/

An MQTT request is a client for an MQTT broker: it connects, subscribes to topics, publishes messages and logs everything that arrives. Use it to watch what IoT devices and backend services publish, to send a test command to a device, or to check a broker's behavior in the collection runner. Cloak Proxy supports MQTT 3.1.1 and MQTT 5.0, over plain TCP, TLS, and WebSockets.

## Connect, subscribe and publish

1. In the API client, click **New › Other Protocols › MQTT**, or right-click a collection and choose **Add Other Request › MQTT**. Search Everything (<kbd>⇧</kbd> <kbd>⌘</kbd> <kbd>A</kbd>) also has **New MQTT Request**.

   The new request points at the public test broker `mqtt://test.mosquitto.org:1883`, subscribes to `cloak/test/#` and publishes to `cloak/test/hello`.

2. Type your broker's URL, for example `mqtts://broker.example.com:8883`.

3. If the broker needs credentials, fill in **Authorization**. Choose the MQTT version in **Settings**.

4. In **Topics**, list the topic filters you want to receive.

5. Press <kbd>⌘</kbd> <kbd>↩</kbd> or click **Connect**. Cloak Proxy connects and subscribes to every topic in the list.

6. In **Publish**, enter a topic and payload, then press <kbd>⌘</kbd> <kbd>⇧</kbd> <kbd>↩</kbd> or click **Publish**.

7. Click **Disconnect** when you're done.

*[Screenshot: An MQTT request to mqtt://test.mosquitto.org:1883 with the Publish tab open, topic cloak/test/hello, QoS 0, a Retain checkbox and a JSON temperature payload. The Publish tab of a new MQTT request.]*

## Broker URL

The URL's scheme picks the transport:

| Scheme | Transport | Default port |
|---|---|---|
| `mqtt://` (or no scheme) | TCP | 1883 |
| `mqtts://`, `ssl://` or `tls://` | TLS | 8883 |
| `ws://` | MQTT over WebSocket | 80 |
| `wss://` | MQTT over secure WebSocket | 443 |

**TCP**

```text
mqtt://broker.example.com:1883
```

**TLS**

```text
mqtts://broker.example.com:8883
```

**WebSocket**

```text
wss://broker.example.com/mqtt
```

For WebSocket brokers the URL's path is the WebSocket endpoint, for example `wss://broker.example.com/mqtt`; without a path, `/mqtt` is used. `{{variables}}` work in the URL. MQTT connections go straight to the broker, not through Cloak Proxy.

## Request tabs

### Publish

| Field | Default | What it does |
|---|---|---|
| **Topic** | `cloak/test/hello` | The topic to publish to. |
| **QoS** | **QoS 0** | **QoS 0** (at most once), **QoS 1** (at least once) or **QoS 2** (exactly once). |
| **Retain** | Off | Asks the broker to keep the message and deliver it to future subscribers of the topic. |
| Payload editor | A JSON sample | The message body, sent as UTF-8 text. `{{variables}}` are filled in. |
| **Saved** | | **Save Current Message** keeps the payload; choose a saved one to load it, or remove it with **Delete**. |

**Publish** is enabled only while connected.

### Topics

Each row is a topic filter with its own QoS. `+` matches exactly one level and `#` matches the rest, so `sensors/+/temperature` matches `sensors/kitchen/temperature`, and `sensors/#` matches everything under `sensors/`.

| Control | What it does |
|---|---|
| Topic field | The filter, such as `devices/#`. |
| QoS menu | The maximum QoS you want to receive at, **QoS 0** to **QoS 2**. |
| **Subscribe** / **Unsubscribe** | Subscribes or unsubscribes this row right away. **Subscribe** works only while connected. |
| Remove button | Deletes the row. |
| **Add Topic** | Adds an empty row. |

Every non-empty row is subscribed automatically when you connect. The tab's badge counts the rows.

### Authorization

| Field | Default | What it does |
|---|---|---|
| **Client ID** | `cloak-` and six random characters | Identifies this client to the broker. Two clients with the same ID kick each other off. |
| **Username** | Empty | Sent when not empty. `{{variables}}` work. |
| **Password (supports `{{vault:name}}`)** | Empty | Sent when not empty. The field is masked. |

### Settings

| Setting | Default | What it does |
|---|---|---|
| **Version** | **MQTT 3.1.1** | **MQTT 3.1.1** or **MQTT 5.0**. |
| **Keep alive** | 60 s | The keep-alive interval sent to the broker, 0 to 3,600 seconds in steps of 10. Cloak Proxy pings the broker so the connection never stays silent longer than this. `0` turns keep alive off. With MQTT 5.0 the broker can ask for a different interval, which wins. |
| **Clean session** (3.1.1) / **Clean start** (5.0) | On | Starts with a fresh session. Off, the broker resumes your earlier session and its subscriptions, and the log shows **session present**. |
| **Skip TLS certificate verification** | Off | Accepts any certificate on TLS and `wss://` connections, for development brokers. |
| **Last will topic** | Empty | When set, the broker publishes the last will message to this topic if the client disconnects without saying goodbye. |
| **Last will message** | Empty | The last will payload. |

## Read the Messages log

| Entry | Meaning |
|---|---|
| **Connecting to** `host:port` | The connection started. |
| **Connected** | The broker accepted the connection, with **session present** if it resumed a session. |
| **Subscribed** / **Unsubscribed** | The broker's answer to a subscribe, with the QoS it granted, or the topics you left. |
| `topic · QoS 1 · retained`, incoming | A message from the broker. **retained** means the broker stored it earlier. |
| `topic · QoS 0 · retain`, outgoing | A message you published. |
| **Pong after 35 ms** | A keep-alive ping was answered. |
| **Disconnected** / **Error** | The connection ended or failed, with the reason. |

Select a message to see its payload below: JSON as a tree, text as text, and binary payloads as a hex dump. **Hide events** hides informational entries, the search field filters by topic and payload, and **Clear** empties the log.

## Run MQTT requests in the collection runner

The [collection runner](https://docs.subcloak.com/cloak-proxy/api-client/run/collection-runner/) and [`cloakctl`](https://docs.subcloak.com/cloak-proxy/automation/cloakctl/) run a saved MQTT request in one step:

1. Connect with the saved version, credentials, keep alive and last will. Each run uses the saved client ID plus `-run-` and four random characters, with a clean session, so parallel runs and the editor's own connection don't disconnect each other.
2. Subscribe to every topic in **Topics**.
3. Publish the **Publish** payload to its topic with its QoS and retain flag, unless the topic is empty.
4. Collect incoming messages until none has arrived for half a second, or until the request timeout (30 seconds by default) if none arrive.
5. Disconnect.

The response is `200 OK` with `Content-Type: application/json`, an `x-messages-received` header, and a body that's a JSON array with one object per message:

```json title="Response body"
[
  {
    "topic": "cloak/test/hello",
    "payload": { "temperature": 21.5 },
    "qos": 0,
    "retain": false
  }
]
```

A payload that parses as JSON is included as JSON, other text as a string, and binary data as base64. If you subscribe to the topic you publish to, your own message comes back too, which makes a quick round-trip test.

MQTT requests have no **Scripts** tab of their own. Put tests in the collection's or a folder's post-response script, and check `pm.info.requestName` for tests meant for one request:

```js title="Collection post-response script"
if (pm.info.requestName === "Thermostat round trip") {
  pm.test("message came back", () => {
    const messages = pm.response.json();
    pm.expect(messages.length).to.be.above(0);
    pm.expect(messages[0].payload.temperature).to.be.a("number");
  });
}
```

> **Broker credentials:**
> The username, password and payloads are saved with the request in your workspace files. Store the password in the [vault](https://docs.subcloak.com/cloak-proxy/api-client/variables-and-environments/) and type `{{vault:mqtt_password}}` in the field, so it stays in your Keychain and out of Git and exports. Public test brokers such as `test.mosquitto.org` are readable by anyone: never publish real data to them.

## Related

  - [Collection runner](https://docs.subcloak.com/cloak-proxy/api-client/run/collection-runner/): Run MQTT round trips with tests.
  - [Variables and environments](https://docs.subcloak.com/cloak-proxy/api-client/variables-and-environments/): Vault references for broker passwords.
  - [TCP and UDP](https://docs.subcloak.com/cloak-proxy/api-client/protocols/tcp-and-udp/): Talk raw TCP, TLS or UDP to devices and services.
  - [WebSocket requests](https://docs.subcloak.com/cloak-proxy/api-client/protocols/websocket/): Plain WebSocket connections.
