3

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

1 回答 1

1

我已经测试了您的代码,并且相信您在注释掉您的一个请求后看到您的代码正常工作时,您已经看到了与时间相关的红鲱鱼。clientConnectionLost扭曲的常见问题解答中涵盖了您在未调用的地方看到的行为:为什么不调用我的 connectionLost 方法?

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

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

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

self.timeout.cancel()

requestFetched你再次打电话给你之前,在你的方法中read

于 2016-04-13T12:35:09.110 回答