gpt4 book ai didi

python - Pymodbus/Twisted 异步客户端重新连接

转载 作者:可可西里 更新时间:2023-11-01 02:34:30 29 4
gpt4 key购买 nike

我写了一个测试代码,它从 PLC 的 modbus 服务器读取一些线圈/寄存器。当我调用一个请求时,代码有效。我拔下电缆,然后 Twisted 调用 clientConnectionLost 函数,这样当我重新插入电缆时,我的客户端将重新连接。如果我执行多个请求,就像下面的代码一样,处理中断,什么也不会发生。我不知道是什么导致了这个问题。

#!/usr/bin/env python

from PyQt4 import QtCore, QtGui
from twisted.internet import reactor, protocol,defer
from pymodbus.constants import Defaults
from pymodbus.client.async import ModbusClientProtocol

from time import sleep

def logger():
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)

logger()

class MyModbusClientProtocol(ModbusClientProtocol):

def connectionMade(self):
ModbusClientProtocol.connectionMade(self)
print 'Connected'
self.read()

def read(self):
deferred = self.read_coils(0,1999)
deferred.addCallbacks(self.requestFetched,self.requestNotFetched)
deferred = self.read_holding_registers(0,124)
deferred.addCallbacks(self.requestFetched,self.requestNotFetched)

def requestNotFetched(self,error):
print error
sleep(0.5)

def requestFetched(self,response):
try:
print ("Fetched %d" % response.getRegister(1))
except:
print ("Fetched %d" % response.getBit(1))

self.factory.counter += 1
if self.factory.counter == 2:
self.factory.counter = 0
reactor.callLater(0,self.read)

class MyModbusClientFactory(protocol.ClientFactory):
"""A factory.

A new protocol instance will be created each time we connect to the server.
"""
def __init__(self):
self.counter = 0

def buildProtocol(self, addr):
p = MyModbusClientProtocol()
p.factory = self
return p

def clientConnectionLost(self, connector, reason):
print "connection lost:", reason
connector.connect()

def clientConnectionFailed(self, connector, reason):
print "connection failed:", reason
connector.connect()

if __name__ == "__main__":

factoryinstance = MyModbusClientFactory()

reactor.connectTCP("192.168.2.69", 502, factoryinstance)

reactor.run()

最佳答案

我已经测试了您的代码,并且相信当您的代码在注释掉您的一个请求后可以正常工作时,您已经看到了与时间相关的红鲱鱼。您在未调用 clientConnectionLost 时看到的行为包含在扭曲的常见问题解答中:Why isn't my connectionLost method called?

您需要做的是创建您自己的特定于协议(protocol)的超时,因为您不能总是依赖 TCP 的超时来为您工作。修复代码的一种简单方法是将其添加到 read 方法的末尾:

self.timeout = reactor.callLater(5, self.transport.abortConnection)

这将在等待 5 秒后中止连接。当您的请求成功完成时,您还需要取消此超时:

self.timeout.cancel()

在您再次调用read 之前在您的requestFetched 方法中。

关于python - Pymodbus/Twisted 异步客户端重新连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27184564/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com