nodemcu利用MTTQ连接阿里云

一、固件的选择及产生Bin文件

  1. nodemcu固件生成网站选择自己需要的固件,并且生成bin文件,烧录到ESP8266中
  • 在Select branch里面选择master版本。(稳定版)
  • 在modules里面选择勾选下列:
    crypto----加密模块(hamc加密)
    sntp--获取时间戳模块
    file,gpio,net,node,timer,uart,wifi,mqtt为默认模块
    最后输入你的邮箱,就会把编译好的bin文件发送到你的邮箱,会提供2个版
    本(整形,浮点型)根据实际需求选择

注:这里的邮箱不要选择QQ邮件,不然会收不到邮件,本人使用的是网易邮件可行


固件菜单

二、刷固件

打开刷固件的软件,选择刚才生产的bin文件,选好对应的COM口,直接点击start就可以了(其他配置默认)使用方法在刷固件的软件中有很详细的说明

注:

  1. nodemcu模版的驱动程序为CP2102,所以要在cp2102 usb驱动官网下载安装后使用
  2. 若下载固件后模块不断发送乱码则看本网站,我当时也是糊里糊涂的解决的,看了网上很多解决办法,波特率问题或者开关ESPlorer中的DTR和RTS

三、在阿里云创建产品

这个创建没什么难度就不写出来了,阿里云中的三元组很重要!!!

注:
在阿里云的MTTQ通信中MQTT的Connect报文参数是有规定的,大家可以去阿里云帮助文档查看,在下面的代码编写中会用到

三、代码编写

编译环境esplorer下载

  1. wifi的配置
cfg={}  
cfg.ssid="leon"
cfg.pwd="123456"
----[wifi connect]---------------
wifi.setmode(wifi.STATION)  --设置为STA模式
wifi.sta.config(cfg)        --配置
wifi.sta.connect()          --连接wifi
-----[注册wifi事件]----
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
     print("Connected, IP is "..wifi.sta.getip())
end)

wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
     print("wifi disconnect")
end)
  1. 阿里 MQTT 配置
----[阿里3元认证组]------
ProductKey ="a19bI5MaWV6"   --换成自己的
DeviceName ="ESP01"  -- 换成自己的
DeviceSecret="yourselfDeviceSecret"   --换成自己的设备秘钥

RegionId="cn-shanghai"     --华东2,regionid根据你的服务器选择
topic0="/a19bI5MaWV6/ESP01/DATA"   --这就是我们之前定义的一个topic
myMQTTport=1883    --port
myMQTT=nil      --client
myMQTTtimes='6666'     --随便定义即可
  1. 转换成MQTT的host,clientid,username,password
myMQTThost=ProductKey..".iot-as-mqtt."..RegionId..".aliyuncs.com"   --host
myMQTTClientId=ClientId.."|securemode=3,signmethod=hmacsha1,timestamp="..myMQTTtimes.."|" --设备ID 
myMQTTusername=DeviceName.."&"..ProductKey          --username
  1. hmacsha1 加密得到password
hmacdata="clientId"..ClientId.."deviceName"..DeviceName.."productKey"..ProductKey.."timestamp"..myMQTTtimes  --hmac 校验的数据
myMQTTpassword=crypto.toHex(crypto.hmac("sha1",hmacdata,DeviceSecret))    --hmacdata加上设备的秘钥 ,使用hmacsha1 加密得到password
  1. 创建MQTT客户端
myMQTT=mqtt.Client(myMQTTClientId, 120,myMQTTusername,myMQTTpassword)
  1. MQTT客户端发起连接请求
MQTTconnectFlag=0
tmr.alarm(0,1000,1,function()
    if myMQTT~=nil then
        print("Attempting client connect...")
        myMQTT:connect(myMQTThost, myMQTTport,0,MQTTSuccess,MQTTFailed)
    end
end)
  1. 连接成功,连接失败事件
function MQTTSuccess(client)
    print("MQTT connected")
    client:subscribe(topic0,0, function(conn)     --注册topic0
        print("subscribe success") 
    end) 
    myMQTT=client
    MQTTconnectFlag=1
    tmr.stop(0)        --关闭定时连接
end

---[连接失败]---
function MQTTFailed(client,reson)
    print("Fail reson:"..reson)
    MQTTconnectFlag=0
    tmr.start(0)     --重新启动连接
end
  1. 设备发送和接收数据及下线事件
--[注册 设备接收到订阅的topic 事件]-----
myMQTT:on("message", function(client, topic, data) 
    print(topic ..":") 
    if data ~= nil then
        print(data)
    end
end)

--[topic 定时上传数据]
tmr.alarm(1, 5000, 1, function()    --等待连接上
    if MQTTconnectFlag==1 and myMQTT~=nil then   
        myMQTT:publish(topic0,"this is data upload",0,0,function(client)
                        print("send ok" ) 
        end)
    end
end)
--[设备offline 事件]-----
myMQTT:on("offline", function(client) 
    print ("offline") 
    tmr.start(0)
end)
  1. 全部代码
-----[wifi config]-------------
---------------------------
cfg={}  
cfg.ssid="leon"
cfg.pwd="hyl123456"

-----[Aili MQTT 配置]---------
----------------------------
ProductKey ="a19bI5MaWV6"   --换成自己的
ClientId =wifi.sta.getmac()  -- 自定义clientId,这里使用mac地址
DeviceName ="ESP01"  -- 换成自己的
DeviceSecret="a1wLtTqCn6EzZ"
RegionId="cn-shanghai"     --华东2

myMQTTport=1883    --port
myMQTT=nil      --client

myMQTThost=ProductKey..".iot-as-mqtt."..RegionId..".aliyuncs.com"   --host
myMQTTusername=DeviceName.."&"..ProductKey          --username

topic0="/a19bI5MaWV6/ESP01/DATA"   --device 的topic

----[wifi connect]---------------
wifi.setmode(wifi.STATION)  --设置为STA模式
wifi.sta.config(cfg)        --配置
wifi.sta.connect()          --连接wifi

-----[注册wifi事件]----
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
     print("Connected, IP is "..wifi.sta.getip())
end)

wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
     print("wifi disconnect")
end)


--------[获取时间戳]--------------------
function GetNetTime()
    sntp.sync({"0.nodemcu.pool.ntp.org","1.nodemcu.pool.ntp.org","2.nodemcu.pool.ntp.org","3.nodemcu.pool.ntp.org","www.beijing-time.org"},
         function(sec, usec, server, info)
                 print('sync', sec, usec, server)       
         end,
         function()
            print("get time error")
         end)  
    return 0
end

--------MQTT------------------
myMQTTtimes='6666'
hmacdata="clientId"..ClientId.."deviceName"..DeviceName.."productKey"..ProductKey.."timestamp"..myMQTTtimes  --hmac 校验的数据
myMQTTpassword=crypto.toHex(crypto.hmac("sha1",hmacdata,DeviceSecret))    --hmacdata加上设备的秘钥 ,使用hmacsha1 加密得到password
myMQTTClientId=ClientId.."|securemode=3,signmethod=hmacsha1,timestamp="..myMQTTtimes.."|"   --设备ID    
----[创建MQTT客户端]
myMQTT=mqtt.Client(myMQTTClientId, 120,myMQTTusername,myMQTTpassword) 

   
----[启动定时连接]
MQTTconnectFlag=0
tmr.alarm(0,1000,1,function()
    if myMQTT~=nil then
        print("Attempting client connect...")
        myMQTT:connect(myMQTThost, myMQTTport,0,MQTTSuccess,MQTTFailed)
    end
end)

---[连接成功]---
function MQTTSuccess(client)
    print("MQTT connected")
    client:subscribe(topic0,0, function(conn)     --注册topic0
        print("subscribe success") 
    end) 
    myMQTT=client
    MQTTconnectFlag=1
    tmr.stop(0)        --关闭定时连接
end

---[连接失败]---
function MQTTFailed(client,reson)
    print("Fail reson:"..reson)
    MQTTconnectFlag=0
    tmr.start(0)     --重新启动连接
end

--[设备offline 事件]-----
myMQTT:on("offline", function(client) 
    print ("offline") 
    tmr.start(0)
end)

--[注册 设备接收到订阅的topic 事件]-----
myMQTT:on("message", function(client, topic, data) 
    print(topic ..":") 
    if data ~= nil then
        print(data)
    end
end)

--[topic 定时上传数据]
tmr.alarm(1, 5000, 1, function()    --等待连接上
    if MQTTconnectFlag==1 and myMQTT~=nil then   
        myMQTT:publish(topic0,"this is data upload",0,0,function(client)
                        print("send ok" ) 
        end)
    end
end)

注:

  1. 上述代码中的tmr模块代码在现在及以后生成的固件中已经发送了改变,请大家在nodemcu官方API中查看最新的方法
  2. 由于阿里云用的是自己的ALink协议,如果大家想提交设备属性就必须为ALink JSON的数据格式。nodemcu如果要提交JSON就要在每个引号前加转义字符\而且还要删掉所有空格。下面是我写的例子
myMQTT:publish(topic1,"{\"id\": \"123\",\"version\": \"1.0\",\"params\": {\"LightSwitch\": {\"value\": 1,}},\"method\": \"thing.event.property.post\"}",0,0,function(client)
        end)

本文本参考自leon@suzhou
本人自写代码就不贴出了,大家可以参考本文章进行开发

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容