作者:z494627 | 更新时间:2016-05-20 | 浏览量:3791
代码源自例子代码中的远程开关代码,可以处理多个gpio,并且检测两次心跳无返回会重启设备
--定义变量
DEVICEID = "ID"
APIKEY = "Key"
INPUTID = "255"
host = host or "www.bigiot.net"
port = port or 8181
--存活标记
bLive=0
--初始化GPIO列表
LED=4
LEDList={1,2,3,4,5,6,7,8,9}
for i,v in ipairs(LEDList) do
print("GPIO:"..v)
gpio.mode(tonumber(v),gpio.OUTPUT)
print("GPIO:"..v.."OUTPUT")
end
--连接服务器(TCP连接)
cu = net.createConnection(net.TCP)
cu:connect(port, host)
--接收处理
cu:on("receive", function(cu, c)
print(c)
r = cjson.decode(c)
--如果存货标记为1,置为0
if bLive==1 then
if r.M=="isOL" then
bLive=0
end
end
--如果是say代表命令
if r.M == "say" then
if (string.sub(r.C,1,3)=="LED") then
--找到需要打开的LED号码
pos=string.sub(r.C,4,4)
--获取对应的GPIO号(见nodemcu对照)
LED=(LEDList[tonumber(pos)])
--ON--发送高电平
if (string.sub(r.C,5,6)=="ON") then
gpio.write(LED, gpio.HIGH)
ok, played = pcall(cjson.encode, {M="say",ID=r.ID,C=string.sub(r.C,1,4).." turn on!"})
else
--OFF 发送低电平
gpio.write(LED, gpio.LOW)
ok, played = pcall(cjson.encode, {M="say",ID=r.ID,C=string.sub(r.C,1,4).." turn off!"})
end
--反馈
print(played);
cu:send( played.."\n")
end
end
--收到连接正常,发送checkin
if r.M == "WELCOME TO BIGIOT" then
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" )
bLive=0
--定时心跳,防止掉线
tmr.alarm(1, 40000, 1, function()
--如果标记为1,表示未收到上次的心跳返回,重启
if bLive==1 then
node.restart()
end
ok, ticket = pcall(cjson.encode, {M="isOL",ID="D"..DEVICEID})
print(ticket)
cu:send(ticket.."\n" )
--发送后将标记置为1
bLive=1
end)
end
end)