sourceperl / pyModbusTCP

A simple Modbus/TCP library for Python
MIT License
308 stars 106 forks source link

Most Recent RX Timestamp? #85

Open cousmaso opened 4 months ago

cousmaso commented 4 months ago

Is there a way to receive a timestamp of my most recently received data? I looked through the source code a little, but as a pretty amateur programmer I might have missed it. I often use this library to talk to industrial equipment to feed DAQ devices data while they're measuring analog and digital sensors. As DAQs timesync everything, it would be incredibly useful if this client provided a property containing the timestamp of the most recent RX data.

sourceperl commented 4 months ago

Hello, I may have misunderstood your request but the timestamp at the source is not managed by the Modbus protocol. At least, in the basic standard functions.

However, you can do it in your code:

import time
from dataclasses import dataclass
from pyModbusTCP.client import ModbusClient

# a simple data container
@dataclass
class MyData:
    timestamp: float
    data: list

# init modbus client
c = ModbusClient(host='localhost')

# polling loop
while True:
    # modbus i/o
    ret_read = c.read_holding_registers(reg_addr=0, reg_nb=4)

    if ret_read is not None:
        my_data = MyData(timestamp=time.time(), data=ret_read)
        print(my_data)

    # wait 5s before next polling
    time.sleep(5)