DocsReferenceClient protocolMQTT gateway

MQTT gateway

How the client protocol travels over MQTT, for boards and firmware that already speak it. Any MQTT library works: there's nothing of ours to install. You log in over HTTPS, connect with the token, and send the same JSON messages as every other client.

Address mqtts://mqtt.dev.wbskt.com:8883Versions MQTT 5, 3.1.1Updated 9 Nov 2026

What you need

WBSKT's MQTT gateway is not a general broker. Each board talks only to WBSKT, on two topics of its own, never to another board. In return, there's no broker to run and no topics to design.

  • An MQTT client library that speaks MQTT 5 or 3.1.1 over TLS, like PubSubClient or ESP-MQTT on an ESP32, or paho-mqtt in Python.
  • HTTPS, to register once and to log in about once an hour. MQTT carries the messages, but the token comes from the API.
  • A JSON library, because every message is a JSON object.
  • A policy PIN, from Policies in the console, as for any board.

Then it's five steps, the same on any board:

StepHow
1  Register, onceHTTPS, with the PIN. Keep the clientRefId and secret for good.
2  Log inHTTPS, for an access token. Reuse it until it nearly expires.
3  ConnectMQTT, with the clientRefId as client id and user name, and the token as password.
4  Say what it can doPublish capabilities to the up topic, first thing on every connection.
5  TalkPublish readings to …/up. Read commands and pings from …/down, and answer them.

1. Get a token

Registering and logging in work exactly as on the protocol page. Here they are as two curl calls, handy for trying things out before you write firmware.

terminal
# Once: register with a policy PIN. Keep clientRefId and secret for good.
curl -s https://api.dev.wbskt.com/api/v1/client-registrations/initiate \
  -H "Content-Type: application/json" \
  -d '{ "pin": "483920", "name": "greenhouse-sensor" }'
# { "clientRefId": "6f1c2a9e-4d3b-4c1a-9a57-2e0b8f3d7c10", "secret": "k3Jx…", "status": 1 }

# Whenever it needs a token: log in. Reuse the token until it nearly expires.
curl -s https://api.dev.wbskt.com/api/v1/client-auth/login \
  -H "Content-Type: application/json" \
  -d '{ "clientRefId": "6f1c2a9e-4d3b-4c1a-9a57-2e0b8f3d7c10", "secret": "k3Jx…" }'
# { "accessToken": "eyJhbGciOi…", "expiresIn": 3600 }

Never register again while you have the credentials: each registration is a new client and counts against the policy's limit.

2. Connect

Open an MQTT connection with these settings. Set the client id and the user name to the clientRefId, and put the access token in the password.

connection settings
Host        mqtt.dev.wbskt.com
Port        8883 (TLS)
Protocol    MQTT 5 or MQTT 3.1.1
Client id   6f1c2a9e-4d3b-4c1a-9a57-2e0b8f3d7c10   # the clientRefId
User name   6f1c2a9e-4d3b-4c1a-9a57-2e0b8f3d7c10   # the clientRefId again
Password    eyJhbGciOi…                            # the accessToken
Clean start true
Keep alive  45 s
  • Clean start is always on: WBSKT keeps no MQTT session between connections. Commands sent while the board was offline still arrive, because WBSKT holds them itself for up to 24 hours.
  • A will is ignored. WBSKT shows a board as offline on its own when its connection drops.
  • Your TLS library needs Let's Encrypt's root, ISRG Root X1. Most systems have it already; on a microcontroller you paste it in.
  • As soon as CONNACK says success, publish capabilities, before anything else.
Port 1883mqtt://mqtt.dev.wbskt.com:1883 is open for boards too small for TLS. It behaves exactly like 8883, but everything travels in clear text, the token included, so anyone on the network path can read it and connect as your board until it expires. Use 8883 whenever the board can.

3. When the connection is refused

The CONNACK's reason code says why. MQTT 3.1.1 libraries report the 3.1.1 return code instead (PubSubClient's state(), for example).

MQTT 53.1.1MeansDo
0x000Connected.Publish capabilities.
0x864The token is expired or not valid, or the user name isn't the token's client.Drop the token and log in again.
0x875The client was revoked, deleted or had its secret rotated since the token was issued.Keep the token and retry on the schedule. Once it expires, login says what happened.
0x852The client id isn't the token's client.A bug, not something to retry.
0x841MQTT 3.1 or another version this gateway doesn't speak.Use MQTT 5 or 3.1.1.
0x88, or no answer3The gateway can't check tokens right now, or is restarting.Keep the token and retry on the schedule.

4. Topics

Each board has exactly two topics, named after its clientRefId.

TopicDirectionCarries
wbskt/v1/{clientRefId}/upboard → WBSKTEverything the board sends: capabilities, readings, sys.pong, sys.ack, state.report.
wbskt/v1/{clientRefId}/downWBSKT → boardEverything WBSKT sends: sys.ping and commands.
  • You don't need to subscribe. WBSKT subscribes the board to its down topic as it connects. Subscribing to it yourself is fine; any other subscription is refused (SUBACK 0x87).
  • A publish to any other topic is dropped (PUBACK 0x87 at QoS 1). That includes another board's topics and your own down topic.
  • Each PUBLISH carries one message, one JSON object in UTF-8, at most 64 KB. A bigger packet ends the connection at once.
  • WBSKT sends at QoS 0. Publish at QoS 0 or 1: QoS 1 gets a PUBACK, but a command is confirmed by sys.ack, not by MQTT.
  • Retained messages are ignored and never stored.

5. A session, message by message

The messages are the same JSON as on every gateway (type, payload). Only the topic shows the direction. A typical first minute, with the board's clientRefId shortened:

session
# 1. First, on every connection: say what the board can do
PUBLISH wbskt/v1/6f1c2a9e-…/up
{ "type": "capabilities",
  "payload": { "agent": "greenhouse-firmware", "firmwareVersion": "1.0.0",
    "capabilities": [ { "command": "relay.set", "description": "Switch the relay",
      "parameters": [ { "name": "on", "label": "On", "dataType": "boolean", "isRequired": true } ] } ] } }

# 2. Every few seconds WBSKT pings, to time the round trip
RECEIVE wbskt/v1/6f1c2a9e-…/down
{ "type": "sys.ping", "payload": { "timestamp": "2026-11-09T12:00:05Z", "id": "p-81" } }

# 3. Answer at once, echoing both fields
PUBLISH wbskt/v1/6f1c2a9e-…/up
{ "type": "sys.pong", "payload": { "originalTimestamp": "2026-11-09T12:00:05Z", "id": "p-81" } }

# 4. Your own readings, under any type that isn't reserved. Workflows trigger on them.
PUBLISH wbskt/v1/6f1c2a9e-…/up
{ "type": "temperature", "payload": { "celsius": 21.5 }, "sentAt": "2026-11-09T12:00:07Z" }

# 5. A command from the console or a workflow
RECEIVE wbskt/v1/6f1c2a9e-…/down
{ "type": "relay.set", "payload": { "on": true }, "commandId": "c-5f2e", "expiresAt": "2026-11-09T12:05:00Z" }

# 6. Confirm it as soon as it arrives, then act on it
PUBLISH wbskt/v1/6f1c2a9e-…/up
{ "type": "sys.ack", "payload": { "commandId": "c-5f2e" } }

If a command's expiresAt has passed and the board keeps time, don't act on it: answer { "type": "sys.ack", "payload": { "commandId": "c-5f2e", "type": "relay.set", "refused": "expired" } }. Leave sentAt out on a board without a clock; WBSKT uses the time of arrival.

6. Complete examples

Both connect, say what they can do, answer pings, confirm and run a relay.set command, and send a reading every 10 seconds. The ESP32 one uses PubSubClient and ArduinoJson 7 over MQTT 3.1.1; the Python one uses paho-mqtt 2 over MQTT 5.

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>

#define RELAY_PIN 5

// From registration. On a real board, keep these in NVS.
const char* CLIENT_REF = "6f1c2a9e-4d3b-4c1a-9a57-2e0b8f3d7c10";
const char* SECRET     = "k3Jx…";

// Let's Encrypt's root certificate, ISRG Root X1, from letsencrypt.org/certificates
const char* ROOT_CA = R"(-----BEGIN CERTIFICATE-----
…
-----END CERTIFICATE-----)";

WiFiClientSecure net;
PubSubClient mqtt(net);
String upTopic   = String("wbskt/v1/") + CLIENT_REF + "/up";
String downTopic = String("wbskt/v1/") + CLIENT_REF + "/down";
String token;
unsigned long tokenRenewAt = 0;
unsigned long lastReading = 0;

bool login() {
  HTTPClient http;
  http.begin(net, "https://api.dev.wbskt.com/api/v1/client-auth/login");
  http.addHeader("Content-Type", "application/json");
  JsonDocument body;
  body["clientRefId"] = CLIENT_REF;
  body["secret"] = SECRET;
  String json;
  serializeJson(body, json);
  if (http.POST(json) != 200) {
    http.end();
    return false;
  }
  JsonDocument answer;
  deserializeJson(answer, http.getString());
  http.end();
  token = answer["accessToken"].as<String>();
  // Log in again a minute before the token runs out.
  tokenRenewAt = millis() + (answer["expiresIn"].as<unsigned long>() - 60) * 1000;
  return true;
}

void send(const char* type, JsonDocument& payload) {
  JsonDocument message;
  message["type"] = type;
  message["payload"] = payload;
  String json;
  serializeJson(message, json);
  mqtt.publish(upTopic.c_str(), json.c_str());
}

void sendCapabilities() {
  JsonDocument caps;
  caps["agent"] = "greenhouse-firmware";
  caps["firmwareVersion"] = "1.0.0";
  JsonObject relay = caps["capabilities"].add<JsonObject>();
  relay["command"] = "relay.set";
  relay["description"] = "Switch the relay";
  JsonObject on = relay["parameters"].add<JsonObject>();
  on["name"] = "on";
  on["label"] = "On";
  on["dataType"] = "boolean";
  on["isRequired"] = true;
  send("capabilities", caps);
}

void onMessage(char* topic, byte* data, unsigned int length) {
  JsonDocument message;
  if (deserializeJson(message, data, length)) {
    return;
  }
  String type = message["type"] | "";
  JsonDocument reply;

  if (type == "sys.ping") {
    reply["originalTimestamp"] = message["payload"]["timestamp"];
    reply["id"] = message["payload"]["id"];
    send("sys.pong", reply);
    return;
  }

  // A command: confirm it as soon as it arrives, then act on it.
  if (message["commandId"].is<const char*>()) {
    reply["commandId"] = message["commandId"];
    send("sys.ack", reply);
  }
  if (type == "relay.set") {
    digitalWrite(RELAY_PIN, message["payload"]["on"].as<bool>() ? HIGH : LOW);
  }
}

void connectMqtt() {
  while (!mqtt.connected()) {
    if ((token.isEmpty() || (long)(millis() - tokenRenewAt) >= 0) && !login()) {
      delay(random(2000, 10000));
      continue;
    }
    if (mqtt.connect(CLIENT_REF, CLIENT_REF, token.c_str())) {
      sendCapabilities();   // always first
      return;
    }
    // CONNACK 4: the token is no good. Log in again. Any other refusal: keep it and retry.
    if (mqtt.state() == MQTT_CONNECT_BAD_CREDENTIALS) {
      token = "";
    }
    delay(random(0, 10000));
  }
}

void setup() {
  pinMode(RELAY_PIN, OUTPUT);
  WiFi.begin("home-wifi", "wifi-password");
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
  }
  net.setCACert(ROOT_CA);
  mqtt.setServer("mqtt.dev.wbskt.com", 8883);
  mqtt.setBufferSize(4096);   // the token alone is longer than the 256-byte default
  mqtt.setKeepAlive(45);
  mqtt.setCallback(onMessage);
}

void loop() {
  connectMqtt();
  mqtt.loop();
  if (millis() - lastReading > 10000) {
    lastReading = millis();
    JsonDocument reading;
    reading["celsius"] = 21.5;
    send("temperature", reading);
  }
}
import json
import random
import time

import paho.mqtt.client as mqtt
import requests

API = "https://api.dev.wbskt.com/api/v1"
CLIENT_REF = "6f1c2a9e-4d3b-4c1a-9a57-2e0b8f3d7c10"  # from registration
SECRET = "k3Jx…"
UP = f"wbskt/v1/{CLIENT_REF}/up"


def refresh_token(client):
    answer = requests.post(f"{API}/client-auth/login",
                           json={"clientRefId": CLIENT_REF, "secret": SECRET})
    if answer.ok:
        client.username_pw_set(CLIENT_REF, answer.json()["accessToken"])
    else:
        print("login refused:", answer.status_code)  # pending or revoked: retry later


def send(client, type, payload):
    client.publish(UP, json.dumps({"type": type, "payload": payload}))


def on_connect(client, userdata, flags, reason_code, properties):
    if reason_code.is_failure:
        if reason_code.value == 0x86:  # the token is no good: log in again
            refresh_token(client)
        return  # paho retries on its own
    send(client, "capabilities", {
        "agent": "greenhouse-py",
        "firmwareVersion": "1.0.0",
        "capabilities": [{
            "command": "relay.set",
            "description": "Switch the relay",
            "parameters": [{"name": "on", "label": "On", "dataType": "boolean", "isRequired": True}],
        }],
    })


def on_message(client, userdata, msg):
    message = json.loads(msg.payload)
    payload = message.get("payload") or {}
    if message["type"] == "sys.ping":
        send(client, "sys.pong", {"originalTimestamp": payload.get("timestamp"), "id": payload.get("id")})
        return
    if "commandId" in message:  # confirm on arrival, before acting
        send(client, "sys.ack", {"commandId": message["commandId"]})
    if message["type"] == "relay.set":
        print("relay", "on" if payload["on"] else "off")


def on_disconnect(client, userdata, flags, reason_code, properties):
    if reason_code.value == 0x87:  # revoked: drop the token
        refresh_token(client)
    elif reason_code.value == 0x96:  # throttled: back off, then send less
        time.sleep(random.uniform(30, 60))
    elif reason_code.value == 0x8E:  # superseded: another connection uses these credentials
        print("superseded")


client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=CLIENT_REF, protocol=mqtt.MQTTv5)
refresh_token(client)
client.tls_set()
client.reconnect_delay_set(min_delay=2, max_delay=60)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.connect("mqtt.dev.wbskt.com", 8883, keepalive=45, clean_start=True)
client.loop_start()

while True:
    if client.is_connected():  # only after CONNACK, so capabilities has gone first
        send(client, "temperature", {"celsius": 21.5})
    time.sleep(10)
  • PubSubClient's buffer is 256 bytes by default, too small for the token in CONNECT. Raise it with setBufferSize, as above. The buffer also caps every message both ways, and PubSubClient silently drops a command bigger than it, so size it for your largest command.
  • On an ESP32 the WBSKT library does all of this for you, over WebSocket, along with the offline buffer and firmware updates. Use MQTT when your firmware already has an MQTT stack, or when you'd rather not add a library.

7. Keepalive

Two things keep a board connected. MQTT's own PINGREQ and PINGRESP keep the connection alive; your library sends them on its own, at the keep alive you set (30 to 60 seconds is a good default). Separately, answer WBSKT's sys.ping with sys.pong like any other message. That's how the console shows the board's latency.

8. Reason codes

On MQTT 5, WBSKT says why it ended a connection with the reason code on DISCONNECT. Branch on the code, not on the reason string. MQTT 3.1.1 has no reason codes on DISCONNECT, so a 3.1.1 board sees only the connection drop and reconnects on the schedule.

CodeReasonDo
0x00NormalReconnect on the schedule.
0x8BRestartingReconnect after a random 0–30 s.
0x95Too bigA message was over 64 KB. Fix the sender.
0x83Server errorReconnect on the schedule.
0x8ESupersededThe same client connected again, over MQTT or WebSocket. Repeated, it means two boards share credentials.
0x87RevokedDrop the token; the next login says what happened.
0x96ThrottledWait a random 30–60 s and send less.

Closing to install firmware

A board closing to install a firmware update sends an MQTT 5 DISCONNECT with the user property reason set to updating. WBSKT then shows it as updating rather than offline, for up to 5 minutes or until it connects again. On MQTT 3.1.1, which has no properties on DISCONNECT, an update reads as an ordinary close.

update.py
from paho.mqtt.packettypes import PacketTypes
from paho.mqtt.properties import Properties

props = Properties(PacketTypes.DISCONNECT)
props.UserProperty = ("reason", "updating")
client.disconnect(properties=props)

Checklist

A board, or an SDK, does MQTT right when it:

  • connects over TLS on 8883 by default, with its clientRefId as client id and user name, and the access token as password;
  • reuses the token until it nearly expires, logs in again after CONNACK 0x86, and keeps the token after any other refusal;
  • publishes capabilities first on every connection;
  • publishes only to its up topic, and reads its messages from its down topic;
  • answers every sys.ping and confirms every command with sys.ack;
  • sends at most 8 messages a second after a burst of 50 (limits), and waits a random time before each reconnect (schedule);
  • on MQTT 5: drops the token after DISCONNECT 0x87, waits 30–60 s after 0x96, and closes for a firmware update with reason: updating.