Pymodbustcp Documentation: Release 0.1.10
Pymodbustcp Documentation: Release 0.1.10
Release 0.1.10
Loïc Lefebvre
3 pyModbusTCP examples 17
3.1 An example for add float support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2 Simple read registers example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.3 Simple read bits example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.4 Simple write bits example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.5 An example with a modbus polling thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.6 Simple blocking server example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.7 Server example with alive word and downtime period . . . . . . . . . . . . . . . . . . . . . . . . . 22
Index 29
i
ii
CHAPTER 1
pyModbusTCP give access to modbus/TCP server through the ModbusClient object. This class is define in the client
module.
Since version 0.1.0, a server is available as ModbusServer class. This server is currently in test (API can change at any
time).
To deal with frequent need of modbus data mangling (for example convert 32 bits IEEE float to 2x16 bits words) a
special module named utils provide some helpful functions.
Package map:
from PyPi:
# for Python 2
sudo pip2 install pyModbusTCP
# or for Python 3
(continues on next page)
1
pyModbusTCP Documentation, Release 0.1.10
from Github:
you can also init module from functions host/port return None if error:
Now, it’s possible to use auto mode to let module deal with TCP open/close.
For keep TCP open, add auto_open=True in init:
c = ModbusClient(host="localhost", auto_open=True)
You can also open manually the TCP link. After this, you call a modbus request function (see list in next section):
if c.open():
regs_list_1 = c.read_holding_registers(0, 10)
regs_list_2 = c.read_holding_registers(55, 10)
c.close()
while True:
if c.is_open():
regs_list_1 = c.read_holding_registers(0, 10)
regs_list_2 = c.read_holding_registers(55, 10)
else:
c.open()
time.sleep(1)
If need, you can enable a debug mode for ModbusClient like this:
or:
c.debug(True)
when debug is enable all debug message is print on console and you can see modbus frame:
c.read_holding_registers(0, 4)
print:
Tx
[E7 53 00 00 00 06 01] 03 00 00 00 04
Rx
[E7 53 00 00 00 0B 01] 03 08 00 00 00 6F 00 00 00 00
[0, 111, 0, 0]
# display "-1"
print(utils.get_2comp(list_16_bits[1], 16))
Contents:
This module provide the ModbusClient class used to deal with modbus server.
7
pyModbusTCP Documentation, Release 0.1.10
read_holding_registers(reg_addr, reg_nb=1)
Modbus function READ_HOLDING_REGISTERS (0x03)
Parameters
• reg_addr (int) – register address (0 to 65535)
• reg_nb (int) – number of registers to read (1 to 125)
Returns registers list or None if fail
Return type list of int or None
read_input_registers(reg_addr, reg_nb=1)
Modbus function READ_INPUT_REGISTERS (0x04)
Parameters
• reg_addr (int) – register address (0 to 65535)
• reg_nb (int) – number of registers to read (1 to 125)
Returns registers list or None if fail
Return type list of int or None
timeout(timeout=None)
Get or set timeout field
Parameters timeout (float or None) – socket timeout in seconds or None for get value
Returns timeout or None if set fail
Return type float or None
unit_id(unit_id=None)
Get or set unit ID field
Parameters unit_id (int or None) – unit ID (0 to 255) or None for get value
Returns unit ID or None if set fail
Return type int or None
version()
Get package version
Returns current version of the package (like “0.0.1”)
Return type str
write_multiple_coils(bits_addr, bits_value)
Modbus function WRITE_MULTIPLE_COILS (0x0F)
Parameters
• bits_addr (int) – bits address (0 to 65535)
• bits_value (list) – bits values to write
Returns True if write ok or None if fail
Return type bool or None
write_multiple_registers(regs_addr, regs_value)
Modbus function WRITE_MULTIPLE_REGISTERS (0x10)
Parameters
class pyModbusTCP.server.DataBank
Data class for thread safe access to bits and words space
classmethod get_bits(address, number=1)
Read data on server bits space
Parameters
• address (int) – start address
• number (int) – number of bits (optional)
Returns list of bool or None if error
Return type list or None
classmethod get_words(address, number=1)
Read data on server words space
Parameters
• address (int) – start address
• number (int) – number of words (optional)
Returns list of int or None if error
Return type list or None
classmethod set_bits(address, bit_list)
Write data to server bits space
Parameters
• address (int) – start address
• bit_list (list) – a list of bool to write
Returns True if success or None if error
Return type bool or None
Raises ValueError – if bit_list members cannot be convert to bool
classmethod set_words(address, word_list)
Write data to server words space
Parameters
• address (int) – start address
• word_list (list) – a list of word to write
Returns True if success or None if error
Return type bool or None
Raises ValueError – if word_list members cannot be convert to int
pyModbusTCP.utils.get_bits_from_int(val_int, val_size=16)
Get the list of bits of val_int integer (default size is 16 bits)
Return bits list, least significant bit first. Use list.reverse() if need.
Parameters
• val_int (int) – integer value
• val_size (int) – bit size of integer (word = 16, long = 32) (optional)
Returns list of boolean “bits” (least significant first)
Return type list
pyModbusTCP.utils.set_bit(value, offset)
Set a bit at offset position
Parameters
• value (int) – value of integer where set the bit
• offset (int) – bit offset (0 is lsb)
Returns value of integer with bit set
Return type int
pyModbusTCP.utils.reset_bit(value, offset)
Reset a bit at offset position
Parameters
• value (int) – value of integer where reset the bit
• offset (int) – bit offset (0 is lsb)
Returns value of integer with bit reset
Return type int
pyModbusTCP.utils.toggle_bit(value, offset)
Return an integer with the bit at offset position inverted
Parameters
• value (int) – value of integer where invert the bit
• offset (int) – bit offset (0 is lsb)
Returns value of integer with bit inverted
Return type int
pyModbusTCP.utils.test_bit(value, offset)
Test a bit at offset position
Parameters
• value (int) – value of integer to test
• offset (int) – bit offset (0 is lsb)
Returns value of bit at offset position
Return type bool
pyModbusTCP.utils.get_2comp(val_int, val_size=16)
Get the 2’s complement of Python int val_int
Parameters
• val_int (int) – int value to apply 2’s complement
• val_size (int) – bit size of int value (word = 16, long = 32) (optional)
Returns 2’s complement result
Return type int
Raises ValueError – if mismatch between val_int and val_size
pyModbusTCP.utils.get_list_2comp(val_list, val_size=16)
Get the 2’s complement of Python list val_list
Parameters
• val_list (list) – list of int value to apply 2’s complement
• val_size (int) – bit size of int value (word = 16, long = 32) (optional)
Returns 2’s complement result
pyModbusTCP.utils.decode_ieee(val_int, double=False)
Decode Python int (32 bits integer) as an IEEE single or double precision format
Support NaN.
Parameters
• val_int (int) – a 32 or 64 bits integer as an int Python value
• double (bool) – set to decode as a 64 bits double precision, default is 32 bits single
(optional)
Returns float result
Return type float
pyModbusTCP.utils.encode_ieee(val_float, double=False)
Encode Python float to int (32 bits integer) as an IEEE single or double precision format
Support NaN.
Parameters
• val_float (float) – float value to convert
• double (bool) – set to encode as a 64 bits double precision, default is 32 bits single
(optional)
Returns IEEE 32 bits (single precision) as Python int
Return type int
pyModbusTCP.utils.crc16(frame)
Compute CRC16
Parameters frame (str (Python2) or class bytes (Python3)) – frame
Returns CRC16
Return type int
pyModbusTCP examples
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class FloatModbusClient(ModbusClient):
def read_float(self, address, number=1):
reg_l = self.read_holding_registers(address, number * 2)
if reg_l:
return [utils.decode_ieee(f) for f in utils.word_list_to_long(reg_l)]
else:
return None
# write 10.0 at @0
c.write_float(0, [10.0])
17
pyModbusTCP Documentation, Release 0.1.10
c.close()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# read_register
# read 10 registers and print result on stdout
# you can use the tiny modbus server "mbserverd" to test this code
# mbserverd is here: https://github.com/sourceperl/mbserverd
SERVER_HOST = "localhost"
SERVER_PORT = 502
c = ModbusClient()
while True:
# open or reconnect TCP to server
if not c.is_open():
if not c.open():
print("unable to connect to "+SERVER_HOST+":"+str(SERVER_PORT))
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# read_bit
# read 10 bits and print result on stdout
SERVER_HOST = "localhost"
SERVER_PORT = 502
SERVER_U_ID = 1
c = ModbusClient()
while True:
# open or reconnect TCP to server
if not c.is_open():
if not c.open():
print("unable to connect to "+SERVER_HOST+":"+str(SERVER_PORT))
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# write_bit
# write 4 bits to True, wait 2s, write False, restart...
SERVER_HOST = "localhost"
(continues on next page)
c = ModbusClient()
toggle = True
while True:
# open or reconnect TCP to server
if not c.is_open():
if not c.open():
print("unable to connect to "+SERVER_HOST+":"+str(SERVER_PORT))
time.sleep(1)
print("")
print("read bits")
print("---------")
print("")
bits = c.read_coils(0, 4)
if bits:
print("bits #0 to 3: "+str(bits))
else:
print("unable to read")
#!/usr/bin/env python
# -*- coding: utf-8 -*-
(continues on next page)
# modbus_thread
# start a thread for polling a set of registers, display result on console
# exit with ctrl+c
import time
from threading import Thread, Lock
from pyModbusTCP.client import ModbusClient
SERVER_HOST = "localhost"
SERVER_PORT = 502
# set global
regs = []
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Modbus/TCP server
#
# run this as root to listen on TCP priviliged ports (<= 1024)
# default Modbus/TCP port is 502 so we prefix call with sudo
# add "--host 0.0.0.0" to listen on all available IPv4 addresses of the host
#
# sudo ./server.py --host 0.0.0.0
import argparse
from pyModbusTCP.server import ModbusServer
if __name__ == '__main__':
# parse args
parser = argparse.ArgumentParser()
parser.add_argument('-H', '--host', type=str, default='localhost', help='Host')
parser.add_argument('-p', '--port', type=int, default=502, help='TCP port')
args = parser.parse_args()
# start modbus server
server = ModbusServer(host=args.host, port=args.port)
server.start()
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import time
from pyModbusTCP.server import ModbusServer, DataBank
# need https://github.com/dbader/schedule
import schedule
if __name__ == "__main__":
# parse args
parser = argparse.ArgumentParser()
parser.add_argument("-H", "--host", type=str, default="localhost", help="Host")
parser.add_argument("-p", "--port", type=int, default=502, help="TCP port")
args = parser.parse_args()
# init modbus server and start it
server = ModbusServer(host=args.host, port=args.port, no_block=True)
server.start()
(continues on next page)
• genindex
• modindex
• search
25
pyModbusTCP Documentation, Release 0.1.10
p
pyModbusTCP.client, 7
pyModbusTCP.server, 11
pyModbusTCP.utils, 15
27
pyModbusTCP Documentation, Release 0.1.10
Symbols I
__init__() (pyModbusTCP.client.ModbusClient is_open() (pyModbusTCP.client.ModbusClient
method), 7 method), 8
is_run (pyModbusTCP.server.ModbusServer attribute),
A 11
auto_close() (pyModbusTCP.client.ModbusClient
method), 8 L
auto_open() (pyModbusTCP.client.ModbusClient last_error() (pyModbusTCP.client.ModbusClient
method), 8 method), 8
last_error_txt() (pyMod-
C busTCP.client.ModbusClient method), 8
close() (pyModbusTCP.client.ModbusClient method), last_except() (pyModbusTCP.client.ModbusClient
8 method), 9
crc16() (in module pyModbusTCP.utils), 15 last_except_txt() (pyMod-
busTCP.client.ModbusClient method), 9
D long_list_to_word() (in module pyMod-
busTCP.utils), 14
DataBank (class in pyModbusTCP.server), 12
debug() (pyModbusTCP.client.ModbusClient method),
8
M
decode_ieee() (in module pyModbusTCP.utils), 15 ModbusClient (class in pyModbusTCP.client), 7
ModbusServer (class in pyModbusTCP.server), 11
E mode() (pyModbusTCP.client.ModbusClient method), 9
encode_ieee() (in module pyModbusTCP.utils), 15
O
G open() (pyModbusTCP.client.ModbusClient method), 9
get_2comp() (in module pyModbusTCP.utils), 14
get_bits() (pyModbusTCP.server.DataBank class
P
method), 12 port() (pyModbusTCP.client.ModbusClient method), 9
get_bits_from_int() (in module pyMod- pyModbusTCP.client (module), 7
busTCP.utils), 13 pyModbusTCP.server (module), 11
get_list_2comp() (in module pyModbusTCP.utils), pyModbusTCP.utils (module), 13–15
14
get_words() (pyModbusTCP.server.DataBank class R
method), 12 read_coils() (pyModbusTCP.client.ModbusClient
method), 9
H read_discrete_inputs() (pyMod-
host() (pyModbusTCP.client.ModbusClient method), 8 busTCP.client.ModbusClient method), 9
read_holding_registers() (pyMod-
busTCP.client.ModbusClient method), 9
29
pyModbusTCP Documentation, Release 0.1.10
read_input_registers() (pyMod-
busTCP.client.ModbusClient method), 10
reset_bit() (in module pyModbusTCP.utils), 13
S
set_bit() (in module pyModbusTCP.utils), 13
set_bits() (pyModbusTCP.server.DataBank class
method), 12
set_words() (pyModbusTCP.server.DataBank class
method), 12
start() (pyModbusTCP.server.ModbusServer
method), 11
stop() (pyModbusTCP.server.ModbusServer method),
11
T
test_bit() (in module pyModbusTCP.utils), 13
timeout() (pyModbusTCP.client.ModbusClient
method), 10
toggle_bit() (in module pyModbusTCP.utils), 13
U
unit_id() (pyModbusTCP.client.ModbusClient
method), 10
V
version() (pyModbusTCP.client.ModbusClient
method), 10
W
word_list_to_long() (in module pyMod-
busTCP.utils), 14
write_multiple_coils() (pyMod-
busTCP.client.ModbusClient method), 10
write_multiple_registers() (pyMod-
busTCP.client.ModbusClient method), 10
write_single_coil() (pyMod-
busTCP.client.ModbusClient method), 11
write_single_register() (pyMod-
busTCP.client.ModbusClient method), 11
30 Index