I’m using a python program to communicate with a PLC using OPCUA as well as a mass flow controller to dose some substances, using modbus. The python script reads and writes to both.
async def read_input_registers(modbusclient, start_address, num_elements, slave, datatype):
response = await modbusclient.read_input_registers(start_address, num_elements, unit=slave)
if response.isError():
logging.error(f"Read Input Registers Error for {datatype}: {response}")
else:
if datatype == 'B':
data = response.registers[0]
else:
data_bytes = b''.join(pack('>H', register) for register in response.registers)
data = unpack(datatype, data_bytes)
print(f"{datatype} Data:", data)
return data
This is the function i use to read from the modbus registers and the following is where I use this function
MFC_01DosedQuantity_g = await read_input_registers(modbusclient, 8, 2, 1, '>f' ) #Float datatype (big-endian)
await record_variables('MFC01_DosedQuantity_g', MFC_01DosedQuantity_g)
MFC_02DosedQuantity_g = await read_input_registers(modbusclient, 18, 2, 1, '>f') #Float datatype (big-endian)
await record_variables('MFC02_DosedQuantity_g', MFC_02DosedQuantity_g)
MFC_01DosingStatus = await read_input_registers(modbusclient,1, 1, 1, 'B') # Unsigned8 datatype
await record_variables('MFC01_DosingStatus', MFC_01DosingStatus)
MFC_02DosingStatus = await read_input_registers(11, 1, 1, 'B') # Unsigned8 datatype
await record_variables('MFC02_DosingStatus', MFC_02DosingStatus)
status = await read_input_value(client, 'ns=4;s=|var|C6 S14 PRO.Application.GVL.Stage')
if MFC_01DosingStatus == 512 or MFC_02DosingStatus == 512:
print(f"Error detected at stage {status}, shutting down...")
sys.exit()
My problem is that my if condition does not seem to work. The code always goes to sys.exit() despite the value of MFC_01DosingStatus and MFC_02DosingStatus being 256.
I’ve tried to check for a type mismatch, they seem like integers. The record_variables function records them into a .csv file as integers. I’m not sure what else to try.