8.5 推送平台
IoTBoX™支持自定义推送协议到云平台
8.5.1 内置变量
g
: 全局table,可以在任意函数内调用与修改publisher
: 当前推送平台, 类型为Publisher
8.5.2 基础架构
最简代码如下
--@return number 初始化返回 固定为0
---@description 第一次启动程序时调用
---@usage 用于初始化推送所需的内容,包括推送协议,协议配置等
function Init()
return 0
end
---@return number 推送状态 0为OK,非零为推送失败
---@description 内部循环调用,用于推送数据
---@usage 将Format后的数据推送出去
function Push()
return 0
end
---@return number 格式化返回 固定返回0
---@description 内部循环调用,用于数据格式化
---@usage 系统在推送数据之前先调用此函数用于数据格式化
function Format()
return 0
end
---@return number 连接状态 0表示连接成功,其他值表示未连接
---@description 系统会在连接失败时调用连接函数
---@usage 此函数会被自动调用
function Connect()
return 0
end
---@return number 连接状态 0表示连接成功,其他值表示未连接
---@description 内部循环调用,检查MQTT连接状态
---@usage 在需要确保MQTT连接的场景中反复调用此函数以监测连接状态
function CheckConnect()
return 0
end
- IoTBoX™会在初始化时调用
Init
函数,完成推送平台的初始化 - 初始化后会调用
Connect
函数,连接云平台,如果连接成功返回0失败返回非0 - IoTBoX™内部会循环调用
CheckConnect
函数,如果返回非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 CheckConnect()
local r= g.mqtt:CheckConnect()
return r
end