/usr/share/pyshared/pymodbus/client/async.py is in python-pymodbus 0.9.0+r175-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | """
Implementation of a Modbus Client Using Twisted
--------------------------------------------------
Example run::
from twisted.internet import reactor, protocol
from pymodbus.client.async import ModbusClientProtocol
def printResult(result):
print "Result: %d" % result.bits[0]
def process(client):
result = client.write_coil(1, True)
result.addCallback(printResult)
reactor.callLater(1, reactor.stop)
defer = protocol.ClientCreator(reactor, ModbusClientProtocol
).connectTCP("localhost", 502)
defer.addCallback(process)
Another example::
from twisted.internet import reactor
from pymodbus.client.async import ModbusClientFactory
def process():
factory = reactor.connectTCP("localhost", 502, ModbusClientFactory())
reactor.stop()
if __name__ == "__main__":
reactor.callLater(1, process)
reactor.run()
"""
from collections import deque
from twisted.internet import defer, protocol
from pymodbus.factory import ClientDecoder
from pymodbus.exceptions import ConnectionException
from pymodbus.transaction import ModbusSocketFramer, ModbusTransactionManager
from pymodbus.client.common import ModbusClientMixin
#---------------------------------------------------------------------------#
# Logging
#---------------------------------------------------------------------------#
import logging
_logger = logging.getLogger(__name__)
#---------------------------------------------------------------------------#
# A manager for the transaction identifiers
#---------------------------------------------------------------------------#
_manager = ModbusTransactionManager()
#---------------------------------------------------------------------------#
# Connected Client Protocols
#---------------------------------------------------------------------------#
class ModbusClientProtocol(protocol.Protocol, ModbusClientMixin):
'''
This represents the base modbus client protocol. All the application
layer code is deferred to a higher level wrapper.
'''
def __init__(self, framer=None):
''' Initializes the framer module
:param framer: The framer to use for the protocol
'''
self.framer = framer or ModbusSocketFramer(ClientDecoder())
self._requests = deque() # link queue to tid
self._connected = False
def connectionMade(self):
''' Called upon a successful client connection.
'''
_logger.debug("Client connected to modbus server")
self._connected = True
def connectionLost(self, reason):
''' Called upon a client disconnect
:param reason: The reason for the disconnect
'''
_logger.debug("Client disconnected from modbus server: %s" % reason)
self._connected = False
def dataReceived(self, data):
''' Get response, check for valid message, decode result
:param data: The data returned from the server
'''
def _callback(reply): # todo errback/callback
if self._requests:
self._requests.popleft().callback(reply)
self.framer.processIncomingPacket(data, _callback)
def execute(self, request):
''' Starts the producer to send the next request to
consumer.write(Frame(request))
'''
request.transaction_id = _manager.getNextTID()
#self.handler[request.transaction_id] = request
packet = self.framer.buildPacket(request)
self.transport.write(packet)
return self._buildResponse()
def _buildResponse(self):
''' Helper method to return a deferred response
for the current request.
:returns: A defer linked to the latest request
'''
if not self._connected:
return defer.fail(ConnectionException('Client is not connected'))
d = defer.Deferred()
self._requests.append(d)
return d
#----------------------------------------------------------------------#
# Extra Functions
#----------------------------------------------------------------------#
#if send_failed:
# if self.retry > 0:
# deferLater(clock, self.delay, send, message)
# self.retry -= 1
#---------------------------------------------------------------------------#
# Not Connected Client Protocol
#---------------------------------------------------------------------------#
class ModbusUdpClientProtocol(protocol.DatagramProtocol, ModbusClientMixin):
'''
This represents the base modbus client protocol. All the application
layer code is deferred to a higher level wrapper.
'''
__tid = 0
def __init__(self, framer=None):
''' Initializes the framer module
:param framer: The framer to use for the protocol
'''
self.framer = framer or ModbusSocketFramer(ClientDecoder())
self._requests = deque() # link queue to tid
def datagramReceived(self, data, (host, port)):
''' Get response, check for valid message, decode result
:param data: The data returned from the server
'''
def _callback(reply): # todo errback/callback
if self._requests:
self._requests.popleft().callback(reply)
_logger.debug("Datagram from: %s:%d" % (host, port))
self.framer.processIncomingPacket(data, _callback)
def execute(self, request):
''' Starts the producer to send the next request to
consumer.write(Frame(request))
'''
request.transaction_id = _manager.getNextTID()
#self.handler[request.transaction_id] = request
packet = self.framer.buildPacket(request)
self.transport.write(packet)
return self._buildResponse()
def _buildResponse(self):
''' Helper method to return a deferred response
for the current request.
:returns: A defer linked to the latest request
'''
d = defer.Deferred()
self._requests.append(d)
return d
#---------------------------------------------------------------------------#
# Client Factories
#---------------------------------------------------------------------------#
class ModbusClientFactory(protocol.ReconnectingClientFactory):
''' Simple client protocol factory '''
protocol = ModbusClientProtocol
#---------------------------------------------------------------------------#
# Exported symbols
#---------------------------------------------------------------------------#
__all__ = [
"ModbusClientProtocol", "ModbusUdpClientProtocol",
"ModbusClientFactory",
]
|