├── .flake8 ├── .github └── workflows │ ├── pre-commit.yml │ ├── publish-pypi.yml │ └── run_tests.yml ├── .gitignore ├── .isort.cfg ├── .mypy.ini ├── .pre-commit-config.yaml ├── .readthedocs.yml ├── LICENSE ├── MANIFEST.in ├── curves.svg ├── docs ├── conf.py ├── index.rst ├── pyartnet.rst └── requirements.txt ├── readme.md ├── requirements.txt ├── setup.py ├── src └── pyartnet │ ├── __init__.py │ ├── __version__.py │ ├── base │ ├── __init__.py │ ├── background_task.py │ ├── base_node.py │ ├── channel.py │ ├── channel_fade.py │ ├── output_correction.py │ ├── seq_counter.py │ └── universe.py │ ├── errors.py │ ├── fades │ ├── __init__.py │ ├── fade_base.py │ └── fade_linear.py │ ├── impl_artnet │ ├── __init__.py │ ├── node.py │ └── universe.py │ ├── impl_kinet │ ├── __init__.py │ ├── node.py │ └── universe.py │ ├── impl_sacn │ ├── __init__.py │ ├── node.py │ └── universe.py │ └── output_correction.py ├── tests ├── channel │ ├── __init__.py │ ├── test_boundaries.py │ ├── test_buffer.py │ ├── test_channel.py │ ├── test_fade.py │ └── test_set_values.py ├── conftest.py ├── helper.py ├── test_base_node.py ├── test_channel_fade.py ├── test_impl │ ├── test_impl.py │ └── test_sacn.py ├── test_output_correction.py ├── test_sequence_counter.py └── test_universe.py └── tox.ini /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore = 3 | # E201 whitespace after '(' 4 | E201, 5 | # E221 multiple spaces before operator 6 | E203, 7 | # E203 whitespace before ':' 8 | E221, 9 | # E251 unexpected spaces around keyword / parameter equals 10 | E251 11 | # E303 too many blank lines 12 | E303 13 | 14 | #-------------------------------------------------------------------------- 15 | # PLUGINS 16 | #-------------------------------------------------------------------------- 17 | 18 | # PT007 wrong values type in @pytest.mark.parametrize, expected list 19 | PT007 20 | 21 | 22 | max-line-length = 120 23 | exclude = 24 | .git, 25 | .tox, 26 | __pycache__, 27 | build, 28 | dist, 29 | __init__.py, 30 | -------------------------------------------------------------------------------- /.github/workflows/pre-commit.yml: -------------------------------------------------------------------------------- 1 | name: Pre-Commit 2 | 3 | on: 4 | pull_request: 5 | branches: [main, master] 6 | 7 | jobs: 8 | main: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v3 12 | - uses: actions/setup-python@v4 13 | with: 14 | python-version: '3.10' 15 | - uses: pre-commit/action@v3.0.0 16 | -------------------------------------------------------------------------------- /.github/workflows/publish-pypi.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python distributions to PyPI 2 | on: 3 | release: 4 | types: [published] 5 | 6 | jobs: 7 | build-n-publish: 8 | name: Build and publish Python 🐍 distributions 📦 to PyPI and TestPyPI 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - uses: actions/checkout@v3 13 | with: 14 | ref: master 15 | - name: Set up Python 3.10 16 | uses: actions/setup-python@v4 17 | with: 18 | python-version: '3.10' 19 | 20 | - name: Install setuptools 21 | run: | 22 | python -m pip install --upgrade pip 23 | python -m pip install --upgrade setuptools wheel twine 24 | 25 | - name: Build a binary wheel and a source tarball 26 | run: | 27 | python setup.py sdist bdist_wheel 28 | 29 | - name: Publish distribution to PyPI 30 | uses: pypa/gh-action-pypi-publish@master 31 | with: 32 | user: __token__ 33 | password: ${{ secrets.pypi_api_key }} 34 | -------------------------------------------------------------------------------- /.github/workflows/run_tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | max-parallel: 4 10 | matrix: 11 | python-version: ['3.8', '3.9', '3.10', '3.11'] 12 | 13 | steps: 14 | - uses: actions/checkout@v3 15 | - name: Set up Python ${{ matrix.python-version }} 16 | uses: actions/setup-python@v4 17 | with: 18 | python-version: ${{ matrix.python-version }} 19 | - name: Install dependencies 20 | run: | 21 | python -m pip install --upgrade pip 22 | pip install tox tox-gh-actions 23 | - name: Test with tox 24 | run: tox 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .mypy_cache 2 | .idea 3 | __pycache__ 4 | /conf 5 | /build 6 | /log.log 7 | /venv/ 8 | -------------------------------------------------------------------------------- /.isort.cfg: -------------------------------------------------------------------------------- 1 | [settings] 2 | line_length = 120 3 | 4 | src_paths = src, tests 5 | 6 | ensure_newline_before_comments = True 7 | force_alphabetical_sort_within_sections = True 8 | 9 | balanced_wrapping = True 10 | multi_line_output = 2 11 | -------------------------------------------------------------------------------- /.mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | check_untyped_defs = True 3 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | 3 | - repo: https://github.com/pre-commit/pre-commit-hooks 4 | rev: v4.4.0 5 | hooks: 6 | - id: check-yaml 7 | - id: end-of-file-fixer 8 | exclude: \.(?:pdf|svg)$ 9 | - id: trailing-whitespace 10 | 11 | 12 | - repo: https://github.com/pycqa/isort 13 | rev: 5.12.0 14 | hooks: 15 | - id: isort 16 | name: isort (python) 17 | 18 | 19 | - repo: https://github.com/PyCQA/flake8 20 | rev: '6.0.0' 21 | hooks: 22 | - id: flake8 23 | additional_dependencies: 24 | - flake8-bugbear==23.1.20 25 | - flake8-comprehensions==3.10.1 26 | - flake8-pytest-style==1.6 27 | - flake8-noqa==1.3 28 | - pep8-naming==0.13.3 29 | 30 | - repo: https://github.com/pre-commit/pygrep-hooks 31 | rev: v1.10.0 32 | hooks: 33 | - id: rst-backticks 34 | 35 | 36 | - repo: meta 37 | hooks: 38 | - id: check-hooks-apply 39 | - id: check-useless-excludes 40 | -------------------------------------------------------------------------------- /.readthedocs.yml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yml 2 | # Read the Docs configuration file 3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 4 | 5 | # Required 6 | version: 2 7 | 8 | # Build documentation in the docs/ directory with Sphinx 9 | sphinx: 10 | configuration: docs/conf.py 11 | 12 | # Build documentation with MkDocs 13 | #mkdocs: 14 | # configuration: mkdocs.yml 15 | 16 | # Optionally build your docs in additional formats such as PDF and ePub 17 | formats: all 18 | 19 | build: 20 | os: ubuntu-22.04 21 | tools: 22 | python: "3.10" 23 | 24 | # Optionally set the version of Python and requirements required to build your docs 25 | python: 26 | install: 27 | - requirements: docs/requirements.txt 28 | - method: setuptools 29 | path: . 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | -------------------------------------------------------------------------------- /curves.svg: -------------------------------------------------------------------------------- 1 | 020406080100120140160180200220240260020406080100120140160180200220240260 -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import sys 4 | 5 | RTD_BUILD = os.environ.get('READTHEDOCS') == 'True' 6 | 7 | # Configuration file for the Sphinx documentation builder. 8 | # 9 | # For the full list of built-in configuration values, see the documentation: 10 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 11 | 12 | 13 | # -- Project information ----------------------------------------------------- 14 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information 15 | 16 | project = 'PyArtNet' 17 | copyright = '2023, spacemanspiff2007' 18 | author = 'spacemanspiff2007' 19 | 20 | 21 | # -- General configuration --------------------------------------------------- 22 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration 23 | 24 | extensions = [ 25 | 'sphinx_exec_code', 26 | 'sphinx.ext.autodoc', 27 | 'sphinx.ext.intersphinx', 28 | 'sphinx_autodoc_typehints', 29 | ] 30 | 31 | templates_path = ['_templates'] 32 | exclude_patterns = [] 33 | 34 | 35 | # -- Options for HTML output ------------------------------------------------- 36 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output 37 | 38 | html_theme = 'sphinx_rtd_theme' 39 | html_static_path = ['_static'] 40 | 41 | 42 | # -- Options for exec code ------------------------------------------------- 43 | exec_code_working_dir = '../src' 44 | exec_code_source_folders = ['../src', '../tests'] 45 | 46 | 47 | # -- Options for autodoc ------------------------------------------------- 48 | autodoc_member_order = 'bysource' 49 | autoclass_content = 'class' 50 | 51 | # required for autodoc 52 | sys.path.insert(0, os.path.join(os.path.abspath('..'), 'src')) 53 | 54 | 55 | # -- Options for intersphinx ------------------------------------------------- 56 | # https://www.sphinx-doc.org/en/master/usage/extensions/intersphinx.html 57 | if RTD_BUILD: 58 | intersphinx_mapping = { 59 | 'python': ('https://docs.python.org/3', None) 60 | } 61 | 62 | 63 | # -- Options for nitpick ------------------------------------------------- 64 | nitpick_ignore_regex = [ 65 | (re.compile(r'py:class'), re.compile(r'pyartnet\.fades\.fade_base\.FadeBase')) 66 | ] 67 | 68 | # Don't show warnings for missing python references since these are created via intersphinx during the RTD build 69 | if not RTD_BUILD: 70 | nitpick_ignore_regex.append( 71 | (re.compile(r'py:data|py:class'), re.compile(r'typing\..+')) 72 | ) 73 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | :github_url: https://github.com/spacemanspiff2007/PyArtNet 2 | 3 | 4 | Welcome to PyArtNet's documentation! 5 | ==================================== 6 | 7 | .. toctree:: 8 | :maxdepth: 2 9 | :caption: Contents: 10 | 11 | pyartnet 12 | 13 | 14 | Indices and tables 15 | ================== 16 | 17 | * :ref:`genindex` 18 | * :ref:`modindex` 19 | * :ref:`search` 20 | -------------------------------------------------------------------------------- /docs/pyartnet.rst: -------------------------------------------------------------------------------- 1 | .. py:currentmodule:: pyartnet 2 | 3 | ###################################### 4 | PyArtNet 5 | ###################################### 6 | pyartnet is a python implementation of the ArtNet protocol using 7 | `asyncio `_. 8 | Supported protocols are ArtNet, sACN and KiNet. 9 | 10 | 11 | Getting Started 12 | ================================== 13 | 14 | .. exec_code:: 15 | 16 | # hide: start 17 | from helper import MockedSocket 18 | MockedSocket().mock() 19 | # hide: stop 20 | 21 | import asyncio 22 | from pyartnet import ArtNetNode 23 | 24 | async def main(): 25 | # Run this code in your async function 26 | node = ArtNetNode('IP', 6454) 27 | 28 | # Create universe 0 29 | universe = node.add_universe(0) 30 | 31 | # Add a channel to the universe which consists of 3 values 32 | # Default size of a value is 8Bit (0..255) so this would fill 33 | # the DMX values 1..3 of the universe 34 | channel = universe.add_channel(start=1, width=3) 35 | 36 | # Fade channel to 255,0,0 in 5s 37 | # The fade will automatically run in the background 38 | channel.add_fade([255,0,0], 1000) 39 | 40 | # this can be used to wait till the fade is complete 41 | await channel 42 | 43 | # hide: start 44 | node.stop_refresh() 45 | # hide: stop 46 | 47 | asyncio.run(main()) 48 | 49 | 50 | Channels 51 | ================================== 52 | 53 | 54 | Accessing channels 55 | ---------------------------------- 56 | 57 | Created channels can be requested from the universe through the ``[]`` syntax or through :meth:`BaseUniverse.get_channel`. 58 | If no channel name is specified during creation the default name will be built with ``{START}/{WIDTH}``. 59 | 60 | .. exec_code:: 61 | 62 | # hide: start 63 | from helper import MockedSocket 64 | MockedSocket().mock() 65 | 66 | import asyncio 67 | from pyartnet import ArtNetNode 68 | 69 | async def main(): 70 | # hide: stop 71 | 72 | # create node/universe 73 | node = ArtNetNode('IP', 6454) 74 | universe = node.add_universe(0) 75 | 76 | # create the channel 77 | channel = universe.add_channel(start=1, width=3) 78 | 79 | # after creation this would also work (default name) 80 | channel = universe['1/3'] 81 | channel = universe.get_channel('1/3') 82 | 83 | 84 | # it's possible to name the channel during creation 85 | universe.add_channel(start=4, width=3, channel_name='Dimmer1') 86 | 87 | # access is then by name 88 | channel = universe['Dimmer1'] 89 | channel = universe.get_channel('Dimmer1') 90 | 91 | # hide: start 92 | asyncio.run(main()) 93 | # hide: stop 94 | 95 | 96 | Wider channels 97 | ---------------------------------- 98 | Currently there is support for 8Bit, 16Bit, 24Bit and 32Bit channels. 99 | Channel properties can be set when creating the channel through :meth:`BaseUniverse.add_channel`. 100 | 101 | .. exec_code:: 102 | 103 | # hide: start 104 | from helper import MockedSocket 105 | MockedSocket().mock() 106 | 107 | import asyncio 108 | from pyartnet import ArtNetNode 109 | 110 | async def main(): 111 | # hide: stop 112 | 113 | # create node/universe 114 | node = ArtNetNode('IP', 6454) 115 | universe = node.add_universe(0) 116 | 117 | # create a 16bit channel 118 | channel = universe.add_channel(start=1, width=3, byte_size=2) 119 | 120 | # hide: start 121 | asyncio.run(main()) 122 | # hide: stop 123 | 124 | 125 | Output correction 126 | ================================== 127 | 128 | Output correction 129 | ---------------------------------- 130 | It is possible to use an output correction to create different brightness curves. 131 | `Output correction `_ can be set on the channel, the universe or the node. 132 | The universe output correction overrides the node output correction and the channel output 133 | correction overwrites the universe output correction. 134 | 135 | 136 | The graph shows different output values depending on the output correction. 137 | 138 | From left to right: 139 | linear (default when nothing is set), quadratic, cubic then quadruple 140 | 141 | .. image:: ../curves.svg 142 | :alt: Value curves for output correction 143 | 144 | Quadratic or cubic results in much smoother and more pleasant fades when using LED Strips. 145 | 146 | Example 147 | ---------------------------------- 148 | 149 | .. exec_code:: 150 | 151 | # hide: start 152 | from helper import MockedSocket 153 | MockedSocket().mock() 154 | 155 | import asyncio 156 | 157 | async def main(): 158 | # hide: stop 159 | from pyartnet import ArtNetNode, output_correction 160 | 161 | # create node/universe/channel 162 | node = ArtNetNode('IP', 6454) 163 | universe = node.add_universe(0) 164 | channel = universe.add_channel(start=1, width=3) 165 | 166 | # set quadratic correction for the whole universe to quadratic 167 | universe.set_output_correction(output_correction.quadratic) 168 | 169 | # Explicitly set output for this channel to linear 170 | channel.set_output_correction(output_correction.linear) 171 | 172 | # Remove output correction for the channel. 173 | # The channel will now use the correction from the universe again 174 | channel.set_output_correction(None) 175 | 176 | 177 | # hide: start 178 | asyncio.run(main()) 179 | # hide: stop 180 | 181 | 182 | Class Reference 183 | ================================== 184 | 185 | 186 | Universe and Channel 187 | ---------------------------------- 188 | 189 | .. autoclass:: BaseUniverse 190 | :members: 191 | :inherited-members: 192 | :member-order: groupwise 193 | 194 | .. autoclass:: Channel 195 | :members: 196 | :inherited-members: 197 | :member-order: groupwise 198 | 199 | 200 | Node implementations 201 | ---------------------------------- 202 | 203 | .. autoclass:: ArtNetNode 204 | :members: 205 | :inherited-members: 206 | :member-order: groupwise 207 | 208 | 209 | .. autoclass:: KiNetNode 210 | :members: 211 | :inherited-members: 212 | :member-order: groupwise 213 | 214 | 215 | .. autoclass:: SacnNode 216 | :members: 217 | :inherited-members: 218 | :member-order: groupwise 219 | 220 | 221 | Fades 222 | ---------------------------------- 223 | 224 | .. autoclass:: pyartnet.fades.LinearFade 225 | :members: 226 | :inherited-members: 227 | :member-order: groupwise 228 | 229 | 230 | Available output corrections 231 | ---------------------------------- 232 | 233 | .. automodule:: pyartnet.output_correction 234 | :members: 235 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | # Packages required to build the documentation 2 | sphinx >= 5.3, < 6 3 | sphinx-autodoc-typehints >= 1.22, < 2 4 | sphinx_rtd_theme == 1.1.1 5 | sphinx-exec-code == 0.8 6 | 7 | # monkeypatch 8 | pytest >=7.2, < 7.3 9 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # pyartnet 2 | ![Tests](https://github.com/spacemanspiff2007/PyArtNet/workflows/Tests/badge.svg) 3 | [![Documentation Status](https://readthedocs.org/projects/pyartnet/badge/?version=latest)](https://pyartnet.readthedocs.io/en/latest/?badge=latest) 4 | ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pyartnet) 5 | [![Downloads](https://static.pepy.tech/badge/pyartnet/month)](https://pepy.tech/project/pyartnet) 6 | 7 | 8 | PyArtNet is a python implementation of the ArtNet protocol using [asyncio](https://docs.python.org/3/library/asyncio.html). 9 | Supported protocols are ArtNet, sACN and KiNet. 10 | 11 | # Docs 12 | 13 | Docs and examples can be found [here](https://pyartnet.readthedocs.io/en/latest/pyartnet.html) 14 | 15 | 16 | # Changelog 17 | 18 | #### 1.0.1 (2023-02-20) 19 | - Fixed an issue where consecutive fades would not start from the correct value 20 | - renamed `channel.add_fade` to `channel.set_fade` (`channel.add_fade` will issue a `DeprecationWarning`) 21 | 22 | #### 1.0.0 (2023-02-08) 23 | - Complete rework of library (breaking change) 24 | - Add support for sACN and KiNet 25 | 26 | #### 0.8.4 (2022-07-13) 27 | - Added linear fade (closes #14) 28 | - Updated max FPS (closes #17) 29 | - All raised Errors inherit now from PyArtNetError 30 | - Some refactoring and cleanup 31 | - Activated tests for Python 3.10 32 | 33 | #### 0.8.3 (2021-07-23) 34 | - No more jumping fades when using output correction with bigger channels 35 | - Reformatted files 36 | 37 | #### 0.8.2 (2021-03-14) 38 | - Using nonblocking sockets 39 | - Added option to send frames to a broadcast address 40 | 41 | #### 0.8.1 (2021-02-26) 42 | - Fixed an issue with the max value for channels with 16bits and more 43 | 44 | #### 0.8.0 (2021-02-11) 45 | - Added support for channels with 16, 24 and 32bits 46 | 47 | #### 0.7.0 (2020-10-28) 48 | - renamed logger to ``pyartnet`` to make it consistent with the module name 49 | - callbacks on the channel now get the channel passed in as an argument 50 | - Adding the same channel multiple times or adding overlapping channels raises an exception 51 | - Added ``pyartnet.errors`` 52 | - optimized logging of sent frames 53 | 54 | #### 0.6.0 (2020-10-27) 55 | - ``ArtnetNode.start`` is now an async function 56 | - ``ArtnetNode.step_time_ms`` renamed to ``ArtnetNode.step_time`` (shouldn't be used manually anyway) 57 | - removed support for python 3.6 58 | - added more and better type hints 59 | - switched to pytest 60 | - small fixes 61 | 62 | --- 63 | 64 | `Art-Net™ Designed by and Copyright Artistic Licence Engineering Ltd` 65 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pytest >=7.2, < 7.3 2 | pytest-asyncio >=0.20.3, < 0.21 3 | 4 | # linter 5 | pre-commit >= 3.0, < 3.1 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import typing 2 | from pathlib import Path 3 | 4 | import setuptools # type: ignore 5 | 6 | 7 | # Load version number without importing HABApp 8 | def load_version() -> str: 9 | version: typing.Dict[str, str] = {} 10 | with open("src/pyartnet/__version__.py") as fp: 11 | exec(fp.read(), version) 12 | assert version['__version__'], version 13 | return version['__version__'] 14 | 15 | 16 | __version__ = load_version() 17 | 18 | print(f'Version: {__version__}') 19 | print('') 20 | 21 | # When we run tox tests we don't have these files available so we skip them 22 | readme = Path(__file__).with_name('readme.md') 23 | long_description = '' 24 | if readme.is_file(): 25 | with readme.open("r", encoding='utf-8') as fh: 26 | long_description = fh.read() 27 | 28 | 29 | setuptools.setup( 30 | name="pyartnet", 31 | version=__version__, 32 | author="spaceman_spiff", 33 | # author_email="", 34 | description="Python wrappers for the Art-Net protocol to send DMX over Ethernet", 35 | keywords='DMX, Art-Net, ArtNet, sACN E1.31, E1.31, KiNet', 36 | long_description=long_description, 37 | long_description_content_type="text/markdown", 38 | url="https://github.com/spacemanspiff2007/PyArtNet", 39 | project_urls={ 40 | 'Documentation': 'https://pyartnet.readthedocs.io', 41 | 'GitHub': 'https://github.com/spacemanspiff2007/PyArtNet' 42 | }, 43 | package_dir={'': 'src'}, 44 | package_data={'pyartnet': ['py.typed']}, 45 | packages=setuptools.find_packages('src', exclude=['tests*']), 46 | python_requires='>=3.8', 47 | classifiers=[ 48 | "Development Status :: 4 - Beta", 49 | "Programming Language :: Python :: 3.8", 50 | "Programming Language :: Python :: 3.9", 51 | "Programming Language :: Python :: 3.10", 52 | "Programming Language :: Python :: 3.11", 53 | "Programming Language :: Python :: 3 :: Only", 54 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 55 | "Operating System :: OS Independent", 56 | ], 57 | ) 58 | -------------------------------------------------------------------------------- /src/pyartnet/__init__.py: -------------------------------------------------------------------------------- 1 | from . import errors, fades, output_correction 2 | from .__version__ import __version__ 3 | 4 | # isort: split 5 | 6 | from .base import BaseUniverse, Channel 7 | 8 | # isort: split 9 | 10 | from .impl_artnet import ArtNetNode 11 | from .impl_kinet import KiNetNode 12 | from .impl_sacn import SacnNode 13 | -------------------------------------------------------------------------------- /src/pyartnet/__version__.py: -------------------------------------------------------------------------------- 1 | __version__ = '1.0.1' 2 | -------------------------------------------------------------------------------- /src/pyartnet/base/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_node import BaseNode 2 | from .channel import Channel, ChannelBoundFade 3 | from .seq_counter import SequenceCounter 4 | from .universe import BaseUniverse 5 | -------------------------------------------------------------------------------- /src/pyartnet/base/background_task.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from asyncio import create_task, sleep, Task 3 | from time import monotonic 4 | from traceback import format_exc 5 | from typing import Any, Callable, Coroutine, Final, Optional, Set 6 | 7 | log = logging.getLogger('pyartnet.Task') 8 | 9 | 10 | def log_exception(e: Exception, name: str): 11 | log.error(f'Error in worker for {name:s}:') 12 | for line in format_exc().splitlines(): 13 | log.error(line) 14 | 15 | 16 | _BACKGROUND_TASKS: Set[Task] = set() 17 | 18 | # use variables, so it's easy to e.g. implement thread safe scheduling 19 | CREATE_TASK = create_task 20 | EXCEPTION_HANDLER: Callable[[Exception, str], Any] = log_exception 21 | 22 | 23 | class SimpleBackgroundTask: 24 | 25 | def __init__(self, coro: Callable[[], Coroutine], name: str): 26 | self.coro: Final = coro 27 | self.name: Final = name 28 | self.task: Optional[Task] = None 29 | 30 | def start(self): 31 | if self.task is not None: 32 | return None 33 | 34 | self.task = task = CREATE_TASK(self.coro_wrap(), name=self.name) 35 | _BACKGROUND_TASKS.add(task) 36 | task.add_done_callback(_BACKGROUND_TASKS.discard) 37 | 38 | def cancel(self): 39 | if self.task is None: 40 | return None 41 | 42 | self.task.cancel() 43 | self.task = None 44 | 45 | async def coro_wrap(self): 46 | log.debug(f'Started {self.name}') 47 | task = self.task 48 | assert task is not None 49 | 50 | try: 51 | await self.coro() 52 | except Exception as e: 53 | EXCEPTION_HANDLER(e, self.name) 54 | finally: 55 | if self.task is task: 56 | self.task = None 57 | log.debug(f'Stopped {self.name}') 58 | 59 | 60 | class ExceptionIgnoringTask(SimpleBackgroundTask): 61 | async def coro_wrap(self): 62 | log.debug(f'Started {self.name}') 63 | task = self.task 64 | assert task is not None 65 | 66 | wait = 0 67 | 68 | try: 69 | while True: 70 | await sleep(wait) 71 | start = monotonic() 72 | try: 73 | await self.coro() 74 | except Exception as e: 75 | EXCEPTION_HANDLER(e, self.name) 76 | 77 | # simple sleep logic with an increasing timeout 78 | time_to_exception = monotonic() - start 79 | if time_to_exception < 16 or time_to_exception < wait: 80 | wait = max(2, wait * 2) 81 | else: 82 | wait = 0 83 | 84 | log.debug(f'Retry in {wait:d} seconds') 85 | finally: 86 | if self.task is task: 87 | self.task = None 88 | log.debug(f'Stopped {self.name}') 89 | -------------------------------------------------------------------------------- /src/pyartnet/base/base_node.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import socket 3 | from asyncio import sleep 4 | from time import monotonic 5 | from typing import Dict, Final, Generic, List, Optional, Tuple, TypeVar, Union 6 | 7 | import pyartnet 8 | 9 | from ..errors import DuplicateUniverseError, UniverseNotFoundError 10 | from .background_task import ExceptionIgnoringTask, SimpleBackgroundTask 11 | from .output_correction import OutputCorrection 12 | 13 | log = logging.getLogger('pyartnet.ArtNetNode') 14 | 15 | 16 | TYPE_U = TypeVar('TYPE_U', bound='pyartnet.base.BaseUniverse') 17 | 18 | 19 | # noinspection PyProtectedMember 20 | class BaseNode(Generic[TYPE_U], OutputCorrection): 21 | def __init__(self, ip: str, port: int, *, 22 | max_fps: int = 25, 23 | refresh_every: Union[int, float, None] = 2, start_refresh_task: bool = True, 24 | source_address: Optional[Tuple[str, int]] = None): 25 | super().__init__() 26 | 27 | # Destination 28 | self._ip: Final = ip 29 | self._port: Final = port 30 | self._dst: Final = (self._ip, self._port) 31 | 32 | # socket setup 33 | self._socket: Final = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP 34 | self._socket.setblocking(False) # nonblocking for true asyncio 35 | 36 | # option to set source port/ip 37 | if source_address is not None: 38 | self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 39 | self._socket.bind(source_address) 40 | 41 | # Name used for the Tasks (e.g. in error msg) 42 | name: Final = f'{self._ip:s}:{self._port}' 43 | 44 | # refresh task 45 | self._refresh_every: float = max(0.1, refresh_every) 46 | self._refresh_task: Final = ExceptionIgnoringTask(self._periodic_refresh_worker, f'Process task {name:s}') 47 | if start_refresh_task: 48 | self._refresh_task.start() 49 | 50 | # fade task 51 | self._process_every: float = 1 / max(1, max_fps) 52 | self._process_task: Final = SimpleBackgroundTask(self._process_values_task, f'Refresh task {name:s}') 53 | self._process_jobs: List['pyartnet.base.ChannelBoundFade'] = [] 54 | 55 | # packet data 56 | self._packet_base: Union[bytearray, bytes] = bytearray() 57 | self._last_send: float = 0 58 | 59 | # containing universes 60 | self._universes: Tuple[TYPE_U, ...] = () 61 | self._universe_map: Dict[int, TYPE_U] = {} 62 | 63 | def _apply_output_correction(self): 64 | for u in self._universes: 65 | u._apply_output_correction() 66 | 67 | def _send_universe(self, id: int, byte_size: int, values: bytearray, universe: TYPE_U): 68 | raise NotImplementedError() 69 | 70 | def _send_data(self, data: Union[bytearray, bytes]) -> int: 71 | 72 | ret = self._socket.sendto(self._packet_base + data, self._dst) 73 | 74 | self._last_send = monotonic() 75 | return ret 76 | 77 | async def _process_values_task(self): 78 | # wait a little, so we can schedule multiple tasks/updates, and they all start together 79 | await sleep(0.01) 80 | 81 | idle_ct = 0 82 | while idle_ct < 10: 83 | idle_ct += 1 84 | 85 | # process jobs 86 | to_remove = [] 87 | for job in self._process_jobs: 88 | job.process() 89 | idle_ct = 0 90 | 91 | if job.is_done: 92 | to_remove.append(job) 93 | 94 | # send data of universe 95 | for universe in self._universes: 96 | if not universe._data_changed: 97 | continue 98 | universe.send_data() 99 | idle_ct = 0 100 | 101 | if to_remove: 102 | for job in to_remove: 103 | self._process_jobs.remove(job) 104 | job.fade_complete() 105 | 106 | await sleep(self._process_every) 107 | 108 | def start_refresh(self): 109 | """Manually start the refresh task (if not already running)""" 110 | self._refresh_task.start() 111 | 112 | def stop_refresh(self): 113 | """Manually stop the refresh task""" 114 | self._refresh_task.cancel() 115 | 116 | async def _periodic_refresh_worker(self): 117 | while True: 118 | # sync the refresh messages 119 | next_refresh = monotonic() 120 | for u in self._universes: 121 | next_refresh = min(next_refresh, u._last_send) 122 | 123 | diff = monotonic() - next_refresh 124 | if diff < self._refresh_every: 125 | await sleep(diff) 126 | continue 127 | 128 | for u in self._universes: 129 | u.send_data() 130 | 131 | def get_universe(self, nr: int) -> TYPE_U: 132 | """Get universe by number 133 | 134 | :param nr: universe nr 135 | :return: The universe 136 | """ 137 | if not isinstance(nr, int) or not nr >= 0: 138 | raise ValueError('BaseUniverse must be an int >= 0!') 139 | nr = int(nr) 140 | 141 | try: 142 | return self._universe_map[nr] 143 | except KeyError: 144 | raise UniverseNotFoundError(f'BaseUniverse {nr:d} not found!') from None 145 | 146 | def add_universe(self, nr: int = 0) -> TYPE_U: 147 | """Creates a new universe and adds it to the parent node 148 | 149 | :param nr: universe nr 150 | :return: The universe 151 | """ 152 | if not isinstance(nr, int) or not nr >= 0: 153 | raise ValueError('BaseUniverse must be an int >= 0!') 154 | nr = int(nr) 155 | 156 | if nr in self._universe_map: 157 | raise DuplicateUniverseError(f'BaseUniverse {nr:d} does already exist!') 158 | 159 | # add to data 160 | self._universe_map[nr] = universe = self._create_universe(nr) 161 | self._universes = tuple(u for _, u in sorted(self._universe_map.items())) # ascending 162 | 163 | return universe 164 | 165 | def _create_universe(self, nr: int) -> TYPE_U: 166 | raise NotImplementedError() 167 | 168 | def __await__(self): 169 | while self._process_jobs: 170 | for job in self._process_jobs: 171 | yield from job.channel.__await__() 172 | 173 | def __getitem__(self, nr: int) -> TYPE_U: 174 | return self.get_universe(nr) 175 | 176 | def __len__(self): 177 | return len(self._universes) 178 | -------------------------------------------------------------------------------- /src/pyartnet/base/channel.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import warnings 3 | from array import array 4 | from logging import DEBUG as LVL_DEBUG 5 | from math import ceil 6 | from typing import Any, Callable, Collection, Final, List, Literal, Optional, Type, Union 7 | 8 | from pyartnet.errors import ChannelOutOfUniverseError, ChannelValueOutOfBoundsError, \ 9 | ChannelWidthError, ValueCountDoesNotMatchChannelWidthError 10 | from pyartnet.output_correction import linear 11 | 12 | from ..fades import FadeBase, LinearFade 13 | from .channel_fade import ChannelBoundFade 14 | from .output_correction import OutputCorrection 15 | from .universe import BaseUniverse 16 | 17 | log = logging.getLogger('pyartnet.Channel') 18 | 19 | 20 | ARRAY_TYPE: Final = { 21 | 1: 'B', # unsigned char : min size 1 byte 22 | 2: 'H', # unsigned short: min size 2 bytes 23 | 3: 'L', # unsigned long : min size 4 bytes 24 | 4: 'L' # unsigned long : min size 4 bytes 25 | } 26 | 27 | 28 | class Channel(OutputCorrection): 29 | def __init__(self, universe: BaseUniverse, 30 | start: int, width: int, 31 | byte_size: int = 1, byte_order: Literal['big', 'little'] = 'little'): 32 | super().__init__() 33 | 34 | # Validate Boundaries 35 | if byte_size not in ARRAY_TYPE: 36 | raise ValueError(f'Value size must be {", ".join(map(str, ARRAY_TYPE))}') 37 | 38 | if start < 1 or start > 512: 39 | raise ChannelOutOfUniverseError( 40 | f'Start position of channel out of universe (1..512): {start}') 41 | 42 | if width <= 0 or not isinstance(width, int): 43 | raise ChannelWidthError( 44 | f'Channel width must be int > 0: {width} ({type(width)})') 45 | 46 | total_byte_width: Final = width * byte_size 47 | 48 | self._start: Final = start 49 | self._width: Final = width 50 | self._stop: Final = start + total_byte_width - 1 51 | 52 | if self._stop > 512: 53 | raise ChannelOutOfUniverseError( 54 | f'End position of channel out of universe (1..512): ' 55 | f'start: {self._start} width: {self._width} * {byte_size}bytes -> {self._stop}' 56 | ) 57 | 58 | # value representation 59 | self._byte_size: Final = byte_size 60 | self._byte_order: Final = byte_order 61 | self._value_max: Final = 256 ** self._byte_size - 1 62 | self._buf_start: Final = self._start - 1 63 | 64 | null_vals = [0 for _ in range(self._width)] 65 | self._values_raw: array[int] = array(ARRAY_TYPE[self._byte_size], null_vals) # uncorrected values 66 | self._values_act: array[int] = array(ARRAY_TYPE[self._byte_size], null_vals) # values after output correction 67 | 68 | # Parents 69 | self._parent_universe: Final = universe 70 | self._parent_node: Final = universe._node 71 | 72 | self._correction_current: Callable[[float, int], float] = linear 73 | 74 | # Fade 75 | self._current_fade: Optional[ChannelBoundFade] = None 76 | 77 | # --------------------------------------------------------------------- 78 | # Values that can be set by the user 79 | # --------------------------------------------------------------------- 80 | # Callbacks 81 | self.callback_fade_finished: Optional[Callable[[Channel], Any]] = None 82 | 83 | def _apply_output_correction(self): 84 | # default correction is linear 85 | self._correction_current = linear 86 | 87 | # inherit correction if it is not set first from universe and then from the node 88 | for obj in (self, self._parent_universe, self._parent_node): 89 | if obj._correction_output is not None: 90 | self._correction_current = obj._correction_output 91 | return None 92 | 93 | def get_values(self) -> List[int]: 94 | """Get the current (uncorrected) channel values 95 | 96 | :return: list of channel values 97 | """ 98 | return self._values_raw.tolist() 99 | 100 | def set_values(self, values: Collection[Union[int, float]]): 101 | """Set values for a channel without a fade 102 | 103 | :param values: Iterable of values with the same size as the channel width 104 | """ 105 | # get output correction function 106 | if len(values) != self._width: 107 | raise ValueCountDoesNotMatchChannelWidthError( 108 | f'Not enough fade values specified, expected {self._width} but got {len(values)}!') 109 | 110 | correction = self._correction_current 111 | value_max = self._value_max 112 | 113 | changed = False 114 | for i, val in enumerate(values): 115 | raw_new = round(val) 116 | if not 0 <= raw_new <= value_max: 117 | raise ChannelValueOutOfBoundsError(f'Channel value out of bounds! 0 <= {val} <= {value_max:d}') 118 | 119 | self._values_raw[i] = raw_new 120 | act_new = round(correction(val, value_max)) if correction is not linear else raw_new 121 | if self._values_act[i] != act_new: 122 | changed = True 123 | self._values_act[i] = act_new 124 | 125 | if changed: 126 | self._parent_universe.channel_changed(self) 127 | return self 128 | 129 | def to_buffer(self, buf: bytearray): 130 | byte_order = self._byte_order 131 | byte_size = self._byte_size 132 | 133 | start = self._buf_start 134 | for value in self._values_act: 135 | buf[start: start + byte_size] = value.to_bytes(byte_size, byte_order, signed=False) 136 | start += byte_size 137 | return self 138 | 139 | def add_fade(self, values: Collection[Union[int, FadeBase]], duration_ms: int, 140 | fade_class: Type[FadeBase] = LinearFade): 141 | warnings.warn( 142 | f"{self.set_fade.__name__:s} is deprecated, use {self.set_fade.__name__:s} instead", DeprecationWarning) 143 | return self.set_fade(values, duration_ms, fade_class) 144 | 145 | # noinspection PyProtectedMember 146 | def set_fade(self, values: Collection[Union[int, FadeBase]], duration_ms: int, 147 | fade_class: Type[FadeBase] = LinearFade): 148 | """Add and schedule a new fade for the channel 149 | 150 | :param values: Target values for the fade 151 | :param duration_ms: Duration for the fade in ms 152 | :param fade_class: What kind of fade 153 | """ 154 | # check that we passed all values 155 | if len(values) != self._width: 156 | raise ValueCountDoesNotMatchChannelWidthError( 157 | f'Not enough fade values specified, expected {self._width} but got {len(values)}!') 158 | 159 | if self._current_fade is not None: 160 | self._current_fade.cancel() 161 | self._current_fade = None 162 | 163 | # calculate how much steps we will be having 164 | step_time_ms = int(self._parent_node._process_every * 1000) 165 | duration_ms = max(duration_ms, step_time_ms) 166 | fade_steps: int = ceil(duration_ms / step_time_ms) 167 | 168 | # build fades 169 | fades: List[FadeBase] = [] 170 | for i, target in enumerate(values): 171 | # default is linear 172 | k = fade_class() if not isinstance(target, FadeBase) else target 173 | fades.append(k) 174 | 175 | if not 0 <= target <= self._value_max: 176 | raise ChannelValueOutOfBoundsError( 177 | f'Target value out of bounds! 0 <= {target} <= {self._value_max}') 178 | 179 | k.initialize(self._values_raw[i], target, fade_steps) 180 | 181 | # Add to scheduling 182 | self._current_fade = ChannelBoundFade(self, fades) 183 | self._parent_node._process_jobs.append(self._current_fade) 184 | 185 | # start fade/refresh task if necessary 186 | self._parent_node._process_task.start() 187 | 188 | # todo: this on the ChannelBoundFade 189 | if log.isEnabledFor(LVL_DEBUG): 190 | log.debug(f'Added fade with {fade_steps} steps:') 191 | for i, fade in enumerate(fades): 192 | log.debug(f'CH {self._start + i}: {fade.debug_initialize():s}') 193 | return self 194 | 195 | def __await__(self): 196 | if self._current_fade is None: 197 | return False 198 | yield from self._current_fade.event.wait().__await__() 199 | return True 200 | 201 | def __repr__(self): 202 | return f'<{self.__class__.__name__:s} {self._start:d}/{self._width:d} {self._byte_size * 8:d}bit>' 203 | -------------------------------------------------------------------------------- /src/pyartnet/base/channel_fade.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from asyncio import Event 3 | from typing import Final, Iterable, List, Tuple, TYPE_CHECKING 4 | 5 | if TYPE_CHECKING: 6 | import pyartnet 7 | 8 | 9 | log = logging.getLogger('pyartnet.DmxChannel') 10 | 11 | 12 | # noinspection PyProtectedMember 13 | class ChannelBoundFade: 14 | def __init__(self, channel: 'pyartnet.base.Channel', fades: Iterable['pyartnet.fades.FadeBase']): 15 | super().__init__() 16 | self.channel: 'pyartnet.base.Channel' = channel 17 | 18 | self.fades: Tuple['pyartnet.fades.FadeBase', ...] = tuple(fades) 19 | self.values: List[float] = [0 for _ in fades] 20 | 21 | self.is_done = False 22 | self.event: Final = Event() 23 | 24 | def process(self): 25 | finished = True 26 | for i, fade in enumerate(self.fades): 27 | if fade.is_done: 28 | continue 29 | 30 | self.values[i] = fade.calc_next_value() 31 | 32 | if not fade.is_done: 33 | finished = False 34 | 35 | self.is_done = finished 36 | self.channel.set_values(self.values) 37 | 38 | def cancel(self): 39 | # remove fade from channel 40 | c = self.channel 41 | self.channel = None # type: ignore[assignment] 42 | c._current_fade = None 43 | 44 | self.event.set() 45 | 46 | # remove from parent node 47 | c._parent_node._process_jobs.remove(self) 48 | 49 | def fade_complete(self): 50 | # remove fade from channel 51 | c = self.channel 52 | self.channel = None # type: ignore[assignment] 53 | c._current_fade = None 54 | 55 | self.event.set() 56 | 57 | if c.callback_fade_finished is not None: 58 | c.callback_fade_finished(c) 59 | 60 | def __repr__(self): 61 | # Channel part 62 | if self.channel is not None: 63 | channel_part = f'channel={self.channel._start:d}/{self.channel._width:d}' 64 | else: 65 | channel_part = 'channel=None' 66 | 67 | return f'<{self.__class__.__name__:s} {channel_part}, is_done={self.is_done}>' 68 | -------------------------------------------------------------------------------- /src/pyartnet/base/output_correction.py: -------------------------------------------------------------------------------- 1 | from typing import Callable, Optional 2 | 3 | 4 | class OutputCorrection: 5 | def __init__(self): 6 | super().__init__() 7 | self._correction_output: Optional[Callable[[float, int], float]] = None 8 | 9 | def set_output_correction(self, func: Optional[Callable[[float, int], float]]) -> None: 10 | """Set the output correction function. 11 | 12 | :param func: None to disable output correction or the function which will be used to transform the values 13 | """ 14 | self._correction_output = func 15 | self._apply_output_correction() 16 | return None 17 | 18 | def _apply_output_correction(self) -> None: 19 | raise NotImplementedError() 20 | -------------------------------------------------------------------------------- /src/pyartnet/base/seq_counter.py: -------------------------------------------------------------------------------- 1 | from typing import Final 2 | 3 | 4 | class SequenceCounter: 5 | __slots__ = ('_ctr', '_start', '_upper') 6 | 7 | def __init__(self, start: int = 0, upper: int = 255): 8 | self._ctr: int = start 9 | assert start <= upper 10 | self._start: Final = start 11 | self._upper: Final = upper 12 | 13 | @property 14 | def value(self) -> int: 15 | ret = self._ctr 16 | self._ctr += 1 17 | if self._ctr > self._upper: 18 | self._ctr = self._start 19 | return ret 20 | 21 | def __repr__(self) -> str: 22 | return f'<{self.__class__.__name__} {self._ctr:d}>' 23 | -------------------------------------------------------------------------------- /src/pyartnet/base/universe.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from time import monotonic 3 | from typing import Dict, Final, Literal 4 | 5 | import pyartnet 6 | from pyartnet.errors import ChannelExistsError, ChannelNotFoundError, \ 7 | InvalidUniverseAddressError, OverlappingChannelError 8 | 9 | from .output_correction import OutputCorrection 10 | 11 | log = logging.getLogger('pyartnet.Universe') 12 | 13 | 14 | # noinspection PyProtectedMember 15 | class BaseUniverse(OutputCorrection): 16 | def __init__(self, node: 'pyartnet.base.BaseNode', universe: int = 0): 17 | super().__init__() 18 | 19 | if not 0 <= universe <= 32767: 20 | raise InvalidUniverseAddressError() 21 | 22 | self._node: Final = node 23 | self._universe: Final = universe 24 | 25 | self._data: bytearray = bytearray() 26 | self._data_size: int = 0 27 | self._data_changed = True 28 | self._last_send: float = 0 29 | 30 | self._channels: Dict[str, 'pyartnet.base.Channel'] = {} 31 | 32 | def _apply_output_correction(self): 33 | for c in self._channels.values(): 34 | c._apply_output_correction() 35 | 36 | def channel_changed(self, channel: 'pyartnet.base.Channel'): 37 | # update universe buffer 38 | channel.to_buffer(self._data) 39 | 40 | # signal that this universe has changed 41 | self._data_changed = True 42 | 43 | # start fade/refresh task if necessary 44 | # noinspection PyProtectedMember 45 | self._node._process_task.start() 46 | 47 | def send_data(self): 48 | self._node._send_universe(self._universe, self._data_size, self._data, self) 49 | self._last_send = monotonic() 50 | self._data_changed = False 51 | 52 | def get_channel(self, channel_name: str) -> 'pyartnet.base.Channel': 53 | """Return a channel by name or raise an exception 54 | 55 | :param channel_name: name of the channel 56 | """ 57 | if not isinstance(channel_name, str): 58 | raise TypeError('Channel name must be str') 59 | 60 | try: 61 | return self._channels[channel_name] 62 | except KeyError: 63 | raise ChannelNotFoundError(f'Channel "{channel_name}" not found in the universe!') from None 64 | 65 | def add_channel(self, 66 | start: int, width: int, 67 | channel_name: str = '', 68 | byte_size: int = 1, byte_order: Literal['big', 'little'] = 'little') -> 'pyartnet.base.Channel': 69 | """Add a new channel to the universe. This will automatically resize the universe accordingly. 70 | 71 | :param start: start position in the universe 72 | :param width: how many values the channel has 73 | :param channel_name: name of the channel for requesting it from the universe 74 | :param byte_size: byte size of a value 75 | :param byte_order: byte order of a value 76 | """ 77 | 78 | chan = pyartnet.base.Channel(self, start, width, byte_size=byte_size, byte_order=byte_order) 79 | 80 | # build name if not supplied 81 | if not channel_name: 82 | channel_name = f'{start:d}/{width:d}' 83 | 84 | # Make sure we don't accidentally overwrite the channel 85 | if channel_name in self._channels: 86 | raise ChannelExistsError(f'Channel "{channel_name}" does already exist in the universe!') 87 | 88 | # Make sure channels are not overlapping because they will overwrite each other 89 | # and this leads to unintended behavior 90 | for _n, _c in self._channels.items(): 91 | if _c._start > chan._stop or _c._stop < chan._start: 92 | continue 93 | for i in range(_c._start, _c._stop + 1): 94 | if start <= i <= chan._stop: 95 | raise OverlappingChannelError(f'New channel {channel_name} is overlapping with channel {_n:s}!') 96 | 97 | self._resize_universe(chan._stop) 98 | 99 | # add channel to universe 100 | self._channels[channel_name] = chan 101 | log.debug(f'Added channel "{channel_name}": start: {start:d}, stop: {start + width - 1:d}') 102 | 103 | chan._apply_output_correction() 104 | return chan 105 | 106 | def _resize_universe(self, min_size: int): 107 | 108 | new_size = max(min_size, 2) 109 | for c in self._channels.values(): 110 | new_size = max(new_size, c._stop) 111 | if new_size % 2: 112 | new_size += 1 113 | 114 | diff = new_size - self._data_size 115 | if not diff: 116 | return None 117 | 118 | self._data_size = new_size 119 | if diff < 0: 120 | for _ in range(- diff): 121 | self._data.pop() 122 | else: 123 | for _ in range(diff): 124 | # pad universe data with 0 is it's off 125 | self._data.append(0) 126 | 127 | # ----------------------------------------------------------- 128 | # emulate container 129 | def __len__(self): 130 | return len(self._channels) 131 | 132 | def __getitem__(self, item: str) -> 'pyartnet.base.Channel': 133 | return self.get_channel(item) 134 | -------------------------------------------------------------------------------- /src/pyartnet/errors.py: -------------------------------------------------------------------------------- 1 | class PyArtNetError(Exception): 2 | pass 3 | 4 | 5 | # ----------------------------------------------------------------------------- 6 | # Implementation specific Errors 7 | # ----------------------------------------------------------------------------- 8 | class InvalidCidError(PyArtNetError): 9 | pass 10 | 11 | 12 | # ----------------------------------------------------------------------------- 13 | # Universe Errors 14 | # ----------------------------------------------------------------------------- 15 | class InvalidUniverseAddressError(PyArtNetError): 16 | pass 17 | 18 | 19 | class DuplicateUniverseError(PyArtNetError): 20 | pass 21 | 22 | 23 | class UniverseNotFoundError(PyArtNetError): 24 | pass 25 | 26 | 27 | # ----------------------------------------------------------------------------- 28 | # Channel Errors 29 | # ----------------------------------------------------------------------------- 30 | class ChannelExistsError(PyArtNetError): 31 | pass 32 | 33 | 34 | class ChannelNotFoundError(PyArtNetError): 35 | pass 36 | 37 | 38 | class OverlappingChannelError(PyArtNetError): 39 | pass 40 | 41 | 42 | class ChannelOutOfUniverseError(PyArtNetError): 43 | pass 44 | 45 | 46 | class ChannelWidthError(PyArtNetError): 47 | pass 48 | 49 | 50 | class ChannelValueOutOfBoundsError(PyArtNetError): 51 | pass 52 | 53 | 54 | class ValueCountDoesNotMatchChannelWidthError(PyArtNetError): 55 | pass 56 | -------------------------------------------------------------------------------- /src/pyartnet/fades/__init__.py: -------------------------------------------------------------------------------- 1 | from .fade_base import FadeBase 2 | from .fade_linear import LinearFade 3 | -------------------------------------------------------------------------------- /src/pyartnet/fades/fade_base.py: -------------------------------------------------------------------------------- 1 | 2 | class FadeBase: 3 | 4 | def __init__(self): 5 | self.is_done = False 6 | 7 | def initialize(self, current: int, target: int, steps: int): 8 | raise NotImplementedError() 9 | 10 | def debug_initialize(self) -> str: 11 | """return debug string of the calculated values in initialize fade""" 12 | return "" 13 | 14 | def calc_next_value(self) -> float: 15 | raise NotImplementedError() 16 | -------------------------------------------------------------------------------- /src/pyartnet/fades/fade_linear.py: -------------------------------------------------------------------------------- 1 | from .fade_base import FadeBase 2 | 3 | 4 | class LinearFade(FadeBase): 5 | 6 | def __init__(self): 7 | super().__init__() 8 | self.target: int = 0 # Target Value 9 | self.current: float = 0.0 # Current Value 10 | self.factor: float = 1.0 11 | 12 | def debug_initialize(self) -> str: 13 | return f"{self.current:03.0f} -> {self.target:03d} | step: {self.factor:+5.1f}" 14 | 15 | def initialize(self, start: int, target: int, steps: int): 16 | self.current = start 17 | self.target = target 18 | self.factor = (self.target - start) / steps 19 | 20 | def calc_next_value(self) -> float: 21 | self.current += self.factor 22 | 23 | # is_done status 24 | curr = round(self.current) 25 | if self.factor <= 0: 26 | if curr <= self.target: 27 | self.is_done = True 28 | else: 29 | if curr >= self.target: 30 | self.is_done = True 31 | 32 | return self.current 33 | -------------------------------------------------------------------------------- /src/pyartnet/impl_artnet/__init__.py: -------------------------------------------------------------------------------- 1 | from .node import ArtNetNode 2 | from .universe import ArtNetUniverse 3 | -------------------------------------------------------------------------------- /src/pyartnet/impl_artnet/node.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import Final, Optional, Tuple, Union 3 | 4 | import pyartnet 5 | from pyartnet.base import BaseNode 6 | from pyartnet.base.seq_counter import SequenceCounter 7 | from pyartnet.errors import InvalidUniverseAddressError 8 | 9 | # ----------------------------------------------------------------------------- 10 | # Documentation for ArtNet Protocol: 11 | # https://artisticlicence.com/support-and-resources/art-net-4/ 12 | # ----------------------------------------------------------------------------- 13 | 14 | log = logging.getLogger('pyartnet.ArtNetNode') 15 | 16 | 17 | class ArtNetNode(BaseNode['pyartnet.impl_artnet.ArtNetUniverse']): 18 | def __init__(self, ip: str, port: int, *, 19 | max_fps: int = 25, 20 | refresh_every: Union[int, float, None] = 2, start_refresh_task: bool = True, 21 | source_address: Optional[Tuple[str, int]] = None, 22 | 23 | # ArtNet specific fields 24 | sequence_counter: bool = True 25 | ): 26 | super().__init__(ip=ip, port=port, 27 | max_fps=max_fps, 28 | refresh_every=refresh_every, start_refresh_task=start_refresh_task, 29 | source_address=source_address) 30 | 31 | # ArtNet specific fields 32 | self._sequence_ctr: Final = SequenceCounter(1) if sequence_counter else SequenceCounter(0, 0) 33 | 34 | # build base packet 35 | packet = bytearray() 36 | packet.extend(map(ord, "Art-Net")) 37 | packet.append(0x00) # Null terminate Art-Net 38 | packet.extend([0x00, 0x50]) # Opcode ArtDMX 0x5000 (Little endian) 39 | packet.extend([0x00, 0x0e]) # Protocol version 14 40 | self._packet_base = bytes(packet) 41 | 42 | def _send_universe(self, id: int, byte_size: int, values: bytearray, 43 | universe: 'pyartnet.impl_artnet.ArtNetUniverse'): 44 | 45 | # pre allocate the bytearray 46 | _size = 6 + byte_size 47 | packet = bytearray(_size) 48 | 49 | packet[0] = self._sequence_ctr.value # 1 | Sequence, 50 | packet[1] = 0x00 # 1 | Physical input port (not used) 51 | packet[2:4] = id.to_bytes(2, byteorder='little') # 2 | Universe 52 | 53 | packet[4:6] = byte_size.to_bytes(2, 'big') # 2 | Number of channels Big Endian 54 | packet[6: _size] = values # 0 - 512 | Channel values 55 | 56 | self._send_data(packet) 57 | 58 | # log complete packet 59 | if log.isEnabledFor(logging.DEBUG): 60 | self.__log_artnet_frame(self._packet_base + packet) 61 | 62 | def _create_universe(self, nr: int) -> 'pyartnet.impl_artnet.ArtNetUniverse': 63 | if nr >= 32_768: 64 | raise InvalidUniverseAddressError() 65 | return pyartnet.impl_artnet.ArtNetUniverse(self, nr) 66 | 67 | def __log_artnet_frame(self, p: Union[bytearray, bytes]): 68 | """Log Artnet Frame""" 69 | assert isinstance(p, (bytearray, bytes)) 70 | 71 | # runs the first time 72 | if not hasattr(self, '_log_ctr'): 73 | self._log_ctr = -1 74 | self._log_show = [False for k in range(103)] 75 | 76 | self._log_ctr += 1 77 | if self._log_ctr >= 10: 78 | self._log_ctr = 0 79 | show_description: bool = self._log_ctr == 0 80 | 81 | host_fmt = ' ' * (36 + len(self._ip)) 82 | out_desc = '{:s} {:2s} {:2s} {:4s} {:4s}'.format(host_fmt, 'Sq', '', 'Univ', ' Len') 83 | 84 | _max_channel = p[16] << 8 | p[17] 85 | pre = bytearray(p[:12]).hex().upper() 86 | out = f'Packet to {self._ip:s}: {pre} {p[12]:02x} {p[13]:02x} {p[13]:02x}{p[14]:02x} {_max_channel:04x}' 87 | 88 | # check what to print 89 | for k in range(_max_channel): 90 | if p[18 + k]: 91 | # once we change something print channel index 92 | if self._log_show[k // 5] is False: 93 | show_description = True 94 | self._log_show[k // 5] = True 95 | 96 | for k in range(0, _max_channel, 5): 97 | 98 | # if there was never anything active do not print, but print the last block 99 | if not self._log_show[k // 5] and not k + 5 > _max_channel: 100 | # do not print multiple dots 101 | if out.endswith('...'): 102 | continue 103 | 104 | out_desc += ' - ' 105 | out += ' ...' 106 | continue 107 | 108 | # format block of channels 109 | _block_vals = [] 110 | _block_desc = [] 111 | for i in range(5): 112 | if k + i < _max_channel: 113 | if show_description: 114 | _block_desc.append(f'{k + i + 1:<3d}') 115 | _block_vals.append(f'{p[18 + k + i]:03d}') 116 | 117 | # separator 118 | if out.endswith('...'): 119 | out_desc += ' ' 120 | out += ' ' 121 | else: 122 | out_desc += ' ' 123 | out += ' ' 124 | 125 | out += ' '.join(_block_vals) 126 | if show_description: 127 | out_desc += ' '.join(_block_desc) 128 | 129 | if show_description: 130 | log.debug(out_desc) 131 | log.debug(out) 132 | -------------------------------------------------------------------------------- /src/pyartnet/impl_artnet/universe.py: -------------------------------------------------------------------------------- 1 | from pyartnet.base import BaseUniverse 2 | 3 | 4 | class ArtNetUniverse(BaseUniverse): 5 | pass 6 | -------------------------------------------------------------------------------- /src/pyartnet/impl_kinet/__init__.py: -------------------------------------------------------------------------------- 1 | from .node import KiNetNode 2 | from .universe import KiNetUniverse 3 | -------------------------------------------------------------------------------- /src/pyartnet/impl_kinet/node.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from logging import DEBUG as LVL_DEBUG 3 | from struct import pack as s_pack 4 | from typing import Optional, Tuple, Union 5 | 6 | import pyartnet 7 | from pyartnet.base import BaseNode 8 | from pyartnet.errors import InvalidUniverseAddressError 9 | 10 | # ----------------------------------------------------------------------------- 11 | # Documentation for KiNet Protocol: 12 | # todo: find links 13 | # ----------------------------------------------------------------------------- 14 | 15 | log = logging.getLogger('pyartnet.KiNetNode') 16 | 17 | 18 | class KiNetNode(BaseNode['pyartnet.impl_kinet.KiNetUniverse']): 19 | def __init__(self, ip: str, port: int, *, 20 | max_fps: int = 25, 21 | refresh_every: Union[int, float, None] = 2, start_refresh_task: bool = True, 22 | source_address: Optional[Tuple[str, int]] = None): 23 | super().__init__(ip=ip, port=port, 24 | max_fps=max_fps, 25 | refresh_every=refresh_every, start_refresh_task=start_refresh_task, 26 | source_address=source_address) 27 | 28 | # build base packet 29 | packet = bytearray() 30 | packet.extend(s_pack(">IHH", 0x0401DC4A, 0x0100, 0x0101)) # Magic, version, type 31 | packet.extend(s_pack(">IBBHI", 0, 0, 0, 0, 0xFFFFFFFF)) # sequence, port, padding, flags, timer 32 | self._packet_base = bytes(packet) 33 | 34 | def _send_universe(self, id: int, byte_size: int, values: bytearray, universe: 'pyartnet.impl_kinet.KiNetUniverse'): 35 | packet = bytearray() 36 | packet.append(byte_size) 37 | packet.extend(values) 38 | 39 | self._send_data(packet) 40 | 41 | if log.isEnabledFor(LVL_DEBUG): 42 | # log complete packet 43 | log.debug(f"Sending KiNet frame to {self._ip}:{self._port}: {(self._packet_base + packet).hex()}") 44 | 45 | def _create_universe(self, nr: int) -> 'pyartnet.impl_kinet.KiNetUniverse': 46 | if nr >= 32_768: 47 | raise InvalidUniverseAddressError() 48 | return pyartnet.impl_kinet.KiNetUniverse(self, nr) 49 | -------------------------------------------------------------------------------- /src/pyartnet/impl_kinet/universe.py: -------------------------------------------------------------------------------- 1 | from pyartnet.base import BaseUniverse 2 | 3 | 4 | class KiNetUniverse(BaseUniverse): 5 | pass 6 | -------------------------------------------------------------------------------- /src/pyartnet/impl_sacn/__init__.py: -------------------------------------------------------------------------------- 1 | from .node import SacnNode 2 | from .universe import SacnUniverse 3 | -------------------------------------------------------------------------------- /src/pyartnet/impl_sacn/node.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa: E262 2 | import logging 3 | from logging import DEBUG as LVL_DEBUG 4 | from typing import Final, Optional, Tuple, Union 5 | from uuid import uuid4 6 | 7 | import pyartnet.impl_sacn.universe 8 | from pyartnet.base import BaseNode 9 | from pyartnet.errors import InvalidCidError, InvalidUniverseAddressError 10 | 11 | # ----------------------------------------------------------------------------- 12 | # Documentation for E1.31 Protocol: 13 | # https://tsp.esta.org/tsp/documents/published_docs.php 14 | # ----------------------------------------------------------------------------- 15 | 16 | log = logging.getLogger('pyartnet.SacnNode') 17 | 18 | 19 | # Package constant 20 | ACN_PACKET_IDENTIFIER: Final = (0x41, 0x53, 0x43, 0x2d, 0x45, 0x31, 0x2e, 0x31, 0x37, 0x00, 0x00, 0x00) 21 | 22 | # Field constants 23 | VECTOR_ROOT_E131_DATA: Final = b'\x00\x00\x00\x04' 24 | VECTOR_E131_DATA_PACKET: Final = b'\x00\x00\x00\x02' 25 | VECTOR_DMP_SET_PROPERTY: Final = 0x02 26 | 27 | 28 | class SacnNode(BaseNode['pyartnet.impl_sacn.SacnUniverse']): 29 | def __init__(self, ip: str, port: int, *, 30 | max_fps: int = 25, 31 | refresh_every: Union[int, float, None] = 2, start_refresh_task: bool = True, 32 | source_address: Optional[Tuple[str, int]] = None, 33 | 34 | # sACN E1.31 specific fields 35 | cid: Optional[bytes] = None, source_name: Optional[str] = None 36 | ): 37 | super().__init__(ip=ip, port=port, 38 | max_fps=max_fps, 39 | refresh_every=refresh_every, start_refresh_task=start_refresh_task, 40 | source_address=source_address) 41 | 42 | # CID Field 43 | if cid is not None: 44 | if not isinstance(cid, bytes) or len(cid) != 16: 45 | raise InvalidCidError('CID must be 16bytes!') 46 | else: 47 | cid = uuid4().bytes 48 | 49 | # Source field 50 | if source_name is None: 51 | source_name = 'PyArtNet' 52 | source_name_byte = source_name.encode('utf-8').ljust(64, b'\x00') 53 | if len(source_name_byte) > 64: 54 | raise ValueError('Source name too long!') 55 | 56 | # build base packet 57 | packet = bytearray() 58 | 59 | # Root layer 60 | packet.extend(b'\x00\x10') # | 2 | Preamble Size 61 | packet.extend(b'\x00\x00') # | 2 | Post-amble Size 62 | packet.extend(ACN_PACKET_IDENTIFIER) # | 12 | Packet Identifier 63 | packet.extend([0x72, 0x57]) # | 2 | Flags, Length 64 | packet.extend(VECTOR_ROOT_E131_DATA) # | 4 | Vector 65 | packet.extend(cid) # | 16 | CID, a unique identifier 66 | 67 | # Framing layer Part 1 68 | packet.extend([0x72, 0x57]) # | 2 | Flags and length 69 | packet.extend(VECTOR_E131_DATA_PACKET) # | 4 | Vector 70 | packet.extend(source_name_byte) # | 64 |Source Name 71 | packet.append(100) # | 1 |Priority 72 | packet.extend(int(50).to_bytes(2, 'big')) # | 2 | Synchronization universe 73 | 74 | self._packet_base: bytearray = packet 75 | 76 | 77 | def _send_universe(self, id: int, byte_size: int, values: bytearray, 78 | universe: 'pyartnet.impl_sacn.universe.SacnUniverse'): 79 | packet = bytearray() 80 | 81 | # DMX Start Code is not included in the byte size from the universe 82 | prop_count = byte_size + 1 83 | 84 | # Framing layer Part 2 85 | packet.append(universe._sequence_ctr.value) # | 1 | Sequence, 86 | packet.append(0x00) # | 1 | Options 87 | packet.extend(id.to_bytes(2, byteorder='big')) # | 2 | BaseUniverse Number 88 | 89 | # DMP Layer 90 | dmp_length = ((10 + prop_count) | 0x7000).to_bytes(2, 'big') 91 | packet.extend(dmp_length) # | 2 | Flags and length 92 | packet.append(VECTOR_DMP_SET_PROPERTY) # | 1 | Vector 93 | packet.append(0xA1) # | 1 | Address Type & Data Type 94 | packet.extend(b'\x00\x00') # | 2 | First Property Address 95 | packet.extend(b'\x00\x01') # | 2 | Address Increment 96 | 97 | packet.extend(prop_count.to_bytes(2, 'big')) # | 2 | Property Value Count 98 | packet.append(0x00) # | 1 | Property Values - DMX Start Code 99 | packet.extend(values) # | 0-512 | Property Values - DMX Data 100 | 101 | # Update length for base packet 102 | base_packet = self._packet_base 103 | base_packet[16:18] = ((109 + prop_count) | 0x7000).to_bytes(2, 'big') # root layer 104 | base_packet[38:40] = (( 87 + prop_count) | 0x7000).to_bytes(2, 'big') # framing layer 105 | 106 | self._send_data(packet) 107 | 108 | if log.isEnabledFor(LVL_DEBUG): 109 | # log complete packet 110 | log.debug(f"Sending sACN frame to {self._ip}:{self._port}: {(base_packet + packet).hex()}") 111 | 112 | def _create_universe(self, nr: int) -> 'pyartnet.impl_sacn.SacnUniverse': 113 | # 6.2.7 E1.31 Data Packet: Universe 114 | if not 1 <= nr < 63_999: 115 | raise InvalidUniverseAddressError() 116 | return pyartnet.impl_sacn.SacnUniverse(self, nr) 117 | -------------------------------------------------------------------------------- /src/pyartnet/impl_sacn/universe.py: -------------------------------------------------------------------------------- 1 | from typing import Final 2 | 3 | import pyartnet 4 | from pyartnet.base import BaseUniverse 5 | from pyartnet.base.seq_counter import SequenceCounter 6 | 7 | 8 | class SacnUniverse(BaseUniverse): 9 | 10 | def __init__(self, node: 'pyartnet.impl_sacn.SacnNode', universe: int = 0): 11 | super().__init__(node, universe) 12 | 13 | # sACN has the sequence counter on the universe 14 | self._sequence_ctr: Final = SequenceCounter() 15 | -------------------------------------------------------------------------------- /src/pyartnet/output_correction.py: -------------------------------------------------------------------------------- 1 | def linear(val: float, max_val: int = 0xFF) -> float: 2 | """linear output correction""" 3 | return val 4 | 5 | 6 | def quadratic(val: float, max_val: int = 0xFF) -> float: 7 | """Quadratic output correction""" 8 | return (val ** 2) / max_val 9 | 10 | 11 | def cubic(val: float, max_val: int = 0xFF) -> float: 12 | """Cubic output correction""" 13 | return (val ** 3) / (max_val ** 2) 14 | 15 | 16 | def quadruple(val: float, max_val: int = 0xFF) -> float: 17 | """Quadruple output correction""" 18 | return (val ** 4) / (max_val ** 3) 19 | -------------------------------------------------------------------------------- /tests/channel/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spacemanspiff2007/PyArtNet/53b0750df18dd6697f725acbe99d665410244ac1/tests/channel/__init__.py -------------------------------------------------------------------------------- /tests/channel/test_boundaries.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import Mock 2 | 3 | import pytest 4 | 5 | from pyartnet.base.channel import Channel 6 | from pyartnet.errors import ChannelOutOfUniverseError, \ 7 | ChannelValueOutOfBoundsError, ValueCountDoesNotMatchChannelWidthError 8 | 9 | 10 | def test_channel_boundaries(): 11 | univ = Mock() 12 | 13 | with pytest.raises(ChannelOutOfUniverseError) as r: 14 | Channel(univ, 0, 1) 15 | assert str(r.value) == 'Start position of channel out of universe (1..512): 0' 16 | Channel(univ, 1, 1) 17 | 18 | with pytest.raises(ChannelOutOfUniverseError) as r: 19 | Channel(univ, 513, 1) 20 | assert str(r.value) == 'Start position of channel out of universe (1..512): 513' 21 | Channel(univ, 512, 1) 22 | 23 | with pytest.raises(ChannelOutOfUniverseError) as r: 24 | Channel(univ, 512, 2) 25 | assert str(r.value) == 'End position of channel out of universe (1..512): start: 512 width: 2 * 1bytes -> 513' 26 | Channel(univ, 511, 2) 27 | 28 | # 16 Bit Channels 29 | with pytest.raises(ChannelOutOfUniverseError) as r: 30 | Channel(univ, 512, 1, byte_size=2) 31 | assert str(r.value) == 'End position of channel out of universe (1..512): start: 512 width: 1 * 2bytes -> 513' 32 | Channel(univ, 511, 1, byte_size=2) 33 | 34 | 35 | def get_node_universe_mock(): 36 | node = Mock() 37 | node._process_every = 0.001 38 | 39 | universe = Mock() 40 | universe._node = node 41 | universe.output_correction = None 42 | return node, universe 43 | 44 | 45 | @pytest.mark.parametrize( 46 | ('width', 'byte_size', 'invalid', 'valid'), 47 | ((1, 1, -1, 255), (1, 1, 256, 255), (3, 1, 256, 255), 48 | (1, 2, -1, 65535), (1, 2, 65536, 65535), (3, 2, 65536, 65535), )) 49 | def test_set_invalid(width, byte_size, invalid, valid): 50 | node, universe = get_node_universe_mock() 51 | 52 | invalid_values = [0] * (width - 1) + [invalid] 53 | valid_values = [0] * (width - 1) + [valid] 54 | 55 | # test set_values 56 | c = Channel(universe, 1, width, byte_size=byte_size) 57 | with pytest.raises(ChannelValueOutOfBoundsError) as e: 58 | c.set_values(invalid_values) 59 | assert str(e.value) == f'Channel value out of bounds! 0 <= {invalid:d} <= {valid}' 60 | c.set_values(valid_values) 61 | 62 | # test set_fade 63 | c = Channel(universe, 1, width, byte_size=byte_size) 64 | with pytest.raises(ChannelValueOutOfBoundsError) as e: 65 | c.set_fade(invalid_values, 100) 66 | assert str(e.value) == f'Target value out of bounds! 0 <= {invalid:d} <= {valid}' 67 | c.set_fade(valid_values, 100) 68 | 69 | 70 | async def test_set_missing(): 71 | node, universe = get_node_universe_mock() 72 | 73 | c = Channel(universe, 1, 1) 74 | with pytest.raises(ValueCountDoesNotMatchChannelWidthError) as e: 75 | c.set_values([0, 0, 255]) 76 | assert str(e.value) == 'Not enough fade values specified, expected 1 but got 3!' 77 | 78 | with pytest.raises(ValueCountDoesNotMatchChannelWidthError) as e: 79 | c.set_fade([0, 0, 255], 0) 80 | assert str(e.value) == 'Not enough fade values specified, expected 1 but got 3!' 81 | 82 | c = Channel(universe, 1, 3) 83 | with pytest.raises(ValueCountDoesNotMatchChannelWidthError) as e: 84 | c.set_values([0, 255]) 85 | assert str(e.value) == 'Not enough fade values specified, expected 3 but got 2!' 86 | 87 | with pytest.raises(ValueCountDoesNotMatchChannelWidthError) as e: 88 | c.set_fade([0, 255], 0) 89 | assert str(e.value) == 'Not enough fade values specified, expected 3 but got 2!' 90 | -------------------------------------------------------------------------------- /tests/channel/test_buffer.py: -------------------------------------------------------------------------------- 1 | from typing import Iterable, Optional 2 | from unittest.mock import Mock 3 | 4 | from pyartnet.base.channel import Channel 5 | 6 | 7 | def to_buf(c: Channel, v: Iterable[int], buf: Optional[bytearray] = None) -> bytearray: 8 | c.set_values(v) 9 | assert c.get_values() == list(v) 10 | 11 | if buf is None: 12 | buf = bytearray(b'\x00' * 5) 13 | c.to_buffer(buf) 14 | return buf 15 | 16 | 17 | def test_channel_1b_values_single(): 18 | universe = Mock() 19 | universe.output_correction = None 20 | 21 | a = Channel(universe, 1, 1) 22 | assert a.get_values() == [0] 23 | assert to_buf(a, [255]) == b'\xff\x00\x00\x00\x00' 24 | 25 | b = Channel(universe, 3, 1) 26 | assert to_buf(b, [255]) == b'\x00\x00\xff\x00\x00' 27 | 28 | c = Channel(universe, 5, 1) 29 | 30 | buf = bytearray(b'\x00' * 5) 31 | to_buf(a, [0xF0], buf=buf) 32 | to_buf(b, [0xFF], buf=buf) 33 | to_buf(c, [0x0F], buf=buf) 34 | assert buf == b'\xf0\x00\xff\x00\x0f' 35 | 36 | 37 | def test_channel_1b_values_multiple(): 38 | universe = Mock() 39 | universe.output_correction = None 40 | 41 | c = Channel(universe, 1, 3) 42 | assert c.get_values() == [0, 0, 0] 43 | assert to_buf(c, [128, 0, 255]) == b'\x80\x00\xff\x00\x00' 44 | 45 | c = Channel(universe, 3, 3) 46 | assert to_buf(c, [128, 0, 255]) == b'\x00\x00\x80\x00\xff' 47 | 48 | 49 | def test_channel_2b_values_single(): 50 | universe = Mock() 51 | universe.output_correction = None 52 | 53 | c = Channel(universe, 1, 1, byte_size=2) 54 | assert c.get_values() == [0] 55 | assert to_buf(c, [65535]) == b'\xff\xff\x00\x00\x00' 56 | assert to_buf(c, [0xF00F]) == b'\x0f\xf0\x00\x00\x00' 57 | 58 | c = Channel(universe, 3, 1, byte_size=2) 59 | assert to_buf(c, [0xF00F]) == b'\x00\x00\x0f\xf0\x00' 60 | 61 | c = Channel(universe, 4, 1, byte_size=2) 62 | assert to_buf(c, [0xF00F]) == b'\x00\x00\x00\x0f\xf0' 63 | -------------------------------------------------------------------------------- /tests/channel/test_channel.py: -------------------------------------------------------------------------------- 1 | from pyartnet.base import BaseUniverse 2 | 3 | 4 | def test_values_add_channel(universe: BaseUniverse): 5 | u = universe.add_channel(1, 2, byte_size=3, byte_order='big') 6 | assert u._start == 1 7 | assert u._width == 2 8 | assert u._byte_size == 3 9 | assert u._byte_order == 'big' 10 | 11 | u = universe.add_channel(10, 5, byte_size=2, byte_order='little') 12 | assert u._start == 10 13 | assert u._width == 5 14 | assert u._byte_size == 2 15 | assert u._byte_order == 'little' 16 | -------------------------------------------------------------------------------- /tests/channel/test_fade.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from time import monotonic 3 | 4 | from pyartnet.base import BaseUniverse 5 | from pyartnet.base.channel import Channel 6 | from tests.conftest import STEP_MS, TestingNode 7 | 8 | 9 | async def test_channel_await(node: TestingNode, universe: BaseUniverse, caplog): 10 | a = Channel(universe, 1, 1) 11 | assert a.get_values() == [0] 12 | 13 | a.set_fade([255], 200) 14 | 15 | start = monotonic() 16 | await asyncio.wait_for(a, 1) 17 | stop = monotonic() 18 | 19 | assert stop - start >= 0.2 20 | 21 | 22 | async def test_single_step(node: TestingNode, universe: BaseUniverse, caplog): 23 | caplog.set_level(0) 24 | 25 | a = Channel(universe, 1, 1) 26 | assert a.get_values() == [0] 27 | 28 | a.set_fade([255], 0) 29 | assert a.get_values() == [0] 30 | 31 | assert list(caplog.messages) == [ 32 | 'Added fade with 1 steps:', 33 | 'CH 1: 000 -> 255 | step: +255.0' 34 | ] 35 | 36 | await node.sleep_steps(2) 37 | assert a.get_values() == [255] 38 | assert node.data == ['ff'] 39 | 40 | await node.wait_for_task_finish() 41 | assert node.data == ['ff'] 42 | 43 | 44 | async def test_single_fade(node: TestingNode, universe: BaseUniverse, caplog): 45 | caplog.set_level(0) 46 | 47 | a = Channel(universe, 1, 1) 48 | assert a.get_values() == [0] 49 | 50 | a.set_fade([2], 2 * STEP_MS) 51 | assert a.get_values() == [0] 52 | 53 | assert list(caplog.messages) == [ 54 | 'Added fade with 2 steps:', 55 | 'CH 1: 000 -> 002 | step: +1.0' 56 | ] 57 | 58 | await node.sleep_steps(3) 59 | assert a.get_values() == [2] 60 | assert node.data == ['01', '02'] 61 | 62 | await node.wait_for_task_finish() 63 | assert node.data == ['01', '02'] 64 | 65 | 66 | async def test_tripple_fade(node: TestingNode, universe: BaseUniverse, caplog): 67 | caplog.set_level(0) 68 | 69 | a = Channel(universe, 1, 3) 70 | assert a.get_values() == [0, 0, 0] 71 | 72 | a.set_fade([3, 6, 9], 3 * STEP_MS) 73 | assert a.get_values() == [0, 0, 0] 74 | 75 | assert list(caplog.messages) == [ 76 | 'Added fade with 3 steps:', 77 | 'CH 1: 000 -> 003 | step: +1.0', 78 | 'CH 2: 000 -> 006 | step: +2.0', 79 | 'CH 3: 000 -> 009 | step: +3.0' 80 | ] 81 | 82 | await node.sleep_steps(4) 83 | assert a.get_values() == [3, 6, 9] 84 | assert node.data == ['010203', '020406', '030609'] 85 | 86 | await node.wait_for_task_finish() 87 | assert node.data == ['010203', '020406', '030609'] 88 | 89 | 90 | async def test_fade_await(node: TestingNode, universe: BaseUniverse, caplog): 91 | caplog.set_level(0) 92 | 93 | channel = Channel(universe, 1, 1) 94 | assert channel.get_values() == [0] 95 | 96 | async def check_no_wait_time_when_no_fade(): 97 | start = monotonic() 98 | for _ in range(1000): 99 | assert not await channel 100 | assert monotonic() - start < 0.001 101 | 102 | await check_no_wait_time_when_no_fade() 103 | 104 | channel.set_fade([2], 2 * STEP_MS) 105 | assert channel.get_values() == [0] 106 | 107 | assert list(caplog.messages) == [ 108 | 'Added fade with 2 steps:', 109 | 'CH 1: 000 -> 002 | step: +1.0' 110 | ] 111 | 112 | assert channel._current_fade is not None 113 | assert await channel 114 | assert channel._current_fade is None 115 | assert channel.get_values() == [2] 116 | assert node.data == ['01', '02'] 117 | 118 | await check_no_wait_time_when_no_fade() 119 | 120 | channel.set_fade([10], 2 * STEP_MS) 121 | 122 | assert channel._current_fade is not None 123 | await channel 124 | assert channel._current_fade is None 125 | assert node.data == ['01', '02', '06', '0a'] 126 | 127 | await check_no_wait_time_when_no_fade() 128 | await node.wait_for_task_finish() 129 | 130 | 131 | async def test_up_down_fade(node: TestingNode, universe: BaseUniverse, caplog): 132 | caplog.set_level(0) 133 | 134 | a = Channel(universe, 1, 1) 135 | for _ in range(5): 136 | node.data.clear() 137 | assert a.get_values() == [0] 138 | 139 | a.set_fade([255], 2 * STEP_MS) 140 | assert a.get_values() == [0] 141 | 142 | await a 143 | 144 | assert a.get_values() == [255] 145 | assert node.data == ['80', 'ff'] 146 | 147 | # Fade down 148 | a.set_fade([0], 2 * STEP_MS) 149 | assert a.get_values() == [255] 150 | 151 | await a 152 | 153 | assert a.get_values() == [0] 154 | assert node.data == ['80', 'ff', '80', '00'] 155 | -------------------------------------------------------------------------------- /tests/channel/test_set_values.py: -------------------------------------------------------------------------------- 1 | from pyartnet.base import BaseUniverse 2 | from pyartnet.base.channel import Channel 3 | from tests.conftest import TestingNode 4 | 5 | 6 | async def test_channel_set_values(node: TestingNode, universe: BaseUniverse, caplog): 7 | a = Channel(universe, 1, 1) 8 | assert a.get_values() == [0] 9 | 10 | a.set_values([255]) 11 | assert a.get_values() == [255] 12 | 13 | await node.sleep_steps(2) 14 | assert node.data == ['ff'] 15 | 16 | a.set_values([125]) 17 | assert a.get_values() == [125] 18 | 19 | await node.sleep_steps(1) 20 | assert node.data == ['ff', '7d'] 21 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from asyncio import sleep 3 | from typing import List 4 | 5 | import pytest 6 | 7 | import pyartnet.base.base_node 8 | from pyartnet.base import BaseNode, BaseUniverse 9 | from pyartnet.base.base_node import TYPE_U 10 | from tests.helper import MockedSocket 11 | 12 | STEP_MS = 15 13 | 14 | 15 | class TestingNode(BaseNode): 16 | __test__ = False # prevent this from being collected by pytest 17 | 18 | def __init__(self, ip: str, port: int): 19 | super().__init__(ip, port, max_fps=1_000 // STEP_MS, start_refresh_task=False) 20 | self.data = [] 21 | 22 | def _send_universe(self, id: int, byte_size: int, values: bytearray, universe: 'pyartnet.base.BaseUniverse'): 23 | self.data.append(values.hex()) 24 | 25 | async def sleep_steps(self, steps: int): 26 | # use sleep because await sleep might actually take longer 27 | for _ in range(steps): 28 | await sleep(self._process_every) 29 | 30 | async def wait_for_task_finish(self): 31 | await self 32 | 33 | def _create_universe(self, nr: int) -> TYPE_U: 34 | return BaseUniverse(self, nr) 35 | 36 | 37 | @pytest.fixture(autouse=True) 38 | def patched_socket(monkeypatch): 39 | with MockedSocket() as sock_sendto: 40 | yield sock_sendto 41 | 42 | 43 | def test_patched_socket(patched_socket): 44 | node = TestingNode('IP', 9999) 45 | assert node._socket.sendto is patched_socket 46 | 47 | 48 | @pytest.fixture() 49 | def node(): 50 | node = TestingNode('IP', 9999) 51 | return node 52 | 53 | 54 | @pytest.fixture() 55 | def universe(node: BaseNode): 56 | return node.add_universe() 57 | 58 | 59 | @pytest.fixture(autouse=True) 60 | def ensure_no_errors(caplog): 61 | caplog.set_level(logging.DEBUG) 62 | 63 | yield None 64 | 65 | log_records: List[logging.LogRecord] = [] 66 | name_indent = 0 67 | level_indent = 0 68 | 69 | for when in ('setup', 'call', 'teardown'): 70 | records = caplog.get_records(when) 71 | if any(x.levelno >= logging.WARNING for x in records): 72 | for rec in records: 73 | name_indent = max(name_indent, len(rec.name)) 74 | level_indent = max(level_indent, len(rec.levelname)) 75 | log_records.extend(records) 76 | 77 | if log_records: 78 | msgs = [ 79 | f'[{rec.name:>{name_indent:d}s}] | {rec.levelname:{level_indent:d}s} | {rec.getMessage()}' 80 | for rec in log_records 81 | ] 82 | pytest.fail('Error in log:\n' + '\n'.join(msgs)) 83 | -------------------------------------------------------------------------------- /tests/helper.py: -------------------------------------------------------------------------------- 1 | import socket 2 | from unittest.mock import Mock 3 | 4 | from pytest import MonkeyPatch # noqa: PT013 5 | 6 | import pyartnet 7 | 8 | 9 | class MockedSocket: 10 | def __init__(self): 11 | self.mp = MonkeyPatch() 12 | 13 | def mock(self): 14 | m_socket_obj = Mock(['sendto', 'setblocking'], name='socket_obj') 15 | m_socket_obj.sendto = m_sendto = Mock(name='socket_obj.sendto') 16 | 17 | m = Mock(['socket', 'AF_INET', 'SOCK_DGRAM'], name='Mock socket package') 18 | m.socket = Mock([], return_value=m_socket_obj, name='Mock socket obj') 19 | m.AF_INET = socket.AF_INET 20 | m.SOCK_DGRAM = socket.AF_INET 21 | 22 | self.mp.setattr(pyartnet.base.base_node, 'socket', m) 23 | return m_sendto 24 | 25 | def undo(self): 26 | self.mp.undo() 27 | 28 | def __enter__(self): 29 | return self.mock() 30 | 31 | def __exit__(self, exc_type, exc_val, exc_tb): 32 | self.undo() 33 | -------------------------------------------------------------------------------- /tests/test_base_node.py: -------------------------------------------------------------------------------- 1 | from time import monotonic 2 | 3 | import pytest 4 | 5 | from pyartnet.base import BaseUniverse 6 | from pyartnet.base.channel import Channel 7 | from pyartnet.errors import DuplicateUniverseError 8 | from tests.conftest import STEP_MS, TestingNode 9 | 10 | 11 | def test_universe_add_get(node: TestingNode): 12 | for i in (1.3, -1): 13 | with pytest.raises(ValueError, match='BaseUniverse must be an int >= 0!'): 14 | node.add_universe(i) 15 | 16 | with pytest.raises(ValueError, match='BaseUniverse must be an int >= 0!'): 17 | node.get_universe(i) 18 | 19 | u = node.add_universe() 20 | assert len(node) == 1 21 | assert node.get_universe(0) is u 22 | assert node[0] is u 23 | 24 | # Duplicate 25 | with pytest.raises(DuplicateUniverseError, match='BaseUniverse 0 does already exist!'): 26 | node.add_universe() 27 | 28 | # Check that the nodes are ascending 29 | node.add_universe(50) 30 | node.add_universe(3) 31 | 32 | assert len(node) == 3 33 | assert node._universes == ( 34 | node.get_universe(0), node.get_universe(3), node.get_universe(50) 35 | ) 36 | 37 | 38 | async def test_fade_await(node: TestingNode, universe: BaseUniverse, caplog): 39 | async def check_no_wait_time_when_no_fade(): 40 | start = monotonic() 41 | for _ in range(1000): 42 | assert not await node 43 | assert monotonic() - start < 0.001 44 | 45 | async def check_wait_time_when_fade(steps: int): 46 | start = monotonic() 47 | await node 48 | assert monotonic() - start >= ((steps - 1) * STEP_MS) / 1000 49 | 50 | caplog.set_level(0) 51 | 52 | channel = Channel(universe, 1, 1) 53 | 54 | await check_no_wait_time_when_no_fade() 55 | 56 | channel.set_fade([2], 2 * STEP_MS) 57 | assert channel.get_values() == [0] 58 | 59 | assert list(caplog.messages) == [ 60 | 'Added fade with 2 steps:', 61 | 'CH 1: 000 -> 002 | step: +1.0' 62 | ] 63 | 64 | assert channel._current_fade is not None 65 | await check_wait_time_when_fade(2) 66 | assert channel._current_fade is None 67 | assert channel.get_values() == [2] 68 | assert node.data == ['01', '02'] 69 | 70 | await check_no_wait_time_when_no_fade() 71 | 72 | channel.set_fade([10], 2 * STEP_MS) 73 | 74 | assert channel._current_fade is not None 75 | await check_wait_time_when_fade(2) 76 | assert channel._current_fade is None 77 | assert node.data == ['01', '02', '06', '0a'] 78 | 79 | await check_no_wait_time_when_no_fade() 80 | await node.wait_for_task_finish() 81 | -------------------------------------------------------------------------------- /tests/test_channel_fade.py: -------------------------------------------------------------------------------- 1 | from unittest.mock import Mock 2 | 3 | from pyartnet.base import Channel 4 | from pyartnet.base.channel_fade import ChannelBoundFade 5 | 6 | 7 | def test_repr(): 8 | universe = Mock() 9 | universe.output_correction = None 10 | 11 | a = Channel(universe, 1, 2) 12 | 13 | a = ChannelBoundFade(a, []) 14 | assert repr(a) == '' 15 | 16 | a.is_done = True 17 | assert repr(a) == '' 18 | 19 | a = ChannelBoundFade(a, []) 20 | a.channel = None 21 | assert repr(a) == '' 22 | -------------------------------------------------------------------------------- /tests/test_impl/test_impl.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | import logging 3 | from asyncio import sleep 4 | 5 | import pytest 6 | 7 | from pyartnet import ArtNetNode, KiNetNode, SacnNode 8 | from pyartnet.base import BaseNode 9 | from tests.conftest import TestingNode 10 | 11 | 12 | @pytest.mark.parametrize('c', (ArtNetNode, KiNetNode, SacnNode)) 13 | def test_same_cls_signature(c): 14 | sig_base = inspect.signature(BaseNode) 15 | sig_obj = inspect.signature(c) 16 | 17 | for name, parameter in sig_base.parameters.items(): 18 | assert name in sig_obj.parameters 19 | assert sig_obj.parameters[name] == parameter 20 | 21 | 22 | @pytest.mark.parametrize('cls', [ArtNetNode, SacnNode, KiNetNode]) 23 | async def test_set_funcs(node: TestingNode, caplog, cls): 24 | caplog.set_level(logging.DEBUG) 25 | 26 | n = cls('ip', 9999) 27 | u = n.add_universe(1) 28 | c = u.add_channel(1, 1) 29 | 30 | c.set_values([5]) 31 | await sleep(0.1) 32 | 33 | c.set_fade([250], 700) 34 | await c 35 | -------------------------------------------------------------------------------- /tests/test_impl/test_sacn.py: -------------------------------------------------------------------------------- 1 | from binascii import a2b_hex 2 | 3 | from pyartnet import SacnNode 4 | 5 | 6 | async def test_sacn(patched_socket): 7 | sacn = SacnNode( 8 | 'ip', 9999999, 9 | cid=b'\x41\x68\xf5\x2b\x1a\x7b\x2d\xe1\x17\x12\xe9\xee\x38\x3d\x22\x58', 10 | source_name="default source name") 11 | universe = sacn.add_universe(1) 12 | channel = universe.add_channel(1, 10) 13 | channel.set_values(range(1, 11)) 14 | 15 | universe.send_data() 16 | 17 | data = '001000004153432d45312e31370000007078000000044168f52b1a7b2de11712e9ee383d225870620000000264656661756c7420' \ 18 | '736f75726365206e616d650000000000000000000000000000000000000000000000000000000000000000000000000000000000' \ 19 | '0000000064003200000001701502a100000001000b000102030405060708090a' 20 | 21 | m = sacn._socket 22 | m.sendto.assert_called_once_with(bytearray(a2b_hex(data)), ('ip', 9999999)) 23 | 24 | 25 | await channel 26 | -------------------------------------------------------------------------------- /tests/test_output_correction.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from pyartnet.output_correction import cubic, quadratic, quadruple 4 | 5 | 6 | @pytest.mark.parametrize('max_val', [ 7 | pytest.param(k, id=f'{k:X}') for k in (0xFF, 0xFFFF, 0xFFFFFF, 0xFFFFFFFF, 0xFFFFFFFFFF)]) 8 | @pytest.mark.parametrize('corr', [quadratic, quadruple, cubic]) 9 | def test_correction(corr, max_val): 10 | assert corr(0, max_val=max_val) == 0 11 | assert corr(max_val, max_val=max_val) == max_val 12 | -------------------------------------------------------------------------------- /tests/test_sequence_counter.py: -------------------------------------------------------------------------------- 1 | from pyartnet.base.seq_counter import SequenceCounter 2 | 3 | 4 | def test_seq(): 5 | s = SequenceCounter() 6 | assert s.value == 0 7 | assert s.value == 1 8 | assert s.value == 2 9 | 10 | s._ctr = 254 11 | assert s.value == 254 12 | assert s.value == 255 13 | assert s.value == 0 14 | assert s.value == 1 15 | 16 | 17 | def test_seq_artnet(): 18 | s = SequenceCounter(1) 19 | assert s.value == 1 20 | assert s.value == 2 21 | 22 | s._ctr = 254 23 | assert s.value == 254 24 | assert s.value == 255 25 | assert s.value == 1 26 | 27 | 28 | def test_seq_const(): 29 | s = SequenceCounter(0, 0) 30 | assert s.value == 0 31 | assert s.value == 0 32 | assert s.value == 0 33 | 34 | 35 | def test_repr(): 36 | s = SequenceCounter() 37 | assert repr(s) == '' 38 | assert repr(s) == '' 39 | assert s.value == 0 40 | assert repr(s) == '' 41 | -------------------------------------------------------------------------------- /tests/test_universe.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from pyartnet import errors 4 | from pyartnet.base import BaseUniverse 5 | from pyartnet.errors import ChannelNotFoundError 6 | 7 | 8 | def test_exceptions(universe: BaseUniverse): 9 | universe.add_channel(1, 1) 10 | 11 | with pytest.raises(errors.ChannelExistsError) as e: 12 | universe.add_channel(1, 1) 13 | assert str(e.value) == 'Channel "1/1" does already exist in the universe!' 14 | 15 | # Channels 16 | with pytest.raises(errors.ChannelNotFoundError) as e: 17 | universe.get_channel('2') 18 | assert str(e.value) == 'Channel "2" not found in the universe!' 19 | with pytest.raises(errors.ChannelNotFoundError) as e: 20 | _ = universe['2'] 21 | assert str(e.value) == 'Channel "2" not found in the universe!' 22 | 23 | # Overlapping channels 24 | universe.add_channel(10, 3) 25 | 26 | with pytest.raises(errors.OverlappingChannelError) as e: 27 | universe.add_channel(1, 3) 28 | assert str(e.value) == 'New channel 1/3 is overlapping with channel 1/1!' 29 | 30 | with pytest.raises(errors.OverlappingChannelError): 31 | universe.add_channel(9, 2) 32 | with pytest.raises(errors.OverlappingChannelError): 33 | universe.add_channel(12, 1) 34 | with pytest.raises(errors.OverlappingChannelError): 35 | universe.add_channel(8, 20) 36 | 37 | 38 | def test_universe_resize(universe: BaseUniverse): 39 | assert universe._data_size == 0 40 | assert universe._data == b'' 41 | 42 | universe.add_channel(1, 1) 43 | assert universe._data_size == 2 44 | assert universe._data == b'\x00\x00' 45 | 46 | universe.add_channel(6, 1) 47 | assert universe._data_size == 6 48 | assert universe._data == b'\x00\x00\x00\x00\x00\x00' 49 | 50 | universe._channels.popitem() 51 | universe.add_channel(2, 1) 52 | assert universe._data_size == 2 53 | assert universe._data == b'\x00\x00' 54 | 55 | universe.add_channel(3, 1) 56 | assert universe._data_size == 4 57 | assert universe._data == b'\x00\x00\x00\x00' 58 | 59 | 60 | def test_access(universe: BaseUniverse): 61 | 62 | with pytest.raises(ChannelNotFoundError) as e: 63 | universe.get_channel('1') 64 | assert str(e.value) == 'Channel "1" not found in the universe!' 65 | 66 | with pytest.raises(ChannelNotFoundError) as e: 67 | universe.get_channel('1/1') 68 | assert str(e.value) == 'Channel "1/1" not found in the universe!' 69 | 70 | c = universe.add_channel(1, 1) 71 | assert len(universe) == 1 72 | assert universe.get_channel('1/1') is c 73 | assert universe['1/1'] is c 74 | 75 | c = universe.add_channel(2, 1) 76 | assert len(universe) == 2 77 | assert universe.get_channel('2/1') is c 78 | assert universe['2/1'] is c 79 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # content of: tox.ini , put in same dir as setup.py 2 | [tox] 3 | envlist = 4 | py38 5 | py39 6 | py310 7 | py311 8 | flake 9 | docs 10 | 11 | [gh-actions] 12 | python = 13 | 3.8: py38 14 | 3.9: py39 15 | 3.10: py310, flake, docs 16 | 3.11: py311 17 | 18 | [testenv] 19 | deps = 20 | pytest 21 | pytest-asyncio 22 | asynctest 23 | -r{toxinidir}/requirements.txt 24 | 25 | commands = 26 | python -m pytest 27 | 28 | [testenv:flake] 29 | deps = 30 | {[testenv]deps} 31 | flake8 32 | # pydocstyle 33 | commands = 34 | flake8 -v 35 | # pydocstyle 36 | 37 | 38 | [testenv:docs] 39 | description = invoke sphinx-build to build the HTML docs 40 | 41 | deps = 42 | {[testenv]deps} 43 | -r{toxinidir}/docs/requirements.txt 44 | 45 | commands = 46 | mkdir -p docs{/}_static 47 | sphinx-build -d "{envtmpdir}{/}doctree" docs "{toxworkdir}{/}docs_out" --color -b html -E -W -n --keep-going 48 | 49 | allowlist_externals=mkdir 50 | 51 | 52 | [pytest] 53 | asyncio_mode = auto 54 | addopts = -p no:cacheprovider 55 | --------------------------------------------------------------------------------