1

我有一个可以使用 pymodbus3 库连续读取线圈状态的工作代码。代码如下所示。这改编自一个基本示例,用于查找线圈状态(地址 0x01)更改为“1”并按要求执行任务而不会失败。

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()

现在,我还需要并行监视保持寄存器(例如地址 400001)并读取值。由于保存寄存器已经在 run_server() 函数中初始化,我想我不必在那里做任何事情。但是我不确定在 updatevalues(a) 函数中要做什么,以便也可以监视保持寄存器。

谢谢您的帮助。

4

0 回答 0