gpio.mode(2,gpio.OUTPUT)
wifi.setmode(wifi.STATION)
cfg = {}
cfg.ssid = "kyn"
cfg.pwd = "20160118"
wifi.sta.config(cfg)
wifi.sta.connect()
DeviceId = "587667371"
ProductId = "325428"
AuthoInfo = "test"
host = "183.230.40.39"
port = 6002
url = 'http://api.heclouds.com/devices/'..DeviceId..'/datapoints?type=3'
headers = 'api-key:BO6XuBiKw07JRXakBNvn4JKX7MI=\r\n'
dht_pin = 5
timer = tmr.create()
function con()
if wifi.sta.getip() == nil then
print("coneting........")
else
timer:stop()
print("success!~")
gpio.write(2,gpio.HIGH)
print(wifi.sta.getip())
client_hum = mqtt.Client(DeviceId,120,ProductId,AuthoInfo)
client_hum:connect(host,port,0,function(client)
print("connect success!")
end)
function h()
status,temp,humi,temp_dec, humi_dec = dht.read11(dht_pin)
print("DHT Temperature:"..temp..";".."Humidity:"..humi)
--代码如下:
weather表用来存储数据流Temperature和Humidity
weather = {}
weather.Temperature = temp
weather.Humidity = humi
--使用pacall方法将weather表中的数据转换为sjson格式,返回状态state和weather的值weather_message
state,weather_message = pcall(sjson.encode,weather)
--内容主体(参照下边的图来理解):string.char()方法是将字符转化为一个对应的ascii码
payload = string.char(3,0,string.len(weather_message))..weather_message
--通过官网查询mqtt的推送方法 mqtt:publish(topic, payload, qos, retain[, function(client)])topic:订阅Field名称,payload:数据主体,qos:QoS等级(百度下),retain:保留标志(百度下),后边位回调函数
client_hum:publish("$dp", payload, 0, 0, function(client)
print("upload success!~")
end)
end
tmr.create():alarm(1500,tmr.ALARM_AUTO,h)
end
end
timer:alarm(1000,tmr.ALARM_AUTO,con)
关于几点说明:
1、pcall()方法:lua中pcall函数提供了一种安全的环境来运行函数,同时会捕获函数运行时的异常。pcall函数第一个返回值是函数的运行状态(true,false),第二个返回值是pcall中函数的返回值。参见博文
2、sjson格式:
3、payload(内容主体):
转换的sjson有四部分组成的:
Byte1(3)+ Byte2(0,也就是最低位)+ Byte3(string.len(weather_message),也就是最高位)+ 内容主体(weather_message)
payload = string.char(3,0,string.len(weather_message))…weather_message
4、mqtt推送方法:
topic:参见MQTT协议
payload:内容主体(参见上边内容)
function(client):回调函数