物联网项目现在越来越多,MQTT的使用场景也越来越广泛,同时遇到的技术问题也是越来越复杂。
最近在做一个小程序连接阿里云的微消息队列MQTT版,说实话,通过这次debug,发现阿里的技术文档很多方面不完善,对前端的SDK,文档只有js,好吧。只能靠自己鸟。
进入lmq-js-demo目录,看一下demo文件,这写法,双子座的表示受不了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Aliyun Mqtt Websockets</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js" type="text/javascript"></script> <script type="text/javascript"> instanceId = 'XXXX';//实例 ID,购买后从控制台获取 host = 'XXXX.mqtt.aliyuncs.com';// 设置当前用户的接入点域名,接入点获取方法请参考接入准备章节文档,先在控制台创建实例 port = 80;//WebSocket 协议服务端口,如果是走 HTTPS,设置443端口 topic = 'XXXX';//需要操作的 Topic,第一级父级 topic 需要在控制台申请 useTLS = false;//是否走加密 HTTPS,如果走 HTTPS,设置为 true accessKey = 'XXXXX';//账号的 AccessKey,在阿里云控制台查看 secretKey = 'XXXXX';//账号的的 SecretKey,在阿里云控制台查看 cleansession = true; groupId = 'GID_XXXX';//MQTT GroupID,创建实例后从 MQTT 控制台创建 clientId = groupId + '@@@00001';//GroupId@@@DeviceId,由控制台创建的 Group ID 和自己指定的 Device ID 组合构成 var mqtt; var reconnectTimeout = 2000; var username = 'Signature|' + accessKey + '|' + instanceId;//username和 Password 签名模式下的设置方法,参考文档 https://help.aliyun.com/document_detail/48271.html?spm=a2c4g.11186623.6.553.217831c3BSFry7 var password = CryptoJS.HmacSHA1(clientId, secretKey).toString(CryptoJS.enc.Base64); function MQTTconnect() { mqtt = new Paho.MQTT.Client( host,//MQTT 域名 port,//WebSocket 端口,如果使用 HTTPS 加密则配置为443,否则配置80 clientId//客户端 ClientId ); var options = { timeout: 3, onSuccess: onConnect, mqttVersion: 4, cleanSession: cleansession, onFailure: function (message) { setTimeout(MQTTconnect, reconnectTimeout); } }; mqtt.onConnectionLost = onConnectionLost; mqtt.onMessageArrived = onMessageArrived; if (username != null) { options.userName = username; options.password = password; options.useSSL = useTLS;//如果使用 HTTPS 加密则配置为 true } mqtt.connect(options); } function onConnect() { // Connection succeeded; subscribe to our topic mqtt.subscribe(topic, {qos: 0}); message = new Paho.MQTT.Message("Hello mqtt!!");//set body message.destinationName = topic;// set topic //发送 P2P 消息,topic 设置方式参考https://help.aliyun.com/document_detail/96176.html?spm=a2c4g.11186623.6.586.694f7cb4oookL7 message = new Paho.MQTT.Message("Hello mqtt P2P Msg!!");//set body message.destinationName = topic + "/p2p/" + clientId;// set topic mqtt.send(message); } function onConnectionLost(response) { setTimeout(MQTTconnect, reconnectTimeout); }; function onMessageArrived(message) { var topic = message.destinationName; var payload = message.payloadString; console.log("recv msg : " + topic + " " + payload); }; MQTTconnect(); </script> </head> </html>
上面是原封不动的弄过来了,第一次看肯定觉得乱七八糟。不管它了,先想想怎么整合到小程序来。
demo中有两个文件是需要引入的,mqttws31.js和crypto-js.js。想着按上面的风格直接在小程序引入试试,结果是各种报错。
当new Paho.MQTT.Client()时,paho not defined. Client not defined.Message not defined.
第一次调试嘛,有问题很正常,往下看。。。
不如先查一下 Paho.MQTT有没有小程序的js文件或demo文件?github和gitee查了个遍,没有。
那就去官网查吧,Eclipse Paho JavaScript Client
全英文的文档,查了个寂寞,啥也没查到。一个小时过去了,得想其他办法。
其实问题应该就出在mqtt文件的引入问题,html引入js文件和小程序引入js文件肯定有不同之处的。就从这方面入手吧,找找有没有相关的paho.mqtt又适合小程序的文件。
终于找到了个paho-mqtt.js的文件,下载地址
下载后在小程序文件里直接引入试试,最下面会贴出完整的代码^_^
1
2
3
4
5
6
7const app = getApp(); const PahoMQTT = require('../../utils/paho-mqtt'); //引入paho-mqtt const CryptoJS = require('../../utils/crypto-js'); //引入阿里云密码加密文件 Page({ data: { } });
然后 const client = new PahoMQTT(
host,//MQTT 域名
port,//WebSocket 端口,如果使用 HTTPS 加密则配置为443,否则配置80
clientId//客户端 ClientId
);
调用时又报错。直接看源文件,发现需要调用Client方法才使用。
真是一波多折呀。
好了,不费话了,直接上最终代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61const app = getApp(); const PahoMQTT = require('../../utils/paho-mqtt'); const CryptoJS = require('../../utils/crypto-js.js'); var mqttClient; Page({ data: { }, onLoad(option){ this.initAliYunMqtt(); }, /** * 初始化 aliyun 微消息队列 MQTT */ connectMqttAliyun() { const that = this; const instanceId = "mqtt-cn-*******";//阿里云管理后台添加获取 const accessKey = '****************';//阿里云管理后台获取 const secretKey = '********************************';//阿里云管理后台添加获取 const port = 443; const cleansession = true; const useTLS = true; const groupId = 'GID_weChe'; //阿里云管理后台添加获取 const clientId = groupId + '@@@'+Math.random().toString(16).substr(2, 8); const host = 'mqtt-cn-******.mqtt.aliyuncs.com'; const username = 'Signature|' + accessKey + '|' + instanceId; const password = CryptoJS.HmacSHA1(clientId, secretKey).toString(CryptoJS.enc.Base64); mqttClient = new PahoMQTT.Client( host,//MQTT 域名 port,//WebSocket 端口,如果使用 HTTPS 加密则配置为443,否则配置80 clientId//客户端ClientId ); //连接mqtt const onConnect = () => { console.log("mqtt connect success!"); mqttClient.subscribe("subTopic"); //订阅一个主题 }; //连接丢失回调 const onConnectionLost = (ret) => { console.log("连接丢失了:"+ret) }; let options = { timeout: 3, onSuccess: onConnect, mqttVersion: 4, cleanSession: cleansession, onFailure: function (message) { console.log(message) setTimeout(that.connectMqttAliyun(), 2000); //重连 } }; if (username != null) { options.userName = username; options.password = password; options.useSSL = useTLS;//如果使用 HTTPS 加密则配置为 true } //监听数据 const onMessageArrived = (ret) => { console.log(ret.payloadString) }; } })
显示这玩意儿,就算成功咯!
主题订阅:
1
2
3
4
5
6
7/** * mqtt订阅 */ subscribeMqtt(topic){ mqttClient.subscribe(topic); console.log("主题:" + topic + "订阅成功") }
发布:
1
2
3
4
5
6
7
8
9/** * mqtt发布 */ publishMqtt(topic, info){ let message = new PahoMQTT.Message(info); message.destinationName = topic; mqttClient.send(message); console.log("主题:" + topic + "发布成功") }
是不是很简单!费时1.2天,其中加班0.5天,哈哈!路过的点个赞呗!!!!
最后
以上就是轻松羊最近收集整理的关于小程序paho.mqtt连接微消息队列 MQTT 版的全部内容,更多相关小程序paho.mqtt连接微消息队列内容请搜索靠谱客的其他文章。
发表评论 取消回复