Repository: favalex/modbus-cli Branch: master Commit: aa4067009ef4 Files: 17 Total size: 53.6 KB Directory structure: gitextract_oonpleyj/ ├── .github/ │ └── workflows/ │ └── python-app.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.rst ├── modbus/ │ ├── __init__.py │ └── __main__.py ├── modbus_cli/ │ ├── access.py │ ├── definitions.py │ ├── modbus_rtu.py │ └── modbus_tcp.py ├── requirements.txt ├── setup.cfg ├── setup.py └── tests/ ├── simple.modbus ├── test_access.py └── test_definitions.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/python-app.yml ================================================ # This workflow will install Python dependencies, run tests and lint with a single version of Python # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Python application on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python 3.10 uses: actions/setup-python@v2 with: python-version: "3.10" - name: Install dependencies run: | python -m pip install --upgrade pip pip install flake8 pytest if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - name: Lint with flake8 run: | # stop the build if there are Python syntax errors or undefined names flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - name: Test with pytest run: | python -m pytest tests ================================================ FILE: .gitignore ================================================ venv __pycache__/ *.egg-info/ ================================================ FILE: LICENSE ================================================ Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. ================================================ FILE: MANIFEST.in ================================================ include tests/simple.modbus ================================================ FILE: README.rst ================================================ ========= modbus ========= --------------------------------------------- Access Modbus devices from the command line --------------------------------------------- :Author: favalex@gmail.com :Date: 2023-02-26 :Copyright: MPL 2.0 :Version: 0.1.10 :Manual section: 1 SYNOPSIS ======== modbus [-h] [-r REGISTERS] [-s SLAVE_ID] [-b BAUD] [-p STOP_BITS] [-P {e,o,n}] [-v] device access [access ...] DESCRIPTION =========== Read and write registers of Modbus devices. Access both TCP and RTU (i.e. serial) devices and encode and decode types larger than 16 bits (e.g. floats) into Modbus 16 bits registers. Optionally access registers by symbolic names, as defined in a registers file. Symbolic names for enumerations and bitfields are supported too. Designed to work nicely with other standard UNIX tools (``watch``, ``socat``, etc.), see the examples. Implemented in python on top of the protocol implementation provided by the umodbus python library. INSTALL ======= Regular python install, either ``pip install modbus_cli`` to install from pypi or ``python setup.py install`` to install from source. OPTIONS ======= device ``/dev/ttyXXX`` for serial devices, or ``hostname[:port]`` for TCP devices access One or more read or write operations. See ACCESS SYNTAX below. -r FILE, --registers=FILE Read registers definitions from FILE. Can be specified multiple times. -v, --verbose Print on screen the bytes transferred on the wire. -b BAUD, --baud=BAUD Set the baud rate for serial connections. -p BITS, --stop-bits=BITS Set the number of stop bits for serial connections. -P PARITY, --parity=PARITY Set the parity for serial connections: (e)ven, (o)dd or (n)one -B ORDER, --byte-order=ORDER Set the byte order to one of 'le' (little endian), 'be' (big endian) or 'mixed' -h, --help Show this help message and exit. ACCESS SYNTAX ============= :: [MODBUS_TYPE@]ADDRESS[/BINARY_TYPE][:ENUMERATION_NAME][=VALUE] Mnemonic: access the register(s) of MODBUS_TYPE starting *at* ADDRESS, interpreting them as BINARY_TYPE. The ``/`` syntax is inspired by gdb (but the available types are different.) MODBUS_TYPE = h|H|i|c|C|d The modbus type, one of ========== ================ ======= ========= code name size writable ========== ================ ======= ========= ``h or H`` holding register 16 bits yes ``i`` input register 16 bits no ``c or C`` coil 1 bit yes ``d`` discrete input 1 bit no ========== ================ ======= ========= Types ``C`` and ``H`` force the use of "write multiple registers" even when accessing a single register. This is useful for some devices that don't support singular write functions. The default modbus type is holding register. ADDRESS = 0-based register address BINARY_TYPE = Any format description accepted by the python standard ``pack`` module. Some common formats are: ===== ==== code type ===== ==== ``h`` 16 bits signed integer ``H`` 16 bits unsigned integer ``i`` 32 bits signed integer ``I`` 32 bits unsigned integer ``f`` 32 bits IEEE 754 float ===== ==== The default byte order is big-endian. To use little endian, use a ``<`` prefix, or ``--byte-order=le``. To use mixed endian (little endian, but individual 16 bit registers are big endian), use ``--byte-order=mixed``. VALUE = The value to be written to the register. If not present, the register will be read instead. If only one register is written to, the modbus function ``6 (0x6)``, "write single register" is used. If multiple registers are written to, the modbus function ``16 (0x10)``, "write multiple registers" is used. EXAMPLES ======== Read a holding register ----------------------- :: $ modbus $IP_OF_MODBUS_DEVICE 100 Write a holding register ------------------------ :: $ modbus $IP_OF_MODBUS_DEVICE 100=42 Read multiple registers ----------------------- To read (or write) multiple registers simply list them on the command line:: $ modbus $IP_OF_MODBUS_DEVICE 100 c@2000 When performing access to multiple contiguous registers, one single modbus operation is performed. When multiple modbus operations are needed, they are all initiated at once, and the results are collected as they arrive. More examples of the access syntax ---------------------------------- ==================== ==== ``h@39/I`` read the 32-bits unsigned integer stored in holding registers at addresses 39 and 40 ``39/I`` same as above (h is the default modbus type) ``39/I=42`` write the integer 42 to that register ``SOME_REGISTER=42`` same as above, provided the registers file contains the definition ``SOME_REGISTER h@39/I`` ``39/I=0xcafe`` the value can be specified in hexadecimal ``c@5`` read coil at address 5 ``h@24/f=6.78`` write a floating point value to holding registers at addresses 24 and 25 ``i@1/6B`` read six unsigned bytes stored in input registers at addresses 1, 2 and 3 ==================== ==== Monitor a register ------------------ The UNIX command ``watch`` can be used to read a register at regular intervals:: $ watch modbus $IP_OF_MODBUS_DEVICE 100 Read a serial device attached to a remote computer -------------------------------------------------- The UNIX command ``socat`` can be used to access a remote device through a TCP tunnel:: remote$ socat -d -d tcp-l:54321,reuseaddr file:/dev/ttyUSB0,raw,b19200 local$ socat -d -d tcp:sc:54321 pty,waitslave,link=/tmp/local_device,unlink-close=0 local$ modbus /tmp/local_device 100 Read multiple registers based on their names -------------------------------------------- Given the following registers definitions:: $ cat registers.modbus di0 d@0 di1 d@1 ai0 i@512 ai1 i@513 glob matching (\*, ?, etc.) can be used to read all the ``ai`` registers at once:: $ modbus -r registers.modbus $IP_OF_MODBUS_DEVICE ai\* REGISTERS FILES ===================== The purpose of the registers files is to be able to refer to registers by name. There can be multiple definition files, specified using either the ``-r`` command line switch or the ``MODBUS_DEFINITIONS`` environment variable. A ``#`` in a definition file starts a comment. Each line contains a symbolic name followed by a register definition. The name and the definitions are separated by spaces, for example:: status i@512:STATUS leds 513:LEDS The file can also contain the possible values for an enumeration or a bitmask, for example:: # This is an enumeration named STATUS :STATUS 0=OFF 1=ON 2=ERROR # This is a bitmask named LEDS |LEDS 0=LED0 1=LED1 3=LED3 4=LED4 ENVIRONMENT =========== MODBUS_DEFINITIONS A colon separated list of register definitions files. SEE ALSO ======== * `modbus `__ * `umodbus `__ * `pack format `__ ================================================ FILE: modbus/__init__.py ================================================ #! /usr/bin/env python import argparse import sys import os import logging import urllib.parse import colorama as clr from modbus_cli.definitions import Definitions from modbus_cli.modbus_rtu import ModbusRtu from modbus_cli.modbus_tcp import ModbusTcp from modbus_cli.access import parse_accesses class ColourHandler(logging.Handler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.formatter = logging.Formatter("%(style)s%(message)s" + clr.Style.RESET_ALL) def emit(self, record): if record.levelname == "DEBUG": record.style = clr.Style.DIM elif record.levelname == "WARNING": record.style = clr.Style.BRIGHT elif record.levelname == "ERROR": record.style = clr.Style.BRIGHT + clr.Fore.RED elif record.levelname == "CRITICAL": record.style = clr.Style.BRIGHT + clr.Back.BLUE + clr.Fore.RED else: record.style = clr.Style.NORMAL msg = self.format(record) print(msg) def connect_to_device(args): if args.device[0] == "/": modbus = ModbusRtu( device=args.device, baud=args.baud, parity=args.parity, stop_bits=args.stop_bits, slave_id=args.slave_id, timeout=args.timeout, ) else: try: result = urllib.parse.urlsplit("//" + args.device) host = result.hostname or "localhost" port = result.port or 502 except ValueError: logging.error("Invalid device %r", args.device) sys.exit(1) modbus = ModbusTcp(host, port, args.slave_id, args.timeout) modbus.connect() return modbus def main(): parser = argparse.ArgumentParser() parser.add_argument("-r", "--registers", action="append", default=[]) parser.add_argument("-s", "--slave-id", type=int) parser.add_argument("-b", "--baud", type=int, default=19200) parser.add_argument("-p", "--stop-bits", type=int, default=1) parser.add_argument("-P", "--parity", choices=["e", "o", "n"], default="n") parser.add_argument("-v", "--verbose", action="store_true") parser.add_argument("-S", "--silent", action="store_true") parser.add_argument("-t", "--timeout", type=float, default=5.0) parser.add_argument( "-B", "--byte-order", choices=["le", "be", "mixed"], default="be" ) parser.add_argument("device") parser.add_argument("access", nargs="+") args = parser.parse_args() clr.init() try: mainLogger = logging.getLogger() # Main logger if args.verbose: mainLogger.setLevel(logging.DEBUG) else: mainLogger.setLevel(logging.INFO) ch = ColourHandler() mainLogger.addHandler(ch) definitions = Definitions(args.silent) definitions.parse( args.registers + os.environ.get("MODBUS_DEFINITIONS", "").split(":") ) connect_to_device(args).perform_accesses( parse_accesses(args.access, definitions, args.byte_order, args.silent), definitions, ).close() finally: # restore stdout/stderr if colorama has modified them (mostly on windows) # Leaving this out doesn't seem to hurt anything, but they say to call deinit, so we call deinit. clr.deinit() ================================================ FILE: modbus/__main__.py ================================================ from . import main if __name__ == '__main__': main() ================================================ FILE: modbus_cli/access.py ================================================ import struct from itertools import zip_longest, groupby import logging import re import fnmatch import umodbus.exceptions from .definitions import REGISTER_RE def grouper(iterable, n, fillvalue=None): 'Collect data into fixed-length chunks or blocks' # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) def dump(xs): return ' '.join('{:02x}'.format(x) for x in xs) class Access: def __init__(self, modbus_type, addresses, pack_types, values=None, names=None, presenters=None, byte_order='be', silent=False): self.modbus_type = modbus_type self.values_to_write = values or [None] * len(addresses) self.addresses = addresses self.pack_types = pack_types self.names = names or [None] * len(addresses) self.presenters = presenters or [None] * len(addresses) self.byte_order = byte_order self.silent = silent def address(self): return self.addresses[0] def pack_type(self): return self.pack_types[0] def presenter(self): return self.presenters[0] def endianness(self): return self.pack_type()[0] @property def write(self): return any(x is not None for x in self.values_to_write) def size(self): """Number of registers""" total = 0 for p in self.pack_types: size = struct.calcsize(p) if self.modbus_type in ('h', 'H', 'i'): assert size % 2 == 0 size //= 2 total += size return total def operations(self): if self.write: return zip(self.pack_types, self.values_to_write) else: return self.pack_types def append(self, other): self.names.extend(other.names) self.pack_types.extend(other.pack_types) self.addresses.extend(other.addresses) self.presenters.extend(other.presenters) if self.write: self.values_to_write.extend(other.values_to_write) def labels(self): return (name or address for (name, address) in zip(self.names, self.addresses)) def print_values(self, definitions=None): for label, value, presenter in zip(self.labels(), self.values, self.presenters): if len(value) == 1: value = value[0] if self.silent: logging.info('{}'.format(value)) else: logging.info('{}: {} {}'.format(label, value, self.present_value(value, presenter, definitions))) def present_value(self, value, presenter, definitions): if type(value) != int: return '' presentation = [hex(value)] if presenter: if presenter[0] == ':': presentation.append(definitions.presenters[presenter][value]) elif presenter[0] == '|': names = [] for bit, name in definitions.presenters[presenter].items(): if value & (1 << bit): names.append(name) presentation.append(' | '.join(names)) return ' '.join(presentation) def perform(self, modbus): if self.write: self.write_registers_send(modbus) self.write_registers_receive(modbus) else: self.read_registers_send(modbus) self.read_registers_receive(modbus) def read_registers_send(self, modbus): if self.modbus_type in 'cCd': n_registers = 0 for pack_type in self.pack_types: n_registers += struct.calcsize(pack_type) else: n_bytes = 0 for pack_type in self.pack_types: n_bytes += struct.calcsize(pack_type) assert n_bytes % 2 == 0 n_registers = n_bytes // 2 reader = { 'c': 'read_coils', 'C': 'read_coils', 'd': 'read_discrete_inputs', 'h': 'read_holding_registers', 'H': 'read_holding_registers', 'i': 'read_input_registers', }[self.modbus_type] self.request = getattr(modbus.protocol, reader)(modbus.slave_id, self.address(), n_registers) logging.debug('→ < %s >', dump(self.request)) modbus.send(self.request) def read_registers_receive(self, modbus): try: words = modbus.receive(self.request) except umodbus.exceptions.IllegalDataAddressError: self.values = ('Invalid address', ) return except umodbus.exceptions.IllegalFunctionError: self.values = ('Invalid modbus type', ) return logging.debug('← %s', words) if self.modbus_type in 'cd': self.values = [(w,) for w in words] else: if self.byte_order == 'mixed': # reinterpret each big endian register as little endian repack_byte_order = '<' else: # just pack it again to the same stream of bytes we read repack_byte_order = '>' packed = struct.pack('{}{}H'.format(repack_byte_order, len(words)), *words) self.values = [] for pack in self.pack_types: size = struct.calcsize(pack) self.values.append(struct.unpack(pack, packed[:size])) packed = packed[size:] def write_registers_send(self, modbus): if self.modbus_type == 'c': if len(self.values_to_write) == 1: # TODO validate value, should be boolean message = modbus.protocol.write_single_coil( modbus.slave_id, self.address(), int(self.values_to_write[0])) else: message = modbus.protocol.write_multiple_coils(modbus.slave_id, self.address(), [int(v) for v in self.values_to_write]) elif self.modbus_type == 'C': message = modbus.protocol.write_multiple_coils(modbus.slave_id, self.address(), [int(v) for v in self.values_to_write]) else: words = [] if self.byte_order == 'mixed': register_fmt = '', dump(message)) self.request = message return modbus.send(message) def write_registers_receive(self, modbus): modbus.receive(self.request) def __str__(self): return '{}@{}/{}{}'.format(self.modbus_type, self.address(), self.pack_types, '={}'.format(self.values_to_write) if self.write else '') def __repr__(self): return 'Access({!r}, {!r}, {!r}, {!r}, {!r})'.format( self.modbus_type, self.addresses, self.pack_types, self.values_to_write, self.names) def by_type(access): return access.modbus_type, access.write, access.endianness() def by_address(access): return access.address() def group_accesses(accesses): grouped = [] for (modbus_type, write, _), xs in groupby(sorted(accesses, key=by_type), key=by_type): xs = sorted(xs, key=by_address) while len(xs): first = xs.pop(0) while len(xs): second = xs[0] if first.address() + first.size() == second.address(): first.append(second) xs.pop(0) else: break grouped.append(first) return grouped def parse_access(register, name, write, value, byte_order, silent): modbus_type, address, pack_type, presenter = re.match(REGISTER_RE, register).groups() if not address: logging.warn('%r is not a known named register nor a valid register definition. Skipping it.', register) return None if not modbus_type: modbus_type = 'h' else: modbus_type = modbus_type[:-1] if not pack_type: if modbus_type in 'cCd': pack_type = 'B' else: pack_type = 'H' else: pack_type = pack_type[1:] address = int(address, 0) if pack_type[0] not in '@=<>!': if byte_order in ('le', 'mixed'): pack_type = '<' + pack_type elif byte_order == 'be': pack_type = '!' + pack_type if modbus_type not in 'cCdhHi': raise ValueError("Invalid Modbus type '{}'. Valid ones are 'cCdhHi'".format(modbus_type)) if write and modbus_type not in 'cChH': raise ValueError("Invalid Modbus type '{}'. Only coils and holding registers are writable".format(modbus_type)) return Access(modbus_type, [address], [pack_type], [value], names=[name], presenters=[presenter], byte_order=byte_order, silent=silent) def parse_accesses(s, definitions, byte_order='be', silent=False): accesses = [] for access in s: parts = access.split('=') if len(parts) == 1: register = parts[0] value = None write = False else: register, value = parts write = True if re.fullmatch(REGISTER_RE, register): access = parse_access(register, None, write, value, byte_order, silent) if access: accesses.append(access) else: register_re = re.compile(fnmatch.translate(register)) for name, definition in definitions.registers.items(): if register_re.match(name): access = parse_access(definition, name, write, value, byte_order, silent) if access: accesses.append(access) return group_accesses(accesses) ================================================ FILE: modbus_cli/definitions.py ================================================ import re import logging REGISTER_RE = re.compile(r'^([cCdhHi]@)?(\d+|0x[0-9a-fA-F]+)(/[^:|]*)?([:|].*)?$') class Definitions: def __init__(self, silent): self.registers = {} self.presenters = {} self.silent = silent def parse(self, filenames): for filename in filenames: if filename: with open(filename) as f: self.filename = filename self.line = 0 accumulated_line = '' for line in f: self.line += 1 if line[0].isspace(): accumulated_line += line else: self.parse_line(accumulated_line) accumulated_line = line self.parse_line(accumulated_line) if not self.silent: logging.info('Parsed %d registers definitions from %d files', len(self.registers), len(filenames)) def parse_line(self, line): if not line: return line = line.split('#')[0] line = line.strip() if not line: return if line[0] in ':|': name, values = self.parse_presenter(line) self.presenters[name] = values else: parts = line.split() if len(parts) == 2: name, definition = parts if REGISTER_RE.match(definition): self.registers[name] = definition else: logging.warning('%s:%d:Invalid definition %r for register %r. Skipping it.', self.filename, self.line, definition, name) else: logging.warning('%s:%d:Invalid definition %r. Skipping it.', self.filename, self.line, line) def parse_presenter(self, line): parts = line.split() name = parts[0] values = {} for definition in parts[1:]: value, symbol = definition.split('=') values[int(value, 0)] = symbol return name, values ================================================ FILE: modbus_cli/modbus_rtu.py ================================================ import logging from .access import dump class ModbusRtu: def __init__(self, device, baud, parity, stop_bits, slave_id, timeout): from serial import PARITY_EVEN, PARITY_ODD, PARITY_NONE parity_opts = {'e': PARITY_EVEN, 'o': PARITY_ODD, 'n': PARITY_NONE} self.device = device self.timeout = timeout self.baud = baud self.parity = parity_opts[parity] self.stop_bits = stop_bits if slave_id is None: slave_id = 1 self.slave_id = slave_id import umodbus.client.serial.rtu as modbus self.protocol = modbus def connect(self): from serial import Serial logging.debug("Serial port %s. Parameters: %s baud, %s stop bit(s), parity: %s, timeout %ss.", self.device, self.baud, self.stop_bits, self.parity, self.timeout, ) self.connection = Serial(port=self.device, baudrate=self.baud, parity=self.parity, stopbits=self.stop_bits, bytesize=8, timeout=self.timeout) def send(self, request): self.connection.write(request) def receive(self, request): response = self.connection.read(2) if len(response) != 2: raise RuntimeError('timeout') slave_id, function = response try: if function in (1, 2, 3, 4): # Functions with variable size response += self.connection.read(1) count = 2 + response[-1] response += self.connection.read(count) elif function in (5, 6, 15, 16): # Function with fixed size response += self.connection.read(6) elif function & 0x80: response += self.connection.read(3) else: response += self.connection.read(1024) raise NotImplementedError('RTU function {}'.format(function)) finally: logging.debug('← < %s > %s bytes', dump(response), len(response)) return self.protocol.parse_response_adu(response, request) def close(self): self.connection.close() def perform_accesses(self, accesses, definitions): for access in accesses: access.perform(self) if not access.write: access.print_values(definitions) return self ================================================ FILE: modbus_cli/modbus_tcp.py ================================================ import struct import logging import time from .access import dump class ModbusTcp: def __init__(self, host, port, slave_id, timeout): self.host = host self.port = port if slave_id is None: slave_id = 255 self.slave_id = slave_id self.timeout = timeout import umodbus.client.tcp as modbus self.protocol = modbus def connect(self): import socket addr_info = socket.getaddrinfo( self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM ) for af, socktype, proto, _, sa in addr_info: try: self.connection = socket.socket(af, socktype, proto) self.connection.connect(sa) self.connection.settimeout(self.timeout) return except OSError: if self.connection: self.connection.close() raise OSError(f"Could not connect to {self.host}") def send(self, request): self.connection.send(request) def receive(self, request): header = self.receive_n(6) seq, _, count = struct.unpack(">3H", header) sent_seq = struct.unpack(">H", request[:2])[0] if seq != sent_seq: logging.warn("Sequence mismatch: sent %s, received %s", sent_seq, seq) response = header + self.receive_n(count) logging.debug("← < %s > %s bytes", dump(response), len(response)) return self.protocol.parse_response_adu(response, request) def receive_n(self, n): data = bytes() while len(data) < n: len_before = len(data) data += self.connection.recv(n - len(data)) if len(data) == len_before: time.sleep(0.1) return data def close(self): self.connection.close() def perform_accesses(self, accesses, definitions): for access in accesses: if access.write: access.write_registers_send(self) else: access.read_registers_send(self) for access in accesses: if access.write: access.write_registers_receive(self) else: access.read_registers_receive(self) access.print_values(definitions) return self ================================================ FILE: requirements.txt ================================================ umodbus colorama ================================================ FILE: setup.cfg ================================================ [flake8] max-line-length = 120 ================================================ FILE: setup.py ================================================ from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name='modbus_cli', version='0.1.10', description='Command line tool to access Modbus devices', long_description=readme(), long_description_content_type='text/x-rst', url='http://github.com/favalex/modbus-cli', author='Gabriele Favalessa', author_email='favalex@gmail.com', license='MPL 2.0', packages=['modbus', 'modbus_cli'], entry_points={ 'console_scripts': [ 'modbus=modbus:main' ], }, install_requires=['umodbus', 'colorama'], zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ]) ================================================ FILE: tests/simple.modbus ================================================ # a comment a_register i@100/4H:a_presenter :a_presenter 0=x 1=y another_register invalid_register xxx ================================================ FILE: tests/test_access.py ================================================ import unittest from unittest.mock import Mock import logging from modbus_cli.access import parse_accesses, Access logging.basicConfig(level=logging.DEBUG) def mocked_modbus(): modbus = Mock() modbus.slave_id = 42 modbus.protocol = Mock() modbus.protocol.read_input_registers = Mock(return_value=[]) modbus.protocol.read_holding_registers = Mock(return_value=[]) modbus.protocol.read_discrete_inputs = Mock(return_value=[]) modbus.protocol.read_coils = Mock(return_value=[]) modbus.protocol.write_multiple_registers = Mock(return_value=[]) modbus.protocol.write_multiple_coils = Mock(return_value=[]) return modbus class TestAccess(unittest.TestCase): def test_defaults(self): it = parse_accesses(['123'], None) self.assertEqual(1, len(it)) it = it[0] self.assertEqual('h', it.modbus_type) self.assertEqual(123, it.address()) self.assertEqual('!H', it.pack_type()) self.assertEqual(None, it.presenter()) self.assertEqual(1, it.size()) def test_full(self): it = parse_accesses(['i@123/<4H:STATUS'], None) self.assertEqual(1, len(it)) it = it[0] self.assertEqual('i', it.modbus_type) self.assertEqual(123, it.address()) self.assertEqual('<4H', it.pack_type()) self.assertEqual(':STATUS', it.presenter()) self.assertEqual(4, it.size()) def test_full_hex(self): it = parse_accesses(['i@0xa12B/<4H:STATUS'], None) self.assertEqual(1, len(it)) it = it[0] self.assertEqual('i', it.modbus_type) self.assertEqual(0xa12b, it.address()) self.assertEqual('<4H', it.pack_type()) self.assertEqual(':STATUS', it.presenter()) self.assertEqual(4, it.size()) def test_grouping(self): it = parse_accesses(['123', '124'], None) self.assertEqual(1, len(it)) it = it[0] self.assertEqual('h', it.modbus_type) self.assertEqual(123, it.address()) self.assertEqual('!H', it.pack_type()) self.assertEqual(None, it.presenter()) self.assertEqual(2, it.size()) def test_read_input_registers(self): modbus = mocked_modbus() modbus.receive = Mock(return_value=[0x1234, 0x5678]) access = Access('i', [123, 124], ['!H', '!H']) access.perform(modbus) modbus.protocol.read_input_registers.assert_called_once_with(42, 123, 2) modbus.send.assert_called_once() self.assertEqual([(0x1234, ), (0x5678, )], access.values) def test_read_holding_registers(self): modbus = mocked_modbus() modbus.receive = Mock(return_value=[0x1234, 0x5678]) access = Access('h', [123, 124], ['!H', '!H']) access.perform(modbus) modbus.protocol.read_holding_registers.assert_called_once_with(42, 123, 2) modbus.send.assert_called_once() self.assertEqual([(0x1234, ), (0x5678, )], access.values) def test_read_discrete_inputs(self): modbus = mocked_modbus() modbus.receive = Mock(return_value=[1, 0]) access = Access('d', [123, 124], ['!B', '!B']) access.perform(modbus) modbus.protocol.read_discrete_inputs.assert_called_once_with(42, 123, 2) modbus.send.assert_called_once() self.assertEqual([(1,), (0,)], access.values) def test_read_coils(self): modbus = mocked_modbus() modbus.receive = Mock(return_value=[1, 0]) access = Access('c', [123, 124], ['!B', '!B']) access.perform(modbus) modbus.protocol.read_coils.assert_called_once_with(42, 123, 2) modbus.send.assert_called_once() self.assertEqual([(1,), (0,)], access.values) def test_write_registers(self): modbus = mocked_modbus() access = Access('h', [123, 124], ['!H', '!H'], values=['10', '11']) access.perform(modbus) modbus.protocol.write_multiple_registers.assert_called_once_with(42, 123, [10, 11]) modbus.send.assert_called_once() def test_write_coils(self): modbus = mocked_modbus() access = Access('c', [123, 124], ['!B', '!B'], values=['1', '0']) access.perform(modbus) modbus.protocol.write_multiple_coils.assert_called_once_with(42, 123, [1, 0]) modbus.send.assert_called_once() def test_presenter(self): pass def test_endianness_read(self): modbus = mocked_modbus() # given these two 16 bit registers, what do we interpret? modbus.receive = Mock(return_value=[0x1122, 0x3344]) def perform(byte_order, fields): addresses = list(range(len(fields))) access = Access('h', addresses, fields, byte_order=byte_order) access.perform(modbus) return access.values # big endian 16/32 bit fields self.assertEqual(perform('be', ['>H', '>H']), [(0x1122, ), (0x3344, )]) self.assertEqual(perform('be', ['>I']), [(0x11223344, )]) # little endian 16/32 bit fields self.assertEqual(perform('le', ['H', '>H'], values16), [0x1122, 0x3344]) self.assertEqual(perform('be', ['>I'], values32), [0x1122, 0x3344]) # little endian 16/32 bit fields self.assertEqual(perform('le', ['