Skip to content

V1

ModbusTCPBlockV1 ΒΆ

Bases: WorkflowBlock

A Modbus TCP communication block using pymodbus.

Supports: - 'read': Reads specified registers. - 'write': Writes values to specified registers. - 'read_and_write': Reads and writes in one execution.

On failures, errors are printed and marked as "ReadFailure" or "WriteFailure".

Source code in inference/enterprise/workflows/enterprise_blocks/sinks/PLC_modbus/v1.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
class ModbusTCPBlockV1(WorkflowBlock):
    """A Modbus TCP communication block using pymodbus.

    Supports:
    - 'read': Reads specified registers.
    - 'write': Writes values to specified registers.
    - 'read_and_write': Reads and writes in one execution.

    On failures, errors are printed and marked as "ReadFailure" or "WriteFailure".
    """

    def __init__(self):
        self.client: Optional[ModbusClient] = None

    def __del__(self):
        if self.client:
            try:
                self.client.close()
            except Exception as exc:
                logger.debug("Failed to release modbus client: %s", exc)

    @classmethod
    def get_manifest(cls) -> Type[WorkflowBlockManifest]:
        return ModbusTCPBlockManifest

    def run(
        self,
        plc_ip: str,
        plc_port: int,
        mode: str,
        registers_to_read: List[int],
        registers_to_write: Dict[int, int],
        depends_on: any,
        image: Optional[WorkflowImageData] = None,
        metadata: Optional[VideoMetadata] = None,
    ) -> dict:
        read_results = {}
        write_results = {}

        if not self.client:
            self.client: ModbusClient = ModbusClient(plc_ip, port=plc_port)
            if not self.client.connect():
                print("Failed to connect to PLC")
                return {"modbus_results": [{"error": "ConnectionFailure"}]}

        # If mode involves reading
        if mode in ["read", "read_and_write"]:
            for address in registers_to_read:
                try:
                    response = self.client.read_holding_registers(address)
                    if not response.isError():
                        read_results[address] = (
                            response.registers[0] if response.registers else None
                        )
                    else:
                        print(f"Error reading register {address}: {response}")
                        read_results[address] = "ReadFailure"
                except Exception as e:
                    print(f"Exception reading register {address}: {e}")
                    read_results[address] = "ReadFailure"

        # If mode involves writing
        if mode in ["write", "read_and_write"]:
            for address, value in registers_to_write.items():
                try:
                    response = self.client.write_register(address, value)
                    if not response.isError():
                        write_results[address] = "WriteSuccess"
                    else:
                        print(
                            f"Error writing register {address} with value {value}: {response}"
                        )
                        write_results[address] = "WriteFailure"
                except Exception as e:
                    print(
                        f"Exception writing register {address} with value {value}: {e}"
                    )
                    write_results[address] = "WriteFailure"

        modbus_output = {}
        if read_results:
            modbus_output["read"] = read_results
        if write_results:
            modbus_output["write"] = write_results

        return {"modbus_results": [modbus_output]}