cy-plugin-mqtt
v1.0.9
Published
自定义mqtt插件
Downloads
21
Readme
cy-plugin-mqtt
基于 mqtt 和 emittery 封装的插件,适用于浏览器环境。
✨ 特性
- 封装
mqtt,提供更友好的 API - 基于
Emittery实现事件发布/订阅 - ESM 格式输出,支持 TypeScript 类型提示
📦 安装
⚠️ 注意:
cy-plugin-mqtt依赖mqtt和emittery,它们不会被打包进来,需要额外安装。
npm install cy-plugin-mqtt [email protected] [email protected] --save🔨 使用
// npm i [email protected]
// npm i [email protected]
// ws://xxxx:8083/mqtt
// wss://xxxx:8084/mqtt
// 注意: 在页面关闭前 要取消所有订阅并释放 mqqt 资源,否则会造成内存泄漏
import MqttPlugin from 'cy-plugin-mqtt';
try {
const mqtt = new CyMqtt({
url: '192.168.1.1:8083/mqtt', // 必传
username: 'admin', // 必传
password: '123456', // 必传
wss: false, // 默认 ws
debug: false, // 默认 false
subscribeTopic: 'device/', // 默认 ''
publishTopic: 'device/', // 默认 ''
qos: 0, // 默认 0
handleData: (msg) => {
return xxxx;
}, // 如果要自定义处理数据,可以传入一个回调函数
connectOption: {
connectTimeout: 60_000,
keepalive: 10,
maxCount: Infinity,
interval: 5_000,
maxInterval: 60_000
}
});
// 连接到 MQTT 服务器
mqtt.connect();
// 断开连接
mqtt.disConnect();
// 发送消息
mqtt.publish({ text: 'hello' });
// 订阅
mqtt.subscribe('device123');
// 取消订阅
mqtt.unsubscribe('device123');
// 事件
const funcA = (topic, data) => {
console.log('收到消息:', data);
};
// 监听
mqtt.on(enumMqttEvent.MESSAGE, funcA);
// 取消监听
mqtt.off(enumMqttEvent.MESSAGE, funcA);
} catch (error) {
console.error('MQTT 连接失败', error);
}