webOs-backend/mqtt/server.js
2023-02-23 13:50:16 +08:00

61 lines
1.7 KiB
JavaScript

/* eslint-disable no-undef */
const mqtt = require('mqtt');
const config = require('../config')
module.exports = class mqttService{
constructor(){
this.mqtt = mqtt
this.options = config.options
this.mqttUrl =config.mqttUrl
// this.client = this.mqtt.connect(this.mqttUrl, this.options)
}
// 订阅
subscribe(topic){
this.client.subscribe(topic, this.options, (err) => {
if (err) {
//
} else {
//
}
})
}
// 发布
publish(topic,sendMsg){
this.client.publish(topic, JSON.stringify(sendMsg))
console.log('发步成功');
}
// 连接
connect(){
this.client = this.mqtt.connect(this.mqttUrl, this.options);
this.client.subscribe("rep/hcc/588a6897-5286-4ceb-8318-bb256869ab03/iotDev/func/#",{qos:0})
this.client.on('connect', ()=>{
console.log(`成功连接到服务器[${this.mqttUrl}]`);
});
this.client.on('message', (topic, message)=>{
let arr=topic.split("/")
let devid=arr[arr.length-1]
console.log("devid:",devid)
let repdata = JSON.stringify({
devid:devid,
data:message.toString()
});
// eslint-disable-next-line no-unused-vars
socketmap.forEach(function(value, key) {
value.send(repdata)
}, socketmap)
});
this.client.on('reconnect', (err) => {
console.log('mqtt 正在重连:', err)
})
this.client.on('error', (err)=>{
console.log(`mqtt连接失败,${err}`);
});
}
}