Modbus realtime reading

36 views Asked by At

In my current Python code, I'm trying to read bit values ​​inside discrete_inputs in real time. When I write I have no problems, in fact in the other program I notice that the bits go up correctly. The problem I have is in reading because, when I go to modify an "output" in my external program, the python program always continues to read 0. I can't understand why, nor what I'm doing wrong. Here is my code:

# Import necessary modules
from pymodbus.datastore import ModbusSequentialDataBlock, ModbusSlaveContext, ModbusServerContext
from pymodbus.server.async_io import StartTcpServer
import time
import threading

# Define a ModbusSequentialDataBlock for discrete inputs
discrete_inputs = ModbusSequentialDataBlock(0, [0] * 100)

# Function to continuously check discrete inputs
def check_discrete_inputs():
    while True:
        # Create a new instance of ModbusSequentialDataBlock at each iteration
        discrete_inputs = ModbusSequentialDataBlock(0, [0] * 100)

        # Read the current values of input registers
        values = discrete_inputs.getValues(1, 10)
        beforeLast_value = values[-2]  # Get the second last value from the list
        lastValue = values[-1]

        # Check if the second last bit is 1
        if beforeLast_value & 0b000000001:
            # Read the current values of input registers
            current_values = discrete_inputs.getValues(1, 10)

            # Check if the tenth bit has been modified externally
            if beforeLast_value & 0b000000001 & lastValue != 1:
                # Read the current values of input registers
                current_values = discrete_inputs.getValues(1, 10)

                current_values[9] = 1  # Set the tenth bit to 1

                # Set the new values
                discrete_inputs.setValues(1, current_values)
                
        else:
            if lastValue != 0:
                # Read the current values of input registers
                current_values = discrete_inputs.getValues(1, 10)
                current_values[9] = 0
                # Set the new values
                discrete_inputs.setValues(1, current_values)
                print("Reset", discrete_inputs.getValues(1, 10))

        time.sleep(3)

# Define the Modbus slave context
slave_context = ModbusSlaveContext(
    di=discrete_inputs
)

# Create a thread for the check_discrete_inputs function
thread = threading.Thread(target=check_discrete_inputs)
thread.daemon = True
thread.start()

# Define the Modbus server context
server_context = ModbusServerContext(slaves=slave_context, single=True)

# Start the Modbus TCP server
StartTcpServer(context=server_context, address=("127.0.0.1", 502))

I have tried several times in output to check the change in reading status at various points, but nothing changes. I expect that within my code, certain bits will change in real time when I change them from my external program

0

There are 0 answers