DEVICEID = "939"
APIKEY = "0XXXXXXXe"
INPUTID = "875"
host = host or "www.bigiot.net"
port = port or 8181
uOnline = 0
LED = 8
gpio.mode(LED,gpio.OUTPUT)
local function run()
local cu = net.createConnection(net.TCP)
cu:on("receive", function(cu, c)
print("R:"..c)
r = cjson.decode(c)
if r.M == "say" then
if r.C == "play" then
gpio.write(LED, gpio.HIGH)
ok, played = pcall(cjson.encode, {M="say",ID=r.ID,C="LED turn on!"})
cu:send( played.."\n" )
end
if r.C == "stop" then
gpio.write(LED, gpio.LOW)
ok, stoped = pcall(cjson.encode, {M="say",ID=r.ID,C="LED turn off!"})
cu:send( stoped.."\n" )
end
firstidx, lastidx, key, value = string.find(r.C, "(%a+)%s+(%d+)")
if key == "open" then
print(key,value)
time=tonumber(value)
gpio.write(LED,gpio.HIGH)
tmr.alarm(2,time*1000,0,function()
gpio.write(LED,gpio.LOW)
end)
ok, stoped = pcall(cjson.encode, {M="say",ID=r.ID,C="LED turn off!"})
cu:send("open "..value.."\n" )
end
end
if r.M == "checkinok" then
pwm.close(signLed)
pwm.setup(signLed,1,1000)
pwm.start(signLed)
uOnline=1
end
end)
cu:on('disconnection',function(scu)
cu = nil
--停止心跳包发送定时器,5秒后重试
tmr.stop(1)
pwm.close(signLed)
pwm.setup(signLed,1,512)
pwm.start(signLed)
uOnline=0
tmr.alarm(6, 5000, 0, run)
end)
cu:connect(port, host)
ok, s = pcall(cjson.encode, {M="checkin",ID=DEVICEID,K=APIKEY})
if ok then
print(s)
else
print("failed to encode!")
end
cu:send(s.."\n")
tmr.alarm(1, 30000, 1, function()
temp=adc.read(0)
str="{\"M\":\"update\",\"ID\":\""..DEVICEID.."\",\"V\":{\""..INPUTID.."\":\""..temp.."\"},\"K\":\""..APIKEY.."\"}\n"
if uOnline==1 then
cu:send(str.."\n")
print(str)
else
cu:send(s.."\n")
-- print(s)
end
end)
end
run()