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