/usr/share/pyshared/pymodbus/factory.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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 | """
Modbus Request/Response Decoder Factories
-------------------------------------------
The following factories make it easy to decode request/response messages.
To add a new request/response pair to be decodeable by the library, simply
add them to the respective function lookup table (order doesn't matter, but
it does help keep things organized).
Regardless of how many functions are added to the lookup, O(1) behavior is
kept as a result of a pre-computed lookup dictionary.
"""
from pymodbus.pdu import IllegalFunctionRequest
from pymodbus.pdu import ExceptionResponse
from pymodbus.pdu import ModbusExceptions as ecode
from pymodbus.interfaces import IModbusDecoder
from pymodbus.exceptions import ModbusException
from pymodbus.bit_read_message import *
from pymodbus.bit_write_message import *
from pymodbus.diag_message import *
from pymodbus.file_message import *
from pymodbus.other_message import *
from pymodbus.mei_message import *
from pymodbus.register_read_message import *
from pymodbus.register_write_message import *
#---------------------------------------------------------------------------#
# Logging
#---------------------------------------------------------------------------#
import logging
_logger = logging.getLogger(__name__)
#---------------------------------------------------------------------------#
# Server Decoder
#---------------------------------------------------------------------------#
class ServerDecoder(IModbusDecoder):
''' Request Message Factory (Server)
To add more implemented functions, simply add them to the list
'''
__function_table = [
ReadHoldingRegistersRequest,
ReadDiscreteInputsRequest,
ReadInputRegistersRequest,
ReadCoilsRequest,
WriteMultipleCoilsRequest,
WriteMultipleRegistersRequest,
WriteSingleRegisterRequest,
WriteSingleCoilRequest,
ReadWriteMultipleRegistersRequest,
DiagnosticStatusRequest,
ReadExceptionStatusRequest,
GetCommEventCounterRequest,
GetCommEventLogRequest,
ReportSlaveIdRequest,
ReadFileRecordRequest,
WriteFileRecordRequest,
MaskWriteRegisterRequest,
ReadFifoQueueRequest,
ReadDeviceInformationRequest,
]
__sub_function_table = [
ReturnQueryDataRequest,
RestartCommunicationsOptionRequest,
ReturnDiagnosticRegisterRequest,
ChangeAsciiInputDelimiterRequest,
ForceListenOnlyModeRequest,
ClearCountersRequest,
ReturnBusMessageCountRequest,
ReturnBusCommunicationErrorCountRequest,
ReturnBusExceptionErrorCountRequest,
ReturnSlaveMessageCountRequest,
ReturnSlaveNoResponseCountRequest,
ReturnSlaveNAKCountRequest,
ReturnSlaveBusyCountRequest,
ReturnSlaveBusCharacterOverrunCountRequest,
ReturnIopOverrunCountRequest,
ClearOverrunCountRequest,
GetClearModbusPlusRequest,
ReadDeviceInformationRequest,
]
def __init__(self):
''' Initializes the client lookup tables
'''
functions = set(f.function_code for f in self.__function_table)
self.__lookup = dict([(f.function_code, f) for f in self.__function_table])
self.__sub_lookup = dict((f, {}) for f in functions)
for f in self.__sub_function_table:
self.__sub_lookup[f.function_code][f.sub_function_code] = f
def decode(self, message):
''' Wrapper to decode a request packet
:param message: The raw modbus request packet
:return: The decoded modbus message or None if error
'''
try:
return self._helper(message)
except ModbusException, er:
_logger.warn("Unable to decode request %s" % er)
return None
def lookupPduClass(self, function_code):
''' Use `function_code` to determine the class of the PDU.
:param function_code: The function code specified in a frame.
:returns: The class of the PDU that has a matching `function_code`.
'''
return self.__lookup.get(function_code, ExceptionResponse)
def _helper(self, data):
'''
This factory is used to generate the correct request object
from a valid request packet. This decodes from a list of the
currently implemented request types.
:param data: The request packet to decode
:returns: The decoded request or illegal function request object
'''
function_code = ord(data[0])
_logger.debug("Factory Request[%d]" % function_code)
request = self.__lookup.get(function_code, lambda: None)()
if not request:
request = IllegalFunctionRequest(function_code)
request.decode(data[1:])
if hasattr(request, 'sub_function_code'):
lookup = self.__sub_lookup.get(request.function_code, {})
subtype = lookup.get(request.sub_function_code, None)
if subtype: request.__class__ = subtype
return request
#---------------------------------------------------------------------------#
# Client Decoder
#---------------------------------------------------------------------------#
class ClientDecoder(IModbusDecoder):
''' Response Message Factory (Client)
To add more implemented functions, simply add them to the list
'''
__function_table = [
ReadHoldingRegistersResponse,
ReadDiscreteInputsResponse,
ReadInputRegistersResponse,
ReadCoilsResponse,
WriteMultipleCoilsResponse,
WriteMultipleRegistersResponse,
WriteSingleRegisterResponse,
WriteSingleCoilResponse,
ReadWriteMultipleRegistersResponse,
DiagnosticStatusResponse,
ReadExceptionStatusResponse,
GetCommEventCounterResponse,
GetCommEventLogResponse,
ReportSlaveIdResponse,
ReadFileRecordResponse,
WriteFileRecordResponse,
MaskWriteRegisterResponse,
ReadFifoQueueResponse,
ReadDeviceInformationResponse,
]
__sub_function_table = [
ReturnQueryDataResponse,
RestartCommunicationsOptionResponse,
ReturnDiagnosticRegisterResponse,
ChangeAsciiInputDelimiterResponse,
ForceListenOnlyModeResponse,
ClearCountersResponse,
ReturnBusMessageCountResponse,
ReturnBusCommunicationErrorCountResponse,
ReturnBusExceptionErrorCountResponse,
ReturnSlaveMessageCountResponse,
ReturnSlaveNoReponseCountResponse,
ReturnSlaveNAKCountResponse,
ReturnSlaveBusyCountResponse,
ReturnSlaveBusCharacterOverrunCountResponse,
ReturnIopOverrunCountResponse,
ClearOverrunCountResponse,
GetClearModbusPlusResponse,
ReadDeviceInformationResponse,
]
def __init__(self):
''' Initializes the client lookup tables
'''
functions = set(f.function_code for f in self.__function_table)
self.__lookup = dict([(f.function_code, f) for f in self.__function_table])
self.__sub_lookup = dict((f, {}) for f in functions)
for f in self.__sub_function_table:
self.__sub_lookup[f.function_code][f.sub_function_code] = f
def lookupPduClass(self, function_code):
''' Use `function_code` to determine the class of the PDU.
:param function_code: The function code specified in a frame.
:returns: The class of the PDU that has a matching `function_code`.
'''
return self.__lookup.get(function_code, ExceptionResponse)
def decode(self, message):
''' Wrapper to decode a response packet
:param message: The raw packet to decode
:return: The decoded modbus message or None if error
'''
try:
return self._helper(message)
except ModbusException, er:
_logger.error("Unable to decode response %s" % er)
return None
def _helper(self, data):
'''
This factory is used to generate the correct response object
from a valid response packet. This decodes from a list of the
currently implemented request types.
:param data: The response packet to decode
:returns: The decoded request or an exception response object
'''
function_code = ord(data[0])
_logger.debug("Factory Response[%d]" % function_code)
response = self.__lookup.get(function_code, lambda: None)()
if function_code > 0x80:
code = function_code & 0x7f # strip error portion
response = ExceptionResponse(code, ecode.IllegalFunction)
if not response:
raise ModbusException("Unknown response %d" % function_code)
response.decode(data[1:])
if hasattr(response, 'sub_function_code'):
lookup = self.__sub_lookup.get(response.function_code, {})
subtype = lookup.get(response.sub_function_code, None)
if subtype: response.__class__ = subtype
return response
#---------------------------------------------------------------------------#
# Exported symbols
#---------------------------------------------------------------------------#
__all__ = ['ServerDecoder', 'ClientDecoder']
|