# Extra functions

Pymodbus: Modbus Protocol Implementation.

Released under the BSD license

class pymodbus.ExceptionResponse(function_code, exception_code=None, **kwargs)

  Bases: `ModbusResponse`

  Base class for a modbus exception PDU.

  ExceptionOffset = 128
  decode(data)

    Decode a modbus exception response.

    Parameters:

      data – The packet data to decode

  encode()

    Encode a modbus exception response.

    Returns:

      The encoded exception packet

class pymodbus.Framer(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

  Bases: `str`, `Enum`

  These represent the different framers.

  ASCII = 'ascii'
  BINARY = 'binary'
  RTU = 'rtu'
  SOCKET = 'socket'
  TLS = 'tls'

exception pymodbus.ModbusException(string)

  Bases: `Exception`

  Base modbus exception.

  isError()

    Error

pymodbus.pymodbus_apply_logging_config(level: str | int = 10, log_file_name: str | None = None)

  Apply basic logging configuration used by default by Pymodbus maintainers.

  Parameters:

    - level – (optional) set log level, if not set it is inherited.

    - log_file_name – (optional) log additional to file

  Please call this function to format logging appropriately when opening issues.

Bit Reading Request/Response messages.

class pymodbus.bit_read_message.ReadBitsResponseBase(values, slave=0, **kwargs)

  Bases: `ModbusResponse`

  Base class for Messages responding to bit-reading values.

  The requested bits can be found in the .bits list.

  bits

    A list of booleans representing bit values

  decode(data)

    Decode response pdu.

    Parameters:

      data – The packet data to decode

  encode()

    Encode response pdu.

    Returns:

      The encoded packet message

  getBit(address)

    Get the specified bit’s value.

    Parameters:

      address – The bit to query

    Returns:

      The value of the requested bit

  resetBit(address)

    Set the specified bit to 0.

    Parameters:

      address – The bit to reset

  setBit(address, value=1)

    Set the specified bit.

    Parameters:

      - address – The bit to set

      - value – The value to set the bit to

class pymodbus.bit_read_message.ReadCoilsRequest(address=None, count=None, slave=0, **kwargs)

  Bases: `ReadBitsRequestBase`

  This function code is used to read from 1 to 2000(0x7d0) contiguous status of coils in a remote device.

  The Request PDU specifies the starting address, ie the address of the first coil specified, and the number of coils. In the PDU Coils are addressed starting at zero. Therefore coils numbered 1-16 are addressed as 0-15.

  async execute(context)

    Run a read coils request against a datastore.

    Before running the request, we make sure that the request is in the max valid range (0x001-0x7d0). Next we make sure that the request is valid against the current datastore.

    Parameters:

      context – The datastore to request from

    Returns:

      An initialized `ReadCoilsResponse`, or an `ExceptionResponse` if an error occurred

  function_code = 1
  function_code_name = 'read_coils'

class pymodbus.bit_read_message.ReadCoilsResponse(values=None, slave=0, **kwargs)

  Bases: `ReadBitsResponseBase`

  The coils in the response message are packed as one coil per bit of the data field.

  Status is indicated as 1= ON and 0= OFF. The LSB of the first data byte contains the output addressed in the query. The other coils follow toward the high order end of this byte, and from low order to high order in subsequent bytes.

  If the returned output quantity is not a multiple of eight, the remaining bits in the final data byte will be padded with zeros (toward the high order end of the byte). The Byte Count field specifies the quantity of complete bytes of data.

  The requested coils can be found in boolean form in the .bits list.

  function_code = 1

class pymodbus.bit_read_message.ReadDiscreteInputsRequest(address=None, count=None, slave=0, **kwargs)

  Bases: `ReadBitsRequestBase`

  This function code is used to read from 1 to 2000(0x7d0).

  Contiguous status of discrete inputs in a remote device. The Request PDU specifies the starting address, ie the address of the first input specified, and the number of inputs. In the PDU Discrete Inputs are addressed starting at zero. Therefore Discrete inputs numbered 1-16 are addressed as 0-15.

  async execute(context)

    Run a read discrete input request against a datastore.

    Before running the request, we make sure that the request is in the max valid range (0x001-0x7d0). Next we make sure that the request is valid against the current datastore.

    Parameters:

      context – The datastore to request from

    Returns:

      An initialized `ReadDiscreteInputsResponse`, or an `ExceptionResponse` if an error occurred

  function_code = 2
  function_code_name = 'read_discrete_input'

class pymodbus.bit_read_message.ReadDiscreteInputsResponse(values=None, slave=0, **kwargs)

  Bases: `ReadBitsResponseBase`

  The discrete inputs in the response message are packed as one input per bit of the data field.

  Status is indicated as 1= ON; 0= OFF. The LSB of the first data byte contains the input addressed in the query. The other inputs follow toward the high order end of this byte, and from low order to high order in subsequent bytes.

  If the returned input quantity is not a multiple of eight, the remaining bits in the final data byte will be padded with zeros (toward the high order end of the byte). The Byte Count field specifies the quantity of complete bytes of data.

  The requested coils can be found in boolean form in the .bits list.

  function_code = 2

Bit Writing Request/Response.

TODO write mask request/response

class pymodbus.bit_write_message.WriteMultipleCoilsRequest(address=None, values=None, slave=None, **kwargs)

  Bases: `ModbusRequest`

  This function code is used to forcea sequence of coils.

  To either ON or OFF in a remote device. The Request PDU specifies the coil references to be forced. Coils are addressed starting at zero. Therefore coil numbered 1 is addressed as 0.

  The requested ON/OFF states are specified by contents of the request data field. A logical “1” in a bit position of the field requests the corresponding output to be ON. A logical “0” requests it to be OFF.”

  decode(data)

    Decode a write coils request.

    Parameters:

      data – The packet data to decode

  encode()

    Encode write coils request.

    Returns:

      The byte encoded message

  async execute(context)

    Run a write coils request against a datastore.

    Parameters:

      context – The datastore to request from

    Returns:

      The populated response or exception message

  function_code = 15
  function_code_name = 'write_coils'
  get_response_pdu_size()

    Get response pdu size.

    Func_code (1 byte) + Output Address (2 byte) + Quantity of Outputs (2 Bytes) :return:

class pymodbus.bit_write_message.WriteMultipleCoilsResponse(address=None, count=None, **kwargs)

  Bases: `ModbusResponse`

  The normal response returns the function code.

  Starting address, and quantity of coils forced.

  decode(data)

    Decode a write coils response.

    Parameters:

      data – The packet data to decode

  encode()

    Encode write coils response.

    Returns:

      The byte encoded message

  function_code = 15

class pymodbus.bit_write_message.WriteSingleCoilRequest(address=None, value=None, slave=None, **kwargs)

  Bases: `ModbusRequest`

  This function code is used to write a single output to either ON or OFF in a remote device.

  The requested ON/OFF state is specified by a constant in the request data field. A value of FF 00 hex requests the output to be ON. A value of 00 00 requests it to be OFF. All other values are illegal and will not affect the output.

  The Request PDU specifies the address of the coil to be forced. Coils are addressed starting at zero. Therefore coil numbered 1 is addressed as 0. The requested ON/OFF state is specified by a constant in the Coil Value field. A value of 0XFF00 requests the coil to be ON. A value of 0X0000 requests the coil to be off. All other values are illegal and will not affect the coil.

  decode(data)

    Decode a write coil request.

    Parameters:

      data – The packet data to decode

  encode()

    Encode write coil request.

    Returns:

      The byte encoded message

  async execute(context)

    Run a write coil request against a datastore.

    Parameters:

      context – The datastore to request from

    Returns:

      The populated response or exception message

  function_code = 5
  function_code_name = 'write_coil'
  get_response_pdu_size()

    Get response pdu size.

    Func_code (1 byte) + Output Address (2 byte) + Output Value (2 Bytes) :return:

class pymodbus.bit_write_message.WriteSingleCoilResponse(address=None, value=None, **kwargs)

  Bases: `ModbusResponse`

  The normal response is an echo of the request.

  Returned after the coil state has been written.

  decode(data)

    Decode a write coil response.

    Parameters:

      data – The packet data to decode

  encode()

    Encode write coil response.

    Returns:

      The byte encoded message

  function_code = 5

Modbus Device Controller.

These are the device management handlers. They should be maintained in the server context and the various methods should be inserted in the correct locations.

class pymodbus.device.DeviceInformationFactory

  Bases: `object`

  This is a helper factory.

  That really just hides some of the complexity of processing the device information requests (function code 0x2b 0x0e).

  classmethod get(control, read_code=DeviceInformation.BASIC, object_id=0)

    Get the requested device data from the system.

    Parameters:

      - control – The control block to pull data from

      - read_code – The read code to process

      - object_id – The specific object_id to read

    Returns:

      The requested data (id, length, value)

class pymodbus.device.ModbusDeviceIdentification(info=None, info_name=None)

  Bases: `object`

  This is used to supply the device identification.

  For the readDeviceIdentification function

  For more information read section 6.21 of the modbus application protocol.

  property MajorMinorRevision
  property ModelName
  property ProductCode
  property ProductName
  property UserApplicationName
  property VendorName
  property VendorUrl
  summary()

    Return a summary of the main items.

    Returns:

      An dictionary of the main items

  update(value)

    Update the values of this identity.

    using another identify as the value

    Parameters:

      value – The value to copy values from

class pymodbus.device.ModbusPlusStatistics

  Bases: `object`

  This is used to maintain the current modbus plus statistics count.

  As of right now this is simply a stub to complete the modbus implementation. For more information, see the modbus implementation guide page 87.

  encode()

    Return a summary of the modbus plus statistics.

    Returns:

      54 16-bit words representing the status

  reset()

    Clear all of the modbus plus statistics.

  summary()

    Return a summary of the modbus plus statistics.

    Returns:

      54 16-bit words representing the status

Diagnostic Record Read/Write.

These need to be tied into a the current server context or linked to the appropriate data

class pymodbus.diag_message.ChangeAsciiInputDelimiterRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Change ascii input delimiter.

  The character “CHAR” passed in the request data field becomes the end of message delimiter for future messages (replacing the default LF character). This function is useful in cases of a Line Feed is not required at the end of ASCII messages.

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 3

class pymodbus.diag_message.ChangeAsciiInputDelimiterResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Change ascii input delimiter.

  The character “CHAR” passed in the request data field becomes the end of message delimiter for future messages (replacing the default LF character). This function is useful in cases of a Line Feed is not required at the end of ASCII messages.

  sub_function_code = 3

class pymodbus.diag_message.ClearCountersRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Clear ll counters and the diagnostic register.

  Also, counters are cleared upon power-up

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 10

class pymodbus.diag_message.ClearCountersResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Clear ll counters and the diagnostic register.

  Also, counters are cleared upon power-up

  sub_function_code = 10

class pymodbus.diag_message.ClearOverrunCountRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Clear the overrun error counter and reset the error flag.

  An error flag should be cleared, but nothing else in the specification mentions is, so it is ignored.

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 20

class pymodbus.diag_message.ClearOverrunCountResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Clear the overrun error counter and reset the error flag.

  sub_function_code = 20

class pymodbus.diag_message.DiagnosticStatusRequest(**kwargs)

  Bases: `ModbusRequest`

  This is a base class for all of the diagnostic request functions.

  decode(data)

    Decode a diagnostic request.

    Parameters:

      data – The data to decode into the function code

  encode()

    Encode a diagnostic response.

    we encode the data set in self.message

    Returns:

      The encoded packet

  function_code = 8
  function_code_name = 'diagnostic_status'
  get_response_pdu_size()

    Get response pdu size.

    Func_code (1 byte) + Sub function code (2 byte) + Data (2 * N bytes) :return:

class pymodbus.diag_message.DiagnosticStatusResponse(**kwargs)

  Bases: `ModbusResponse`

  Diagnostic status.

  This is a base class for all of the diagnostic response functions

  It works by performing all of the encoding and decoding of variable data and lets the higher classes define what extra data to append and how to execute a request

  decode(data)

    Decode diagnostic response.

    Parameters:

      data – The data to decode into the function code

  encode()

    Encode diagnostic response.

    we encode the data set in self.message

    Returns:

      The encoded packet

  function_code = 8

class pymodbus.diag_message.ForceListenOnlyModeRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Forces the addressed remote device to its Listen Only Mode for MODBUS communications.

  This isolates it from the other devices on the network, allowing them to continue communicating without interruption from the addressed remote device. No response is returned.

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 4

class pymodbus.diag_message.ForceListenOnlyModeResponse(**kwargs)

  Bases: `DiagnosticStatusResponse`

  Forces the addressed remote device to its Listen Only Mode for MODBUS communications.

  This isolates it from the other devices on the network, allowing them to continue communicating without interruption from the addressed remote device. No response is returned.

  This does not send a response

  should_respond = False
  sub_function_code = 4

class pymodbus.diag_message.GetClearModbusPlusRequest(slave=None, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Get/Clear modbus plus request.

  In addition to the Function code (08) and Subfunction code (00 15 hex) in the query, a two-byte Operation field is used to specify either a “Get Statistics” or a “Clear Statistics” operation. The two operations are exclusive - the “Get” operation cannot clear the statistics, and the “Clear” operation does not return statistics prior to clearing them. Statistics are also cleared on power-up of the slave device.

  encode()

    Encode a diagnostic response.

    we encode the data set in self.message

    Returns:

      The encoded packet

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  get_response_pdu_size()

    Return a series of 54 16-bit words (108 bytes) in the data field of the response.

    This function differs from the usual two-byte length of the data field. The data contains the statistics for the Modbus Plus peer processor in the slave device. Func_code (1 byte) + Sub function code (2 byte) + Operation (2 byte) + Data (108 bytes) :return:

  sub_function_code = 21

class pymodbus.diag_message.GetClearModbusPlusResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Return a series of 54 16-bit words (108 bytes) in the data field of the response.

  This function differs from the usual two-byte length of the data field. The data contains the statistics for the Modbus Plus peer processor in the slave device.

  sub_function_code = 21

class pymodbus.diag_message.RestartCommunicationsOptionRequest(toggle=False, slave=None, **kwargs)

  Bases: `DiagnosticStatusRequest`

  Restart communication.

  The remote device serial line port must be initialized and restarted, and all of its communications event counters are cleared. If the port is currently in Listen Only Mode, no response is returned. This function is the only one that brings the port out of Listen Only Mode. If the port is not currently in Listen Only Mode, a normal response is returned. This occurs before the restart is executed.

  async execute(*_args)

    Clear event log and restart.

    Returns:

      The initialized response message

  sub_function_code = 1

class pymodbus.diag_message.RestartCommunicationsOptionResponse(toggle=False, **kwargs)

  Bases: `DiagnosticStatusResponse`

  Restart Communication.

  The remote device serial line port must be initialized and restarted, and all of its communications event counters are cleared. If the port is currently in Listen Only Mode, no response is returned. This function is the only one that brings the port out of Listen Only Mode. If the port is not currently in Listen Only Mode, a normal response is returned. This occurs before the restart is executed.

  sub_function_code = 1

class pymodbus.diag_message.ReturnBusCommunicationErrorCountRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Return bus comm. count.

  The response data field returns the quantity of CRC errors encountered by the remote device since its last restart, clear counter operation, or power-up

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 12

class pymodbus.diag_message.ReturnBusCommunicationErrorCountResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Return bus comm. error.

  The response data field returns the quantity of CRC errors encountered by the remote device since its last restart, clear counter operation, or power-up

  sub_function_code = 12

class pymodbus.diag_message.ReturnBusExceptionErrorCountRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Return bus exception.

  The response data field returns the quantity of modbus exception responses returned by the remote device since its last restart, clear counters operation, or power-up

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 13

class pymodbus.diag_message.ReturnBusExceptionErrorCountResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Return bus exception.

  The response data field returns the quantity of modbus exception responses returned by the remote device since its last restart, clear counters operation, or power-up

  sub_function_code = 13

class pymodbus.diag_message.ReturnBusMessageCountRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Return bus message count.

  The response data field returns the quantity of messages that the remote device has detected on the communications systems since its last restart, clear counters operation, or power-up

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 11

class pymodbus.diag_message.ReturnBusMessageCountResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Return bus message count.

  The response data field returns the quantity of messages that the remote device has detected on the communications systems since its last restart, clear counters operation, or power-up

  sub_function_code = 11

class pymodbus.diag_message.ReturnDiagnosticRegisterRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  The contents of the remote device’s 16-bit diagnostic register are returned in the response.

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 2

class pymodbus.diag_message.ReturnDiagnosticRegisterResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Return diagnostic register.

  The contents of the remote device’s 16-bit diagnostic register are returned in the response

  sub_function_code = 2

class pymodbus.diag_message.ReturnIopOverrunCountRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Return IopOverrun.

  An IOP overrun is caused by data characters arriving at the port faster than they can be stored, or by the loss of a character due to a hardware malfunction. This function is specific to the 884.

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 19

class pymodbus.diag_message.ReturnIopOverrunCountResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Return Iop overrun count.

  The response data field returns the quantity of messages addressed to the slave that it could not handle due to an 884 IOP overrun condition, since its last restart, clear counters operation, or power-up.

  sub_function_code = 19

class pymodbus.diag_message.ReturnQueryDataRequest(message=b'\x00\x00', slave=None, **kwargs)

  Bases: `DiagnosticStatusRequest`

  Return query data.

  The data passed in the request data field is to be returned (looped back) in the response. The entire response message should be identical to the request.

  async execute(*_args)

    Execute the loopback request (builds the response).

    Returns:

      The populated loopback response message

  sub_function_code = 0

class pymodbus.diag_message.ReturnQueryDataResponse(message=b'\x00\x00', **kwargs)

  Bases: `DiagnosticStatusResponse`

  Return query data.

  The data passed in the request data field is to be returned (looped back) in the response. The entire response message should be identical to the request.

  sub_function_code = 0

class pymodbus.diag_message.ReturnSlaveBusCharacterOverrunCountRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Return slave character overrun.

  The response data field returns the quantity of messages addressed to the remote device that it could not handle due to a character overrun condition, since its last restart, clear counters operation, or power-up. A character overrun is caused by data characters arriving at the port faster than they can be stored, or by the loss of a character due to a hardware malfunction.

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 18

class pymodbus.diag_message.ReturnSlaveBusCharacterOverrunCountResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Return the quantity of messages addressed to the remote device unhandled due to a character overrun.

  Since its last restart, clear counters operation, or power-up. A character overrun is caused by data characters arriving at the port faster than they can be stored, or by the loss of a character due to a hardware malfunction.

  sub_function_code = 18

class pymodbus.diag_message.ReturnSlaveBusyCountRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Return slave busy count.

  The response data field returns the quantity of messages addressed to the remote device for which it returned a Slave Device Busy exception response, since its last restart, clear counters operation, or power-up.

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 17

class pymodbus.diag_message.ReturnSlaveBusyCountResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Return slave busy count.

  The response data field returns the quantity of messages addressed to the remote device for which it returned a Slave Device Busy exception response, since its last restart, clear counters operation, or power-up.

  sub_function_code = 17

class pymodbus.diag_message.ReturnSlaveMessageCountRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Return slave message count.

  The response data field returns the quantity of messages addressed to the remote device, or broadcast, that the remote device has processed since its last restart, clear counters operation, or power-up

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 14

class pymodbus.diag_message.ReturnSlaveMessageCountResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Return slave message count.

  The response data field returns the quantity of messages addressed to the remote device, or broadcast, that the remote device has processed since its last restart, clear counters operation, or power-up

  sub_function_code = 14

class pymodbus.diag_message.ReturnSlaveNAKCountRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Return slave NAK count.

  The response data field returns the quantity of messages addressed to the remote device for which it returned a Negative Acknowledge (NAK) exception response, since its last restart, clear counters operation, or power-up. Exception responses are described and listed in section 7 .

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 16

class pymodbus.diag_message.ReturnSlaveNAKCountResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Return slave NAK.

  The response data field returns the quantity of messages addressed to the remote device for which it returned a Negative Acknowledge (NAK) exception response, since its last restart, clear counters operation, or power-up. Exception responses are described and listed in section 7.

  sub_function_code = 16

class pymodbus.diag_message.ReturnSlaveNoResponseCountRequest(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleRequest`

  Return slave no response.

  The response data field returns the quantity of messages addressed to the remote device, or broadcast, that the remote device has processed since its last restart, clear counters operation, or power-up

  async execute(*args)

    Execute the diagnostic request on the given device.

    Returns:

      The initialized response message

  sub_function_code = 15

class pymodbus.diag_message.ReturnSlaveNoResponseCountResponse(data=0, **kwargs)

  Bases: `DiagnosticStatusSimpleResponse`

  Return slave no response.

  The response data field returns the quantity of messages addressed to the remote device, or broadcast, that the remote device has processed since its last restart, clear counters operation, or power-up

  sub_function_code = 15

Modbus Remote Events.

An event byte returned by the Get Communications Event Log function can be any one of four types. The type is defined by bit 7 (the high-order bit) in each byte. It may be further defined by bit 6.

class pymodbus.events.CommunicationRestartEvent

  Bases: `ModbusEvent`

  Restart remote device Initiated Communication.

  The remote device stores this type of event byte when its communications port is restarted. The remote device can be restarted by the Diagnostics function (code 08), with sub-function Restart Communications Option (code 00 01).

  That function also places the remote device into a “Continue on Error” or “Stop on Error” mode. If the remote device is placed into “Continue on Error” mode, the event byte is added to the existing event log. If the remote device is placed into “Stop on Error” mode, the byte is added to the log and the rest of the log is cleared to zeros.

  The event is defined by a content of zero.

  decode(event)

    Decode the event message to its status bits.

    Parameters:

      event – The event to decode

    Raises:

      ParameterException –

  encode()

    Encode the status bits to an event message.

    Returns:

      The encoded event message

  value = 0

class pymodbus.events.EnteredListenModeEvent

  Bases: `ModbusEvent`

  Enter Remote device Listen Only Mode.

  The remote device stores this type of event byte when it enters the Listen Only Mode. The event is defined by a content of 04 hex.

  decode(event)

    Decode the event message to its status bits.

    Parameters:

      event – The event to decode

    Raises:

      ParameterException –

  encode()

    Encode the status bits to an event message.

    Returns:

      The encoded event message

  value = 4

class pymodbus.events.ModbusEvent

  Bases: `object`

  Define modbus events.

  decode(event)

    Decode the event message to its status bits.

    Parameters:

      event – The event to decode

    Raises:

      NotImplementedException –

  encode()

    Encode the status bits to an event message.

    Raises:

      NotImplementedException –

class pymodbus.events.RemoteReceiveEvent(**kwargs)

  Bases: `ModbusEvent`

  Remote device MODBUS Receive Event.

  The remote device stores this type of event byte when a query message is received. It is stored before the remote device processes the message. This event is defined by bit 7 set to logic “1”. The other bits will be set to a logic “1” if the corresponding condition is TRUE. The bit layout is:

      Bit Contents
      ----------------------------------
      0   Not Used
      2   Not Used
      3   Not Used
      4   Character Overrun
      5   Currently in Listen Only Mode
      6   Broadcast Receive
      7   1

  decode(event: bytes) → None

    Decode the event message to its status bits.

    Parameters:

      event – The event to decode

  encode() → bytes

    Encode the status bits to an event message.

    Returns:

      The encoded event message

class pymodbus.events.RemoteSendEvent(**kwargs)

  Bases: `ModbusEvent`

  Remote device MODBUS Send Event.

  The remote device stores this type of event byte when it finishes processing a request message. It is stored if the remote device returned a normal or exception response, or no response.

  This event is defined by bit 7 set to a logic “0”, with bit 6 set to a “1”. The other bits will be set to a logic “1” if the corresponding condition is TRUE. The bit layout is:

      Bit Contents
      -----------------------------------------------------------
      0   Read Exception Sent (Exception Codes 1-3)
      1   Slave Abort Exception Sent (Exception Code 4)
      2   Slave Busy Exception Sent (Exception Codes 5-6)
      3   Slave Program NAK Exception Sent (Exception Code 7)
      4   Write Timeout Error Occurred
      5   Currently in Listen Only Mode
      6   1
      7   0

  decode(event)

    Decode the event message to its status bits.

    Parameters:

      event – The event to decode

  encode()

    Encode the status bits to an event message.

    Returns:

      The encoded event message

Pymodbus Exceptions.

Custom exceptions to be used in the Modbus code.

exception pymodbus.exceptions.ConnectionException(string='')

  Bases: `ModbusException`

  Error resulting from a bad connection.

exception pymodbus.exceptions.InvalidMessageReceivedException(string='')

  Bases: `ModbusException`

  Error resulting from invalid response received or decoded.

exception pymodbus.exceptions.MessageRegisterException(string='')

  Bases: `ModbusException`

  Error resulting from failing to register a custom message request/response.

exception pymodbus.exceptions.ModbusIOException(string='', function_code=None)

  Bases: `ModbusException`

  Error resulting from data i/o.

exception pymodbus.exceptions.NoSuchSlaveException(string='')

  Bases: `ModbusException`

  Error resulting from making a request to a slave that does not exist.

exception pymodbus.exceptions.NotImplementedException(string='')

  Bases: `ModbusException`

  Error resulting from not implemented function.

exception pymodbus.exceptions.ParameterException(string='')

  Bases: `ModbusException`

  Error resulting from invalid parameter.

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.

class pymodbus.factory.ClientDecoder

  Bases: `object`

  Response Message Factory (Client).

  To add more implemented functions, simply add them to the list

  decode(message)

    Decode a response packet.

    Parameters:

      message – The raw packet to decode

    Returns:

      The decoded modbus message or None if error

  function_table = [<class 'pymodbus.register_read_message.ReadHoldingRegistersResponse'>, <class 'pymodbus.bit_read_message.ReadDiscreteInputsResponse'>, <class 'pymodbus.register_read_message.ReadInputRegistersResponse'>, <class 'pymodbus.bit_read_message.ReadCoilsResponse'>, <class 'pymodbus.bit_write_message.WriteMultipleCoilsResponse'>, <class 'pymodbus.register_write_message.WriteMultipleRegistersResponse'>, <class 'pymodbus.register_write_message.WriteSingleRegisterResponse'>, <class 'pymodbus.bit_write_message.WriteSingleCoilResponse'>, <class 'pymodbus.register_read_message.ReadWriteMultipleRegistersResponse'>, <class 'pymodbus.diag_message.DiagnosticStatusResponse'>, <class 'pymodbus.other_message.ReadExceptionStatusResponse'>, <class 'pymodbus.other_message.GetCommEventCounterResponse'>, <class 'pymodbus.other_message.GetCommEventLogResponse'>, <class 'pymodbus.other_message.ReportSlaveIdResponse'>, <class 'pymodbus.file_message.ReadFileRecordResponse'>, <class 'pymodbus.file_message.WriteFileRecordResponse'>, <class 'pymodbus.register_write_message.MaskWriteRegisterResponse'>, <class 'pymodbus.file_message.ReadFifoQueueResponse'>, <class 'pymodbus.mei_message.ReadDeviceInformationResponse'>]
  lookupPduClass(function_code)

    Use function_code to determine the class of the PDU.

    Parameters:

      function_code – The function code specified in a frame.

    Returns:

      The class of the PDU that has a matching function_code.

  register(function)

    Register a function and sub function class with the decoder.

class pymodbus.factory.ServerDecoder

  Bases: `object`

  Request Message Factory (Server).

  To add more implemented functions, simply add them to the list

  decode(message)

    Decode a request packet.

    Parameters:

      message – The raw modbus request packet

    Returns:

      The decoded modbus message or None if error

  classmethod getFCdict() → Dict[int, Callable]

    Build function code - class list.

  lookupPduClass(function_code)

    Use function_code to determine the class of the PDU.

    Parameters:

      function_code – The function code specified in a frame.

    Returns:

      The class of the PDU that has a matching function_code.

  register(function)

    Register a function and sub function class with the decoder.

    Parameters:

      function – Custom function class to register

    Raises:

      MessageRegisterException –

File Record Read/Write Messages.

Currently none of these messages are implemented

class pymodbus.file_message.FileRecord(**kwargs)

  Bases: `object`

  Represents a file record and its relevant data.

class pymodbus.file_message.ReadFifoQueueRequest(address=0, **kwargs)

  Bases: `ModbusRequest`

  Read fifo queue request.

  This function code allows to read the contents of a First-In-First-Out (FIFO) queue of register in a remote device. The function returns a count of the registers in the queue, followed by the queued data. Up to 32 registers can be read: the count, plus up to 31 queued data registers.

  The queue count register is returned first, followed by the queued data registers. The function reads the queue contents, but does not clear them.

  decode(data)

    Decode the incoming request.

    Parameters:

      data – The data to decode into the address

  encode()

    Encode the request packet.

    Returns:

      The byte encoded packet

  execute(_context)

    Run a read exception status request against the store.

    Returns:

      The populated response

  function_code = 24
  function_code_name = 'read_fifo_queue'

class pymodbus.file_message.ReadFifoQueueResponse(values=None, **kwargs)

  Bases: `ModbusResponse`

  Read Fifo queue response.

  In a normal response, the byte count shows the quantity of bytes to follow, including the queue count bytes and value register bytes (but not including the error check field). The queue count is the quantity of data registers in the queue (not including the count register).

  If the queue count exceeds 31, an exception response is returned with an error code of 03 (Illegal Data Value).

  classmethod calculateRtuFrameSize(buffer)

    Calculate the size of the message.

    Parameters:

      buffer – A buffer containing the data that have been received.

    Returns:

      The number of bytes in the response.

  decode(data)

    Decode a the response.

    Parameters:

      data – The packet data to decode

  encode()

    Encode the response.

    Returns:

      The byte encoded message

  function_code = 24

class pymodbus.file_message.ReadFileRecordRequest(records=None, **kwargs)

  Bases: `ModbusRequest`

  Read file record request.

  This function code is used to perform a file record read. All request data lengths are provided in terms of number of bytes and all record lengths are provided in terms of registers.

  A file is an organization of records. Each file contains 10000 records, addressed 0000 to 9999 decimal or 0x0000 to 0x270f. For example, record 12 is addressed as 12. The function can read multiple groups of references. The groups can be separating (non-contiguous), but the references within each group must be sequential. Each group is defined in a separate “sub-request” field that contains seven bytes:

      The reference type: 1 byte (must be 0x06)
      The file number: 2 bytes
      The starting record number within the file: 2 bytes
      The length of the record to be read: 2 bytes

  The quantity of registers to be read, combined with all other fields in the expected response, must not exceed the allowable length of the MODBUS PDU: 235 bytes.

  decode(data)

    Decode the incoming request.

    Parameters:

      data – The data to decode into the address

  encode()

    Encode the request packet.

    Returns:

      The byte encoded packet

  execute(_context)

    Run a read exception status request against the store.

    Returns:

      The populated response

  function_code = 20
  function_code_name = 'read_file_record'

class pymodbus.file_message.ReadFileRecordResponse(records=None, **kwargs)

  Bases: `ModbusResponse`

  Read file record response.

  The normal response is a series of “sub-responses,” one for each “sub-request.” The byte count field is the total combined count of bytes in all “sub-responses.” In addition, each “sub-response” contains a field that shows its own byte count.

  decode(data)

    Decode the response.

    Parameters:

      data – The packet data to decode

  encode()

    Encode the response.

    Returns:

      The byte encoded message

  function_code = 20

class pymodbus.file_message.WriteFileRecordRequest(records=None, **kwargs)

  Bases: `ModbusRequest`

  Write file record request.

  This function code is used to perform a file record write. All request data lengths are provided in terms of number of bytes and all record lengths are provided in terms of the number of 16 bit words.

  decode(data)

    Decode the incoming request.

    Parameters:

      data – The data to decode into the address

  encode()

    Encode the request packet.

    Returns:

      The byte encoded packet

  execute(_context)

    Run the write file record request against the context.

    Returns:

      The populated response

  function_code = 21
  function_code_name = 'write_file_record'

class pymodbus.file_message.WriteFileRecordResponse(records=None, **kwargs)

  Bases: `ModbusResponse`

  The normal response is an echo of the request.

  decode(data)

    Decode the incoming request.

    Parameters:

      data – The data to decode into the address

  encode()

    Encode the response.

    Returns:

      The byte encoded message

  function_code = 21

Encapsulated Interface (MEI) Transport Messages.

class pymodbus.mei_message.ReadDeviceInformationRequest(read_code=None, object_id=0, **kwargs)

  Bases: `ModbusRequest`

  Read device information.

  This function code allows reading the identification and additional information relative to the physical and functional description of a remote device, only.

  The Read Device Identification interface is modeled as an address space composed of a set of addressable data elements. The data elements are called objects and an object Id identifies them.

  decode(data)

    Decode data part of the message.

    Parameters:

      data – The incoming data

  encode()

    Encode the request packet.

    Returns:

      The byte encoded packet

  async execute(_context)

    Run a read exception status request against the store.

    Returns:

      The populated response

  function_code = 43
  function_code_name = 'read_device_information'
  sub_function_code = 14

class pymodbus.mei_message.ReadDeviceInformationResponse(read_code=None, information=None, **kwargs)

  Bases: `ModbusResponse`

  Read device information response.

  classmethod calculateRtuFrameSize(buffer)

    Calculate the size of the message.

    Parameters:

      buffer – A buffer containing the data that have been received.

    Returns:

      The number of bytes in the response.

  decode(data)

    Decode a the response.

    Parameters:

      data – The packet data to decode

  encode()

    Encode the response.

    Returns:

      The byte encoded message

  function_code = 43
  sub_function_code = 14

Diagnostic record read/write.

Currently not all implemented

class pymodbus.other_message.GetCommEventCounterRequest(**kwargs)

  Bases: `ModbusRequest`

  This function code is used to get a status word.

  And an event count from the remote device’s communication event counter.

  By fetching the current count before and after a series of messages, a client can determine whether the messages were handled normally by the remote device.

  The device’s event counter is incremented once for each successful message completion. It is not incremented for exception responses, poll commands, or fetch event counter commands.

  The event counter can be reset by means of the Diagnostics function (code 08), with a subfunction of Restart Communications Option (code 00 01) or Clear Counters and Diagnostic Register (code 00 0A).

  decode(data)

    Decode data part of the message.

    Parameters:

      data – The incoming data

  encode()

    Encode the message.

  async execute(_context=None)

    Run a read exception status request against the store.

    Returns:

      The populated response

  function_code = 11
  function_code_name = 'get_event_counter'

class pymodbus.other_message.GetCommEventCounterResponse(count=0, **kwargs)

  Bases: `ModbusResponse`

  Get comm event counter response.

  The normal response contains a two-byte status word, and a two-byte event count. The status word will be all ones (FF FF hex) if a previously-issued program command is still being processed by the remote device (a busy condition exists). Otherwise, the status word will be all zeros.

  decode(data)

    Decode a the response.

    Parameters:

      data – The packet data to decode

  encode()

    Encode the response.

    Returns:

      The byte encoded message

  function_code = 11

class pymodbus.other_message.GetCommEventLogRequest(**kwargs)

  Bases: `ModbusRequest`

  This function code is used to get a status word.

  Event count, message count, and a field of event bytes from the remote device.

  The status word and event counts are identical to that returned by the Get Communications Event Counter function (11, 0B hex).

  The message counter contains the quantity of messages processed by the remote device since its last restart, clear counters operation, or power-up. This count is identical to that returned by the Diagnostic function (code 08), sub-function Return Bus Message Count (code 11, 0B hex).

  The event bytes field contains 0-64 bytes, with each byte corresponding to the status of one MODBUS send or receive operation for the remote device. The remote device enters the events into the field in chronological order. Byte 0 is the most recent event. Each new byte flushes the oldest byte from the field.

  decode(data)

    Decode data part of the message.

    Parameters:

      data – The incoming data

  encode()

    Encode the message.

  async execute(_context=None)

    Run a read exception status request against the store.

    Returns:

      The populated response

  function_code = 12
  function_code_name = 'get_event_log'

class pymodbus.other_message.GetCommEventLogResponse(**kwargs)

  Bases: `ModbusResponse`

  Get Comm event log response.

  The normal response contains a two-byte status word field, a two-byte event count field, a two-byte message count field, and a field containing 0-64 bytes of events. A byte count field defines the total length of the data in these four field

  decode(data)

    Decode a the response.

    Parameters:

      data – The packet data to decode

  encode()

    Encode the response.

    Returns:

      The byte encoded message

  function_code = 12

class pymodbus.other_message.ReadExceptionStatusRequest(slave=None, **kwargs)

  Bases: `ModbusRequest`

  This function code is used to read the contents of eight Exception Status outputs in a remote device.

  The function provides a simple method for accessing this information, because the Exception Output references are known (no output reference is needed in the function).

  decode(data)

    Decode data part of the message.

    Parameters:

      data – The incoming data

  encode()

    Encode the message.

  async execute(_context=None)

    Run a read exception status request against the store.

    Returns:

      The populated response

  function_code = 7
  function_code_name = 'read_exception_status'

class pymodbus.other_message.ReadExceptionStatusResponse(status=0, **kwargs)

  Bases: `ModbusResponse`

  The normal response contains the status of the eight Exception Status outputs.

  The outputs are packed into one data byte, with one bit per output. The status of the lowest output reference is contained in the least significant bit of the byte. The contents of the eight Exception Status outputs are device specific.

  decode(data)

    Decode a the response.

    Parameters:

      data – The packet data to decode

  encode()

    Encode the response.

    Returns:

      The byte encoded message

  function_code = 7

class pymodbus.other_message.ReportSlaveIdRequest(slave=0, **kwargs)

  Bases: `ModbusRequest`

  This function code is used to read the description of the type.

  The current status, and other information specific to a remote device.

  decode(data)

    Decode data part of the message.

    Parameters:

      data – The incoming data

  encode()

    Encode the message.

  async execute(context=None)

    Run a report slave id request against the store.

    Returns:

      The populated response

  function_code = 17
  function_code_name = 'report_slave_id'

class pymodbus.other_message.ReportSlaveIdResponse(identifier=b'\x00', status=True, **kwargs)

  Bases: `ModbusResponse`

  Show response.

  The data contents are specific to each type of device.

  decode(data)

    Decode a the response.

    Since the identifier is device dependent, we just return the raw value that a user can decode to whatever it should be.

    Parameters:

      data – The packet data to decode

  encode()

    Encode the response.

    Returns:

      The byte encoded message

  function_code = 17

Modbus Payload Builders.

A collection of utilities for building and decoding modbus messages payloads.

class pymodbus.payload.BinaryPayloadBuilder(payload=None, byteorder=Endian.LITTLE, wordorder=Endian.BIG, repack=False)

  Bases: `object`

  A utility that helps build payload messages to be written with the various modbus messages.

  It really is just a simple wrapper around the struct module, however it saves time looking up the format strings. What follows is a simple example:

      builder = BinaryPayloadBuilder(byteorder=Endian.Little)
      builder.add_8bit_uint(1)
      builder.add_16bit_uint(2)
      payload = builder.build()

  add_16bit_float(value: float) → None

    Add a 16 bit float to the buffer.

    Parameters:

      value – The value to add to the buffer

  add_16bit_int(value: int) → None

    Add a 16 bit signed int to the buffer.

    Parameters:

      value – The value to add to the buffer

  add_16bit_uint(value: int) → None

    Add a 16 bit unsigned int to the buffer.

    Parameters:

      value – The value to add to the buffer

  add_32bit_float(value: float) → None

    Add a 32 bit float to the buffer.

    Parameters:

      value – The value to add to the buffer

  add_32bit_int(value: int) → None

    Add a 32 bit signed int to the buffer.

    Parameters:

      value – The value to add to the buffer

  add_32bit_uint(value: int) → None

    Add a 32 bit unsigned int to the buffer.

    Parameters:

      value – The value to add to the buffer

  add_64bit_float(value: float) → None

    Add a 64 bit float(double) to the buffer.

    Parameters:

      value – The value to add to the buffer

  add_64bit_int(value: int) → None

    Add a 64 bit signed int to the buffer.

    Parameters:

      value – The value to add to the buffer

  add_64bit_uint(value: int) → None

    Add a 64 bit unsigned int to the buffer.

    Parameters:

      value – The value to add to the buffer

  add_8bit_int(value: int) → None

    Add a 8 bit signed int to the buffer.

    Parameters:

      value – The value to add to the buffer

  add_8bit_uint(value: int) → None

    Add a 8 bit unsigned int to the buffer.

    Parameters:

      value – The value to add to the buffer

  add_bits(values: list[bool]) → None

    Add a collection of bits to be encoded.

    If these are less than a multiple of eight, they will be left padded with 0 bits to make it so.

    Parameters:

      values – The value to add to the buffer

  add_string(value: str) → None

    Add a string to the buffer.

    Parameters:

      value – The value to add to the buffer

  build() → list[bytes]

    Return the payload buffer as a list.

    This list is two bytes per element and can thus be treated as a list of registers.

    Returns:

      The payload buffer as a list

  encode() → bytes

    Get the payload buffer encoded in bytes.

  reset() → None

    Reset the payload buffer.

  to_coils() → list[bool]

    Convert the payload buffer into a coil layout that can be used as a context block.

    Returns:

      The coil layout to use as a block

  to_registers()

    Convert the payload buffer to register layout that can be used as a context block.

    Returns:

      The register layout to use as a block

class pymodbus.payload.BinaryPayloadDecoder(payload, byteorder=Endian.LITTLE, wordorder=Endian.BIG)

  Bases: `object`

  A utility that helps decode payload messages from a modbus response message.

  It really is just a simple wrapper around the struct module, however it saves time looking up the format strings. What follows is a simple example:

      decoder = BinaryPayloadDecoder(payload)
      first   = decoder.decode_8bit_uint()
      second  = decoder.decode_16bit_uint()

  classmethod bit_chunks(coils, size=8)

    Return bit chunks.

  decode_16bit_float()

    Decode a 16 bit float from the buffer.

  decode_16bit_int()

    Decode a 16 bit signed int from the buffer.

  decode_16bit_uint()

    Decode a 16 bit unsigned int from the buffer.

  decode_32bit_float()

    Decode a 32 bit float from the buffer.

  decode_32bit_int()

    Decode a 32 bit signed int from the buffer.

  decode_32bit_uint()

    Decode a 32 bit unsigned int from the buffer.

  decode_64bit_float()

    Decode a 64 bit float(double) from the buffer.

  decode_64bit_int()

    Decode a 64 bit signed int from the buffer.

  decode_64bit_uint()

    Decode a 64 bit unsigned int from the buffer.

  decode_8bit_int()

    Decode a 8 bit signed int from the buffer.

  decode_8bit_uint()

    Decode a 8 bit unsigned int from the buffer.

  decode_bits(package_len=1)

    Decode a byte worth of bits from the buffer.

  decode_string(size=1)

    Decode a string from the buffer.

    Parameters:

      size – The size of the string to decode

  classmethod fromCoils(coils, byteorder=Endian.LITTLE, _wordorder=Endian.BIG)

    Initialize a payload decoder with the result of reading of coils.

  classmethod fromRegisters(registers, byteorder=Endian.LITTLE, wordorder=Endian.BIG)

    Initialize a payload decoder.

    With the result of reading a collection of registers from a modbus device.

    The registers are treated as a list of 2 byte values. We have to do this because of how the data has already been decoded by the rest of the library.

    Parameters:

      - registers – The register results to initialize with

      - byteorder – The Byte order of each word

      - wordorder – The endianness of the word (when wordcount is >= 2)

    Returns:

      An initialized PayloadDecoder

    Raises:

      ParameterException –

  reset()

    Reset the decoder pointer back to the start.

  skip_bytes(nbytes)

    Skip n bytes in the buffer.

    Parameters:

      nbytes – The number of bytes to skip

Contains base classes for modbus request/response/error packets.

class pymodbus.pdu.ExceptionResponse(function_code, exception_code=None, **kwargs)

  Bases: `ModbusResponse`

  Base class for a modbus exception PDU.

  ExceptionOffset = 128
  decode(data)

    Decode a modbus exception response.

    Parameters:

      data – The packet data to decode

  encode()

    Encode a modbus exception response.

    Returns:

      The encoded exception packet

class pymodbus.pdu.IllegalFunctionRequest(function_code, **kwargs)

  Bases: `ModbusRequest`

  Define the Modbus slave exception type “Illegal Function”.

  This exception code is returned if the slave:

      - does not implement the function code **or**
      - is not in a state that allows it to process the function

  ErrorCode = 1
  decode(_data)

    Decode so this failure will run correctly.

  encode()

    Decode so this failure will run correctly.

  async execute(_context)

    Build an illegal function request error response.

    Returns:

      The error response packet

class pymodbus.pdu.ModbusExceptions

  Bases: `object`

  An enumeration of the valid modbus exceptions.

  Acknowledge = 5
  GatewayNoResponse = 11
  GatewayPathUnavailable = 10
  IllegalAddress = 2
  IllegalFunction = 1
  IllegalValue = 3
  MemoryParityError = 8
  NegativeAcknowledge = 7
  SlaveBusy = 6
  SlaveFailure = 4
  classmethod decode(code)

    Give an error code, translate it to a string error name.

    Parameters:

      code – The code number to translate

class pymodbus.pdu.ModbusRequest(slave=0, **kwargs)

  Bases: `ModbusPDU`

  Base class for a modbus request PDU.

  doException(exception)

    Build an error response based on the function.

    Parameters:

      exception – The exception to return

    Raises:

      An exception response

  function_code = -1

class pymodbus.pdu.ModbusResponse(slave=0, **kwargs)

  Bases: `ModbusPDU`

  Base class for a modbus response PDU.

  should_respond

    A flag that indicates if this response returns a result back to the client issuing the request

  _rtu_frame_size

    Indicates the size of the modbus rtu response used for calculating how much to read.

  function_code = 0
  isError() → bool

    Check if the error is a success or failure.

  should_respond = True

Register Reading Request/Response.

class pymodbus.register_read_message.ReadHoldingRegistersRequest(address=None, count=None, slave=0, **kwargs)

  Bases: `ReadRegistersRequestBase`

  Read holding registers.

  This function code is used to read the contents of a contiguous block of holding registers in a remote device. The Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at zero. Therefore registers numbered 1-16 are addressed as 0-15.

  async execute(context)

    Run a read holding request against a datastore.

    Parameters:

      context – The datastore to request from

    Returns:

      An initialized `ReadHoldingRegistersResponse`

  function_code = 3
  function_code_name = 'read_holding_registers'

class pymodbus.register_read_message.ReadHoldingRegistersResponse(values=None, **kwargs)

  Bases: `ReadRegistersResponseBase`

  Read holding registers.

  This function code is used to read the contents of a contiguous block of holding registers in a remote device. The Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at zero. Therefore registers numbered 1-16 are addressed as 0-15.

  The requested registers can be found in the .registers list.

  function_code = 3

class pymodbus.register_read_message.ReadInputRegistersRequest(address=None, count=None, slave=0, **kwargs)

  Bases: `ReadRegistersRequestBase`

  Read input registers.

  This function code is used to read from 1 to approx. 125 contiguous input registers in a remote device. The Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at zero. Therefore input registers numbered 1-16 are addressed as 0-15.

  async execute(context)

    Run a read input request against a datastore.

    Parameters:

      context – The datastore to request from

    Returns:

      An initialized `ReadInputRegistersResponse`

  function_code = 4
  function_code_name = 'read_input_registers'

class pymodbus.register_read_message.ReadInputRegistersResponse(values=None, **kwargs)

  Bases: `ReadRegistersResponseBase`

  Read/write input registers.

  This function code is used to read from 1 to approx. 125 contiguous input registers in a remote device. The Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at zero. Therefore input registers numbered 1-16 are addressed as 0-15.

  The requested registers can be found in the .registers list.

  function_code = 4

class pymodbus.register_read_message.ReadRegistersResponseBase(values, slave=0, **kwargs)

  Bases: `ModbusResponse`

  Base class for responding to a modbus register read.

  The requested registers can be found in the .registers list.

  decode(data)

    Decode a register response packet.

    Parameters:

      data – The request to decode

  encode()

    Encode the response packet.

    Returns:

      The encoded packet

  getRegister(index)

    Get the requested register.

    Parameters:

      index – The indexed register to retrieve

    Returns:

      The request register

  registers

    A list of register values

class pymodbus.register_read_message.ReadWriteMultipleRegistersRequest(**kwargs)

  Bases: `ModbusRequest`

  Read/write multiple registers.

  This function code performs a combination of one read operation and one write operation in a single MODBUS transaction. The write operation is performed before the read.

  Holding registers are addressed starting at zero. Therefore holding registers 1-16 are addressed in the PDU as 0-15.

  The request specifies the starting address and number of holding registers to be read as well as the starting address, number of holding registers, and the data to be written. The byte count specifies the number of bytes to follow in the write data field.”

  decode(data)

    Decode the register request packet.

    Parameters:

      data – The request to decode

  encode()

    Encode the request packet.

    Returns:

      The encoded packet

  async execute(context)

    Run a write single register request against a datastore.

    Parameters:

      context – The datastore to request from

    Returns:

      An initialized `ReadWriteMultipleRegistersResponse`

  function_code = 23
  function_code_name = 'read_write_multiple_registers'
  get_response_pdu_size()

    Get response pdu size.

    Func_code (1 byte) + Byte Count(1 byte) + 2 * Quantity of Coils (n Bytes) :return:

class pymodbus.register_read_message.ReadWriteMultipleRegistersResponse(values=None, **kwargs)

  Bases: `ModbusResponse`

  Read/write multiple registers.

  The normal response contains the data from the group of registers that were read. The byte count field specifies the quantity of bytes to follow in the read data field.

  The requested registers can be found in the .registers list.

  decode(data)

    Decode the register response packet.

    Parameters:

      data – The response to decode

  encode()

    Encode the response packet.

    Returns:

      The encoded packet

  function_code = 23

Register Writing Request/Response Messages.

class pymodbus.register_write_message.MaskWriteRegisterRequest(address=0, and_mask=65535, or_mask=0, **kwargs)

  Bases: `ModbusRequest`

  This function code is used to modify the contents.

  Of a specified holding register using a combination of an AND mask, an OR mask, and the register’s current contents. The function can be used to set or clear individual bits in the register.

  decode(data)

    Decode the incoming request.

    Parameters:

      data – The data to decode into the address

  encode()

    Encode the request packet.

    Returns:

      The byte encoded packet

  async execute(context)

    Run a mask write register request against the store.

    Parameters:

      context – The datastore to request from

    Returns:

      The populated response

  function_code = 22
  function_code_name = 'mask_write_register'

class pymodbus.register_write_message.MaskWriteRegisterResponse(address=0, and_mask=65535, or_mask=0, **kwargs)

  Bases: `ModbusResponse`

  The normal response is an echo of the request.

  The response is returned after the register has been written.

  decode(data)

    Decode a the response.

    Parameters:

      data – The packet data to decode

  encode()

    Encode the response.

    Returns:

      The byte encoded message

  function_code = 22

class pymodbus.register_write_message.WriteMultipleRegistersRequest(address=None, values=None, slave=None, **kwargs)

  Bases: `ModbusRequest`

  This function code is used to write a block.

  Of contiguous registers (1 to approx. 120 registers) in a remote device.

  The requested written values are specified in the request data field. Data is packed as two bytes per register.

  decode(data)

    Decode a write single register packet packet request.

    Parameters:

      data – The request to decode

  encode()

    Encode a write single register packet packet request.

    Returns:

      The encoded packet

  async execute(context)

    Run a write single register request against a datastore.

    Parameters:

      context – The datastore to request from

    Returns:

      An initialized response, exception message otherwise

  function_code = 16
  function_code_name = 'write_registers'
  get_response_pdu_size()

    Get response pdu size.

    Func_code (1 byte) + Starting Address (2 byte) + Quantity of Registers (2 Bytes) :return:

class pymodbus.register_write_message.WriteMultipleRegistersResponse(address=None, count=None, **kwargs)

  Bases: `ModbusResponse`

  The normal response returns the function code.

  Starting address, and quantity of registers written.

  decode(data)

    Decode a write single register packet packet request.

    Parameters:

      data – The request to decode

  encode()

    Encode a write single register packet packet request.

    Returns:

      The encoded packet

  function_code = 16

class pymodbus.register_write_message.WriteSingleRegisterRequest(address=None, value=None, slave=None, **kwargs)

  Bases: `ModbusRequest`

  This function code is used to write a single holding register in a remote device.

  The Request PDU specifies the address of the register to be written. Registers are addressed starting at zero. Therefore register numbered 1 is addressed as 0.

  decode(data)

    Decode a write single register packet packet request.

    Parameters:

      data – The request to decode

  encode()

    Encode a write single register packet packet request.

    Returns:

      The encoded packet

  async execute(context)

    Run a write single register request against a datastore.

    Parameters:

      context – The datastore to request from

    Returns:

      An initialized response, exception message otherwise

  function_code = 6
  function_code_name = 'write_register'
  get_response_pdu_size()

    Get response pdu size.

    Func_code (1 byte) + Register Address(2 byte) + Register Value (2 bytes) :return:

class pymodbus.register_write_message.WriteSingleRegisterResponse(address=None, value=None, **kwargs)

  Bases: `ModbusResponse`

  The normal response is an echo of the request.

  Returned after the register contents have been written.

  decode(data)

    Decode a write single register packet packet request.

    Parameters:

      data – The request to decode

  encode()

    Encode a write single register packet packet request.

    Returns:

      The encoded packet

  function_code = 6
  get_response_pdu_size()

    Get response pdu size.

    Func_code (1 byte) + Starting Address (2 byte) + And_mask (2 Bytes) + OrMask (2 Bytes) :return:

Collection of transaction based abstractions.

class pymodbus.transaction.DictTransactionManager(client, **kwargs)

  Bases: `ModbusTransactionManager`

  Old alias for ModbusTransactionManager.

class pymodbus.transaction.ModbusAsciiFramer(decoder, client=None)

  Bases: `ModbusFramer`

  Modbus ASCII Frame Controller.

  > [ Start ][Address ][ Function ][ Data ][ LRC ][ End ]

  >   1c 2c 2c Nc 2c 2c

  > - data can be 0 - 2x252 chars

  > - end is “\r\n” (Carriage return line feed), however the line feed character can be changed via a special command

  > - start is “:”

  This framer is used for serial transmission. Unlike the RTU protocol, the data in this framer is transferred in plain text ascii.

  buildPacket(message)

    Create a ready to send modbus packet.

    Parameters:

      message – The request/response to send

    Returns:

      The encoded packet

  decode_data(data)

    Decode data.

  frameProcessIncomingPacket(single, callback, slave, _tid=None, **kwargs)

    Process new packet pattern.

  method = 'ascii'

class pymodbus.transaction.ModbusBinaryFramer(decoder, client=None)

  Bases: `ModbusFramer`

  Modbus Binary Frame Controller.

  > [ Start ][Address ][ Function ][ Data ][ CRC ][ End ]

  >   1b 1b 1b Nb 2b 1b

  > - data can be 0 - 2x252 chars

  > - end is “}”

  > - start is “{”

  The idea here is that we implement the RTU protocol, however, instead of using timing for message delimiting, we use start and end of message characters (in this case { and }). Basically, this is a binary framer.

  The only case we have to watch out for is when a message contains the { or } characters. If we encounter these characters, we simply duplicate them. Hopefully we will not encounter those characters that often and will save a little bit of bandwitch without a real-time system.

  Protocol defined by jamod.sourceforge.net.

  buildPacket(message)

    Create a ready to send modbus packet.

    Parameters:

      message – The request/response to send

    Returns:

      The encoded packet

  decode_data(data)

    Decode data.

  frameProcessIncomingPacket(single, callback, slave, _tid=None, **kwargs)

    Process new packet pattern.

  method = 'binary'

class pymodbus.transaction.ModbusRtuFramer(decoder, client=None)

  Bases: `ModbusFramer`

  Modbus RTU Frame controller.

  > [ Start Wait ] [Address ][ Function Code] [ Data ][ CRC ][ End Wait ]

  >   3.5 chars 1b 1b Nb 2b 3.5 chars

  Wait refers to the amount of time required to transmit at least x many characters. In this case it is 3.5 characters. Also, if we receive a wait of 1.5 characters at any point, we must trigger an error message. Also, it appears as though this message is little endian. The logic is simplified as the following:

      block-on-read:
          read until 3.5 delay
          check for errors
          decode

  The following table is a listing of the baud wait times for the specified baud rates:

      ------------------------------------------------------------------
       Baud  1.5c (18 bits)   3.5c (38 bits)
      ------------------------------------------------------------------
       1200   13333.3 us       31666.7 us
       4800    3333.3 us        7916.7 us
       9600    1666.7 us        3958.3 us
      19200     833.3 us        1979.2 us
      38400     416.7 us         989.6 us
      ------------------------------------------------------------------
      1 Byte = start + 8 bits + parity + stop = 11 bits
      (1/Baud)(bits) = delay seconds

  buildPacket(message)

    Create a ready to send modbus packet.

    Parameters:

      message – The populated request/response to send

  decode_data(data)

    Decode data.

  frameProcessIncomingPacket(_single, callback, slave, _tid=None, **kwargs)

    Process new packet pattern.

  method = 'rtu'
  recvPacket(size)

    Receive packet from the bus with specified len.

    Parameters:

      size – Number of bytes to read

    Returns:

  sendPacket(message)

    Send packets on the bus with 3.5char delay between frames.

    Parameters:

      message – Message to be sent over the bus

    Returns:

class pymodbus.transaction.ModbusSocketFramer(decoder, client=None)

  Bases: `ModbusFramer`

  Modbus Socket Frame controller.

  Before each modbus TCP message is an MBAP header which is used as a message frame. It allows us to easily separate messages as follows:

      [         MBAP Header         ] [ Function Code] [ Data ]         [ tid ][ pid ][ length ][ uid ]
        2b     2b     2b        1b           1b           Nb

      while len(message) > 0:
          tid, pid, length`, uid = struct.unpack(">HHHB", message)
          request = message[0:7 + length - 1`]
          message = [7 + length - 1:]

      * length = uid + function code + data
      * The -1 is to account for the uid byte

  buildPacket(message)

    Create a ready to send modbus packet.

    Parameters:

      message – The populated request/response to send

  decode_data(data)

    Decode data.

  frameProcessIncomingPacket(single, callback, slave, tid=None, **kwargs)

    Process new packet pattern.

    This takes in a new request packet, adds it to the current packet stream, and performs framing on it. That is, checks for complete messages, and once found, will process all that exist. This handles the case when we read N + 1 or 1 // N messages at a time instead of 1.

    The processed and decoded messages are pushed to the callback function to process and send.

  method = 'socket'

class pymodbus.transaction.ModbusTlsFramer(decoder, client=None)

  Bases: `ModbusFramer`

  Modbus TLS Frame controller.

  No prefix MBAP header before decrypted PDU is used as a message frame for Modbus Security Application Protocol. It allows us to easily separate decrypted messages which is PDU as follows:

  > [ Function Code] [ Data ]

  >   1b Nb

  buildPacket(message)

    Create a ready to send modbus packet.

    Parameters:

      message – The populated request/response to send

  decode_data(data)

    Decode data.

  frameProcessIncomingPacket(single, callback, slave, _tid=None, **kwargs)

    Process new packet pattern.

  method = 'tls'

class pymodbus.transaction.ModbusTransactionManager(client, **kwargs)

  Bases: `object`

  Implement a transaction for a manager.

  The transaction protocol can be represented by the following pseudo code:

      count = 0
      do
        result = send(message)
        if (timeout or result == bad)
           count++
        else break
      while (count < 3)

  This module helps to abstract this away from the framer and protocol.

  Results are keyed based on the supplied transaction id.

  addTransaction(request, tid=None)

    Add a transaction to the handler.

    This holds the request in case it needs to be resent. After being sent, the request is removed.

    Parameters:

      - request – The request to hold on to

      - tid – The overloaded transaction id to use

  delTransaction(tid)

    Remove a transaction matching the referenced tid.

    Parameters:

      tid – The transaction to remove

  execute(request)

    Start the producer to send the next request to consumer.write(Frame(request)).

  getNextTID()

    Retrieve the next unique transaction identifier.

    This handles incrementing the identifier after retrieval

    Returns:

      The next unique transaction identifier

  getTransaction(tid)

    Return a transaction matching the referenced tid.

    If the transaction does not exist, None is returned

    Parameters:

      tid – The transaction to retrieve

  reset()

    Reset the transaction identifier.

Modbus Utilities.

A collection of utilities for packing data, unpacking data computing checksums, and decode checksums.

pymodbus.utilities.default(value)

  Return the default value of object.

  Parameters:

    value – The value to get the default of

  Returns:

    The default value

pymodbus.utilities.pack_bitstring(bits: list[bool]) → bytes

  Create a bytestring out of a list of bits.

  Parameters:

    bits – A list of bits

  example:

      bits   = [False, True, False, True]
      result = pack_bitstring(bits)

pymodbus.utilities.rtuFrameSize(data, byte_count_pos)

  Calculate the size of the frame based on the byte count.

  Parameters:

    - data – The buffer containing the frame.

    - byte_count_pos – The index of the byte count in the buffer.

  Returns:

    The size of the frame.

  The structure of frames with a byte count field is always the same:

  - first, there are some header fields

  - then the byte count field

  - then as many data bytes as indicated by the byte count,

  - finally the CRC (two bytes).

  To calculate the frame size, it is therefore sufficient to extract the contents of the byte count field, add the position of this field, and finally increment the sum by three (one byte for the byte count field, two for the CRC).

pymodbus.utilities.unpack_bitstring(data: bytes) → list[bool]

  Create bit list out of a bytestring.

  Parameters:

    data – The modbus data packet to decode

  example:

      bytes  = "bytes to decode"
      result = unpack_bitstring(bytes)