[Python] How do I read values written on a server in pymodbus

Discussão em 'Python' iniciado por Stack, Fevereiro 11, 2025.

  1. Stack

    Stack Membro Participativo

    I have created a server and written values into it using block.setValues. However I cannot read those values from a client. I honestly don't know what I am doing wrong and can't find much on the internet. Even ChatGPT and Copilot can't help me. First I tried to create noise by generating random numbers in a loop and displaying this with plt, but this was even more impossible for me.

    Edit: I tried to set the values before starting the tcp server and this appears to work. So it appears to be stuck on StartTcpServer until I stop the program. Why is that and how can I fix this?

    Edit 2: Copilot says: The start_tcp_server function in pymodbus is a blocking call, which means it will not return control to your program until the server is stopped Changing the values from the client works, so I will have to start doing that. With that change, the reading works fine

    server

    from pymodbus.server import StartTcpServer
    from pymodbus.datastore import ModbusSequentialDataBlock
    from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
    from pymodbus.device import ModbusDeviceIdentification
    import random
    import time


    # Datenblock initialisieren
    block = ModbusSequentialDataBlock(0, [0]*100)
    store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
    context = ModbusServerContext(slaves=store, single=True)

    identity = ModbusDeviceIdentification()
    identity.VendorName = 'FI'
    identity.ProductCode = 'S1'
    identity.VendorUrl = 'http://github.com/riptideio/pymodbus/'
    identity.ProductName = 'Mein Server'
    identity.ModelName = 'S1'
    identity.MajorMinorRevision = '1.0'


    def update_data():
    while True:
    # Zufällige Werte im Register ändern (z.B. für 100 Werte)
    for i in range(0,10):
    block.setValues(i, random.randint(0,255))
    print("Daten aktualisiert...")
    print(block.values)
    time.sleep(5) # Warte 1 Sekunde vor der nächsten Aktualisierung


    if __name__ == '__main__':
    # Starte den Server
    #print("Starte Modbus-Server...")

    # Server starten - der Server läuft hier in einer Blockschleife
    StartTcpServer(context, identity=identity, address=("localhost", 5020))

    # Daten regelmäßig aktualisieren (die Server-Logik läuft hier im Hintergrund)
    while True:
    update_data() # Daten regelmäßig aktualisieren


    client

    from pymodbus.client import ModbusTcpClient
    import time

    # Modbus-Server-Adresse und -Port
    SERVER_IP = 'localhost'
    SERVER_PORT = 5020

    # Erstelle den Modbus-TCP-Client
    client = ModbusTcpClient(SERVER_IP, port=SERVER_PORT)


    def read_data():
    while True:
    list=[]
    for i in range(0,10):
    result = client.read_holding_registers(i)

    if result.isError():
    print("Fehler beim Auslesen der Register.")
    else:
    # Ausgabe der Werte
    list.append(result.registers)

    print("Gelesene Werte:", list)

    # Warte 5 Sekunden bevor die nächsten Daten ausgelesen werden
    time.sleep(5)


    if __name__ == "__main__":
    # Verbindung zum Server aufbauen
    if client.connect():
    print(f"Verbunden mit Modbus-Server {SERVER_IP}:{SERVER_PORT}")
    read_data() # Starte das regelmäßige Auslesen der Daten
    else:
    print(f"Verbindung zum Server {SERVER_IP}:{SERVER_PORT} konnte nicht hergestellt werden.")


    Reading the values right now just gives a list like this: [ [0], [0], ...] I tried between reading coils and holding registers but both do not work. For now I hope to get the reading correct, as I can hopefully build upon that. Thanks for any help

    Continue reading...

Compartilhe esta Página