贝壳物联开关解释lua
local function run()
local cu = net.createConnection(net.TCP)--创建一个客户端
cu:on("receive", function(cu, c)
print(c)
isConnect = true --在回调函数中,打印接收到的数据,并将isConnect设置为true。
r = cjson.decode(c) --将接收到的数据解码为JSON格式(cjson.decode函数)。
if r.M == "say" then --如果解码后的JSON对象的M字段为"say",则执行以下操作:
if r.C == "play" then --如果C字段为"play",则将LED引脚设置为高电平,并设置一个定时器(tmr.alarm)在1秒后执行一个函数。
gpio.write(LED, gpio.HIGH)
tmr.alarm(1, 1000, tmr.ALARM_SINGLE, function()
end)
ok, played = pcall(cjson.encode, {M="say",ID=r.ID,C="LED turn on!"})
cu:send( played.."\n" )
end
if r.C == "stop" then --如果C字段为"stop",则将LED引脚设置为低电平。
gpio.write(LED, gpio.LOW)
ok, stoped = pcall(cjson.encode, {M="say",ID=r.ID,C="LED turn off!"})
cu:send( stoped.."\n" )
end
end
end) --当连接断开时,触发一个回调函数(cu:on('disconnection', ...))
cu:on('disconnection',function(scu)
cu = nil
isConnect = false
--停止心跳包发送定时器,5秒后重试
tmr.stop(1)
tmr.alarm(6, 5000, 0, run)
end)
cu:connect(port, host) --调用cu:connect(port, host)连接到指定的主机和端口。
ok, s = pcall(cjson.encode, {M="checkin",ID=DEVICEID,K=APIKEY}) --使用cjson.encode将一个JSON对象编码为字符串,并尝试发送该字符串到连接
if ok then --如果编码成功,则打印编码后的字符串
print(s)
else
print("failed to encode!")
end
if isConnect then --如果连接已建立(isConnect为true),则发送编码后的字符串到连接。
cu:send(s.."\n")
end
tmr.alarm(1, 60000, 1, function() --设置一个定时器(tmr.alarm(1, 60000, 1, ...)),每隔60秒发送一次编码后的字符串到连接
if isConnect then
cu:send(s.."\n")
end
end)
end
run() --最后调用run()函数开始执行脚本。