案例五 温湿度+LED
--init.lua
print("set up wifi mode")
wifi.setmode(wifi.STATION)
wifi.sta.config("SSID","PASSWORD")
--here SSID and PassWord should be modified according your wireless router
wifi.sta.connect()
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip()== nil then
print("IP unavaiable, Waiting...")
else
tmr.stop(1)
print("IP:"..wifi.sta.getip())
dofile("runtime.lua")
end
end)
dofile("config.lua")
dofile("Dht.lua")
dofile("SendData.lua")
bLive=0
gpio.mode(config.LEDPin,gpio.OUTPUT)
cu = net.createConnection(net.TCP)
cu:connect(config.port, config.host)
cu:on("receive", function(cu, c)
print(c)
r = cjson.decode(c)
--如果存活标记为1,置为0
if r.M=="isOL" then
bLive=0
end
tmr.alarm(1, 10000, 1, function()
print("start send data")
--读取湿度
Humi,Temp=ReadDHT(config.DHTPin)
--发送数据
sendToBigiot(cu,Humi,Temp)
--checkin和心跳
dofile("checkIn.lua")
--执行命令
dofile("sayCommand.lua")
end)
end)
--modify DEVICEID1 INPUTID APIKEY DEVICEID2
config={
host = host or "www.bigiot.net",
port = port or 8181,
DEVICEID = "",
UID="",
TempID="",
HumiID="",
APIKEY = "",
DHTPin= 1,
LEDPin= 4
}
function ReadDHT(pin)
dhstatus, temp, humi, temp_dec, humi_dec = dht.read11(pin)
print(dhstatus)
if dhstatus == dht.OK then
print(string.format("DHT Temperature:%d.%03d;Humidity:%d.%03d\r\n",
math.floor(temp),
temp_dec,
math.floor(humi),
humi_dec
))
--转换实际温度
realTemp=math.floor(temp)
--转换实际湿度
realhumi=math.floor(humi)
return realhumi,realTemp
elseif status == dht.ERROR_CHECKSUM then
print( "DHT Checksum error." )
elseif status == dht.ERROR_TIMEOUT then
print( "DHT timed out." )
end
end
function sendToBigiot(cu,humi,temp)
print(humi)
print(temp)
if humi==nil then
humi=0
end
if temp==nil then
temp=0
end
--上报湿度
local v = {[config.TempID]=string.format("%.2f", math.floor(temp)),[config.HumiID]=string.format("%.3f",math.floor(humi))}
ok3, s3 = pcall(cjson.encode, {M="update",ID=config.DEVICEID,V=v})
print("send data:"..s3)
cu:send( s3.."\n")
end
--收到连接正常,发送checkin
if r.M == "WELCOME TO BIGIOT" then
ok, s = pcall(cjson.encode, {M="checkin",ID=config.DEVICEID,K=config.APIKEY})
if ok then
print(s)
else
print("failed to encode!")
end
cu:send( s.."\n" )
bLive=0
--定时心跳,防止掉线
tmr.alarm(2, 40000, 1, function()
--如果标记为1,表示未收到上次的心跳返回,重启
if bLive==3 then
node.restart()
end
ok, ticket = pcall(cjson.encode, {M="isOL",ID="D"..config.DEVICEID})
print(ticket)
cu:send(ticket.."\n" )
--发送后将标记置为1
bLive=bLive+1
end)
end
--如果是say代表命令
if r.M == "say" then
local commander=r.C
if commander == "play" then
gpio.write(config.LED, gpio.HIGH)
ok, played = pcall(cjson.encode, {M="say",ID=config.UID,C="LED turn on!"})
cu:send( played.."\n" )
elseif commander == "stop" then
gpio.write(config.LED, gpio.LOW)
ok, stoped = pcall(cjson.encode, {M="say",ID=config.UID,C="LED turn off!"})
cu:send( stoped.."\n" )
end
end