协议名称
MQTT
远程控制水肥机项目
//选中订阅主题 w2320308267 waterFertilizer
var selectedTopics = [‘waterFertilizer’];
//选中发布主题
var currentTopic='waterFertilizer';
//客户端选项
var option = {
"ServerUri": "39.98.155.166",
"ServerPort": 8083,
"UserName": "zzokq",
"Password": "123456",
"ClientId": "",
"TimeOut": 5,
"KeepAlive": 100,
"CleanSession": false,
"SSL":false
}
//客户端
var client;
var Afeisu,Bfeisu,Cfeisu,Dfeisu,suanLiu;
option.ClientId = guid();
client = new Paho.Client(option.ServerUri, option.ServerPort, option.ClientId)
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
client.connect({
invocationContext: {
host: option.ServerUri,//IP地址
port: option.ServerPort,//端口号
path: client.path,
clientId: option.ClientId//标识
},
timeout: option.TimeOut,//连接超时时间
keepAliveInterval: option.KeepAlive,//心跳间隔
cleanSession: option.CleanSession,//是否清理Session
useSSL: option.SSL,//是否启用SSL
userName: option.UserName, //用户名
password: option.Password, //密码
onSuccess: onConnect,//连接成功回调事件
onFailure: onError//连接失败回调事件
});
// var msg = “”;
// for(var i in selectedTopics){
// var t = selectedTopics[i];
// console.log(t.Topic)
// client.subscribe(t.Topic);
// msg+=t.Topic+“;”
// }
// WriteToStatus(“成功订阅主题:” + msg);
// setTimeout(function(){
// client.subscribe(‘waterFertilizer’);
// WriteToStatus(“成功订阅主题:” );
// },100)
//连接成功事件
function onConnect() {
WriteToStatus("连接成功!")
client.subscribe('waterFertilizer');
WriteToStatus("成功订阅主题:水肥机主题" );
client.subscribe('meteorology');
WriteToStatus("成功订阅主题:环境监测主题" );
enable($("#btnConnect"), false);
enable($("#btnDisconnect"), true);
enable($("#btnPublish"), true);
enable($("#btnSubscribe"), true);
}
//连接失败事件
function onError(e) {
WriteToStatus("连接失败:" + e)
enable($("#btnConnect"), true);
enable($("#btnDisconnect"), false);
enable($("#btnPublish"), false);
enable($("#btnSubscribe"), false);
}
//连接断开事件
function onConnectionLost(e) {
if (e.errorCode !== 0) {
WriteToStatus("连接异常断开:" + e.errorMessage);
enable($("#btnConnect"), true);
enable($("#btnDisconnect"), false);
enable($("#btnPublish"), false