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和headers
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)
--http協議的post方法,注意參數全用單引號
--url:http://api.heclouds.com/devices/'..DeviceId..'/datapoints?type=3 採用的是設備ID
--headers:api-key:BO6XuBiKw07JRXakBNvn4JKX7MI=\r\n 用的是產品API-KEY,尾部 加\r\n
--回調函數:收到響應或發生錯誤時要調用的回調函數,發生錯誤時date爲-1,也就是<0
--http.post(url, headers, body, callback) [參照網站](https://nodemcu.readthedocs.io/en/master/modules/http/#httppost)
http.post(url, headers, '{"DHT Temperature":'..temp..',"Humidity":'..humi..'}', function(code,date)
if(code < 0) then
print("HTTP request failed")
else
print(code,date)
end
end)
end
tmr.create():alarm(1500,tmr.ALARM_AUTO,h)
end
end
timer:alarm(1000,tmr.ALARM_AUTO,con)
參考文檔:
設備HTTP協議上傳數據到OneNET接口規範