pax_global_header00006660000000000000000000000064142252266240014517gustar00rootroot0000000000000052 comment=011c3b3eaa5d74cb9eaf1a60039c8d58405b7164 tlv8_python-0.10.0/000077500000000000000000000000001422522662400140735ustar00rootroot00000000000000tlv8_python-0.10.0/.coveragerc000066400000000000000000000003051422522662400162120ustar00rootroot00000000000000[run] omit = */.local/* */venv/* */virtualenv/* /usr/* staging/* tests/* [report] omit = */.local/* */venv/* */virtualenv/* /usr/* staging/* tests/*tlv8_python-0.10.0/.github/000077500000000000000000000000001422522662400154335ustar00rootroot00000000000000tlv8_python-0.10.0/.github/workflows/000077500000000000000000000000001422522662400174705ustar00rootroot00000000000000tlv8_python-0.10.0/.github/workflows/main.yml000066400000000000000000000013031422522662400211340ustar00rootroot00000000000000name: run tests on: push: branches: [ main ] pull_request: branches: [ main ] workflow_dispatch: jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: [3.5, 3.6, 3.7, 3.8, 3.9] steps: - uses: actions/checkout@v2 - name: install requirements run: pip install -r requirements.txt - name: run tests run: coverage run -m unittest; coverage lcov - name: run flake8 run: flake8 tlv8 - name: Publish to coveralls.io uses: coverallsapp/github-action@v1.1.2 with: github-token: ${{ github.token }} path-to-lcov: coverage.lcov tlv8_python-0.10.0/.gitignore000066400000000000000000000034371422522662400160720ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ .coverage .idea/ *.html tlv8_python-0.10.0/CHANGES.md000066400000000000000000000026611422522662400154720ustar00rootroot00000000000000 # Changes ## Version 0.10.0 Bug Fix: - Fix for https://github.com/jlusiardi/tlv8_python/issues/15: consider length parameter for integer entries during encoding ## Version 0.9.0 Bug Fix: - Fix for https://github.com/jlusiardi/tlv8_python/issues/13 (and https://github.com/jlusiardi/homekit_python/issues/194) which broke pairing with BLE devices. ## Version 0.8.0 New Features: - `tlv8.encode` can now handle lists of `tlv8.Entry` objects and `tlv8.EntryLists` - adds `tlv8.JsonEncoder` to serialize `tlv8.Entry` and `tlv8.EntryList` objects to json where needed ## Version 0.7.0 New Features: - Add data type `tlv8.DataType.UNSIGNED_INTEGER` to make a distinction between the default of signed integers and unsigned integer. This is important for read network ports from TLV structures ## Version 0.6.0 New Features: - Add function `tlv8.deep_decode` to get a quick view over a TLV structure. ## Version 0.5.0 New Features: - Integration of Coveralls into build pipeline - Add new type `tlv8.EntryList` to have easier access to entries in a TLV list ## Version 0.4.0 New Features: - Support encoding and decoding `IntEnum` keys and and values ## Version 0.3.0 New Features: - `tlv8.decode` now can decode bytearray instances ## Version 0.2.0 New Features: - `tlv8.Entry.encode` now handles also bytearray instances as input for TLV Datatype bytes ## Version 0.1.0 Initial release to the public. tlv8_python-0.10.0/LICENSE000066400000000000000000000261351422522662400151070ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. tlv8_python-0.10.0/README.md000066400000000000000000000344021422522662400153550ustar00rootroot00000000000000# Type-Length-Value8 (TLV8) for python [![run tests](https://github.com/jlusiardi/tlv8_python/actions/workflows/main.yml/badge.svg)](https://github.com/jlusiardi/tlv8_python/actions/workflows/main.yml) [![Coverage Status](https://coveralls.io/repos/github/jlusiardi/tlv8_python/badge.svg?branch=master)](https://coveralls.io/github/jlusiardi/tlv8_python?branch=master) Type-Length-Value (TLV) are used to encode arbitrary data. In this case the type and length are represented by 1 byte each. Hence the name TLV8. A TLV8 entry consists of the following parts: * the **type**: this 8 bit field denotes the type of information that is represented by the data. * the **length**: this 8 bit field denotes the length of the data (this does not include the 2 bytes for type and length. For data longer than 255 bytes, there is a defined procedure available. * the **value**: these **length** bytes represent the value of this TLV. The different types of data is represented differently: * **bytes**: this is raw binary data and will be used as is, no further interpretation takes place * **tlv8**: this is a specialized case of **bytes** values. Using this instead of pure bytes enables nesting of data and creating a hierarchy. * **integer**: integers are stored in little-endian byte order and are encoded with the minimal number of bytes possible (1, 2, 4 or 8) * **float**: floats are stored as little-endian ieee754 numbers * **string**: strings are always UTF-8 encoded and **do not** contain the terminating NULL byte TLV8 entries whose content is longer than 255 bytes are split up into fragments. The type is repeated is repeated in each fragment, only the last fragment may contain less than 255 bytes. Fragments of one TLV8 entry must be continuous. Multiple TLV8 entries can be combined to create larger structures. Entries of different types can placed one after another. Entries of the same type must be separated by a TLV8 entry of a different type (and probably zero length). TLV8 entries of unknown or unwanted type are to be silently ignored. ## Examples ### simple TLV8s Encoding of some atomic examples: * an empty TLV of type 42: `[42, None]` will be encoded as `b'\x2a\x00'`. * a TLV of type 2 with 2 bytes `0x12, 0x34`: `[2, b'\x12\x34']` will be encoded as `b'\x02\x02\x12\x34'` * a TLV of type 3 that contains the TLV from above: `[3, [2, b'\x12\x34']]` will be encoded as `b'\x03\x04\x02\x02\x12\x34'` * a TLV of type 4 that contains 1024: `[4, 1024]` will be encoded as `b'\x04\0x02\x00\x04'` * a TLV of type 5 that contains 3.141: `[4, 3.141]` will be encoded as `b'\x04\x04\x0a\xd7\x23\x41'` * a TLV of type 23 with string `Hello 🌍`: `[23, 'Hello 🌍']` will be encoded as `b'\x17\x0a\x48\x65\x6c\x6c\x6f\x20\xf0\x9f\x8c\x8d'` ### fragmented TLV8s Encoding of a fragmented TLV8 entry: * an TLV of type 6 that contains 256 bytes from 0 to 255: `[6, b'\x00\x01...\xfe\xff']` will be encoded as `b'\x06\xff\x00...\xfe\x06\x01\xff'` ### combined TLV8s Encoding of two TLV8 Entries that follow each other in the input list: * the combination of 2 TLV8 entries (`[1, 123]` and `[2, 'Hello']`) will be encoded as `b'\x01\x01\x7b\x02\x05\x48\x65\x6c\x6c\x6f'` ### sequences of TLV8s of same type: * a sequence of 3 TLV8 entries of type 1 (`[1, 1]`, `[1, 2]` and `[1, 1]`) will be encoded as `b'\x01\x01\x01\xff\x00\x01\x01\x02\xff\x00\x01\x01\x03'` ## Using in code There are two main use cases of this module. ### Create a bytes representation Here we want to have a comfortable way to create a data structure in python and to encode this structure into a bytes value. #### encode a simple list For example, create a representation containing the following structure: * Type: 1, Value: 23 * Type: 2, Value: 2345 This can be code like that: ```python import tlv8 structure = [ tlv8.Entry(1, 23), tlv8.Entry(2, 2345) ] bytes_data = tlv8.encode(structure) print(bytes_data) ``` And this will result in: `b'\x01\x01\x17\x02\x02)\t'` #### Nesting structures Representing a line ([x: 10, y: 20] - [x: 30, y: 40]) between to points could be represented like: * Type: 1, Value: * Type: 3, Value: 10 * Type: 4, Value: 20 * Type: 2, Value: * Type: 3, Value: 30 * Type: 4, Value: 40 ```python import tlv8 structure = [ tlv8.Entry(1, [ tlv8.Entry(3, 10), tlv8.Entry(4, 10), ]), tlv8.Entry(2, [ tlv8.Entry(3, 30), tlv8.Entry(4, 40), ]) ] bytes_data = tlv8.encode(structure) print(bytes_data) ``` And this will result in: `b'\x01\x06\x03\x01\n\x04\x01\n\x02\x06\x03\x01\x1e\x04\x01('` ### Decode a bytes representation Decoding TLV8 entries from bytes data will return all bytes from all first level entries. This includes possible separator entries between entries of the same type. Decoding can be assisted by hinting with an expected structure. To represent the structure in python `dict` objects are used and nested. The keys of the `dict` objects are the type ids of the TLV8 entries. If the id of an entry is not contained in the structure, it will be ignored. #### decode the simple list ```python import tlv8 in_data = b'\x01\x01\x17\x02\x02)\t' expected_structure = { 1: tlv8.DataType.INTEGER, 2: tlv8.DataType.INTEGER } result = tlv8.decode(in_data, expected_structure) print(tlv8.format_string(result)) ``` This will result in: ```text [ <1, 23>, <2, 2345>, ] ``` #### decode nested data ```python import tlv8 in_data = b'\x01\x06\x03\x01\n\x04\x01\n\x02\x06\x03\x01\x1e\x04\x01(' sub_struct = { 3: tlv8.DataType.INTEGER, 4: tlv8.DataType.INTEGER } expected_structure = { 1: sub_struct, 2: sub_struct } result = tlv8.decode(in_data, expected_structure) print(tlv8.format_string(result)) ``` This will result in: ```text [ <1, [ <3, 10>, <4, 10>, ]>, <2, [ <3, 30>, <4, 40>, ]>, ] ``` ### Using IntEnum data during encoding and decoding Using enumerations might increase readabilty of encode end decode processes. ### During encoding It is possible to use `enum.IntEnum` for encoding: ```python import tlv8 import enum class Keys(enum.IntEnum): X = 42 # ... class Values(enum.IntEnum): Y = 23 # ... result = tlv8.encode([ tlv8.Entry(Keys.X, Values.Y) ]) print(result) ``` This will result in: ```text b'*\x01\x17' ``` ### During decoding As during encoding, `enum.IntEnum` can be used for keys and values during decoding: ```python import tlv8 import enum class Keys(enum.IntEnum): X = 42 # ... class Values(enum.IntEnum): Y = 23 # ... result = tlv8.decode(b'*\x01\x17', { Keys.X: Values }) print(tlv8.format_string(result)) print(type(result[0].type_id), type(result[0].data)) ``` This will result in ```text [ , ] ``` So the `type_id` and the `data` fields are not simple `int` instance anymore but values of their enumerations. This alos helps during using `format_string` to get a easier to read output. ## Coding The module offers the following primary functions and classes. ### function `format_string` This function formats a list of TLV8 Entry objects as str. The hierarchy of the entries will be represented by increasing the indentation of the output. The parameters are: * `entries`: a python list of tlv8.Entries objects * `indent`: the level of indentation to be used, this defaults to 0 and is increased on recursive calls for nested entries. The function returns a `str` instance and raises `ValueError` instances if the input is not a list of `tlv8.Entry` objects. Example: ```python import tlv8 data = [ tlv8.Entry(1, 3.141), tlv8.Entry(2, [ tlv8.Entry(3, 'hello'), tlv8.Entry(4, 'world'), ]), tlv8.Entry(1, 2) ] print(tlv8.format_string(data)) ``` This will become: ```text [ <1, 3.141>, <2, [ <3, hello>, <4, world>, ]>, <1, 2>, ] ``` ### function `encode` Function to encode a list of `tlv8.Entry` objects into a sequence of bytes following the rules for creating TLVs. The `separator_type_id` is used for the separating entries between two entries of the same type. The parameters are: * `entries`: a list of `tlv8.Entry` objects * `separator_type_id`: the 8-bit type id of the separator to be used. The default is (as defined in table 5-6, page 51 of HomeKit Accessory Protocol Specification Non-Commercial Version Release R2) 0xff. The function returns an instance of `bytes`. This is empty if nothing was encoded. The function raises `ValueError` if the input parameter is not a list of `tlv8.Entry` objects or a data value is not encodable. A `ValueError` will also be raised if the `separator_type_id` is used as `type_id` in one of the entries as well. Example: ```python import tlv8 data = [ tlv8.Entry(1, 3.141), tlv8.Entry(2, [ tlv8.Entry(3, 'hello'), tlv8.Entry(4, 'world') ]), tlv8.Entry(1, 2) ] print(tlv8.encode(data)) ``` This will result in: ```text b'\x01\x04%\x06I@\x02\x0e\x03\x05hello\x04\x05world\x01\x01\x02' ``` ### function `decode` Function to decode a `bytes` or `bytearray` instance into a list of `tlv8.Entry` instances. This reverses the process done by the `encode` function. The parameters are: * `data`: a `bytes` or `bytearray` instance to be parsed * `expected`: a dict of type ids onto expected `tlv8.DataType` values. If the expected entry is again a `tlv8.Entry` that should be parsed, use another dict to describe the hiearchical structure. This defaults to `None` which means not filtering will be performed but also no interpretation of the entries is done. This means they will be returned as `bytes` sequence. * `strict_mode`: This defaults to `False`. If set to `True`, this will raise additional `ValueError` instances if there are possible missing separators between entries of the same type. The function returns a `list` instance and raises `ValueError` instances if the input is either not a `bytes` object or an invalid tlv8 structure. Example: ```python import tlv8 data = b'\x01\x04%\x06I@\x02\x0e\x03\x05hello\x04\x05world\x03\x01\x02' structure = { 1: tlv8.DataType.FLOAT, 2: { 3: tlv8.DataType.STRING, 4: tlv8.DataType.STRING }, 3: tlv8.DataType.INTEGER } print(tlv8.decode(data, structure)) ``` This will result in: ```text [ <1, 3.1410000324249268>, <2, [ <3, hello>, <4, world>, ]>, <3, 2>, ] ``` ### function `deep_decode` This function works like the `decode` function but tries to do it recursively. That means it decodes the first level of a TLV8 structure first, then looks at each entry and tries to decode that as well. This is mostly meant for debugging purposes in combination with `format_string`. Example: ```python import tlv8 data = b'\x01\x01\x23\x02\x03\x04\x01\x42\x01\x01\x23' print(tlv8.deep_decode(data)) ``` This will result in: ```text [ <1, b'#'>, <2, [ <4, b'B'>, ]>, <1, b'#'>, ] ``` **Notice**: This function might misinterpret data as TLV8 data. For example ```python import tlv8 data = tlv8.encode([ tlv8.Entry(1, 16843330), tlv8.Entry(2, b'\x01') ]) # here data is b'\x01\x04B\x02\x01\x01\x02\x01\x01' print(tlv8.deep_decode(data)) ``` This will result in a misinterpretation of the entry with ID 1: ```text [ <1, [ <66, b'\x01\x01'>, ]>, <2, b'\x01'>, ] ``` ### class `DataType` This enumeration is used to represent the data type of a `tlv8.Entry`. Enumeration Entry | TLV8 type | Python type --- | --- | --- BYTES | bytes | `bytes`, also `bytearray` for encoding TLV8 | tlv8 | custom class `tlv8.Entry` for encoding and `dict` for the expected structure during decoding INTEGER | integer | `int` FLOAT | float | `float` STRING | string | `str` AUTODETECT | n/a | this is used declare that a data type is not preset but will be determined by the python type of the data ### class `Entry` This class represents a single entry in a TLV8 data set. The class overrides the methods `__eq__`, `__str__` and `__repr__` to fit the needs of the application. #### constructor The constructor takes the following parameters: * `type_id`: the type id of the entry. Must be between 0 and 255 (8-bit type id). * `data`: the data to be stored in this entry. * `data_type`: the data type of the entry. Defaults to `DataType.AUTODETECT`. * `length`: if set, this overrides the automatic length detection. This used for integer, when there is special need to set higher byte count than the value would need. The constructor raises a `ValueError` if the `type_id` is not within the 8-bit range. #### `encode() -> bytes` This function is called to encode the data stored in this `Entry`. The data type of the data will be used to decide how to encode the data. It uses the `tlv8.encode()` function to encode nested lists of `tlv8.Entry` objects. #### `format_string() -> str` This function formats the data stored in this entry as readable string. It is mostly called by `tlv8.format_string()`. ### class `EntryList` This class represents a list of entries. The class overrides the methods `__repr__`, `__eq__`, `__len__`, `__getitem__` and `__iter__` to fit the needs of the application. #### constructor The constructor takes the following parameters: * `data`: if set, this `list` of `tlv8.Entry` instances is used to initialize the `EntryList`. The constructor raised a `ValueError` if the data is either not a `list` or not a list of `tlv8.Entry` instances. #### `append(entry)` Append the `tlv8.Entry` to the `EntryList`. It performs type checks, so only `tlv8.Entry` instances can be appended. #### `assert_has(type_id, message)` Looks for a `tlv8.Entry` instance with `type_id` in the first level of the `EntryList`. If none is found, it raises an `AssertionError` with the given `message`. This does not iterate recursivly, because the same type id may have different meanings on different levels (and different contexts). #### `encode(self, separator_type_id)` Encodes the `EntryList` using the given separator type id. This relies on `tlv8.encode()`. #### `by_id(type_id)` Filters the `EntryList` and returns only `Entry` instance whose `type_id` match the given one. If no `Entry` instances were found it returns an empty list. #### `first_by_id(type_id)` Search the `EntryList` for the first `Entry` with the given `type_id`. If no such `Entry` was found, it returns `None`. tlv8_python-0.10.0/requirements.txt000066400000000000000000000000401422522662400173510ustar00rootroot00000000000000coverage flake8 twine coveralls tlv8_python-0.10.0/setup.cfg000066400000000000000000000001561422522662400157160ustar00rootroot00000000000000[metadata] description-file = README.md [run] source = tlv [flake8] max-line-length = 120 statistics = True tlv8_python-0.10.0/setup.py000066400000000000000000000032761422522662400156150ustar00rootroot00000000000000# # Copyright 2020 Joachim Lusiardi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name='tlv8', packages=setuptools.find_packages(exclude=['tests']), version='0.10.0', description='Python module to handle type-length-value (TLV) encoded data 8-bit type, 8-bit length, and N-byte ' 'value as described within the Apple HomeKit Accessory Protocol Specification Non-Commercial Version ' 'Release R2.', author='Joachim Lusiardi', author_email='pypi@lusiardi.de', url='https://github.com/jlusiardi/tlv8_python', download_url='https://github.com/jlusiardi/tlv8_python/archive/0.10.0.tar.gz', keywords=['TLV', 'Type-Length-Value', 'tlv8'], classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Topic :: Home Automation', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop' ], install_requires=[ ], extras_require={ }, license='Apache License 2.0', long_description=long_description, long_description_content_type="text/markdown", ) tlv8_python-0.10.0/tests/000077500000000000000000000000001422522662400152355ustar00rootroot00000000000000tlv8_python-0.10.0/tests/__init__.py000066400000000000000000000023521422522662400173500ustar00rootroot00000000000000# # Copyright 2020 Joachim Lusiardi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # __all__ = [ 'TestTLV8', 'TestTLV8Decode', 'TestTLV8Entry', 'TestTLV8Enum', 'TestTLV8EntryList', 'TestTLV8DeepDecode', 'TestTLV8DecodeInteger', 'TestTLV8RealWorld', 'TestTLV8ToJson' ] from tests.tlv8_encode_tests import TestTLV8 from tests.tlv8_decode_tests import TestTLV8Decode from tests.tlv8_deep_decode_tests import TestTLV8DeepDecode from tests.tlv8_entry_tests import TestTLV8Entry from tests.tlv8_enum_test import TestTLV8Enum from tests.tlv8_entrylist_tests import TestTLV8EntryList from tests.tlv8_decode_integer_tests import TestTLV8DecodeInteger from tests.tlv8_real_world_test import TestTLV8RealWorld from tests.tlv8_to_json_test import TestTLV8ToJson tlv8_python-0.10.0/tests/tlv8_decode_integer_tests.py000066400000000000000000000124061422522662400227510ustar00rootroot00000000000000# # Copyright 2020 Joachim Lusiardi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import unittest from struct import pack import tlv8 class TestTLV8DecodeInteger(unittest.TestCase): def test_decode_int1_neg(self): input_data = b'\x01\x01' + pack('') def test_str_bytes(self): entry1 = tlv8.Entry(1, b'23') self.assertEqual(entry1.__str__(), '') def test_str_int(self): entry1 = tlv8.Entry(1, 23) self.assertEqual(entry1.__str__(), '') def test_str_float(self): entry1 = tlv8.Entry(1, 23.42) self.assertEqual(entry1.__str__(), '') def test_equal_different_types(self): entry1 = tlv8.Entry(1, 42) self.assertNotEqual(entry1, 'ping') def test_equal_different_ids(self): entry1 = tlv8.Entry(1, 42) entry2 = tlv8.Entry(2, 42) self.assertNotEqual(entry1, entry2) def test_equal_different_floats(self): entry1 = tlv8.Entry(1, 42.1) entry2 = tlv8.Entry(1, 42.2) self.assertNotEqual(entry1, entry2) def test_equal_same_floats(self): entry1 = tlv8.Entry(1, 42.1, tlv8.DataType.FLOAT) entry2 = tlv8.Entry(1, 42.10001, tlv8.DataType.FLOAT) self.assertEqual(entry1, entry2) def test_equal(self): entry1 = tlv8.Entry(1, 42) entry2 = tlv8.Entry(1, 41) self.assertFalse(entry1 == entry2) self.assertNotEqual(entry1, entry2) def test_format_string(self): data = [ tlv8.Entry(1, 3.141), tlv8.Entry(2, [ tlv8.Entry(3, 'hello'), tlv8.Entry(4, 'world'), ]), tlv8.Entry(1, 2) ] print(tlv8.format_string(data)) def test_format_string_error_1(self): self.assertRaises(ValueError, tlv8.format_string, {}) def test_format_string_error_2(self): self.assertRaises(ValueError, tlv8.format_string, [1]) def test_create_entry_error(self): self.assertRaises(ValueError, tlv8.Entry, 256, b'') tlv8_python-0.10.0/tests/tlv8_entrylist_tests.py000066400000000000000000000114421422522662400220450ustar00rootroot00000000000000# # Copyright 2020 Joachim Lusiardi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import unittest import tlv8 class TestTLV8EntryList(unittest.TestCase): def test_entrylist_init(self): with self.assertRaises(ValueError) as error_context: tlv8.EntryList('not a list') self.assertEqual(str(error_context.exception), 'No valid list: not a list') with self.assertRaises(ValueError) as error_context: tlv8.EntryList(['not an entry']) self.assertEqual(str(error_context.exception), 'Not a valid tlv8.Entry: not an entry') def test_entrylist_append(self): el = tlv8.EntryList() with self.assertRaises(ValueError) as error_context: el.append('not a list') self.assertEqual(str(error_context.exception), 'Not an tlv8.Entry: not a list') def test_entrylist_compare_empty(self): el_1 = tlv8.EntryList() el_2 = tlv8.EntryList() self.assertEqual(el_1, el_2) def test_entrylist_compare_not_a_list(self): el_1 = tlv8.EntryList() self.assertNotEqual(el_1, 'not a entry list') def test_entrylist_compare_1_equal(self): el_1 = tlv8.EntryList([tlv8.Entry(1, 2)]) el_2 = tlv8.EntryList([tlv8.Entry(1, 2)]) self.assertEqual(el_1, el_2) def test_entrylist_compare_1_not_equal(self): el_1 = tlv8.EntryList([tlv8.Entry(1, 2)]) el_2 = tlv8.EntryList([tlv8.Entry(1, 3)]) self.assertNotEqual(el_1, el_2) def test_entrylist_length(self): el = tlv8.EntryList() self.assertEqual(0, len(el)) el.append(tlv8.Entry(1, 2)) self.assertEqual(1, len(el)) el.append(tlv8.Entry(1, 2)) self.assertEqual(2, len(el)) def test_entrylist_index(self): el = tlv8.EntryList() e1 = tlv8.Entry(1, 2) e2 = tlv8.Entry(3, 4) el.append(e1) el.append(e2) self.assertEqual(e2, el[1]) def test_entrylist_decode(self): input_data = bytearray(b'\x02\x01\x23') result = tlv8.decode(input_data) self.assertIsInstance(result, tlv8.EntryList) self.assertEqual(result, tlv8.EntryList([tlv8.Entry(2, b'\x23')])) def test_entrylist_encode(self): el = tlv8.EntryList([tlv8.Entry(2, b'\x23')]) result = el.encode() self.assertEqual(b'\x02\x01\x23', result) def test_entrylist_encode_same_sep_type(self): el = tlv8.EntryList([ tlv8.Entry(2, b'\x23'), tlv8.Entry(2, b'\x42') ]) result = el.encode(1) self.assertEqual(b'\x02\x01\x23\x01\x00\x02\x01\x42', result) def test_entrylist_assert_has(self): el = tlv8.EntryList([ tlv8.Entry(2, b'\x23') ]) with self.assertRaises(AssertionError) as error_context: el.assert_has(3, 'no bla bla') self.assertEqual(str(error_context.exception), 'no bla bla') el.assert_has(2, 'no bla bla') def test_entrylist_decode_nested(self): data = b'\x01\x04%\x06I@\x02\x0e\x03\x05hello\x04\x05world\x03\x01\x02' result = tlv8.decode(data, { 1: tlv8.DataType.FLOAT, 2: { 3: tlv8.DataType.STRING, 4: tlv8.DataType.STRING, }, 3: tlv8.DataType.INTEGER }) self.assertIsInstance(result, tlv8.EntryList) self.assertIsInstance(result[1].data, tlv8.EntryList) def test_entrylist_by_id(self): el = tlv8.EntryList([ tlv8.Entry(2, b'\x23'), tlv8.Entry(2, b'\x42') ]) self.assertEqual(el.by_id(1), tlv8.EntryList()) self.assertEqual(el.by_id(2), el) def test_entrylist_first_by_id(self): el = tlv8.EntryList([ tlv8.Entry(2, b'\x23'), tlv8.Entry(2, b'\x42') ]) self.assertEqual(el.first_by_id(1), None) self.assertEqual(el.first_by_id(2), el[0]) def test_entrylist_format_string(self): el = tlv8.EntryList([ tlv8.Entry(1, 1), tlv8.Entry(2, tlv8.EntryList([ tlv8.Entry(4, 4), tlv8.Entry(5, 5) ])), tlv8.Entry(3, 3), ]) result = tlv8.format_string(el) expected = """[ <1, 1>, <2, [ <4, 4>, <5, 5>, ]>, <3, 3>, ]""" self.assertEqual(result, expected) tlv8_python-0.10.0/tests/tlv8_enum_test.py000066400000000000000000000051251422522662400205720ustar00rootroot00000000000000# # Copyright 2020 Joachim Lusiardi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import unittest import enum import tlv8 class TestTLV8Enum(unittest.TestCase): def test_decode_enum(self): class TestKeys(enum.IntEnum): KEY_1 = 1 KEY_2 = 2 class TestValues(enum.IntEnum): VALUE_1 = 1 VALUE_2 = 2 data = b'\x01\x01\x02' result = tlv8.decode(data, { TestKeys.KEY_1: TestValues }) expected = tlv8.EntryList([ tlv8.Entry(TestKeys.KEY_1, TestValues.VALUE_2) ]) self.assertIsInstance(result[0].type_id, TestKeys) self.assertIsInstance(result[0].data, TestValues) self.assertEqual(expected, result) def test_decode_key(self): class TestKeys(enum.IntEnum): KEY_1 = 1 KEY_2 = 2 data = b'\x01\x03foo' result = tlv8.decode(data, { TestKeys.KEY_1: tlv8.DataType.STRING }) expected = tlv8.EntryList([ tlv8.Entry(TestKeys.KEY_1, 'foo') ]) self.assertIsInstance(result[0].type_id, TestKeys) self.assertEqual(expected, result) def test_decode_value(self): class TestValues(enum.IntEnum): VALUE_1 = 1 VALUE_2 = 2 data = b'\x01\x01\x02' result = tlv8.decode(data, { 1: TestValues }) expected = tlv8.EntryList([ tlv8.Entry(1, 2) ]) self.assertIsInstance(result[0].data, TestValues) self.assertEqual(expected, result) def test_encode_key(self): class TestKeys(enum.IntEnum): KEY_1 = 1 KEY_2 = 2 data = [ tlv8.Entry(TestKeys.KEY_1, 'foo') ] result = tlv8.encode(data) self.assertEqual(b'\x01\x03foo', result) def test_encode_int_value(self): class TestValues(enum.IntEnum): VAL_1 = 1 VAL_2 = 2 data = [ tlv8.Entry(1, TestValues.VAL_2) ] result = tlv8.encode(data) self.assertEqual(b'\x01\x01\x02', result) tlv8_python-0.10.0/tests/tlv8_real_world_test.py000066400000000000000000000134311422522662400217570ustar00rootroot00000000000000# # Copyright 2020 Joachim Lusiardi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import unittest import enum import binascii import tlv8 class TestTLV8RealWorld(unittest.TestCase): def test_1(self): data = tlv8.EntryList([ tlv8.Entry(1, b'W\x1ah\xac)\x04C\xfd\x84\xb36\t\xd1\x1bO\x83'), tlv8.Entry(3, tlv8.EntryList([ tlv8.Entry(1, 0), tlv8.Entry(2, '192.168.178.222'), ])) ]) encoded = tlv8.encode(data) decoded = tlv8.decode( encoded, { 1: tlv8.DataType.BYTES, 3: { 1: tlv8.DataType.UNSIGNED_INTEGER, 2: tlv8.DataType.STRING } } ) self.assertEqual(data, decoded) encoded_2 = tlv8.encode(decoded) self.assertEqual(encoded, encoded_2) def test_2(self): class Foo(enum.IntEnum): Bar = 1 Baz = 2 data = tlv8.EntryList([ tlv8.Entry(1, b'W\x1ah\xac)\x04C\xfd\x84\xb36\t\xd1\x1bO\x83'), tlv8.Entry(3, tlv8.EntryList([ tlv8.Entry(1, Foo.Bar), tlv8.Entry(2, '192.168.178.222'), ])) ]) encoded = tlv8.encode(data) decoded = tlv8.decode( encoded, { 1: tlv8.DataType.BYTES, 3: { 1: Foo, 2: tlv8.DataType.STRING } } ) self.assertEqual(data, decoded) encoded_2 = tlv8.encode(decoded) self.assertEqual(encoded, encoded_2) def test_3(self): """ Example for a broken decode from https://github.com/jlusiardi/homekit_python/issues/194. """ data = '01ff0601040440371bf8c6cd6a7fb85e77a7b436a1b5300ed2023ca7e23f61303856a57358fd8ac03f288472776854765eb3' \ 'a2fcb4497c8b5497c29c88a574479030ec36b176ae05ff85c337879f0a4146a9cc089e0cb48ba3c9c21af0b206d493b224de' \ 'ee52ff0f9b1d8710db6531748ee6d1d66b8b4a6d0690670fb8f1233010d190c4ede1776cb10806eae66c78881647e82e9ba7' \ 'c806f52184c6f108275719cf425c4f8ea0e86c6534712343f88a1482c986e3dd252715872dee506520903c17d27f02ea8957' \ '719c255631b78a9f2ecb7af0dc245b370cefef28f4652eebbe34afda0138039714665dd880559d1f2667294207892137820c' \ 'd80533d8c0b22601ffa49d1bdc1b641a33297fe59672a89d69391417c77e31283cd7f0d40920004d1bf1fc38357d9599ac2b' \ '4d8ce3ac7ab8725a01500d198e94b00da80aac64ead393b266dcf9d4a07c05ff34548f7ebebd63f8a00ae2c82f6ee8ac6bcc' \ 'e0ab1030e9268c36714e2ec11c3bf21331129d62978e069dd087cbbdc31bdd6e0cf4ca825b91ab3c8b240de19aa097fc01cd' \ '471e8c1b5598044d21be12b84c97a1d70e46681e5ecebbde1c33bae9bbd9b3ad41ba2aff8f1f952d0ef0cfcb8a674d5b4c7f' \ '515ba94341334e86aac277920bd9080b9bf702e16671a3e41c0930beb8a552aefc28a3a9a7f2818e8fbb84c37ae10fb6c5d2' \ '2e6ba9899e01f082381c9a3344ecbaf801ff85e33306ec9823e72ec4c93f9a45aa657b16f46757aaaf7c74daf35840e68749' \ '42c132f4a639562920318b9f9867d8e5b0d50deac48c4e14842c91d565b0dd1fec667d092d123a4e1a05fff0b7070f184b4f' \ '399532c0d1cc0aaea326efea765bc88ace048040a3e07a741e26ef55203bb3f76c075e3b6d20ede89a2eaa63e23376b0dff4' \ 'ef3a797df34a39d8130f60316e86cafcb264b0b570376ba911dc2bda031328ea1c915a724bc69ad2700623ed19c3ae75f946' \ '4e3b1669adb916ad58e3252580911db2b535af3f2b2207aea880a0d24f1f759888bd5e25b6cf7b2e5ce825ab0fd943a8378a' \ 'eb12906e0965540af14dc0bfa3fae2eb5361992efaf56501ff6ed5c6e686a4af3c2fa121c810cb84cd5abac94f6d618af493' \ '29e34fa613d2b758e3bc79eb03cb78328f9cd34df43566589615e42088681b4f69775350c9abf68c107d312b0f2421bb53cf' \ '05ff50c14d6ff0da74b50d9b080c5c06175d66b24b35eb1e25f940170c0815a0ead23703b86da2103cd1b33021fd981d95c6' \ 'a32a3752dc903b0acba949d7d51a1bcabaebc52941bb25d558132feb1794481c0a5911e53553407a8771503d7673d4c3061a' \ '4d2d41a2897fe507423509760fbe4847423a51155b99b67bf43c72958ce9409a459b5ce42e61309e96091411b256ec294fb0' \ 'f32782efc80d9d548f3cee4fdb21babd011e118238ec7545b24e5af74317a2670179930156512875653dce4e957e94a7596f' \ 'a7e2b533a3eacb9781634c79c094e2cbfcfc62128a25431f9b56cc40b6097614e7a4b08c32b3a7f2e471f55a295a9a06e5b0' \ 'e07dec2ad282842aa6f176052acd544cb5d67c206a3e38e80e32f560a57edda173892a39b021d616d8f2862a5d111e6610c1e7' data = binascii.unhexlify(data) resp_data = tlv8.decode(data, {1: tlv8.DataType.BYTES}) self.assertIsNotNone(resp_data.first_by_id(1)) self.assertEqual(len(resp_data.first_by_id(1).data), 510) resp_data = tlv8.decode(resp_data.first_by_id(1).data, {4: tlv8.DataType.BYTES, 6: tlv8.DataType.BYTES}) self.assertIsNotNone(resp_data.first_by_id(4)) print(resp_data.first_by_id(4).data) self.assertEqual(resp_data.first_by_id(4).data, b'7\x1b\xf8\xc6\xcdj\x7f\xb8^w\xa7\xb46\xa1\xb50\x0e\xd2\x02<\xa7\xe2?a08V\xa5sX\xfd\x8a' b'\xc0?(\x84rwhTv^\xb3\xa2\xfc\xb4I|\x8bT\x97\xc2\x9c\x88\xa5tG\x900\xec6\xb1v\xae') self.assertIsNotNone(resp_data.first_by_id(6)) self.assertEqual(resp_data.first_by_id(6).data, b'\x04') tlv8_python-0.10.0/tests/tlv8_to_json_test.py000066400000000000000000000023011422522662400212720ustar00rootroot00000000000000# # Copyright 2020 Joachim Lusiardi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import unittest import json import tlv8 class TestTLV8ToJson(unittest.TestCase): def test_entry_to_json(self): e = tlv8.Entry(1, 'hello') j = json.dumps(e, cls=tlv8.JsonEncoder) self.assertEqual('{"1": "hello"}', j) def test_entry_list_to_json(self): e1 = tlv8.Entry(1, 'hello') e2 = tlv8.Entry(2, 'world') el = tlv8.EntryList([e1, e2]) j = json.dumps(el, cls=tlv8.JsonEncoder) self.assertEqual('[{"1": "hello"}, {"2": "world"}]', j) def test_string_to_json(self): j = json.dumps(True, cls=tlv8.JsonEncoder) self.assertEqual('true', j) tlv8_python-0.10.0/tlv8/000077500000000000000000000000001422522662400147705ustar00rootroot00000000000000tlv8_python-0.10.0/tlv8/__init__.py000066400000000000000000000505001422522662400171010ustar00rootroot00000000000000# # Copyright 2020 Joachim Lusiardi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # __all__ = [ 'encode', 'format_string', 'decode', 'DataType', 'Entry', 'JsonEncoder' ] import enum from struct import pack, unpack, error import json try: from math import isclose except ImportError: def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) class EntryList(object): def __init__(self, data=None): """ Create a new EntryList instance. It is initialized with the given data :param data: this must be a list of Entry instances :raises: ValueError is risen if either data is not a list or not all list entries are Entry instances """ if data: if isinstance(data, list): for entry in data: if not isinstance(entry, Entry): raise ValueError('Not a valid tlv8.Entry: {e}'.format(e=entry)) self.data = data else: raise ValueError('No valid list: {e}'.format(e=data)) else: self.data = [] def append(self, entry): """ Appends an tlv8.Entry to this tlv8.EntryList. This works like list.append(). :param entry: the entry to append :raises: ValueError if the entry to add is no tlv8.Entry """ if not isinstance(entry, Entry): raise ValueError('Not an tlv8.Entry: {e}'.format(e=entry)) self.data.append(entry) def __iter__(self): return self.data.__iter__() def __getitem__(self, item): return self.data[item] def __len__(self): return self.data.__len__() def assert_has(self, type_id, message=''): """ Scan this entry list for entries with the given type id. If no entry was found an AssertionError with the given message is raised. :param type_id: the type id to check for :param message: the message of the AssertionError if raised :raises: AssertionError if no entry with the type id was found """ if self.first_by_id(type_id): return raise AssertionError(message) def __eq__(self, other): if isinstance(other, self.__class__): return self.data == other.data else: return False def __repr__(self): return '' def encode(self, separator_type_id=0xff): """ Function to encode this EntryList into a sequence of bytes following the rules for creating TLVs. :param separator_type_id: the 8-bit id of the separator to be used in two fields of the same type id are directly after one another in the list. The default is (as defined in table 5-6, page 51 of HomeKit Accessory Protocol Specification Non-Commercial Version Release R2) 0xff. :return: an instance of bytes. if nothing was encoded, it returns an empty instance :raises ValueError: if the input parameter is not conform to a list of tlv8.Entry objects """ return encode(self.data, separator_type_id) def by_id(self, type_id): """ Filters the entry list and returns only those entries whose type is of the given value. :param type_id: the type id to look for :return: a EntryList instance containing all found entries, the list may be empty. """ return EntryList([entry for entry in self.data if entry.type_id == type_id]) def first_by_id(self, type_id): """ Scan this entry list and return the first entry whose type is of the given value. :param type_id: the type id to look for :return: a Entry instance or None, if not a single entry has the searched type id """ for entry in self.data: if entry.type_id == type_id: return entry return None def format_string(entries: list, indent=0) -> str: """ Format a list of TLV8 Entry objects or a EntryList as str instance. The hierarchy of the entries will be represented by increasing the indentation of the output. Example: ``` data = [ tlv8.Entry(1, 3.141), tlv8.Entry(2, [ tlv8.Entry(3, 'hello'), tlv8.Entry(4, 'world'), ]), tlv8.Entry(1, 2) ] print(tlv8.format_string(data)) ``` will become: ``` [ <1, 3.141>, <2, [ <3, hello>, <4, world>, ]>, <1, 2>, ] ``` :param entries: a list of tlv8.Entries objects :param indent: the level of indentation to be used :return: a str instance with the formatted representation of the input :raises ValueError: if the input parameter is not conform to a list of tlv8.Entry objects """ if not (isinstance(entries, list) or isinstance(entries, EntryList)): raise ValueError('The parameter entries must be of type list or EntryList') result = '[\n' for entry in entries: if not isinstance(entry, Entry): raise ValueError('The parameter entries must only contain elements of type tlv8.Entry') result += ' ' * (indent + 2) + entry.format_string(indent + 2) + '\n' result += ' ' * indent + ']' return result def encode(entries: list, separator_type_id=0xff) -> bytes: """ Function to encode a list of TLV Entry objects into a sequence of bytes following the rules for creating TLVs. :param entries: a list of tlv8.Entries objects :param separator_type_id: the 8-bit id of the separator to be used in two fields of the same type id are directly after one another in the list. The default is (as defined in table 5-6, page 51 of HomeKit Accessory Protocol Specification Non-Commercial Version Release R2) 0xff. :return: an instance of bytes. if nothing was encoded, it returns an empty instance :raises ValueError: if the input parameter is not conform to a list of tlv8.Entry objects """ if not isinstance(entries, list) and not isinstance(entries, EntryList): raise ValueError('The parameter entries must be of type list') result = b'' last_type_id = None for entry in entries: if not isinstance(entry, Entry): raise ValueError('The parameter entries must only contain elements of type tlv8.Entry') if entry.type_id == separator_type_id: raise ValueError('Separator type id {st} occurs with list of entries!'.format(st=separator_type_id)) if last_type_id == entry.type_id: # must insert separator of two entries of the same type succeed one an other result += pack(' EntryList: if isinstance(data, bytearray): data = bytes(data) if not isinstance(data, bytes): raise ValueError('data parameter must be bytes or bytearray not {}'.format(type(data))) if len(data) == 0: # no data, nothing to do return EntryList() tmp = EntryList() remaining_data = data while len(remaining_data) > 0: if len(remaining_data) < 2: # the shortest encoded TLV8 is 3 bytes, we got less, so raise an error raise ValueError('Bytes with length {len} is not a valid TLV8.'.format(len=len(data))) tlv_id = unpack(' 0: break if len(remaining_data[2:]) < tlv_len: # the remaining data is less than the encoded length raise ValueError('Not enough data left. {} vs {}'.format(len(remaining_data[2:]), tlv_len)) tlv_data = remaining_data[2:2 + tlv_len] if len(tmp) > 0 and tmp[-1].type_id == tlv_id: # we have the same type id so we expect the size of the data so far to be 0 mod 255 if len(tmp[-1].data) % 255 != 0: # it there was no max size fragment before, this is either if strict_mode: # an error in strict mode raise ValueError('Missing separator detected.') else: # or we let it pass as a second instance of the type id. both could be wrong tmp.append(Entry(tlv_id, tlv_data)) else: # max size fragments are added the new data tmp[-1].data += tlv_data else: tmp.append(Entry(tlv_id, tlv_data)) remaining_data = remaining_data[2 + tlv_len:] return tmp def deep_decode(data, strict_mode=False) -> EntryList: """ Decodes a sequence of bytes or bytearray into a list of hierarchical TLV8 Entries. This is done recursivly and does not consider any typing. :param data: a bytes or bytearray instance. :param strict_mode: if set to True, bail out if there consecutive entry of the same type without separators. :return: a list of tlv8.Entry objects :raises: ValueError on failures during decoding """ tmp = _internal_decode(data, None, strict_mode) for entry in tmp: try: r = deep_decode(entry.data) entry.data = r except Exception: pass return tmp def decode(data, expected=None, strict_mode=False) -> EntryList: """ Decodes a sequence of bytes or bytearray into a list of hierarchical TLV8 Entries. :param data: a bytes or bytearray instance. :param expected: a dict of type ids onto expected DataTypes. If an entry is again a TLV8 Entry, use another dict to describe the hierarchical structure. This defaults to None which means not filtering will be performed but also no interpretation of the entries is done. This means they will be returned bytes sequence. :param strict_mode: if set to True, bail out if there consecutive entry of the same type without separators. :return: a list of tlv8.Entry objects :raises: ValueError on failures during decoding """ tmp = _internal_decode(data, expected, strict_mode) # if we do not know what is expected, we just return the unfiltered, uninterpreted but parsed list of entries if not expected: return tmp # generate a map between the int values and the potential enums enum_map = { int(x[0]): x[0] for x in expected.items() } def decode_int(tlv_entry): """ Decode an int value from a tlv entry. This respects the length of the integer. The entry will be updated in place. :param tlv_entry: the tlv entry to decode """ if tlv_len == 1: tlv_entry.data = unpack(''.format(t=self.type_id, d=self.data) def encode(self, separator_type_id=0xff): """ Encode this TLV8 entry into a sequence of bytes. :return: a bytes instance :raises: ValueError if data to encode is not encodable (e.g. an Integer is bigger than 64 bit) """ data_type = self.data_type if data_type == DataType.AUTODETECT: # detect the data type if isinstance(self.data, bytearray): data_type = DataType.BYTES if isinstance(self.data, bytes): data_type = DataType.BYTES if isinstance(self.data, float): data_type = DataType.FLOAT if isinstance(self.data, str): data_type = DataType.STRING if isinstance(self.data, int): data_type = DataType.INTEGER if isinstance(self.data, list): data_type = DataType.TLV8 if isinstance(self.data, EntryList): data_type = DataType.TLV8 remaining_data = None supports_length_overwrite = False if isinstance(data_type, enum.EnumMeta): data_type = DataType.INTEGER if data_type == DataType.BYTES: remaining_data = self.data elif data_type == DataType.TLV8 or isinstance(data_type, dict): remaining_data = encode(self.data, separator_type_id) elif data_type == DataType.INTEGER: supports_length_overwrite = True for int_format in [' 0): remaining_data += bytes(self.length - len(remaining_data)) result = pack(' 0: if len(remaining_data) < 256: result += pack('