ljean / modbus-tk

Create Modbus app easily with Python
Other
557 stars 211 forks source link

Raising ModbusException in modbus.Slave.handle_request doesn't work #166

Open ErikTempelaarVO opened 2 years ago

ErikTempelaarVO commented 2 years ago

To test the robustness of our modbus client we'd like the server to throw some errors on requests.

Attempting to do so via hook "modbus.Slave.handle_request" doesn't work properly, because in the except-clause the function code is expected to be available, but it isn't.

https://github.com/ljean/modbus-tk/blob/c168f7158abd16d487046eaecb2aa49bf863d9dd/modbus_tk/modbus.py#L713-L718

https://github.com/ljean/modbus-tk/blob/c168f7158abd16d487046eaecb2aa49bf863d9dd/modbus_tk/modbus.py#L745-L749

Fix seems trivial, by reordering the code and fetching the function code before calling said hooks.

Hooking more specifically also works fine:

hooks.install_hook("modbus.Slave.handle_read_input_registers_request", self.on_modbus_slave_handle_request) hooks.install_hook("modbus.Slave.handle_read_holding_registers_request", self.on_modbus_slave_handle_request)

Does it make sense to request this to be changed? Could open a PR if that's helpful.