获取pymodbus以异步方式从多个客户端读取寄存器

时间:2014-11-11 17:12:27

标签: python asynchronous twisted modbus

我可以使用pymodbus连接到我的modbus从站,并使用同步客户端读取这些连接。当我尝试使用带有扭曲的异步客户端时,我可以读取多个值,并从其中一个客户端获取输出,如果我没有发出断开连接,后续的一个挂起,但如果我发出断开连接,客户端会断开连接返回值。

我是一个python新手,这只是我从各种来源拼凑代码。我确信有一个超级简单的解决方案。原谅代码,我不是程序员。谢谢!

#!/usr/bin/env python
import logging
from twisted.internet import reactor
from twisted.internet import defer, task
from twisted.internet.endpoints import TCP4ClientEndpoint
from pymodbus.constants import Defaults
from pymodbus.client.async import ModbusClientFactory
import time

logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)


hosts = ['10.3.72.89', '10.3.72.57']

start = time.time()


def show_hreg(response):
    log.debug('1st hreg = {0}'.format(response.getRegister(0)))
    print response.registers

def foo(protocol):
    rlist = []
    r2 = protocol.read_holding_registers(1699, 4, unit=1)
    r2.addCallback(show_hreg)
    r3 = protocol.read_holding_registers(1099, 4, unit=1)
    r3.addCallback(show_hreg)
    r4 = protocol.read_holding_registers(1599, 4, unit=1)
    r4.addCallback(show_hreg)

    rlist.append(r2)
    rlist.append(r3)
    rlist.append(r4)
    results = defer.gatherResults(rlist)
    return results
    #protocol.transport.loseConnection()
    #reactor.callLater(1, protocol.transport.loseConnection)

    #reactor.callLater(1.5, reactor.stop)

def main(reactor, hosts):
    dlist = []
    for server in hosts:
        d = TCP4ClientEndpoint(reactor, server, Defaults.Port)
        protocol = d.connect(ModbusClientFactory())
        protocol.addCallback(foo)
        dlist.append(protocol)

    # finish the process when the "queue" is done
    results = defer.gatherResults(dlist).addCallback(printElapsedTime)
    return results


def printElapsedTime(ignore):
    print "Elapsed Time: %s" % (time.time() - start)


task.react(main, [hosts])

0 个答案:

没有答案