– 设置Lua模块路径
package.cpath = “./?.so”
package.path = “./?.lua”

– 导入依赖模块
cjson = require “cjson”
config = require “config”
require “modbus”

– 控制动作函数
function act_control(m, json)
for k, v in pairs(json) do
if k ~= “Act” then
modbus.write(modbusObj, k, v)
end
end
end

– MQTT数据处理函数
function mqttdata_handle(m, topic, data)
local json = cjson.decode(data)
if json.Act == “Control” then
act_control(m, json)
end
end

– MQTT系统事件处理函数
function mqttsys_handle(m, code)
if code == 0 then
modbus.stop(modbusObj)
elseif code == 1 then
modbus.run(modbusObj)
end
end

– Modbus事件处理函数
function modbusevent_handle(session, code, style_L, val_L, style_E, val_E, z)
if code == 15 then
local json = cjson.encode(mbbuf[session])
mqtt.publish(mqtt3Obj, mbstr[session], “r”, json)
mbbuf[session] = {}
elseif code > 10 then
mbbuf[session][style_L] = val_L
mbbuf[session][style_E] = val_E
else
local json = cjson.encode({[style_L] = val_L, [style_E] = val_E, [“Z”] = z})
mqtt.publish(mqtt3Obj, mbstr[session], “r”, json)
end
end

– 加载Modbus采集节点
function modbus_load_collectnodes(session, nodes)
for k, v in pairs(nodes) do
modbus.add_collectnode(session, v.ID, v.reg, v.addr, v.cnt, v.delay)
end
end

– 加载Modbus变量节点
function modbus_load_varnodes(session, nodes)
for k, v in pairs(nodes) do
modbus.add_varnode(session, v.ID, v.reg, v.addr, v.dtype, v.dBit, v.format, v.len, v.pMode, v.dStyle, v.dOffset, v.dExt)
end
end

– 初始化函数
function init()
mqtt3Obj = mqtt.new()
user.setluaver(config.AprusX.luaver)
user.setdevinfo(config.AprusX.devinfo)
user.ipconfig(config.ApronX.ipmode, config.ApronX.inet_addr, config.ApronX.netmask)
end

– 启动函数
function start()
init()

-- Modbus RTU配置
MBCfg = config.Modbus

-- 初始化Modbus对象
modbusObj = nil
mbbuf = { modbusObj }
mbstr = { modbusObj }

-- 配置Modbus对象
modbusObj = modbus.new(MBCfg.device.type)
mbbuf[modbusObj] = {}
mbstr[modbusObj] = "modbusObj"
modbus.config(modbusObj, MBCfg.device.rate, MBCfg.device.databit, MBCfg.device.stopbit, MBCfg.device.parity)
modbus_load_collectnodes(modbusObj, MBCfg.node.collect)
modbus_load_varnodes(modbusObj, MBCfg.node.variable)

-- 运行MQTT客户端
mqtt.run(mqtt3Obj)

-- 主循环
while true do
    local msg = user.waitmsg()
    if msg.from == "mqtt-sys" then
        mqttsys_handle(msg.session, msg.code)
    elseif msg.from == "mqtt-msg" then
        mqttdata_handle(msg.session, msg.topic, msg.payload)
    elseif msg.from == "modbus" then
        modbusevent_handle(msg.session, msg.code, msg.style_L, msg.val_L, msg.style_E, msg.val_E, msg.z)
    end
end

end

start()

文档更新时间: 2024-10-25 14:48   作者:技术支持