作者:niwusong | 更新時(shí)間:2017-05-19 | 瀏覽量:2279
-----------------------------------------------------------------------------
-- Openwrt與貝殼物聯(lián)平臺(tái)通訊示例
-- http://m.placeboworld.cn/help/5.html
-- Author: 貝殼物聯(lián)
-- Time: 2016/1/10
-----------------------------------------------------------------------------
local socket = require("socket")--引入Luasocket
local json = require("json")--引入Json4lua
local util = require "luci.util"--引入luci,調(diào)用cup負(fù)載
------------此處需修改-------------
DEVICEID = "2" --設(shè)備ID
APIKEY = "2353d24ce" --設(shè)備APIKEY
INPUTID = "2" --數(shù)據(jù)接口ID
-----------------------------------
host = host or "m.placeboworld.cn"
port = port or 8181
lastTime = 0
lastUpdateTime = 0
if arg then
host = arg[1] or host
port = arg[2] or port
end
print("Attempting connection to host '" ..host.. "' and port " ..port.. "...")
c = assert(socket.connect(host, port))
c:settimeout(0)
print("Connected! Please type stuff (empty line to stop):")
while true do
if ((os.time() - lastTime) > 40) then
--print( os.time() )
s = json.encode({M='checkin',ID=DEVICEID,K=APIKEY})
assert(c:send( s.."\n" ))
lastTime=os.time()
end
if ((os.time() - lastUpdateTime) > 10) then
local sysinfo = luci.util.ubus("system", "info") or { }
local load = sysinfo.load or { 0, 0, 0 } --獲取Openwrt系統(tǒng)負(fù)載
local v = {[INPUTID]=load[1]} --多個(gè)接口數(shù)據(jù)可用v = {[INPUTID1]=load[1],[INPUTID2]=load[2]}
local update = json.encode({['M']='update', ['ID']=DEVICEID, ['V']=v})
assert(c:send( update.."\n" ))
lastUpdateTime = os.time()
end
recvt, sendt, status = socket.select({c}, nil, 1)
--#獲取table長(zhǎng)度,即元素?cái)?shù)
while #recvt > 0 do
local response, receive_status = c:receive()
if receive_status ~= "closed" then
if response then
print(response)
r = json.decode(response)
--table.foreach(r, print)
if r.C then
if r.M == "say" then
if r.C == "name"
then
s = json.encode({M='say',ID=r.ID,C='My name is Xiaobei!'})
assert(c:send( s.."\n" ))
else if r.C == "age"
then
s = json.encode({M='say',ID=r.ID,C='I was born in Jan 1, 2016!'})
assert(c:send( s.."\n" ))
else if r.C == "play"
then
s = json.encode({M='say',ID=r.ID,C='沒(méi)什么好玩的-_-!....'})
assert(c:send( s.."\n" ))
else if r.C == "help"
then
s = json.encode({M='say',ID=r.ID,C='我叫小貝,我是貝殼物聯(lián)的第一個(gè)Openwrt示例,你可以嘗試輸入name、age或help,也可以查看實(shí)時(shí)數(shù)據(jù),我隨時(shí)報(bào)告我的負(fù)荷情況。'})
assert(c:send( s.."\n" ))
else
s = json.encode({M='say',ID=r.ID,C='未知命令,你可以嘗試輸入name、age、play或help'})
assert(c:send( s.."\n" ))
end
end
end
end
end
end
recvt, sendt, status = socket.select({c}, nil, 1)
end
else
break
end
end
end