# MQTT Access

FastBee community edition includes a built-in MQTT Broker developed on Netty, so no external EMQX deployment is required. This article describes how devices connect to the platform via the MQTT protocol.

## Page Guide

- **What This Page Covers**: The complete path for connecting a device through the MQTT Broker built into the community edition: connection parameters, authentication modes, topics and message formats.
- **Use Cases**: Open-source users, embedded developers and integration testers who connect devices over MQTT.
- **Prerequisites**: An open-source deployment plus a published MQTT product on the platform, with the product ID, device number and MQTT credentials at hand.

## Connection Workflow

1. Create and publish an MQTT product in Product Management, and confirm the product ID, device number, MQTT username, and password
2. Connect the device or MQTTX to the MQTT service using the agreed `clientId`, `userName`, and `password`
3. After connecting, publish `/info/post` first, then `/property/post` or `/event/post`
4. On the platform side, verify the closed loop via Running Status, Event Logs, and Command Logs on the device detail page

## Connection Info

| Parameter | TCP | WebSocket |
|-----------|-----|-----------|
| Address | Server IP | `ws://ServerIP:8083/mqtt` |
| Port | 1883 | 8083 |
| Protocol | MQTT 3.1.1 | MQTT over WebSocket |

## Device Authentication

```mermaid
%%{init: {"theme": "base", "themeVariables": {"background": "transparent", "primaryColor": "#edf4ff", "primaryTextColor": "#1f2937", "primaryBorderColor": "#536dfe", "lineColor": "#334155", "textColor": "#1f2937", "actorBkg": "#edf4ff", "actorBorder": "#536dfe", "actorTextColor": "#1f2937", "signalColor": "#334155", "signalTextColor": "#1f2937", "sequenceNumberColor": "#1f2937", "activationBkgColor": "#dbeafe", "activationBorderColor": "#536dfe", "noteBkgColor": "#fff7ed", "noteTextColor": "#1f2937", "noteBorderColor": "#f59e0b"}}}%%
sequenceDiagram
  autonumber
  participant D as Device
  participant B as MQTT Broker
  participant P as FastBee Platform
  D->>B: CONNECT(clientId, userName, password)
  B->>P: HTTP Auth
  P->>P: Validate credentials
  alt Auth Failed
    P-->>B: Reject
    B-->>D: Connection refused
  else Auth Success
    P->>P: Check or create device
    P-->>B: Accept
    B-->>D: Connection established
  end
```

::: tip

* Auth type: `S` = Simple Authentication, `E` = Encrypted Authentication
* When the product has device authorization code enabled, the authorization code must not be empty
* The user ID is the ID of the logged-in user; devices using different user IDs belong to different users
* The device number can be a platform-created number or a unique code such as the device MAC/IMEI (the platform auto-registers the device)
  :::

### Simple Authentication (recommended for testing)

```
clientId = S&deviceNumber&productId&userId
userName = MQTT username
password = MQTT password
password = MQTT password&authCode (when device authorization is enabled)
```

**Example:**

```
clientId = "S&D68329VL588&2&1"
userName = "fastbee"
password = "PHYFED93WSFF1DAS"
```

### Encrypted Authentication (recommended for production)

```
clientId = E&deviceNumber&productId&userId
userName = MQTT username
password = AES encrypted(MQTT password&expireTimestamp&authCode(optional))
```

* The password is AES-CBC encrypted with the product secret (IV: `wumei-smart-open`, output: Base64)
* The expiration timestamp is accurate to milliseconds; within 24 hours is recommended

**Example:**

```
clientId = "E&D68329VL588&2&1"
userName = "fastbee"
password = "/W2A/4MK+9cEGBhyBDgr2K5c62DAjAK4m0b5pvwxX6FFMzI3h1pUmaDY3BH1P2mI"
```

### AES Encryption Details

AES-CBC encryption mode is used. For testing, you can use the [online encryption/decryption tool](http://tool.chacuo.net/cryptaes):

| Parameter | Value |
|-----------|-------|
| Mode | CBC |
| Padding | pkcs5padding |
| Block size | 128 bit |
| IV | `wumei-smart-open` |
| Output | Base64 |
| Key | Product secret |
| Plaintext | `MQTT password&expireTime&authCode(optional)` |

## Subscribe Topics (Platform → Device)

| Topic | Description |
|-------|-------------|
| `/{productId}/{deviceNum}/function/get` | Subscribe to platform commands (property set, function invoke) |
| `/{productId}/{deviceNum}/info/get` | Subscribe to device info requests (publish device info upon receipt) |
| `/{productId}/{deviceNum}/monitor/get` | Subscribe to real-time monitoring requests (returns count and interval) |
| `/{productId}/{deviceNum}/ntp/get` | Subscribe to time sync (optional) |
| `/{deviceNum}/http/upgrade/set` | Subscribe to OTA upgrades via HTTPS |
| `/{deviceNum}/fetch/upgrade/set` | Subscribe to OTA upgrades via binary package |

## Publish Topics (Device → Platform)

| Topic | Description |
|-------|-------------|
| `/{productId}/{deviceNum}/property/post` | Publish property/function data (real-time display and storage) |
| `/{productId}/{deviceNum}/event/post` | Publish events |
| `/{productId}/{deviceNum}/info/post` | Publish device info |
| `/{productId}/{deviceNum}/monitor/post` | Publish real-time monitoring data (real-time charts only, not stored) |
| `/{productId}/{deviceNum}/ntp/post` | Publish time sync (optional) |
| `/{deviceNum}/http/upgrade/reply` | Reply to OTA upgrades via HTTPS |
| `/{deviceNum}/fetch/upgrade/reply` | Reply to OTA upgrades via binary package |

::: tip

* `{productId}` is the product ID (not the product number), found on the product detail page
* `{deviceNum}` is the device number and must match the platform device exactly
  :::

## Data Format

Devices and the platform exchange data in JSON format.

### Publish Properties/Functions/Events — `/property/post`, `/event/post`

```json
[{
    "id": "temperature",
    "value": "27.43",
    "remark": "Temperature normal"
}, {
    "id": "switch",
    "value": "1",
    "remark": "Switch turned on"
}]
```

* `id`: Thing model identifier, viewable on the product detail page, unique within the product
* `value`: Passed as a string; boolean uses `"0"`/`"1"`; enum uses the enum key; array is comma-separated
* `remark`: Note information, viewable in device logs

### Subscribe to Platform Commands — `/function/get`

```json
[{
    "id": "gear",
    "value": "1",
    "remark": "Scene linkage triggered"
}, {
    "id": "switch",
    "value": "0",
    "remark": "Scheduled off"
}]
```

```mermaid
%%{init: {"theme": "base", "themeVariables": {"background": "transparent", "primaryColor": "#edf4ff", "primaryTextColor": "#1f2937", "primaryBorderColor": "#536dfe", "lineColor": "#334155", "textColor": "#1f2937", "actorBkg": "#edf4ff", "actorBorder": "#536dfe", "actorTextColor": "#1f2937", "signalColor": "#334155", "signalTextColor": "#1f2937", "sequenceNumberColor": "#1f2937", "activationBkgColor": "#dbeafe", "activationBorderColor": "#536dfe", "noteBkgColor": "#fff7ed", "noteTextColor": "#1f2937", "noteBorderColor": "#f59e0b"}}}%%
sequenceDiagram
  autonumber
  participant P as FastBee Platform
  participant B as MQTT Broker
  participant D as Device
  P->>B: Publish /function/get
  B-->>D: Deliver command
  D->>D: Execute action based on id and value
  D->>B: Publish /property/post
  B-->>P: Push result
  P->>P: Save and refresh status
```

### Publish Device Info — `/info/post`

```json
{
    "rssi": -43,
    "firmwareVersion": 1.2,
    "status": 3,
    "userId": 1,
    "longitude": 0,
    "latitude": 0,
    "summary": {
        "name": "FastBee",
        "chip": "ESP32"
    }
}
```

| Field | Description |
|-------|-------------|
| rssi | Signal strength (excellent \[-55~0], good \[-70~-55], fair \[-85~-70], poor \[-100~-85]) |
| firmwareVersion | Firmware version number |
| status | Device status, fixed at 3 (online) |
| userId | User ID |
| longitude/latitude | Optional, device location |
| summary | Optional, device summary information |

```mermaid
%%{init: {"theme": "base", "themeVariables": {"background": "transparent", "primaryColor": "#edf4ff", "primaryTextColor": "#1f2937", "primaryBorderColor": "#536dfe", "lineColor": "#334155", "textColor": "#1f2937", "actorBkg": "#edf4ff", "actorBorder": "#536dfe", "actorTextColor": "#1f2937", "signalColor": "#334155", "signalTextColor": "#1f2937", "sequenceNumberColor": "#1f2937", "activationBkgColor": "#dbeafe", "activationBorderColor": "#536dfe", "noteBkgColor": "#fff7ed", "noteTextColor": "#1f2937", "noteBorderColor": "#f59e0b"}}}%%
sequenceDiagram
  autonumber
  participant P as FastBee Platform
  participant B as MQTT Broker
  participant D as Device
  P->>B: Publish /info/get
  B-->>D: Request device info
  D->>D: Collect device info
  D->>B: Publish /info/post
  B-->>P: Push info
  P->>P: Update status
```

### Real-time Monitoring — `/monitor/get`, `/monitor/post`

The platform sends a monitoring request:

```json
{
    "count": 60,
    "interval": 1000
}
```

The device reports data at the specified count and interval:

```json
[{
    "id": "temperature",
    "value": "27.43",
    "remark": ""
}]
```

### Time Sync — `/ntp/post`, `/ntp/get`

The device publishes:

```json
{
    "deviceSendTime": "1592361428000"
}
```

The platform replies:

```json
{
    "deviceSendTime": "1592361428000",
    "serverRecvTime": "1592366463548",
    "serverSendTime": "1592366463548"
}
```

Device current time = `(serverRecvTime + serverSendTime + deviceRecvTime - deviceSendTime) / 2`

## Thing Model Identifier Rules

* All identifiers must be unique within a product; use letters and numbers primarily and avoid special characters
* Object sub-model ID format: `parentId_childId`
* Array identifiers start with `array_index` (two-digit index, e.g. `array_00_power_switch`), and the array length must not exceed 100

## Device AP Provisioning (optional, WiFi devices only)

The device opens a hotspot (address `192.168.4.1`), and the mobile side passes configuration information through the device's web service.

### Detect Device

```
GET http://192.168.4.1/api/wifi/status
```

HTTP 200 means the device is detected; the response includes device info and the current network state.

### Configuration API

```
POST http://192.168.4.1/api/wifi/config?SSID=wifi_name&password=wifi_pass&userId=1
```

| Parameter | Description |
|-----------|-------------|
| SSID | WiFi name (required, lowercase `ssid` alias accepted) |
| password | WiFi password (required, `pwd` alias accepted) |
| userId | User ID (required) |
| deviceNum | Device number (optional) |
| extra | Product number (optional) |

HTTP 200 means provisioning succeeded (the device then automatically switches to STA mode), 400 means required parameters are missing, and 500 means saving failed.
See "Network Configuration · Mobile AP Provisioning API" for full endpoint details.

## Testing with MQTTX

1. Download the [MQTTX](https://mqttx.app/) client
2. Create a connection:
   * Host: `mqtt://ServerIP`, Port: `1883`
   * Client ID: `S&deviceNumber&productId&1`
   * Username: MQTT username
   * Password: MQTT password
3. Subscribe to `/{productId}/{deviceNum}/function/get`
4. Publish device info to `/{productId}/{deviceNum}/info/post`
5. Publish property data to `/{productId}/{deviceNum}/property/post`
6. Observe the device online status and running data on the platform console

## Acceptance Checklist

| Step | Check | Expected Result |
|------|-------|----------------|
| 1 | Product published | Product status is "published" |
| 2 | MQTTX connected | Device detail shows online |
| 3 | `/info/post` | Device info, signal, and version fields updated |
| 4 | `/property/post` | Running status shows thing model property values |
| 5 | `/event/post` | Reported events appear in the event log |
| 6 | `/function/get` | Device receives commands after the platform delivers them |
| 7 | Reply results | Device replies with the command result; platform status refreshes |
| 8 | Rules/Scenes | Related rules, scenes, and alerts can be triggered |

## Common Errors

### Connection Refused

1. Whether server port `1883` is open
2. Whether the built-in MQTT Broker is running
3. Whether the `clientId` format is correct (`S&deviceNumber&productId&userId`)
4. Whether the product has device authorization code enabled
5. Whether the device is disabled

### Device Online but Properties Not Refreshing

1. Whether the publish topic is `/{productId}/{deviceNum}/property/post`
2. Whether `productId` is the product ID (not the product number)
3. Whether `deviceNum` matches the device number exactly
4. Whether the message body is in JSON array format
5. Whether `id` matches the thing model identifier exactly
6. Whether `value` matches the data type

### Platform Commands Not Received by Device

1. Whether the device is subscribed to `/{productId}/{deviceNum}/function/get`
2. Whether the device is still online
3. Whether the thing model is a writable function or a deliverable property
4. Whether the user has device detail and command delivery permissions

### Rules or Alerts Not Triggered

1. Whether device data has entered the platform's running status
2. Whether the products, devices, and variables bound to the scene or rule are correct
3. Whether the condition expression matches the reported value type
4. Whether the alert configuration is enabled

## Rule Script Conversion

If a device uses a custom data format, you can write conversion logic in **Rule Scripts** to transform the raw data into the platform standard format. See [Rule Scripts](https://www.fastbee.cn/doc/en/open/v2/manual/script.md).

## Related Documentation

* [Community Edition Overview](https://www.fastbee.cn/doc/en/open/v2.md)
* [Product Management](https://www.fastbee.cn/doc/en/open/v2/manual/product.md)
* [Device Management](https://www.fastbee.cn/doc/en/open/v2/manual/device.md)
* [Thing Model](https://www.fastbee.cn/doc/en/open/v2/manual/things.md)
* [Scene Linkage](https://www.fastbee.cn/doc/en/open/v2/manual/scene.md)

## FAQ

### Do I have to deploy EMQX separately to use MQTT with the community edition?

No. The community edition includes an MQTT Broker built on Netty, listening on port 1883 by default, with WebSocket access on port 8083.

### How is the clientId formatted?

Simple authentication uses the S prefix in the form S\&device number\&product ID\&user ID; encrypted authentication uses the E prefix with a password derived from the product key through AES-CBC, which is recommended for production.

### A device shows online but its properties do not refresh, what should I check first?

Confirm that the publish topic is /{productId}/{deviceNum}/property/post, that productId uses the product ID rather than the product number, that deviceNum exactly matches the device number, and that the payload is a JSON array whose id values match the thing model identifiers.
