Modbus tcp client python

Module pyModbusTCP.client¶

Get or set automatic TCP close after each request mode (True = turn on).

Get or set automatic TCP connect mode (True = turn on).

Close current TCP connection.

Send a custom modbus request.

Parameters: pdu (bytes) – a modbus PDU (protocol data unit)
Returns: modbus frame PDU or None if error
Return type: bytes or None

debug ¶

Get or set the debug flag (True = turn on).

Get or set the server to connect to.

This can be any string with a valid IPv4 / IPv6 address or hostname. Setting host to a new value will close the current socket.

Get current status of the TCP connection (True = open).

Human-readable text that describe last error.

Return the last modbus exception code.

Verbose human-readable text that describe last modbus exception.

Short human-readable text that describe last modbus exception.

Connect to modbus server (open TCP connection).

Returns: connect status (True on success)
Return type: bool

port ¶

Get or set the current TCP port (default is 502).

Setting port to a new value will close the current socket.

read_coils ( bit_addr, bit_nb=1 ) ¶

Modbus function READ_COILS (0x01).

bits list or None if error

Modbus function Read Device Identification (0x2B/0x0E).

  • read_code (int) – read device id code, 1 to 3 for respectively: basic, regular and extended stream access, 4 for one specific identification object individual access (default is 1)
  • object_id (int) – object id of the first object to obtain (default is 0)

a DeviceIdentificationResponse instance with the data or None if the requests fails

Modbus function READ_DISCRETE_INPUTS (0x02).

bits list or None if error

Modbus function READ_HOLDING_REGISTERS (0x03).

registers list or None if fail

Modbus function READ_INPUT_REGISTERS (0x04).

registers list or None if fail

Get or set requests timeout (default is 30 seconds).

The argument may be a floating point number for sub-second precision. Setting timeout to a new value will close the current socket.

Get or set the modbus unit identifier (default is 1).

Any int from 0 to 255 is valid.

Return the current package version as a str.

write_multiple_coils ( bits_addr, bits_value ) ¶

Modbus function WRITE_MULTIPLE_COILS (0x0F).

Modbus function WRITE_MULTIPLE_REGISTERS (0x10).

Modbus function WRITE_READ_MULTIPLE_REGISTERS (0x17).

registers list or None if fail

Modbus function WRITE_SINGLE_COIL (0x05).

Modbus function WRITE_SINGLE_REGISTER (0x06).

class DeviceIdentificationResponse¶

class pyModbusTCP.client. DeviceIdentificationResponse ( conformity_level: int = 0, more_follows: int = 0, next_object_id: int = 0, objects_by_id: Dict[int, bytes] = ) ¶

Modbus TCP client function read_device_identification() response struct.

  • conformity_level (int) – this represents supported access and object type
  • more_follows (int) – for stream request can be set to 0xff if other objects are available (0x00 in other cases)
  • next_object_id (int) – the next object id to be asked by following transaction
  • objects_by_id (dict) – a dictionary with requested object (dict keys are object id as int)

© Copyright 2022, Loïc Lefebvre Revision 66f18285 .

Versions latest stable v0.2.0 v0.1.10 Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

Quick start guide¶

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 2×16 bits words) a special module named utils provide some helpful functions.

Package map:

../_images/map.png

Package setup¶

# install the last available version (stable) sudo pip3 install pyModbusTCP # or upgrade from an older version sudo pip3 install pyModbusTCP --upgrade # you can also install a specific version (here v0.1.10) sudo pip3 install pyModbusTCP==v0.1.10 
git clone https://github.com/sourceperl/pyModbusTCP.git cd pyModbusTCP # here change "python" by your python target(s) version(s) (like python3.9) sudo python setup.py install 

ModbusClient: init¶

Init module from constructor (raise ValueError if host/port error):

from pyModbusTCP.client import ModbusClient try: c = ModbusClient(host='localhost', port=502) except ValueError: print("Error with host or port params") 
from pyModbusTCP.client import ModbusClient c = ModbusClient() c.host = 'localhost' c.port = 502 

Since version 0.2.0, “auto open” mode is the default behaviour to deal with TCP open/close.

The “auto open” mode keep the TCP connection always open, so the default constructor is:

c = ModbusClient(host="localhost", auto_open=True, auto_close=False) 

It’s also possible to open/close TCP socket before and after each request:

c = ModbusClient(host="localhost", auto_open=True, auto_close=True) 

Another way to deal with connection is to manually set it. Like this:

c = ModbusClient(host="localhost", auto_open=False, auto_close=False) # open the socket for 2 reads then close it. if c.open(): regs_list_1 = c.read_holding_registers(0, 10) regs_list_2 = c.read_holding_registers(55, 10) c.close() 

ModbusClient: available modbus requests functions¶

Domain Function name Function code ModbusClient function
Bit Read Discrete Inputs 2 read_discrete_inputs()
Read Coils 1 read_coils()
Write Single Coil 5 write_single_coil()
Write Multiple Coils 15 write_multiple_coils()
Register Read Input Registers 4 read_input_registers()
Read Holding Registers 3 read_holding_registers()
Write Single Register 6 write_single_register()
Write Multiple Registers 16 write_multiple_registers()
Read/Write Multiple Registers 23 write_read_multiple_registers()
Mask Write Register 22 n/a
File Read FIFO Queue 24 n/a
Read File Record 20 n/a
Write File Record 21 n/a
Read Exception Status 7 n/a
Diagnostic Diagnostic 8 n/a
Get Com Event Counter 11 n/a
Get Com Event Log 12 n/a
Report Slave ID 17 n/a
Read Device Identification 43 read_device_identification()

ModbusClient: debug mode¶

If need, you can enable a debug mode for ModbusClient like this:

from pyModbusTCP.client import ModbusClient c = ModbusClient(host="localhost", port=502, 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) 
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] 

utils module: Modbus data mangling¶

When we have to deal with the variety types of registers of PLC device, we often need some data mangling. Utils part of pyModbusTCP can help you in this task. Now, let’s see some use cases.

    deal with negative numbers (two’s complement):

from pyModbusTCP import utils list_16_bits = [0x0000, 0xFFFF, 0x00FF, 0x8001] # show "[0, -1, 255, -32767]" print(utils.get_list_2comp(list_16_bits, 16)) # show "-1" print(utils.get_2comp(list_16_bits[1], 16)) 

    convert integer of val_size bits (default is 16) to an array of boolean:

from pyModbusTCP import utils # show "[True, False, True, False, False, False, False, False]" print(utils.get_bits_from_int(0x05, val_size=8)) 
from pyModbusTCP import utils list_16_bits = [0x0123, 0x4567, 0xdead, 0xbeef] # big endian sample (default) list_32_bits = utils.word_list_to_long(list_16_bits) # show "['0x1234567', '0xdeadbeef']" print([hex(i) for i in list_32_bits]) # little endian sample list_32_bits = utils.word_list_to_long(list_16_bits, big_endian=False) # show "['0x45670123', '0xbeefdead']" print([hex(i) for i in list_32_bits]) 
from pyModbusTCP import utils # 32 bits IEEE single precision # encode : python float 0.3 -> int 0x3e99999a # display "0x3e99999a" print(hex(utils.encode_ieee(0.3))) # decode: python int 0x3e99999a -> float 0.3 # show "0.300000011921" (it's not 0.3, precision leak with float. ) print(utils.decode_ieee(0x3e99999a)) # 64 bits IEEE double precision # encode: python float 6.62606957e-34 -> int 0x390b860bb596a559 # display "0x390b860bb596a559" print(hex(utils.encode_ieee(6.62606957e-34, double=True))) # decode: python int 0x390b860bb596a559 -> float 6.62606957e-34 # display "6.62606957e-34" print(utils.decode_ieee(0x390b860bb596a559, double=True)) 

© Copyright 2022, Loïc Lefebvre Revision 66f18285 .

Versions latest stable v0.2.0 v0.1.10 Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A simple Modbus/TCP library for Python

License

sourceperl/pyModbusTCP

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.rst

A simple Modbus/TCP client library for Python. pyModbusTCP is pure Python code without any extension or external module dependency.

Since version 0.1.0, a server is also available for test purpose only (don’t use in project).

The module is currently test on Python 3.7, 3.8, 3.9, 3.10 and 3.11.

For Linux, Mac OS and Windows.

Documentation of the last release is available online at https://pymodbustcp.readthedocs.io/.

You can install this package from:

# install the last available release (stable) sudo pip install pyModbusTCP
# install a specific version (here release v0.1.10) sudo pip install pyModbusTCP==v0.1.10
# install a specific version (here release v0.1.10) directly from github servers sudo pip install git+https://github.com/sourceperl/pyModbusTCP.git@v0.1.10

Note on the use of versions:

Over time, some things can change. So, it’s a good practice that you always use a specific version of a package for your project, instead of just relying on the default behavior. Without precision, the installation tools will always install the latest version available for a package, this may have some drawbacks. For example, in pyModbusTCP, the TCP automatic open mode will be active by default from version 0.2.0. It is not the case with previous versions and it just doesn’t exist before the 0.0.12. This can lead to some strange behaviour of your application if you are not aware of the change. Look at CHANGES for details on versions available.

See examples/ for full scripts.

from pyModbusTCP.client import ModbusClient

module init (TCP always open)

# TCP auto connect on first modbus request c = ModbusClient(host="localhost", port=502, unit_id=1, auto_open=True)

module init (TCP open/close for each request)

# TCP auto connect on modbus request, close after it c = ModbusClient(host="127.0.0.1", auto_open=True, auto_close=True)

Read 2x 16 bits registers at modbus address 0 :

regs = c.read_holding_registers(0, 2) if regs: print(regs) else: print("read error")

Write value 44 and 55 to registers at modbus address 10 :

if c.write_multiple_registers(10, [44,55]): print("write ok") else: print("write error")

About

A simple Modbus/TCP library for Python

Источник

Читайте также:  What php script is running
Оцените статью