/usr/share/pyshared/pymodbus/client/async.py is in python-pymodbus 1.2.0-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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | """
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 twisted.internet import defer, protocol
from pymodbus.factory import ClientDecoder
from pymodbus.exceptions import ConnectionException
from pymodbus.transaction import ModbusSocketFramer
from pymodbus.transaction import FifoTransactionManager
from pymodbus.transaction import DictTransactionManager
from pymodbus.client.common import ModbusClientMixin
from twisted.python.failure import Failure
#---------------------------------------------------------------------------#
# Logging
#---------------------------------------------------------------------------#
import logging
_logger = logging.getLogger(__name__)
#---------------------------------------------------------------------------#
# 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._connected = False
self.framer = framer or ModbusSocketFramer(ClientDecoder())
if isinstance(self.framer, ModbusSocketFramer):
self.transaction = DictTransactionManager(self)
else: self.transaction = FifoTransactionManager(self)
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
for tid in self.transaction:
self.transaction.getTransaction(tid).errback(Failure(
ConnectionException('Connection lost during request')))
def dataReceived(self, data):
''' Get response, check for valid message, decode result
:param data: The data returned from the server
'''
self.framer.processIncomingPacket(data, self._handleResponse)
def execute(self, request):
''' Starts the producer to send the next request to
consumer.write(Frame(request))
'''
request.transaction_id = self.transaction.getNextTID()
packet = self.framer.buildPacket(request)
self.transport.write(packet)
return self._buildResponse(request.transaction_id)
def _handleResponse(self, reply):
''' Handle the processed response and link to correct deferred
:param reply: The reply to process
'''
if reply is not None:
tid = reply.transaction_id
handler = self.transaction.getTransaction(tid)
if handler:
handler.callback(reply)
else: _logger.debug("Unrequested message: " + str(reply))
def _buildResponse(self, tid):
''' Helper method to return a deferred response
for the current request.
:param tid: The transaction identifier for this response
:returns: A defer linked to the latest request
'''
if not self._connected:
return defer.fail(Failure(
ConnectionException('Client is not connected')))
d = defer.Deferred()
self.transaction.addTransaction(d, tid)
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.
'''
def __init__(self, framer=None):
''' Initializes the framer module
:param framer: The framer to use for the protocol
'''
self.framer = framer or ModbusSocketFramer(ClientDecoder())
if isinstance(self.framer, ModbusSocketFramer):
self.transaction = DictTransactionManager(self)
else: self.transaction = FifoTransactionManager(self)
def datagramReceived(self, data, (host, port)):
''' Get response, check for valid message, decode result
:param data: The data returned from the server
'''
_logger.debug("Datagram from: %s:%d" % (host, port))
self.framer.processIncomingPacket(data, self._handleResponse)
def execute(self, request):
''' Starts the producer to send the next request to
consumer.write(Frame(request))
'''
request.transaction_id = self.transaction.getNextTID()
packet = self.framer.buildPacket(request)
self.transport.write(packet)
return self._buildResponse(request.transaction_id)
def _handleResponse(self, reply):
''' Handle the processed response and link to correct deferred
:param reply: The reply to process
'''
if reply is not None:
tid = reply.transaction_id
handler = self.transaction.getTransaction(tid)
if handler:
handler.callback(reply)
else: _logger.debug("Unrequested message: " + str(reply))
def _buildResponse(self, tid):
''' Helper method to return a deferred response
for the current request.
:param tid: The transaction identifier for this response
:returns: A defer linked to the latest request
'''
d = defer.Deferred()
self.transaction.addTransaction(d, tid)
return d
#---------------------------------------------------------------------------#
# Client Factories
#---------------------------------------------------------------------------#
class ModbusClientFactory(protocol.ReconnectingClientFactory):
''' Simple client protocol factory '''
protocol = ModbusClientProtocol
#---------------------------------------------------------------------------#
# Exported symbols
#---------------------------------------------------------------------------#
__all__ = [
"ModbusClientProtocol", "ModbusUdpClientProtocol",
"ModbusClientFactory",
]
|