## Page Guide

- **Use Cases**: Suitable for connecting direct devices and gateway devices over MQTT, or forwarding fixed-format device messages to the FastBee platform.
- **Prerequisites**: A product has been created and published, and the device number, product ID, MQTT account, password, and device secret are ready.
- **Authentication Recommendation**: Prefer encrypted authentication in production environments; simple authentication is more suitable for joint debugging, demos, and troubleshooting.
- **Acceptance Criteria**: The device connects successfully, passes authentication, subscribes to topics normally, and can complete Thing Model reporting and command receiving.

## Access Flow

::: tip

* Hardware SDK reference: <a href="https://gitee.com/beecue/fastbee" target="_blank" rel="nofollow">FastBee SDK</a>
* If the device MQTT payload format is fixed, you can use the EMQX rule engine to forward and adapt messages to the platform format.
  :::

1. Device authentication
   * Encrypted authentication, recommended for production.
   * Simple authentication, recommended only for testing.
2. Device interaction
   * Publish MQTT topics related to thing models, device information, monitoring data, OTA, and time synchronization.
   * Subscribe to MQTT topics for platform commands, device information requests, OTA, monitoring requests, and time synchronization.
3. AP provisioning, optional for Wi-Fi devices
   * Device detection API.
   * Device configuration API.

## 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
  participant P as FastBee
  D->>B: CONNECT(clientId, userName, password)
  B->>P: HTTP auth
  P->>P: Validate credentials
  alt Authentication failed
    P-->>B: Failed
    B-->>D: Reject
  else Authentication passed
    P->>P: Check or register device
    P-->>B: Passed
    B-->>D: Connected
  end
```

::: tip

* Authentication type: `S` means simple authentication, and `E` means encrypted authentication.
* If device authorization code is enabled for a product, the authorization code cannot be empty.
* `userId` is the login user ID. Devices belong to different users when different user IDs are used. In many deployments, devices can first use the admin user ID `1`, then be assigned through provisioning or QR-code binding.
* `deviceNumber` can be generated by the platform when creating a device, or generated by the hardware as a unique ID. If the device is not created in advance, FastBee can automatically register a device entity after successful authentication.
  :::

### Encrypted Authentication

Get the product ID, MQTT account, MQTT password, and product secret from product details. The MQTT password is encrypted with the product secret and sent to the backend. The MQTT client must provide a unique client ID, username, and password.

```ts
clientId = E & deviceNumber & productId & userId
userName = fastbee
password = mqttPassword & expireTime
password = mqttPassword & expireTime & deviceAuthorizationCode
```

Rules:

* Use `&` to connect authentication type, device number, product ID, and user ID. Do not add spaces.
* Username is the MQTT account.
* Password is the MQTT password, expiry timestamp, and optional authorization code encrypted with AES.
* For security, the password expiry time should be within 24 hours. Use millisecond timestamp format.

Example:

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

### Simple Authentication

Simple authentication uses the MQTT account and password from product details. It is suitable for testing environments. The client ID format is the same as encrypted authentication, but the authentication type is `S`.

```ts
clientId = S & deviceNumber & productId & userId
userName = fastbee
password = mqttPassword
password = mqttPassword & deviceAuthorizationCode
```

Example:

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

### Device Time Synchronization

Devices can call the NTP API to calculate current time. The request sends the device runtime in milliseconds. The response includes device send time, server receive time, and server send time.

```ts
http://localhost:8080/iot/tool/ntp?deviceSendTime=35768

deviceCurrentTime = (serverReceiveTime + serverSendTime + deviceReceiveTime - deviceSendTime) / 2
```

### AES Encryption

FastBee uses AES-CBC mode. The fixed IV is `wumei-smart-open`, output is Base64, and the encryption key is the product secret.

```ts
mode: CBC
padding: pkcs5padding
blockSize: 128
iv: wumei-smart-open
output: base64
key: productSecret
plainText: mqttPassword & expireTime & authorizationCode
```

## MQTT Topics

`{productId}` is the product ID and `{deviceNum}` is the device number. Both can be obtained from the Web platform. If automatic device creation is used, the device number can be a unique hardware code or MAC address.

### Subscribe Topics

| Topic | Description |
| --- | --- |
| `/{productId}/{deviceNum}/function/get` | Subscribe to platform commands |
| `/{productId}/{deviceNum}/info/get` | Subscribe to device information request |
| `/{productId}/{deviceNum}/ota/get` | Subscribe to old OTA upgrade messages |
| `/{productId}/{deviceNum}/upgrade/get` | Subscribe to new OTA upgrade messages |
| `/{productId}/{deviceNum}/monitor/get` | Subscribe to real-time monitoring requests |
| `/{productId}/{deviceNum}/ntp/get` | Subscribe to time synchronization requests |
| `/{productId}/{deviceNum}/property/get` | Deprecated in 2.x: subscribe to property commands |
| `/{productId}/{deviceNum}/property-online/get` | Deprecated in 2.x: online property command |
| `/{productId}/{deviceNum}/function-online/get` | Deprecated in 2.x: online function command |

### Publish Topics

| Topic | Description |
| --- | --- |
| `/{productId}/{deviceNum}/property/post` | Publish property, function, and monitoring data |
| `/{productId}/{deviceNum}/info/post` | Publish device information |
| `/{productId}/{deviceNum}/event/post` | Publish events |
| `/{productId}/{deviceNum}/monitor/post` | Publish real-time monitoring data, not stored |
| `/{productId}/{deviceNum}/ntp/post` | Publish time synchronization data |
| `/{productId}/{deviceNum}/upgrade/reply` | Reply to OTA upgrade messages |
| `/{productId}/{deviceNum}/function/post` | Deprecated in 2.x: publish function data |

## Payload Format

::: tip
Device and platform interaction uses JSON.
:::

### Device Information

When the device receives `/info/get`, it should publish device information to `/info/post`. This helps synchronize online status and device metadata.

```json
{
  "rssi": -43,
  "firmwareVersion": 1.2,
  "status": 3,
  "userId": 2,
  "longitude": 0,
  "latitude": 0,
  "summary": {
    "name": "FastBee",
    "chip": "ESP8266",
    "author": "fastbee",
    "deliveryTime": "2023-06-06",
    "activeTime": "2022-10-01"
  }
}
```

```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
  participant B as MQTT
  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: Forward info
  P->>P: Update status
```

### Real-Time Monitoring Request

Topic: `/monitor/get`

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

### Real-Time Monitoring Report

Topic: `/monitor/post`

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

### Property Report

Topic: `/property/post`

Use the thing-model identifier as `id` and send the collected value as a string.

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

## Integration Checklist

1. Confirm the product protocol, product ID, MQTT account, MQTT password, and product secret.
2. Confirm whether device authorization code is enabled.
3. Generate the correct client ID according to authentication type.
4. Subscribe to command, device information, monitoring, OTA, and time synchronization topics.
5. Publish device information after power-on and after receiving `/info/get`.
6. Use `/property/post` for business data that should be stored or displayed.
7. Use `/monitor/post` only for real-time monitoring data that does not need storage.

## FAQ

### How do I connect a device that uses a fixed message format?

Use the rule engine to transform the payload, or forward the existing format through EMQX to FastBee so the platform can process it uniformly.

### Which parameters are required for MQTT device authentication?

The device number, product number, MQTT account and password are required; the device authorisation code is also required when the product enables it.

### Which MQTT topics does a device need to publish to and subscribe to?

This page lists publish and subscribe topics for thing model data, device information, clock sync and OTA upgrades; implement to the topic tables and formats given there.
