Explanation
I was able to quickly make a small program to achieve MQTT late, I made a MQTT package.
Encapsulation function helps rapid development of late, it is also easy to maintain.
I was late all the code libraries are using this package,
In this section, I will use my detailed description of the package MQTT.js
New construction, copy files
Copy 1 or Section 2 test code inside the following three files to the new project
Explanation
Connection MQTT
Change the following information in accordance with their own server MQTT
Where to start to write the software connection
Note: Just connect the writing, internal automatic reconnection
var MQTT = require("./utils/mqtt.js"); App({ onLaunch: function () { MQTT.ConnectMqtt (); // link MQTT
Successfully connected MQTT
Test reconnection
Subscribe theme
MQTT.subscribeTopic ( " 1111 " , // subscribe 1111 0 , // Message Level function () { console.log ( " subscription success " ); }, function () { console.log("订阅失败"); } );//订阅主题
建议
var MQTT = require("../../utils/mqtt.js"); var TimeNumber;//循环订阅设备主题定时器 //订阅设备发布的主题 try { clearInterval(TimeNumber); } catch (e) { } TimeNumber = setInterval(function() { MQTT.subscribeTopic( "1111", //订阅1111 0,//消息等级 function () { console.log("订阅成功"); clearInterval(TimeNumber);//订阅成功清除定时 }, function () { console.log("订阅失败"); } );//订阅主题 }, 1000, "null");//启动定时器,循环订阅主题,直至订阅成功
取消订阅主题
MQTT.unSubscribeTopic( "1111", //取消订阅的主题 function() { console.log("取消订阅成功"); } );
发布消息
发布字符串消息
MQTT.publishTopic( "222", //发布的主题 "message", //发布的消息 0, //消息等级 false, //不需要服务器保留 function()//发送成功回调 { console.log("发送消息成功"); } );
发布16进制消息
0xAA 0x88 0xFF 0xdd
MQTT.publishStringToHex( "222", //发布的主题 "AA 88 FF dd", //发布的消息 0, //消息等级 false, //不需要服务器保留 function ()//发送成功回调 { console.log("发送消息成功"); } );
接收消息
MQTT.SetonMessageArrivedCallBack( function (arg) { console.log(arg.destinationName + " " + arg.payloadString); } );//注册接收消息回调函数
监听MQTT状态
掉线
MQTT.SetonConnectionLostCallBack(function(arg){ console.log(arg);//打印链接失败详细信息 });//软件掉线
上线
MQTT.SetonConnectionSuccessCallBack(function(){ console.log("连接上MQTT"); });//连接上MQTT