MQTT 官方中文网:http://mqtt.p2hp.com
js 的 MQTT 库为paho-mqtt: https://github.com/eclipse/paho.mqtt.javascript
获取 mqtt 并处理数据
// 引用 mqtt 库
<script src="__JS__/mqtt/paho-mqtt.js"></script>
var MQTT;
// 网络连接正常
var network = true;
// MQTT 实时监听
if(!MQTT){
MQTTconnect();
}
// Create a client instance
var clientId = "{:uniqid()}{:time()}";
function MQTTconnect() {
var useTLS = location.protocol === 'https:';
var port = useTLS ? 8883 :8083
var client = new Paho.Client(location.hostname, port, clientId);
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({
userName: '###',
password: '***',
useSSL: location.protocol == "https:",
onSuccess: onConnect,
reconnect: true,
keepAliveInterval: 30,
onFailure: function (message) {
network = false;
}
});
// called when the client connects
function onConnect() {
client.subscribe("das/realtimes/#", {qos: 0});
client.subscribe("das/event/#", {qos: 1});
// 网络断开,重新进去
if(network == false){
// 重新加载接口方法
// ListenAlarm(_GlobalNode);
network = true;
}
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:", responseObject);
network = false;
}
}
// called when a message arrives
function onMessageArrived(message) {
//告警实时值
if(message.topic.indexOf('das/event/')>-1){
var response = JSON.parse(message.payloadString);
// console.log(response.alarms[0].alarmid);
// console.log(response);
// 获取mqtt后的数据处理...
}
}
window.MQTT=client;
}
发送数据至 mqtt
// called when the client connects
function onConnect() {
var senddata = [{
"equipid": parseInt($("#equipid").val()),
"cmdtype": 3,
"cmddatalen": 3,
"status": -1,
"modelvalue": -1,
"tempvalue": -1,
"option":2,
"uptemp":-1,
"lowtemp":-1,
"cycle":-1,
"isenable":-1,
"selectair1":-1,
"selectair2":-1,
"delay":-1,
"choose": 5,
}];
sendMQTT(senddata);
// client.subscribe("das/ack/{$equipid}/", {qos: 1});
}
function sendMQTT(controldata){
var data = {
"controls": [{
"result": -1,
"controldata": controldata,
"controltime": Math.round(new Date().getTime() / 1000),
"reason": 5,
"variableid": "",
"failuerreason": "",
"action": 1,
"controltype": 2, // 定义
"logid": 0,
"userid": $("#userid").val(),
"userip": "{$_SERVER['REMOTE_ADDR']}",
}],
"updatetime": Math.round(new Date().getTime() / 1000),
"mcukeycode": "",
"fccode": 4,
"token": $.cookie('XSRF-TOKEN'),
"msg": "空调轮换配置"
};
var val = JSON.stringify(data);
var message = new Paho.Message(val);
message.destinationName = "das/controls/{$equipid}/";
message.qos = 2;
// console.log(message);
MQTT.send(message);
}