21.01.2025, 14:03
Hello,
I am currently working with the LuaModbus library to communicate with Modbus RTU devices and have successfully implemented basic register reading functionality. Below is a simplified example of my current approach.
However, I would like to extend this functionality to periodically monitor multiple interfaces in parallel without relying on the Copas library, as it does not meet my performance requirements.
Specifically, I am interested in achieving behavior similar to MQTT, where I can use "socket" to monitor multiple file descriptors and trigger events when data is available. Is it possible to retrieve a file descriptor for a Modbus RTU connection (similar to the MQTT socket), which I can integrate into an event loop?
This would allow me to efficiently manage multiple Modbus interfaces concurrently within the same script.
Any guidance or advice on how to implement this functionality with LuaModbus would be greatly appreciated.
I am currently working with the LuaModbus library to communicate with Modbus RTU devices and have successfully implemented basic register reading functionality. Below is a simplified example of my current approach.
Code:
require('luamodbus')
-- Modbus RTU communication parameters
local port_rtu = "/dev/RS485-2"
local baud_rate = 9600
local parity = 'N'
local data_bits = 8
local stop_bit = 1
local slave_id = 78
local register_address = 19
local timeout = 5
-- Establish Modbus RTU connection
local mb = luamodbus.rtu()
mb:open(port_rtu, baud_rate, parity, data_bits, stop_bit)
mb:connect()
mb:setslave(slave_id)
mb:setresponsetimeout(timeout)
-- Read the register
local value, err = mb:readregisters(register_address, 1)
-- Display the result
if err then
print("Read error: " .. err)
else
print("Value read at register " .. register_address .. ": " .. value[1])
end
-- Close the connection
mb:close()
Specifically, I am interested in achieving behavior similar to MQTT, where I can use "socket" to monitor multiple file descriptors and trigger events when data is available. Is it possible to retrieve a file descriptor for a Modbus RTU connection (similar to the MQTT socket), which I can integrate into an event loop?
Code:
--[[...]] -- Client initialization
while true do
connect_mqtt()
local timerfd = socket.fdmaskset(timer:getfd(), 'r')
local mclientfdset = mclient and socket.fdmaskset(mclient:getfd(), mclient:want_write() and 'rw' or 'r')
local res, timerstat, mclientstat = socket.selectfds(10, timerfd, mclientfdset)
if res then
if timerstat then
handle_timer_event()
end
if mclient and mclientstat then
if socket.fdmaskread(mclientstat) then
mclient:loop_read()
end
if socket.fdmaskwrite(mclientstat) then
mclient:loop_write()
end
mclient:loop_misc()
end
end
os.sleep(1)
end
Any guidance or advice on how to implement this functionality with LuaModbus would be greatly appreciated.