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
  1. IoTBoX会在初始化时调用init函数,完成推送平台的初始化
  2. 初始化后会调用 connect 函数,连接云平台,如果连接成功返回0失败返回非0
  3. IoTBoX内部会循环调用 check_connect函数,如果返回非0,则会调用connect函数进行重新连接
  4. IoTBoX会在每个推送周期执行 format函数,对采集到的数据格式话,返回0
  5. 格式化之后会调用push函数将数据推送到云平台,推送成功返回0,推送失败返回非0

8.5.3 示例MQTT平台连接

function on_connect()
    -- 处理连接后
    box.log("info","mqtt服务器已连接")
    g.mqtt:Subscribe(g.control_topic,0)
    init={};
    init["device_id"] = publisher.gateway_id;
    init["device_type"] = "gateway";
    init["online"] = true;
    g.mqtt:PushMessage(cjson.encode(init), g.data_topic,0,0);
end

function on_disconnect()
    -- 处理断开连接后
    box.log("warn","mqtt服务器离线")
end

function on_message(topic,message)
    -- 处理接收后的数据
    box.log("debug",topic,message)
end

function init()
    -- 初始化推送
    g.control_topic="control_topic"
    g.data_topic="data_topic"
    g.mqtt=MqttClient()
    g.mqtt.address=config.address;
    if config.username ~=nil and #config.username~=0 then
        g.mqtt.username=config.username
    end
    if config.password ~=nil and #config.password~=0 then
        g.mqtt.password=config.password
    end
    g.mqtt.client_id=box.fingerprint;
    g.mqtt.on_connect=on_connect
    g.mqtt.on_disconnect=on_disconnect
    g.mqtt.on_message=on_message
    will={}
    will["device_id"] = publisher.gateway_id
    will["device_type"] = "gateway";
    will["online"] = false;
    g.mqtt.will_msg=cjson.encode(will)
    g.mqtt.will_topic=g.data_topic
    return 0
end

function push()
    box.log("debug","aaaaa  push")
    return g.mqtt:PushMessage(cjson.encode(publisher:GetMessage()),g.data_topic,0,0)
end


function format()
    box.log("debug","aaaaa  format")
    local origin_messages=publisher:GetOriginMessage()
    local result_messages={}
    for i, origin_message in ipairs(origin_messages) do
        local one_message={}
        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={}
        local index=1
        for name, value in pairs(origin_message.values) do
            value.name = name;
            value.id = nil;
            one_message.values[index]=value
            index=index+1
        end
        result_messages[i]=one_message
    end
    publisher:SetMessage(result_messages)
    return 0
end
--- 2
function connect()
    return g.mqtt:Connect()
end
function check_connect()
    local r= g.mqtt:CheckConnect()
    return r
end