Internal documentation for MinimalModbusΒΆ

MinimalModbus: A Python driver for the Modbus RTU and Modbus ASCII protocols via serial port (via RS485 or RS232).

minimalmodbus.BAUDRATE = 19200

Default value for the baudrate in Baud (int).

minimalmodbus.PARITY = 'N'

Default value for the parity. See the pySerial module for documentation. Defaults to serial.PARITY_NONE

minimalmodbus.BYTESIZE = 8

Default value for the bytesize (int).

minimalmodbus.STOPBITS = 1

Default value for the number of stopbits (int).

minimalmodbus.TIMEOUT = 0.05

Default value for the timeout value in seconds (float).

minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL = False

Default value for port closure setting.

class minimalmodbus.Instrument(port, slaveaddress, mode='rtu')[source]

Instrument class for talking to instruments (slaves) via the Modbus RTU or ASCII protocols (via RS485 or RS232).

Args:
  • port (str): The serial port name, for example /dev/ttyUSB0 (Linux), /dev/tty.usbserial (OS X) or COM4 (Windows).
  • slaveaddress (int): Slave address in the range 1 to 247 (use decimal numbers, not hex).
  • mode (str): Mode selection. Can be MODE_RTU or MODE_ASCII.
__init__(port, slaveaddress, mode='rtu')[source]
address = None

Slave address (int). Most often set by the constructor (see the class documentation).

mode = None

Slave mode (str), can be MODE_RTU or MODE_ASCII. Most often set by the constructor (see the class documentation).

New in version 0.6.

debug = None

Set this to True to print the communication details. Defaults to False.

close_port_after_each_call = None

If this is True, the serial port will be closed after each call. Defaults to CLOSE_PORT_AFTER_EACH_CALL. To change it, set the value minimalmodbus.CLOSE_PORT_AFTER_EACH_CALL=True .

precalculate_read_size = None

If this is False, the serial port reads until timeout instead of just reading a specific number of bytes. Defaults to True.

New in version 0.5.

handle_local_echo = None

Set to to True if your RS-485 adaptor has local echo enabled. Then the transmitted message will immeadiately appear at the receive line of the RS-485 adaptor. MinimalModbus will then read and discard this data, before reading the data from the slave. Defaults to False.

New in version 0.7.

__repr__()[source]

String representation of the Instrument object.

read_bit(registeraddress, functioncode=2)[source]

Read one bit from the slave.

Args:
  • registeraddress (int): The slave register address (use decimal numbers, not hex).
  • functioncode (int): Modbus function code. Can be 1 or 2.
Returns:
The bit value 0 or 1 (int).
Raises:
ValueError, TypeError, IOError
write_bit(registeraddress, value, functioncode=5)[source]

Write one bit to the slave.

Args:
  • registeraddress (int): The slave register address (use decimal numbers, not hex).
  • value (int): 0 or 1
  • functioncode (int): Modbus function code. Can be 5 or 15.
Returns:
None
Raises:
ValueError, TypeError, IOError
read_register(registeraddress, numberOfDecimals=0, functioncode=3, signed=False)[source]

Read an integer from one 16-bit register in the slave, possibly scaling it.

The slave register can hold integer values in the range 0 to 65535 (“Unsigned INT16”).

Args:
  • registeraddress (int): The slave register address (use decimal numbers, not hex).
  • numberOfDecimals (int): The number of decimals for content conversion.
  • functioncode (int): Modbus function code. Can be 3 or 4.
  • signed (bool): Whether the data should be interpreted as unsigned or signed.

If a value of 77.0 is stored internally in the slave register as 770, then use numberOfDecimals=1 which will divide the received data by 10 before returning the value.

Similarly numberOfDecimals=2 will divide the received data by 100 before returning the value.

Some manufacturers allow negative values for some registers. Instead of an allowed integer range 0 to 65535, a range -32768 to 32767 is allowed. This is implemented as any received value in the upper range (32768 to 65535) is interpreted as negative value (in the range -32768 to -1).

Use the parameter signed=True if reading from a register that can hold negative values. Then upper range data will be automatically converted into negative return values (two’s complement).

signed Data type in slave Alternative name Range
False Unsigned INT16 Unsigned short 0 to 65535
True INT16 Short -32768 to 32767
Returns:
The register data in numerical value (int or float).
Raises:
ValueError, TypeError, IOError
write_register(registeraddress, value, numberOfDecimals=0, functioncode=16, signed=False)[source]

Write an integer to one 16-bit register in the slave, possibly scaling it.

The slave register can hold integer values in the range 0 to 65535 (“Unsigned INT16”).

Args:
  • registeraddress (int): The slave register address (use decimal numbers, not hex).
  • value (int or float): The value to store in the slave register (might be scaled before sending).
  • numberOfDecimals (int): The number of decimals for content conversion.
  • functioncode (int): Modbus function code. Can be 6 or 16.
  • signed (bool): Whether the data should be interpreted as unsigned or signed.

To store for example value=77.0, use numberOfDecimals=1 if the slave register will hold it as 770 internally. This will multiply value by 10 before sending it to the slave register.

Similarly numberOfDecimals=2 will multiply value by 100 before sending it to the slave register.

For discussion on negative values, the range and on alternative names, see read_register().

Use the parameter signed=True if writing to a register that can hold negative values. Then negative input will be automatically converted into upper range data (two’s complement).

Returns:
None
Raises:
ValueError, TypeError, IOError
read_long(registeraddress, functioncode=3, signed=False)[source]

Read a long integer (32 bits) from the slave.

Long integers (32 bits = 4 bytes) are stored in two consecutive 16-bit registers in the slave.

Args:
  • registeraddress (int): The slave register start address (use decimal numbers, not hex).
  • functioncode (int): Modbus function code. Can be 3 or 4.
  • signed (bool): Whether the data should be interpreted as unsigned or signed.
signed Data type in slave Alternative name Range
False Unsigned INT32 Unsigned long 0 to 4294967295
True INT32 Long -2147483648 to 2147483647
Returns:
The numerical value (int).
Raises:
ValueError, TypeError, IOError
write_long(registeraddress, value, signed=False)[source]

Write a long integer (32 bits) to the slave.

Long integers (32 bits = 4 bytes) are stored in two consecutive 16-bit registers in the slave.

Uses Modbus function code 16.

For discussion on number of bits, number of registers, the range and on alternative names, see read_long().

Args:
  • registeraddress (int): The slave register start address (use decimal numbers, not hex).
  • value (int or long): The value to store in the slave.
  • signed (bool): Whether the data should be interpreted as unsigned or signed.
Returns:
None
Raises:
ValueError, TypeError, IOError
read_float(registeraddress, functioncode=3, numberOfRegisters=2)[source]

Read a floating point number from the slave.

Floats are stored in two or more consecutive 16-bit registers in the slave. The encoding is according to the standard IEEE 754.

There are differences in the byte order used by different manufacturers. A floating point value of 1.0 is encoded (in single precision) as 3f800000 (hex). In this implementation the data will be sent as '\x3f\x80' and '\x00\x00' to two consecutetive registers . Make sure to test that it makes sense for your instrument. It is pretty straight-forward to change this code if some other byte order is required by anyone (see support section).

Args:
  • registeraddress (int): The slave register start address (use decimal numbers, not hex).
  • functioncode (int): Modbus function code. Can be 3 or 4.
  • numberOfRegisters (int): The number of registers allocated for the float. Can be 2 or 4.
Type of floating point number in slave Size Registers Range
Single precision (binary32) 32 bits (4 bytes) 2 registers 1.4E-45 to 3.4E38
Double precision (binary64) 64 bits (8 bytes) 4 registers 5E-324 to 1.8E308
Returns:
The numerical value (float).
Raises:
ValueError, TypeError, IOError
write_float(registeraddress, value, numberOfRegisters=2)[source]

Write a floating point number to the slave.

Floats are stored in two or more consecutive 16-bit registers in the slave.

Uses Modbus function code 16.

For discussion on precision, number of registers and on byte order, see read_float().

Args:
  • registeraddress (int): The slave register start address (use decimal numbers, not hex).
  • value (float or int): The value to store in the slave
  • numberOfRegisters (int): The number of registers allocated for the float. Can be 2 or 4.
Returns:
None
Raises:
ValueError, TypeError, IOError
read_string(registeraddress, numberOfRegisters=16, functioncode=3)[source]

Read a string from the slave.

Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes).

Args:
  • registeraddress (int): The slave register start address (use decimal numbers, not hex).
  • numberOfRegisters (int): The number of registers allocated for the string.
  • functioncode (int): Modbus function code. Can be 3 or 4.
Returns:
The string (str).
Raises:
ValueError, TypeError, IOError
write_string(registeraddress, textstring, numberOfRegisters=16)[source]

Write a string to the slave.

Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes).

Uses Modbus function code 16.

Args:
  • registeraddress (int): The slave register start address (use decimal numbers, not hex).
  • textstring (str): The string to store in the slave
  • numberOfRegisters (int): The number of registers allocated for the string.

If the textstring is longer than the 2*numberOfRegisters, an error is raised. Shorter strings are padded with spaces.

Returns:
None
Raises:
ValueError, TypeError, IOError
read_registers(registeraddress, numberOfRegisters, functioncode=3)[source]

Read integers from 16-bit registers in the slave.

The slave registers can hold integer values in the range 0 to 65535 (“Unsigned INT16”).

Args:
  • registeraddress (int): The slave register start address (use decimal numbers, not hex).
  • numberOfRegisters (int): The number of registers to read.
  • functioncode (int): Modbus function code. Can be 3 or 4.

Any scaling of the register data, or converting it to negative number (two’s complement) must be done manually.

Returns:
The register data (a list of int).
Raises:
ValueError, TypeError, IOError
write_registers(registeraddress, values)[source]

Write integers to 16-bit registers in the slave.

The slave register can hold integer values in the range 0 to 65535 (“Unsigned INT16”).

Uses Modbus function code 16.

The number of registers that will be written is defined by the length of the values list.

Args:
  • registeraddress (int): The slave register start address (use decimal numbers, not hex).
  • values (list of int): The values to store in the slave registers.

Any scaling of the register data, or converting it to negative number (two’s complement) must be done manually.

Returns:
None
Raises:
ValueError, TypeError, IOError
_genericCommand(functioncode, registeraddress, value=None, numberOfDecimals=0, numberOfRegisters=1, signed=False, payloadformat=None)[source]

Generic command for reading and writing registers and bits.

Args:
  • functioncode (int): Modbus function code.
  • registeraddress (int): The register address (use decimal numbers, not hex).
  • value (numerical or string or None or list of int): The value to store in the register. Depends on payloadformat.
  • numberOfDecimals (int): The number of decimals for content conversion. Only for a single register.
  • numberOfRegisters (int): The number of registers to read/write. Only certain values allowed, depends on payloadformat.
  • signed (bool): Whether the data should be interpreted as unsigned or signed. Only for a single register or for payloadformat=’long’.
  • payloadformat (None or string): None, ‘long’, ‘float’, ‘string’, ‘register’, ‘registers’. Not necessary for single registers or bits.

If a value of 77.0 is stored internally in the slave register as 770, then use numberOfDecimals=1 which will divide the received data from the slave by 10 before returning the value. Similarly numberOfDecimals=2 will divide the received data by 100 before returning the value. Same functionality is also used when writing data to the slave.

Returns:
The register data in numerical value (int or float), or the bit value 0 or 1 (int), or None.
Raises:
ValueError, TypeError, IOError
_performCommand(functioncode, payloadToSlave)[source]

Performs the command having the functioncode.

Args:
  • functioncode (int): The function code for the command to be performed. Can for example be ‘Write register’ = 16.
  • payloadToSlave (str): Data to be transmitted to the slave (will be embedded in slaveaddress, CRC etc)
Returns:
The extracted data payload from the slave (a string). It has been stripped of CRC etc.
Raises:
ValueError, TypeError.

Makes use of the _communicate() method. The request is generated with the _embedPayload() function, and the parsing of the response is done with the _extractPayload() function.

_communicate(request, number_of_bytes_to_read)[source]

Talk to the slave via a serial port.

Args:
request (str): The raw request that is to be sent to the slave. number_of_bytes_to_read (int): number of bytes to read
Returns:
The raw data (string) returned from the slave.
Raises:
TypeError, ValueError, IOError

Note that the answer might have strange ASCII control signs, which makes it difficult to print it in the promt (messes up a bit). Use repr() to make the string printable (shows ASCII values for control signs.)

Will block until reaching number_of_bytes_to_read or timeout.

If the attribute Instrument.debug is True, the communication details are printed.

If the attribute Instrument.close_port_after_each_call is True the serial port is closed after each call.

Timing:

                                      Request from master (Master is writing)
                                      |
                                      |       Response from slave (Master is reading)
                                      |       |
----W----R----------------------------W-------R----------------------------------------
         |                            |       |
         |<----- Silent period ------>|       |
                                      |       |
                 Roundtrip time  ---->|-------|<--

The resolution for Python’s time.time() is lower on Windows than on Linux. It is about 16 ms on Windows according to http://stackoverflow.com/questions/157359/accurate-timestamping-in-python

For Python3, the information sent to and from pySerial should be of the type bytes. This is taken care of automatically by MinimalModbus.

__module__ = 'minimalmodbus'
minimalmodbus._embedPayload(slaveaddress, mode, functioncode, payloaddata)[source]

Build a request from the slaveaddress, the function code and the payload data.

Args:
  • slaveaddress (int): The address of the slave.
  • mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
  • functioncode (int): The function code for the command to be performed. Can for example be 16 (Write register).
  • payloaddata (str): The byte string to be sent to the slave.
Returns:
The built (raw) request string for sending to the slave (including CRC etc).
Raises:
ValueError, TypeError.
The resulting request has the format:
  • RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes).
  • ASCII Mode: header (:) + slaveaddress (2 characters) + functioncode (2 characters) + payloaddata + LRC (which is two characters) + footer (CRLF)

The LRC or CRC is calculated from the byte string made up of slaveaddress + functioncode + payloaddata. The header, LRC/CRC, and footer are excluded from the calculation.

minimalmodbus._extractPayload(response, slaveaddress, mode, functioncode)[source]

Extract the payload data part from the slave’s response.

Args:
  • response (str): The raw response byte string from the slave.
  • slaveaddress (int): The adress of the slave. Used here for error checking only.
  • mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
  • functioncode (int): Used here for error checking only.
Returns:
The payload part of the response string.
Raises:
ValueError, TypeError. Raises an exception if there is any problem with the received address, the functioncode or the CRC.

The received response should have the format: * RTU Mode: slaveaddress byte + functioncode byte + payloaddata + CRC (which is two bytes) * ASCII Mode: header (:) + slaveaddress byte + functioncode byte + payloaddata + LRC (which is two characters) + footer (CRLF)

For development purposes, this function can also be used to extract the payload from the request sent TO the slave.

minimalmodbus._predictResponseSize(mode, functioncode, payloadToSlave)[source]

Calculate the number of bytes that should be received from the slave.

Args:
  • mode (str): The modbus protcol mode (MODE_RTU or MODE_ASCII)
  • functioncode (int): Modbus function code.
  • payloadToSlave (str): The raw request that is to be sent to the slave (not hex encoded string)
Returns:
The preducted number of bytes (int) in the response.
Raises:
ValueError, TypeError.
minimalmodbus._calculate_minimum_silent_period(baudrate)[source]

Calculate the silent period length to comply with the 3.5 character silence between messages.

Args:
baudrate (numerical): The baudrate for the serial port
Returns:
The number of seconds (float) that should pass between each message on the bus.
Raises:
ValueError, TypeError.
minimalmodbus._numToOneByteString(inputvalue)[source]

Convert a numerical value to a one-byte string.

Args:
inputvalue (int): The value to be converted. Should be >=0 and <=255.
Returns:
A one-byte string created by chr(inputvalue).
Raises:
TypeError, ValueError
minimalmodbus._numToTwoByteString(value, numberOfDecimals=0, LsbFirst=False, signed=False)[source]

Convert a numerical value to a two-byte string, possibly scaling it.

Args:
  • value (float or int): The numerical value to be converted.
  • numberOfDecimals (int): Number of decimals, 0 or more, for scaling.
  • LsbFirst (bol): Whether the least significant byte should be first in the resulting string.
  • signed (bol): Whether negative values should be accepted.
Returns:
A two-byte string.
Raises:
TypeError, ValueError. Gives DeprecationWarning instead of ValueError for some values in Python 2.6.

Use numberOfDecimals=1 to multiply value by 10 before sending it to the slave register. Similarly numberOfDecimals=2 will multiply value by 100 before sending it to the slave register.

Use the parameter signed=True if making a bytestring that can hold negative values. Then negative input will be automatically converted into upper range data (two’s complement).

The byte order is controlled by the LsbFirst parameter, as seen here:

LsbFirst parameter Endianness Description
False (default) Big-endian Most significant byte is sent first
True Little-endian Least significant byte is sent first
For example:
To store for example value=77.0, use numberOfDecimals = 1 if the register will hold it as 770 internally. The value 770 (dec) is 0302 (hex), where the most significant byte is 03 (hex) and the least significant byte is 02 (hex). With LsbFirst = False, the most significant byte is given first why the resulting string is \x03\x02, which has the length 2.
minimalmodbus._twoByteStringToNum(bytestring, numberOfDecimals=0, signed=False)[source]

Convert a two-byte string to a numerical value, possibly scaling it.

Args:
  • bytestring (str): A string of length 2.
  • numberOfDecimals (int): The number of decimals. Defaults to 0.
  • signed (bol): Whether large positive values should be interpreted as negative values.
Returns:
The numerical value (int or float) calculated from the bytestring.
Raises:
TypeError, ValueError

Use the parameter signed=True if converting a bytestring that can hold negative values. Then upper range data will be automatically converted into negative return values (two’s complement).

Use numberOfDecimals=1 to divide the received data by 10 before returning the value. Similarly numberOfDecimals=2 will divide the received data by 100 before returning the value.

The byte order is big-endian, meaning that the most significant byte is sent first.

For example:
A string \x03\x02 (which has the length 2) corresponds to 0302 (hex) = 770 (dec). If numberOfDecimals = 1, then this is converted to 77.0 (float).
minimalmodbus._longToBytestring(value, signed=False, numberOfRegisters=2)[source]

Convert a long integer to a bytestring.

Long integers (32 bits = 4 bytes) are stored in two consecutive 16-bit registers in the slave.

Args:
  • value (int): The numerical value to be converted.
  • signed (bool): Whether large positive values should be interpreted as negative values.
  • numberOfRegisters (int): Should be 2. For error checking only.
Returns:
A bytestring (4 bytes).
Raises:
TypeError, ValueError
minimalmodbus._bytestringToLong(bytestring, signed=False, numberOfRegisters=2)[source]

Convert a bytestring to a long integer.

Long integers (32 bits = 4 bytes) are stored in two consecutive 16-bit registers in the slave.

Args:
  • bytestring (str): A string of length 4.
  • signed (bol): Whether large positive values should be interpreted as negative values.
  • numberOfRegisters (int): Should be 2. For error checking only.
Returns:
The numerical value (int).
Raises:
ValueError, TypeError
minimalmodbus._floatToBytestring(value, numberOfRegisters=2)[source]

Convert a numerical value to a bytestring.

Floats are stored in two or more consecutive 16-bit registers in the slave. The encoding is according to the standard IEEE 754.

Type of floating point number in slave Size Registers Range
Single precision (binary32) 32 bits (4 bytes) 2 registers 1.4E-45 to 3.4E38
Double precision (binary64) 64 bits (8 bytes) 4 registers 5E-324 to 1.8E308

A floating point value of 1.0 is encoded (in single precision) as 3f800000 (hex). This will give a byte string '\x3f\x80\x00\x00' (big endian).

Args:
  • value (float or int): The numerical value to be converted.
  • numberOfRegisters (int): Can be 2 or 4.
Returns:
A bytestring (4 or 8 bytes).
Raises:
TypeError, ValueError
minimalmodbus._bytestringToFloat(bytestring, numberOfRegisters=2)[source]

Convert a four-byte string to a float.

Floats are stored in two or more consecutive 16-bit registers in the slave.

For discussion on precision, number of bits, number of registers, the range, byte order and on alternative names, see minimalmodbus._floatToBytestring().

Args:
  • bytestring (str): A string of length 4 or 8.
  • numberOfRegisters (int): Can be 2 or 4.
Returns:
A float.
Raises:
TypeError, ValueError
minimalmodbus._textstringToBytestring(inputstring, numberOfRegisters=16)[source]

Convert a text string to a bytestring.

Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes).

Not much of conversion is done, mostly error checking and string padding. If the inputstring is shorter that the allocated space, it is padded with spaces in the end.

Args:
  • inputstring (str): The string to be stored in the slave. Max 2*numberOfRegisters characters.
  • numberOfRegisters (int): The number of registers allocated for the string.
Returns:
A bytestring (str).
Raises:
TypeError, ValueError
minimalmodbus._bytestringToTextstring(bytestring, numberOfRegisters=16)[source]

Convert a bytestring to a text string.

Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes).

Not much of conversion is done, mostly error checking.

Args:
  • bytestring (str): The string from the slave. Length = 2*numberOfRegisters
  • numberOfRegisters (int): The number of registers allocated for the string.
Returns:
A the text string (str).
Raises:
TypeError, ValueError
minimalmodbus._valuelistToBytestring(valuelist, numberOfRegisters)[source]

Convert a list of numerical values to a bytestring.

Each element is ‘unsigned INT16’.

Args:
  • valuelist (list of int): The input list. The elements should be in the range 0 to 65535.
  • numberOfRegisters (int): The number of registers. For error checking.
Returns:
A bytestring (str). Length = 2*numberOfRegisters
Raises:
TypeError, ValueError
minimalmodbus._bytestringToValuelist(bytestring, numberOfRegisters)[source]

Convert a bytestring to a list of numerical values.

The bytestring is interpreted as ‘unsigned INT16’.

Args:
  • bytestring (str): The string from the slave. Length = 2*numberOfRegisters
  • numberOfRegisters (int): The number of registers. For error checking.
Returns:
A list of integers.
Raises:
TypeError, ValueError
minimalmodbus._pack(formatstring, value)[source]

Pack a value into a bytestring.

Uses the built-in struct Python module.

Args:
  • formatstring (str): String for the packing. See the struct module for details.
  • value (depends on formatstring): The value to be packed
Returns:
A bytestring (str).
Raises:
ValueError

Note that the struct module produces byte buffers for Python3, but bytestrings for Python2. This is compensated for automatically.

minimalmodbus._unpack(formatstring, packed)[source]

Unpack a bytestring into a value.

Uses the built-in struct Python module.

Args:
  • formatstring (str): String for the packing. See the struct module for details.
  • packed (str): The bytestring to be unpacked.
Returns:
A value. The type depends on the formatstring.
Raises:
ValueError

Note that the struct module wants byte buffers for Python3, but bytestrings for Python2. This is compensated for automatically.

minimalmodbus._hexencode(bytestring, insert_spaces=False)[source]

Convert a byte string to a hex encoded string.

For example ‘J’ will return ‘4A’, and '\x04' will return ‘04’.

Args:
bytestring (str): Can be for example 'A\x01B\x45'. insert_spaces (bool): Insert space characters between pair of characters to increase readability.
Returns:
A string of twice the length, with characters in the range ‘0’ to ‘9’ and ‘A’ to ‘F’. The string will be longer if spaces are inserted.
Raises:
TypeError, ValueError
minimalmodbus._hexdecode(hexstring)[source]

Convert a hex encoded string to a byte string.

For example ‘4A’ will return ‘J’, and ‘04’ will return '\x04' (which has length 1).

Args:
hexstring (str): Can be for example ‘A3’ or ‘A3B4’. Must be of even length. Allowed characters are ‘0’ to ‘9’, ‘a’ to ‘f’ and ‘A’ to ‘F’ (not space).
Returns:
A string of half the length, with characters corresponding to all 0-255 values for each byte.
Raises:
TypeError, ValueError
minimalmodbus._hexlify(bytestring)[source]

Convert a byte string to a hex encoded string, with spaces for easier reading.

This is just a facade for _hexencode() with insert_spaces = True.

See _hexencode() for details.

minimalmodbus._bitResponseToValue(bytestring)[source]

Convert a response string to a numerical value.

Args:
bytestring (str): A string of length 1. Can be for example \x01.
Returns:
The converted value (int).
Raises:
TypeError, ValueError
minimalmodbus._createBitpattern(functioncode, value)[source]

Create the bit pattern that is used for writing single bits.

This is basically a storage of numerical constants.

Args:
  • functioncode (int): can be 5 or 15
  • value (int): can be 0 or 1
Returns:
The bit pattern (string).
Raises:
TypeError, ValueError
minimalmodbus._twosComplement(x, bits=16)[source]

Calculate the two’s complement of an integer.

Then also negative values can be represented by an upper range of positive values. See https://en.wikipedia.org/wiki/Two%27s_complement

Args:
  • x (int): input integer.
  • bits (int): number of bits, must be > 0.
Returns:
An int, that represents the two’s complement of the input.

Example for bits=8:

x returns
0 0
1 1
127 127
-128 128
-127 129
-1 255
minimalmodbus._fromTwosComplement(x, bits=16)[source]

Calculate the inverse(?) of a two’s complement of an integer.

Args:
  • x (int): input integer.
  • bits (int): number of bits, must be > 0.
Returns:
An int, that represents the inverse(?) of two’s complement of the input.

Example for bits=8:

x returns
0 0
1 1
127 127
128 -128
129 -127
255 -1
minimalmodbus._setBitOn(x, bitNum)[source]

Set bit ‘bitNum’ to True.

Args:
  • x (int): The value before.
  • bitNum (int): The bit number that should be set to True.
Returns:
The value after setting the bit. This is an integer.
For example:
For x = 4 (dec) = 0100 (bin), setting bit number 0 results in 0101 (bin) = 5 (dec).
minimalmodbus._calculateCrcString(inputstring)[source]

Calculate CRC-16 for Modbus.

Args:
inputstring (str): An arbitrary-length message (without the CRC).
Returns:
A two-byte CRC string, where the least significant byte is first.
minimalmodbus._calculateLrcString(inputstring)[source]

Calculate LRC for Modbus.

Args:
inputstring (str): An arbitrary-length message (without the beginning colon and terminating CRLF). It should already be decoded from hex-string.
Returns:
A one-byte LRC bytestring (not encoded to hex-string)

Algorithm from the document ‘MODBUS over serial line specification and implementation guide V1.02’.

The LRC is calculated as 8 bits (one byte).

For example a LRC 0110 0001 (bin) = 61 (hex) = 97 (dec) = ‘a’. This function will then return ‘a’.

In Modbus ASCII mode, this should be transmitted using two characters. This example should be transmitted ‘61’, which is a string of length two. This function does not handle that conversion for transmission.

minimalmodbus._checkMode(mode)[source]

Check that the Modbus mode is valie.

Args:
mode (string): The Modbus mode (MODE_RTU or MODE_ASCII)
Raises:
TypeError, ValueError
minimalmodbus._checkFunctioncode(functioncode, listOfAllowedValues=[])[source]

Check that the given functioncode is in the listOfAllowedValues.

Also verifies that 1 <= function code <= 127.

Args:
  • functioncode (int): The function code
  • listOfAllowedValues (list of int): Allowed values. Use None to bypass this part of the checking.
Raises:
TypeError, ValueError
minimalmodbus._checkSlaveaddress(slaveaddress)[source]

Check that the given slaveaddress is valid.

Args:
slaveaddress (int): The slave address
Raises:
TypeError, ValueError
minimalmodbus._checkRegisteraddress(registeraddress)[source]

Check that the given registeraddress is valid.

Args:
registeraddress (int): The register address
Raises:
TypeError, ValueError
minimalmodbus._checkResponseByteCount(payload)[source]

Check that the number of bytes as given in the response is correct.

The first byte in the payload indicates the length of the payload (first byte not counted).

Args:
payload (string): The payload
Raises:
TypeError, ValueError
minimalmodbus._checkResponseRegisterAddress(payload, registeraddress)[source]

Check that the start adress as given in the response is correct.

The first two bytes in the payload holds the address value.

Args:
  • payload (string): The payload
  • registeraddress (int): The register address (use decimal numbers, not hex).
Raises:
TypeError, ValueError
minimalmodbus._checkResponseNumberOfRegisters(payload, numberOfRegisters)[source]

Check that the number of written registers as given in the response is correct.

The bytes 2 and 3 (zero based counting) in the payload holds the value.

Args:
  • payload (string): The payload
  • numberOfRegisters (int): Number of registers that have been written
Raises:
TypeError, ValueError
minimalmodbus._checkResponseWriteData(payload, writedata)[source]

Check that the write data as given in the response is correct.

The bytes 2 and 3 (zero based counting) in the payload holds the write data.

Args:
  • payload (string): The payload
  • writedata (string): The data to write, length should be 2 bytes.
Raises:
TypeError, ValueError
minimalmodbus._checkString(inputstring, description, minlength=0, maxlength=None)[source]

Check that the given string is valid.

Args:
  • inputstring (string): The string to be checked
  • description (string): Used in error messages for the checked inputstring
  • minlength (int): Minimum length of the string
  • maxlength (int or None): Maximum length of the string
Raises:
TypeError, ValueError

Uses the function _checkInt() internally.

minimalmodbus._checkInt(inputvalue, minvalue=None, maxvalue=None, description='inputvalue')[source]

Check that the given integer is valid.

Args:
  • inputvalue (int or long): The integer to be checked
  • minvalue (int or long, or None): Minimum value of the integer
  • maxvalue (int or long, or None): Maximum value of the integer
  • description (string): Used in error messages for the checked inputvalue
Raises:
TypeError, ValueError

Note: Can not use the function _checkString(), as that function uses this function internally.

minimalmodbus._checkNumerical(inputvalue, minvalue=None, maxvalue=None, description='inputvalue')[source]

Check that the given numerical value is valid.

Args:
  • inputvalue (numerical): The value to be checked.
  • minvalue (numerical): Minimum value Use None to skip this part of the test.
  • maxvalue (numerical): Maximum value. Use None to skip this part of the test.
  • description (string): Used in error messages for the checked inputvalue
Raises:
TypeError, ValueError

Note: Can not use the function _checkString(), as it uses this function internally.

minimalmodbus._checkBool(inputvalue, description='inputvalue')[source]

Check that the given inputvalue is a boolean.

Args:
  • inputvalue (boolean): The value to be checked.
  • description (string): Used in error messages for the checked inputvalue.
Raises:
TypeError, ValueError
minimalmodbus._print_out(inputstring)[source]

Print the inputstring. To make it compatible with Python2 and Python3.

Args:
inputstring (str): The string that should be printed.
Raises:
TypeError
minimalmodbus._interpretRawMessage(inputstr)[source]

Generate a human readable description of a Modbus bytestring.

Args:
inputstr (str): The bytestring that should be interpreted.
Returns:
A descriptive string.

For example, the string '\n\x03\x10\x01\x00\x01\xd0q' should give something like:

TODO: update

Modbus bytestring decoder
Input string (length 8 characters): '\n\x03\x10\x01\x00\x01\xd0q'
Probably modbus RTU mode.
Slave address: 10 (dec). Function code: 3 (dec).
Valid message. Extracted payload: '\x10\x01\x00\x01'

Pos   Character Hex  Dec  Probable interpretation 
-------------------------------------------------
  0:  '\n'      0A    10  Slave address 
  1:  '\x03'    03     3  Function code 
  2:  '\x10'    10    16  Payload    
  3:  '\x01'    01     1  Payload    
  4:  '\x00'    00     0  Payload    
  5:  '\x01'    01     1  Payload    
  6:  '\xd0'    D0   208  Checksum, CRC LSB 
  7:  'q'       71   113  Checksum, CRC MSB 
minimalmodbus._interpretPayload(functioncode, payload)[source]

Generate a human readable description of a Modbus payload.

Args:
  • functioncode (int): Function code
  • payload (str): The payload that should be interpreted. It should be a byte string.
Returns:
A descriptive string.

For example, the payload '\x10\x01\x00\x01' for functioncode 3 should give something like:

TODO: Update
minimalmodbus._getDiagnosticString()[source]

Generate a diagnostic string, showing the module version, the platform, current directory etc.

Returns:
A descriptive string.