Pymodbus / Twisted Asynchronous Client重新连接

时间:2014-11-28 08:23:14

标签: python tcp twisted modbus modbus-tcp

我写了一个测试代码,它从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()

1 个答案:

答案 0 :(得分:1)

我已经测试了您的代码,并且相信您在评论出您的某个请求后,当您的代码被视为工作时,您已经看到与时间相关的 red herring 。扭曲的常见问题解答中涵盖了clientConnectionLost未被调用的行为Why isn't my connectionLost method called?

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

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

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

self.timeout.cancel()
在您再次致电requestFetched之前,使用read方法