8.5 推送平台
IoTBoX支持自定义推送到云平台
8.5.1 内置变量
g
: 全局table,可以在任意函数内调用与修改publisher
: 当前推送平台, 类型为Publisher
8.5.2 基础架构
最简代码如下
function init()
return 0
end
function push()
return 0
end
function format()
return 0
end
function connect()
return 0
end
function check_connect()
return 0
end
- IoTBoX会在初始化时调用
init
函数,完成推送平台的初始化 - 初始化后会调用
connect
函数,连接云平台,如果连接成功返回0失败返回非0 - IoTBoX内部会循环调用
check_connect
函数,如果返回非0,则会调用connect函数进行重新连接 - IoTBoX会在每个推送周期执行
format
函数,对采集到的数据格式话,返回0 - 格式化之后会调用
push
函数将数据推送到云平台,推送成功返回0,推送失败返回非0
8.5.3 示例MQTT平台连接
function on_connect()
-- 处理连接后
.log("info","mqtt服务器已连接")
box.mqtt:Subscribe(g.control_topic,0)
g={};
init["device_id"] = publisher.gateway_id;
init["device_type"] = "gateway";
init["online"] = true;
init.mqtt:PushMessage(cjson.encode(init), g.data_topic,0,0);
gend
function on_disconnect()
-- 处理断开连接后
.log("warn","mqtt服务器离线")
boxend
function on_message(topic,message)
-- 处理接收后的数据
.log("debug",topic,message)
boxend
function init()
-- 初始化推送
.control_topic="control_topic"
g.data_topic="data_topic"
g.mqtt=MqttClient()
g.mqtt.address=config.address;
gif config.username ~=nil and #config.username~=0 then
.mqtt.username=config.username
gend
if config.password ~=nil and #config.password~=0 then
.mqtt.password=config.password
gend
.mqtt.client_id=box.fingerprint;
g.mqtt.on_connect=on_connect
g.mqtt.on_disconnect=on_disconnect
g.mqtt.on_message=on_message
g={}
will["device_id"] = publisher.gateway_id
will["device_type"] = "gateway";
will["online"] = false;
will.mqtt.will_msg=cjson.encode(will)
g.mqtt.will_topic=g.data_topic
greturn 0
end
function push()
.log("debug","aaaaa push")
boxreturn g.mqtt:PushMessage(cjson.encode(publisher:GetMessage()),g.data_topic,0,0)
end
function format()
.log("debug","aaaaa format")
boxlocal origin_messages=publisher:GetOriginMessage()
local result_messages={}
for i, origin_message in ipairs(origin_messages) do
local one_message={}
.device_id=origin_message.device_id
one_message.device_name=origin_message.device_name
one_message.device_state=origin_message.device_state
one_message.device_type=origin_message.device_type
one_message.ts=origin_message.ts
one_message.values={}
one_messagelocal index=1
for name, value in pairs(origin_message.values) do
.name = name;
value.id = nil;
value.values[index]=value
one_message=index+1
indexend
[i]=one_message
result_messagesend
:SetMessage(result_messages)
publisherreturn 0
end
--- 2
function connect()
return g.mqtt:Connect()
end
function check_connect()
local r= g.mqtt:CheckConnect()
return r
end