// app.js const mqtt = require("mqtt");//mqtt api包 const _ = require("lodash")//工具包 class AppBootHook { constructor(app) { this.app = app; } async didReady() { //连接到小车上的mqtt服务器 // const client = mqtt.connect("mqtt://192.168.1.102:1883", { const client = mqtt.connect("mqtt://127.0.0.1:1883", { clean: true,//持续链接 connectTimeout: 4000,//超时 clientId: 'map-editor-' + Math.random().toString(16).substr(2),//连接用户id唯一 username: 'map-editor',//连接用户名(如果没有则可以不写) password: 'leador',//连接用户密码(如果没有则可以不写) }); //连接服务器 client.on("connect", function () { console.log("appmqtt服务器连接成功"); // 订阅电池信息 client.subscribe(`/robot4inspection/fa49e558574df1ec/sensor/battery`, { qos: 0 }, (a, b, c) => { }); // 订阅位置信息 client.subscribe(`/robot4inspection/fa49e558574df1ec/sensor/gps`, { qos: 0 }, (a, b, c) => { }); // 订阅位姿信息 client.subscribe(`/robot4inspection/fa49e558574df1ec/localization/pose`, { qos: 0 }, (a, b, c) => { }); // 订阅错误消息 client.subscribe(`/robot4inspection/fa49e558574df1ec/message/error`, { qos: 0 }, (a, b, c) => { }); // 订阅警告消息 client.subscribe(`/robot4inspection/fa49e558574df1ec/message/warn`, { qos: 0 }, (a, b, c) => { }); // 订阅日志消息 client.subscribe(`/robot4inspection/fa49e558574df1ec/message/info`, { qos: 0 }, (a, b, c) => { }); }); //监听消息 client.on("message", async function (topic, message) { if (_.endsWith(topic, "/sensor/battery")) { //得到电池信息 let resObj = JSON.parse(message.toString()) console.log(resObj) } else if (_.endsWith(topic, "/sensor/gps")) { //得到位置信息 let resObj = JSON.parse(message.toString()) console.log(resObj) } else if (_.endsWith(topic, "/localization/pose")) { //得到位姿信息 let resObj = JSON.parse(message.toString()) console.log(resObj) } else if (_.endsWith(topic, "/message/error")) { //得到错误信息 let resObj = JSON.parse(message.toString()) console.log(resObj) //得到错误信息后需要发布消息(自定义话题即可) client.publish("/errorMessage", JSON.stringify(resObj), { qos: 1, }) } else if (_.endsWith(topic, "/message/warn")) { //得到警告信息 let resObj = JSON.parse(message.toString()) console.log(resObj) } else if (_.endsWith(topic, "/message/info")) { //得到日志信息 let resObj = JSON.parse(message.toString()) console.log(resObj) } }); } } module.exports = AppBootHook;