NodeMCU案例修复
chenyulun opened this issue · 2 comments
chenyulun commented
DEVICEID = "42"
APIKEY = "xxxxf7f36"
INPUTID = "36"
host = host or "www.bigiot.net"
port = port or 8181
LED = 5
gpio.mode(LED,gpio.OUTPUT)
local function run()
local cu = net.createConnection(net.TCP)
cu:on("receive", function(cu, c)
print(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
end
end)
cu:on('disconnection',function(scu)
cu = nil
--停止心跳包发送定时器,5秒后重试
tmr.stop(1)
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, 60000, 1, function()
cu:send(s.."\n")
end)
end
run()
1.新版采用sjson替换cjson;
2. cu:connect后面不能直接cu:send数据,需要监听连接成功后才能通讯
cu:on("connection", function(c, d)
print(d)
ok, s = pcall(sjson.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, 60000, 1, function()
cu:send(s.."\n")
end)
end)
添加以上函数,把后面的cu:send写入到此函数中
bigiot commented
使用sjson可以在文件开头添加
_G.cjson = sjson
进行全局替换。
发送信息放在 on connection 后是更安全些。
谢谢,提出建议。