作者:hzl88688 | 更新時間:2016-03-11 | 瀏覽量:4237
-----------------------------------------------------------------------------
-- Openwrt與貝殼物聯平臺通訊示例
-- http://www.eqytg.org/help/5.html
-- Author: 貝殼物聯
-- Modify: hzl88688
-- Time: 2016/1/10
-----------------------------------------------------------------------------
local socket = require("socket")--引入Luasocket
local json = require("json")--引入Json4lua
local util = require "luci.util"--引入luci,調用cup負載
------------此處需修改-------------
DEVICEID = "xx" --設備ID
APIKEY = "xxxxxxxx" --設備APIKEY
INPUTID = "xx" --數據接口ID
-----------------------------------
host = "www.eqytg.org"
port = 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系統負載
local v = {[INPUTID]=load[1]} --多個接口數據可用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長度,即元素數
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
-------------------------switch-case結構開始(要添加命令只需要復制一段函數改相應變量即可)-------------------
switch={}
switch["name"]=function()
luci.util.exec("xxxxxx") ----------此個XXXXXX填入路由要執行的命令
s = json.encode({M='say',ID=r.ID,C=' 我的名字叫玲玲!'})
assert(c:send( s.."\n" ))
end
switch["age"]=function()
luci.util.exec("xxxxxx") ----------此個XXXXXX填入路由要執行的命令
s = json.encode({M='say',ID=r.ID,C=' 我剛出生喲!'})
assert(c:send( s.."\n" ))
end
switch["play"]=function()
luci.util.exec("xxxxxx") ----------此個XXXXXX填入路由要執行的命令
s = json.encode({M='say',ID=r.ID,C=' 你開啟了音樂播放,音樂現在播放中.......'})
assert(c:send( s.."\n" ))
end
switch["help"]=function()
s = json.encode({M='say',ID=r.ID,C=' 我叫玲玲,我是物聯網Openwrt示例,你可以嘗試輸入name、age或help,也可以查看實時數據,我隨時報告我的負荷情況,還可以遠程啟動音樂播放。'})
assert(c:send( s.."\n" ))
end
--------------switch-case結構結束(要添加命令只需要復制一段函數改相應變量即可--------------
if ( switch[r.C]) then
switch[r.C]()
else
s = json.encode({M='say',ID=r.ID,C='朋友,你輸入的命令我讀不懂!你可以嘗試輸入name、age、play或help 。'})
assert(c:send( s.."\n" ))
end
end
end
recvt, sendt, status = socket.select({c}, nil, 1)
end
else
break
end
end
end