更新记录
0.0.1(2025-04-16)
平台兼容性
App |
快应用 |
微信小程序 |
支付宝小程序 |
百度小程序 |
字节小程序 |
QQ小程序 |
HBuilderX 3.6.8,Android:支持,iOS:支持,HarmonyNext:不确定 |
× |
√ |
× |
× |
× |
× |
钉钉小程序 |
快手小程序 |
飞书小程序 |
京东小程序 |
鸿蒙元服务 |
× |
× |
× |
× |
× |
H5-Safari |
Android Browser |
微信浏览器(Android) |
QQ浏览器(Android) |
Chrome |
IE |
Edge |
Firefox |
PC-Safari |
√ |
√ |
√ |
√ |
√ |
× |
× |
× |
× |
lime-mqtt
- 提供跨平台的 MQTT 协议通信能力,支持连接、订阅、发布、断开等基础操作,支持安卓、Web、微信小程序、(iOS未测)
文档
mqtt
安装
插件市场导入,引入页面后,APP需要自定义基座
演示代码
初始化客户端
import { useMqtt } from '@/uni_modules/lime-mqtt'
const mqttClient = useMqtt()
1. 连接 MQTT 服务器
import type { MQTTConnectOptions } from '@/uni_modules/lime-mqtt'
mqttClient.connect({
host: "broker.example.com",
port: 8083,
clientId: "myClient_123", // 可选,默认自动生成
username: "user", // 可选
password: "pass", // 可选
usessl: true, // 默认 true
keepalive: 60, // 默认 60秒
timeout: 30, // 默认 30秒
success: (res) => {
console.log("连接成功:", res.data.errmsg)
},
fail: (err) => {
console.error("连接失败:", err.errorCode)
}
} as MQTTConnectOptions)
2. 断开连接
import type { MQTTDisconnectOptions } from '@/uni_modules/lime-mqtt'
mqttClient.disconnect({
success: () => {
console.log("已断开连接")
}
} as MQTTDisconnectOptions)
3. 订阅主题
import type { MQTTSubscribeOptions } from '@/uni_modules/lime-mqtt'
mqttClient.subscribe({
topic: "home/sensor/temperature",
qos: 1,
success: (res) => {
console.log(`订阅成功: ${res.data.topic}`)
}
} as MQTTSubscribeOptions)
4. 取消订阅
import type { MQTTUnSubscribeOptions } from '@/uni_modules/lime-mqtt'
mqttClient.unsubscribe({
topic: "home/sensor/temperature",
success: () => {
console.log("已取消订阅")
}
} as MQTTUnSubscribeOptions)
5. 发布消息
import type { MQTTPublishOptions } from '@/uni_modules/lime-mqtt'
mqttClient.publish({
topic: "home/light/control",
payload: "turn_on",
qos: 1
} as MQTTPublishOptions)
6. 消息监听
import type { MqttMessage } from '@/uni_modules/lime-mqtt'
const messageHandler = (msg: MqttMessage) => {
console.log(`收到消息 [${msg.topic}]: ${msg.payloadString}`)
}
mqttClient.onMessage(messageHandler)
// 移除监听
mqttClient.offMessage(messageHandler)
错误代码参考
错误码 |
说明 |
910001 |
连接异常 |
910005 |
缺少 host 或 port 参数 |
9010002 |
订阅/取消订阅失败 |