由于这个是我去年暑假做的东西但是今天看的时候发现很多地方出现了变化。所以如果有哪些步骤出了问题还烦请告知一声。
了解物联网平台的设备接入流程和协议。Mqtt协议:首先,wifi模块需要接入wifi,以wifi作为跳板通过云服务端分配的暗号与云服务端建立连接。建立联系后剩下的就是订阅和发布的问题,在阿里云中可以设置topic,通过topic来确定设备与服务端是进行订阅还是发布功能。
--//设置WiFi的id和密码
q={}
q.ssid="**************"
q.pwd="***************"
--/**************输入阿里云生成的三元数与地区号********/
ProductKey ="***********"
ClientId =wifi.sta.getmac()
DeviceName ="dht11001"
DeviceSecret="*******************"
RegionId="cn-shanghai" --华东2(固定)
设置port口和初始化mqtt
myMQTTport=1883 --port
myMQTT=nil --client
阿里云默认配置
myMQTThost=ProductKey..".iot-as-mqtt."..RegionId..".aliyuncs.com" --host
myMQTTusername=DeviceName.."&"..ProductKey --username
--//topic0用作订阅topic1用作发布
topic0="/a1s1oS3wvy6/dht11001/user/get"
topic1="/sys/a1s1oS3wvy6/dht11001/thing/event/property/post"
设置wifi为连接固定wifi的AP模式
wifi.setmode(wifi.STATION)
wifi.sta.config(q)
wifi.sta.connect()
连接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
创建myMQTT进行三元数转换
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.create():alarm(1000,0,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.create():stop(0) --关闭定时连接
end
function MQTTFailed(client,reson)
print("Fail reson:"..reson)
MQTTconnectFlag=0
tmr.create():start(0)
end
--/************掉线重连*********/
myMQTT:on("offline", function(client)
print ("offline")
tmr.create():start(0)
end)
接收数据并打印
myMQTT:on("message", function(client, topic, data)
print(topic ..":")
if data ~= nil then
print(data)
end
end)
定时温度测量
tmr.create():alarm(10000000, 1, function()
if MQTTconnectFlag==1 and myMQTT~=nil then
status, temp, humi, temp_dec, humi_dec = dht.read11(p)
q=string.format([[
{
"id": "123",
"version": "1.0",
"params": {
"CurrentTemperature": {
"value": %d.%d
},
"CurrentHumidity": {
"value": %d.%d
}
},
"method": "thing.event.property.post"
}]],temp,temp_dec,humi,humi_dec)
myMQTT:publish(topic1,q,0,0,function(client)
print(q)
end)
end
end)