当前位置:首页 > 新闻动态 > 网站文章

【微信小程序控制硬件⑧ 】微信小程序以 websocket 连接阿里云IOT物联网平台mqtt服务器,封装起来使用就是这么简单!(附带Demo)

来源: 浏览:123 时间:2023-08-09

一、前言;

            今天是6月12号,高考过完刚刚不久,我也想起五年前那个夏天了。虽没有汗流浃背备考,但也有面对未来的种种幻想以及迷茫。

            回想到现在工作了,自己学到的东西很多,还真的应了课本的一句话 “人的一生都是在学习中!学习如逆水行舟,不进则退!”,当我看到身边的一些人懒懒散散的,看博文学习不动手做小项目,我的心是有点 “嫌弃”的,我也希望在一个优秀的团队,可以彼此进步,不管是大型企业或者小公司!当身边的人优秀,你也会一定反思自己,有所行动。

            感悟最深的是 ”学会投资自己“ ,不管在生活的衣食住行中,买些舒服的衣服,抑或是每天每周做些美食犒劳自己,还是在职业生涯中,买教程,买课本,消化知识,提升自己。总结我在网上买了几乎几千块的视频,其中也有些乏味的教学视频,也有很多实实在在的干货,的确耐人寻味,那是一种心灵上的快心。

二、微信小程序 websocket;

            微信小程序都不陌生了,一句话:依靠在微信客户端的一个小程序,其开发语言不是原生的,而是采用 html+JavaScript+css 这样类似的前端代码,接近原生体验!

websocket
443https协议websocketmqttmqtt

三、阿里云IOT物联网平台 websocket;

WebSocketWebSocketWebSocketMQTTMQTT over WebSocket
  1. 证书准备。

            WebSocket可以使用ws和wss两种方式,ws就是普通的WebSocket连接,wss就是增加了TLS加密。如果使用wss方式进行安全连接,需要使用和TLS直连一样的根证书。而我本次提供给大家的不需要根证书的。


mqttClientId: clientId+"|securemode=3,signmethod=hmacsha1,timestamp=132323232|"
mqttUsername: deviceName+"&"+productKey
mqttPassword: sign_hmac(deviceSecret,content)sign签名需要把以下参数按字典序排序后,再根据signmethod加签。
content=提交给服务器的参数(productKey,deviceName,timestamp,clientId), 按照字母顺序排序, 然后将参数值依次拼接
clientId = 12345,deviceName = device, productKey = pk, timestamp = 789,signmethod=hmacsha1,deviceSecret=secret
ws://pk.iot-as-mqtt.cn-shanghai.aliyuncs.com:443

mqttclientId=12345|securemode=3,signmethod=hmacsha1,timestamp=789|
mqttUsername=device&pk
mqttPasswrod=hmacsha1("secret","clientId12345deviceNamedeviceproductKeypktimestamp789").toHexString(); 
wss://pk.iot-as-mqtt.cn-shanghai.aliyuncs.com:443
mqttclientId=12345|securemode=2,signmethod=hmacsha1,timestamp=789|
mqttUsername=device&pk
mqttPasswrod=hmacsha1("secret","clientId12345deviceNamedeviceproductKeypktimestamp789").toHexString();

四、如何移植和封装使用;

            因为我做过设备端的 Mqtt协议连接阿里云物联网平台,对协议比较熟悉,所以对于怎么实现在微信小程序上是非常简单的。

            上面已经详细地说明了阿里云物联网平台 websocket 的协议,那么总的来说就是一个 加密算法,因为我之前已经开源了一个在微信小程序上实现 Mqtt协议连接服务器,这只要拿到了连接的一些参数,那就不成问题了!

            上面反复提到 hmacsha1 加密算法,那我就去找一个呗。还好,去官网 GitHub找了一个:点击访问 , 拿到了加密算法文件,按照上面说明,分别生成:mqttclientId、mqttUsername、mqttPasswrod、port端口号、url域名,就可以实现链接啦!

4.1 为了简单实用,降低耦合,我一度封装起来生成的算法,其封装源码如下:


exports.getAliyunIotMqttClient = function(opts) {
//是否传入三元组
    if (!opts || !opts.productKey || !opts.deviceName || !opts.deviceSecret) {
        throw new Error('options need productKey,deviceName,deviceSecret');
    }
if (opts.protocol === 'mqtts' && !opts.ca) {
        throw new Error('mqtts need ca ');
    }
    //是否传入区域
    if (!opts.host && !opts.regionId) {
        throw new Error('options need host or regionId (aliyun regionId)');
    }
const deviceSecret = opts.deviceSecret;
    delete opts.deviceSecret;
let secureMode = (opts.protocol === 'mqtts') ? 3 : 2;
var options = {
        productKey: opts.productKey,
        deviceName: opts.deviceName,
        timestamp: Date.now(),
        clientId: Math.random().toString(36).substr(2)
    }
    let keys = Object.keys(options).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
        list.push(`${key}${options[key]}`);
    });
    const contentStr = list.join('');
    //加密算法生成 password
    opts.password = crypto.hex_hmac_sha1(deviceSecret, contentStr);
    opts.clientId = `${options.clientId}|securemode=${secureMode},signmethod=hmacsha1,timestamp=${options.timestamp}|`;
    opts.username = `${options.deviceName}&${options.productKey}`;
opts.port = opts.port || 1883;
    //生成域名
    opts.host = opts.host || `${opts.productKey}.iot-as-mqtt.${opts.regionId}.aliyuncs.com`;
return (opts); //返回给上层
}

4.2 如何使用呢?

getAliyunIotMqttClient(option)

            option 对象的定义如下:

参数含义
productKey三元组信息 productKey
deviceName三元组信息 deviceName
deviceSecret三元组信息 deviceSecret
regionId可选域,目前国内仅支持上海,所以是 cn-shanghai
port443 不可修改,唯一!

            返回的对象的定义如下:

参数含义
clientId连接参数
password连接参数
username连接参数
host连接的域名
  • 示范:

data: {
    aliyunInfo: {
      productKey: 'a1o3SXAACTs23', 
      deviceName: 'rgb2812',
      deviceSecret: 'RurAqmlt0duwMilKv6Oa856WDcQ279685a', 
      regionId: 'cn-shanghai', 
    }
  }
var that = this
//传进去三元组等信息,拿到mqtt连接的各个参数
    let clientOpt = aliyunOpt.getAliyunIotMqttClient({
      productKey: that.data.aliyunInfo.productKey,
      deviceName: that.data.aliyunInfo.deviceName,
      deviceSecret: that.data.aliyunInfo.deviceSecret,
      regionId: that.data.aliyunInfo.regionId,
      port: that.data.aliyunInfo.port,
    });
//得到连接域名
    let host = 'wxs://'+clientOpt.host;
    this.setData({
      'options.clientId': clientOpt.clientId,
      'options.password': clientOpt.password,
      'options.username': clientOpt.username,
    })
//开始连接
    this.data.client = mqtt.connect(host, this.data.options);
    this.data.client.on('connect', function(connack) {
      wx.showToast({
        title: '连接成功'
      })
    })

五、其他;

GitHub

            更多的使用技巧,你需要具备一定的微信小程序开发经验哦!结合我的代码,让你轻松连接阿里云IOT物联网平台!与你共勉!!

  • 很多人怎么联系我一起学习进步,下面打个小小公告和干货无偿分享:
esp8266 & esp32QQMqtt

地址 · ADDRESS

地址:建邺区新城科技园嘉陵江东街18号2层

邮箱:309474043@qq.Com

点击查看更多案例

联系 · CALL TEL

400-8793-956

售后专线:025-65016872

业务QQ:309474043    售后QQ:1850555641

©南京安优网络科技有限公司 版权所有   苏ICP备12071769号-4  网站地图