ljean / modbus-tk

Create Modbus app easily with Python
Other
566 stars 212 forks source link

How to monitor the data frames on the serial port when use modbus_tk? #126

Closed Junkiwang closed 4 years ago

Junkiwang commented 4 years ago

How to get serial data frame at the same time, when query the value of holding register?
For example: master.execute (1, cst.READ_HOLDING_REGISTERS, 1, 2) . I want to monitor all the data frames that sent and received on the serial port and save them to a file.

ljean commented 4 years ago

Hello. You can use the hooks to do this.

modbus.Master.before_send((master, request)) returns modified request or None
modbus.Master.after_recv((master, response)) returns modified response or None

Here is an example showing how to install an hook:

import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_tcp, hooks
import logging

def main():
    """main"""
    def on_after_recv(args):
        response = args[1]
        logger.debug("on_after_recv {0} bytes received".format(len(response)))

    hooks.install_hook("modbus_tcp.TcpMaster.after_recv", on_after_recv)

   # Connect to the slave
   master = modbus_tcp.TcpMaster()
   master.set_timeout(5.0)
   logger.info("connected")

    master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 3)

if __name__ == "__main__":
    main()

I hope it helps

Junkiwang commented 4 years ago

I will have a try, thank you very much!