巧用事件让设备支持多传感器
2021-01-25 本文已影响0人
Lupino
我们的采集盒发展到现阶段,需要支持多个传感器。
在硬件层面,只要电压一样,地址唯一,485频率一样,或不一样就可以接在一起。
呈现出 1 对 多的这种模式。
但固件上设计就有点麻烦了。
后来用了一个类似事件的模式,解决了这个问题:
local readEvents = {}
local sendEvents = {}
function onReadEvent(cb)
table.insert(readEvents, cb)
end
function runReadEvents()
local idx = nil
for idx=1, #readEvents, 1 do
readEvents[idx]()
end
end
function onSendEvent(cb)
table.insert(sendEvents, cb)
end
function runSendEvents()
local data = {}
local idx = nil
local result, ret, err;
for idx=1, #sendEvents, 1 do
result, ret, err = sendEvents[idx]()
if result then
data = merge(data, ret)
else
log.error('runSendEvents error:', err)
end
end
return data
end
如上代码,定义了两种不同的事件 readEvents 和 sendEvents,
通过 onReadEvent 和 onSendEvent 来注册事件,其实是把相关的回调函数放到 readEvents 和 sendEvents,
然后我们通过 runReadEvents 和 runSendEvents 来执行,
最后合并执行结果,最后我们的对设备支持就通过这种模式,完全支持了。