10. Script Cliente gráfica

El siguiente script realiza una lectura cada 2 segundos del holding reg 0 y lo grafica. Debemos cambiar el host por la dirección del host que vamos a consultar.



_____________________________________________________________________________________________________


import datetime as dt
import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from pyModbusTCP.client import ModbusClient

# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = []
ys = []

# This function is called periodically from FuncAnimation
def animate(i, xs, ys):

    # Read temperature (Celsius) from TMP102
    temp_c=regs_list=client.read_holding_registers(0,1)
    print("registro leido:")
    print(temp_c)
    #round(5, 2)
    
    # Add x and y to lists
    xs.append(dt.datetime.now().strftime('%H:%M:%S'))
    ys.append(temp_c)

    # Limit x and y lists to 20 items
    xs = xs[-20:]
    ys = ys[-20:]

    # Draw x and y lists
    ax.clear()
    ax.plot(xs, ys)

    # Format plot
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.title('Lectura de Servidor Modbus TCP ')
    plt.ylabel('Temperature (deg C)')

# Set up plot to call animate() function periodically
ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=2000)
client = ModbusClient(host='localhost', port=502, auto_open=True, auto_close=True)
client.open()
plt.show()