I have a working code that can reads the coil status continuously using pymodbus3 library. The code is something like below. This is adapted from a basic sample and serves the purpose of looking for the coil status(address 0x01) change to "1" and perform the task as required without fail.
def run_server():
# ----------------------------------------------------------------------- #
# initialize your data store
# ----------------------------------------------------------------------- #
store = ModbusSlaveContext(
di=ModbusSequentialDataBlock(0, [17]*100),
co=ModbusSequentialDataBlock(0, [17]*100),
hr=ModbusSequentialDataBlock(0, [17]*100),
ir=ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)
interval = 3
server = ModbusTcpServer(context, identity=identity, address=('0.0.0.0', 1502))
t = threading.Thread(target=server.serve_forever,name='server connection')
t.start()
loop = LoopingCall(f=updatevalues, a=server)
loop.start(interval, now=True)
reactor.run()
def updatevalues(a):
rfuncode = 1
wfuncode = 5
slave_id = 0x01
address = 0x02
contxt = a.context[slave_id]
values = contxt.get_values(rfuncode, address, count=1)
print(values[0])
#below part is checking the coil status whether its 0 or 1 and perform the necessary task
if(values[0]==1 or values[0]==17):
#Do my stuff if this case is satisfied
#reset the coil back to "0" after the task is performed
values = [0]
contxt.set_values(wfuncode, address, values)
if __name__ == "__main__":
run_server()
Now, I need to also monitor the holding registers (Address 400001 for e.g.) in parallel and read the value as well. Since the holding registers are already initialized in the run_server() function, I guess I don't have to do anything there. But I am not sure what to do in the updatevalues(a) function, so that the holding register can be monitored as well.
Thank you for your help.