MQTT相关工具
MQTT 工具类
@pt/utils/modules/mqtt 提供了一个封装好的MQTT客户端类,支持WebSocket连接、消息收发、自动重连等功能。
依赖文件下载
请先下载 mqttws31.js 文件,并将其放置到项目的 public/js 目录下。
下载地址:点击下载 mqttws31.js
注意: 文件路径必须为 public/js/mqttws31.js,否则MQTT功能无法正常使用。
基本使用
typescript
import MQTT from '@pt/utils/modules/mqtt';
// 创建MQTT实例
const mqtt = new MQTT({
topic: 'my/topic', // 可以是字符串或字符串数组
satoken: 'your-token',
mqttConfig: {
vhost: 'mqtt',
password: 'your-password',
webUri: 'ws://your-mqtt-server:9080',
username: 'your-username',
useSSL: false,
},
basePath: import.meta.env.BASE_URL
});
// 初始化连接
await mqtt.init();
// 接收消息
mqtt.get((topic, message) => {
console.log(`收到消息: topic=${topic}, message=${message}`);
});
// 发送消息
mqtt.send('Hello MQTT!', 'my/topic');
// 取消订阅
mqtt.unsubscribes();
// 断开连接
mqtt.over();API 参考
MQTT类构造函数
typescript
interface MQTTConfig {
vhost: string;
password: string;
webUri: string;
username: string;
useSSL?: boolean;
}
interface MQTTOptions {
topic: string | string[];
satoken: string;
mqttConfig: MQTTConfig;
basePath?: string;
}
class MQTT {
constructor(options: MQTTOptions);
}方法
| 方法名 | 参数 | 返回值 | 描述 |
|---|---|---|---|
| init | - | Promise<void> | 初始化MQTT连接 |
| get | callback: (topic: string | string[], message: string) => void | void | 设置消息接收回调 |
| send | message: string, topic: string | void | 发送消息到指定topic |
| unsubscribes | - | void | 取消所有订阅 |
| over | - | void | 断开MQTT连接 |
示例
基本订阅和发送
typescript
import MQTT from '@pt/utils/modules/mqtt';
const mqtt = new MQTT({
topic: 'test/topic',
satoken: 'your-token',
mqttConfig: {
vhost: 'mqtt',
password: 'password123',
webUri: 'ws://mqtt.example.com:9080',
username: 'user123',
useSSL: false // 根据weburl来决定是 true 或 false, 假如 weburl为“ws://mqtt.example.com:9080”,则useSSL为false,假如 weburl为“wss://mqtt.example.com:9080”,则useSSL为true
},
basePath: import.meta.env.BASE_URL
});
// 初始化连接
await mqtt.init();
// 接收消息
mqtt.get((topic, message) => {
console.log(`Topic: ${topic}`);
console.log(`Message: ${message}`);
});
// 发送消息
mqtt.send('Hello World', 'test/topic');多Topic订阅
typescript
const mqtt = new MQTT({
topic: ['topic1', 'topic2', 'topic3'],
// ... 其他配置
});
await mqtt.init();
mqtt.get((topics, message) => {
if (Array.isArray(topics)) {
console.log(`Received on topics: ${topics.join(', ')}`);
} else {
console.log(`Received on topic: ${topics}`);
}
console.log(`Message: ${message}`);
});