- Использование функций Python3 modbus-tk для работы с Modbus-устройствами
- Создание клиента Modbus TCP
- Чтение регистра Modbus
- Запись регистра Modbus
- Чтение нескольких регистров Modbus подряд
- Чтение бита из регистра Modbus
- Запись бита в регистр Modbus
- Чтение нескольких битов из регистра Modbus подряд
- Запись нескольких битов в регистр Modbus подряд
- Пример использования функций Python3 modbus-tk для чтения регистров Modbus
- Saved searches
- Use saved searches to filter your results more quickly
- License
- sourceperl/pyModbusTCP
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.rst
- About
- Quick start guide¶
- Package setup¶
- ModbusClient: init¶
- ModbusClient: TCP link management¶
- ModbusClient: available modbus requests functions¶
- ModbusClient: debug mode¶
- utils module: Modbus data mangling¶
Использование функций Python3 modbus-tk для работы с Modbus-устройствами
Modbus – это открытый протокол передачи данных, основанный на клиент-серверной архитектуре, который используется для связи между разными устройствами. Он широко используется в промышленности для организации связи между контроллерами, датчиками и другими устройствами.
Python3 modbus-tk – это библиотека, которая позволяет использовать Python 3 для работы с Modbus-устройствами. Эта библиотека является бесплатной и распространяется под лицензией LGPL.
Основные функции, которые можно использовать с помощью Python3 modbus-tk:
Создание клиента Modbus TCP
from modbus_tk import modbus_tcp # Создание клиента master = modbus_tcp.TcpMaster('192.168.1.50', port=502)
Чтение регистра Modbus
# Чтение регистра 0x0001 value = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 1)
Запись регистра Modbus
# Запись значения 0x0001 в регистр 0x0002 master.execute(1, cst.WRITE_SINGLE_REGISTER, 1, output_value=1)
Чтение нескольких регистров Modbus подряд
# Чтение 10 регистров, начиная с регистра 0x0001 values = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 10)
Чтение бита из регистра Modbus
# Чтение первого бита из регистра 0x0001 value = master.execute(1, cst.READ_COILS, 0, 1)
Запись бита в регистр Modbus
# Запись значения True в первый бит регистра 0x0001 master.execute(1, cst.WRITE_SINGLE_COIL, 0, output_value=True)
Чтение нескольких битов из регистра Modbus подряд
# Чтение 10 битов, начиная с первого бита регистра 0x0001 values = master.execute(1, cst.READ_COILS, 0, 10)
Запись нескольких битов в регистр Modbus подряд
# Запись значений [True, False, True, False, True] в регистр 0x0001, начиная со второго бита master.execute(1, cst.WRITE_MULTIPLE_COILS, 1, output_value=[True, False, True, False, True])
Python3 modbus-tk позволяет работать с разными типами регистров Modbus, включая holding registers, input registers, coils и discrete inputs. Библиотека также поддерживает работу с несколькими устройствами и обмен данными с ними одновременно.
Пример использования функций Python3 modbus-tk для чтения регистров Modbus
from modbus_tk import modbus_tcp # Создание клиента Modbus TCP master = modbus_tcp.TcpMaster('192.168.1.50', port=502) # Чтение регистров 0x0001, 0x0002 и 0x0003 values = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 3) # Вывод полученных значений на экран print('Значения регистров: <>'.format(values))
В результате выполнения этого скрипта будут выведены значения регистров 0x0001, 0x0002 и 0x0003.
Python3 modbus-tk – это мощная и гибкая библиотека, которая облегчает работу программистов с Modbus-устройствами. Она поддерживает большое количество функций и типов регистров Modbus, что позволяет использовать ее для различных задач, связанных с управлением и мониторингом промышленных устройств.
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
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:
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
ModbusClient: TCP link management¶
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.