pax_global_header00006660000000000000000000000064146403172260014517gustar00rootroot0000000000000052 comment=d1dc263c9c29fc429921846bf07ee09cf4304c84 kk7ds-pynx584-d1dc263/000077500000000000000000000000001464031722600144075ustar00rootroot00000000000000kk7ds-pynx584-d1dc263/.docker/000077500000000000000000000000001464031722600157345ustar00rootroot00000000000000kk7ds-pynx584-d1dc263/.docker/Dockerfile000066400000000000000000000002661464031722600177320ustar00rootroot00000000000000FROM python:2.7 ENV LISTEN=0.0.0.0 RUN pip install --no-cache-dir pynx584 ADD entrypoint.sh /usr/local/bin/entrypoint.sh EXPOSE 5007 ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] kk7ds-pynx584-d1dc263/.docker/entrypoint.sh000077500000000000000000000004611464031722600205070ustar00rootroot00000000000000#!/bin/bash args=() if [ ! -z "$SERIAL" ]; then args+=(--serial $SERIAL) fi if [ ! -z "$BAUD" ]; then args+=(--baud $BAUD) fi if [ ! -z "$CONNECT" ]; then args+=(--connect $CONNECT) fi if [ ! -z "$CONFIG" ]; then args+=(--config $CONFIG) fi nx584_server --listen $LISTEN "${args[@]}" kk7ds-pynx584-d1dc263/.github/000077500000000000000000000000001464031722600157475ustar00rootroot00000000000000kk7ds-pynx584-d1dc263/.github/workflows/000077500000000000000000000000001464031722600200045ustar00rootroot00000000000000kk7ds-pynx584-d1dc263/.github/workflows/test.yaml000066400000000000000000000007241464031722600216520ustar00rootroot00000000000000name: Tests on: pull_request: push: jobs: test: name: Unit tests runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Install dependencies run: | sudo apt-get update sudo apt-get install python3-requests python3-stevedore python3-prettytable python3-serial python3-flask python3-pytest python3-mock pytest-3 tests kk7ds-pynx584-d1dc263/.gitignore000066400000000000000000000000111464031722600163670ustar00rootroot00000000000000*~ *.pyc kk7ds-pynx584-d1dc263/LICENSE000066400000000000000000001045151464031722600154220ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . kk7ds-pynx584-d1dc263/README.rst000066400000000000000000000113551464031722600161030ustar00rootroot00000000000000NetworX NX584/NX8E Interface Library and Server =============================================== .. image:: https://github.com/kk7ds/pynx584/actions/workflows/test.yaml/badge.svg This is a tool to let you interact with your NetworX alarm panel via the NX584 module (which is built into NX8E panels). You must enable it in the configuration and enable the operations you want to be able to do before this will work. This tool supports both the ASCII or Binary home automation protocol (and works with the binary only NX590E in addition to the ASCII or binary NX584/NX8E) Install Locally *************** :: # pip install pynx584 The server must be run on a machine with connectivity to the panel, which can be a local serial port, or a Serial-over-LAN device (i.e. a TCP socket). For example:: # nx584_server --serial /dev/ttyS0 --baud 38400 or:: # nx584_server --connect 192.168.1.101:23 Once that is running, you should be able to do something like this:: $ nx584_client summary +------+-----------------+--------+--------+ | Zone | Name | Bypass | Status | +------+-----------------+--------+--------+ | 1 | FRONT DOOR | - | False | | 2 | GARAGE DOOR | - | False | | 3 | SLIDING | - | False | | 4 | MOTION DETECTOR | - | False | +------+-----------------+--------+--------+ Partition 1 armed # Arm for stay with auto-bypass $ nx584_client arm-stay # Arm for exit (requires tripping an entry zone) $ nx584_client arm-exit # Auto-arm (no bypass, no entry zone trip required) $ nx584_client arm-auto # Disarm $ nx584_client disarm --master 1234 Install via Docker Compose ************************** Before creating the Docker container, you need to define how you connect to the panel (local serial port, or a Serial-over-LAN device (i.e. a TCP socket)) in the :code:`docker-compose.yml` file. Uncomment and edit the :code:`environment` section to fit your needs:: version: "3.2" services: pynx584: container_name: pynx584 image: kk7ds/pynx584 build: context: .docker dockerfile: Dockerfile restart: unless-stopped ports: - 5007:5007 environment: # Uncomment these as needed, depending on how you connect to the panel (via Serial or TCP Socket) # - SERIAL=/dev/ttyS0 # - BAUD=38400 # - CONNECT=192.168.1.101:23 To build the image, create the Docker container and then run it, make sure you're at the root of the checked out repo and run:: # docker-compose up -d You should now be able to conect to the pynx584 Docker container via its exposed port (default :code:`5007`). Config ------ The `config.ini` should be generated once the controller reports the first zone name. However, here is a full `config.ini` if you want to pre-populate it with zone names:: [config] # max_zone is the highest numbered zone you have populated max_zone = 5 # Disable zone name updates from NX8 system. If your system doesn't set zone # names and you prefer define them through pynx584, set this value to False. # Defaults to True # zone_name_update = False # Set to true if your unit sends DD/MM dates instead of MM/DD euro_date_format = False # Set To true if using binary protocol # Defaults to False # use_binary_protocol = True # Length of idle time before sending heartbeat keep alive # (This is useful with the NX590 as it disconnects idle connections in a # short period of time) # Defaults to 120 seconds # idle_time_heartbeat_seconds = 20 [email] fromaddr = security@foo.com smtphost = imap.foo.com [zones] # Zone names 1 = Front Door 2 = Garage Entry 3 = Garage Side 4 = Garage Back 5 = Kitchen Panel Configuration ------------------- Your NX panel must be configured properly to allow this software to work with it. If it was configured by a monitoring company, there is a very good chance that it will need quite a bit of tweaking first. Here is a good start to what needs to be set and how: - Protocol: ASCII - Speed: 38400 Baud (OR WHICHEVER YOU CHOOSE) - Enabled Transition Messages: * Interface Configuration Message * Zone Status Message * Partition Status Message * System Status Message * Log Event Message * Keypad Message Received (OPTIONAL) * X-10 Message Received (OPTIONAL) - Enabled Commands: * Interface Configuration Request * Zone Name Request * Zone Status Request * Zones Snapshot Request * Partition Status Request * Partitions Snapshot Request * Send X-10 Message (OPTIONAL) * Log Event Request * Send Keypad Text Message (OPTIONAL) * System Status Request * Program Data Request (OPTIONAL) * Program Data Command (OPTIONAL) * Set Clock / Calendar Command * Primary Keypad Function with PIN (OPTIONAL) * Secondary Keypad Function (OPTIONAL) * Zone Bypass Toggle (OPTIONAL) kk7ds-pynx584-d1dc263/docker-compose.yml000066400000000000000000000012061464031722600200430ustar00rootroot00000000000000version: "3.2" services: pynx584: container_name: pynx584 image: kk7ds/pynx584 # Uncomment to expose tty device in container  #devices: # - "/dev/ttyS0:/dev/ttyS0" build: context: .docker dockerfile: Dockerfile restart: unless-stopped ports: - 5007:5007 environment: # Uncomment these as needed, depending on how you connect to the panel (via Serial or TCP Socket) # - SERIAL=/dev/ttyS0 # - BAUD=38400 # - CONNECT=192.168.1.101:23 # Uncomment as needed, depending on the location of the config file # - CONFIG=/config.ini network_mode: bridge kk7ds-pynx584-d1dc263/nx584/000077500000000000000000000000001464031722600152755ustar00rootroot00000000000000kk7ds-pynx584-d1dc263/nx584/__init__.py000066400000000000000000000000001464031722600173740ustar00rootroot00000000000000kk7ds-pynx584-d1dc263/nx584/api.py000066400000000000000000000120171464031722600164210ustar00rootroot00000000000000import flask import json import logging LOG = logging.getLogger('api') CONTROLLER = None app = flask.Flask('nx584') def show_zone(zone): return { 'number': zone.number, 'name': zone.name, 'state': zone.state, 'bypassed': zone.bypassed, 'condition_flags': zone.condition_flags, 'type_flags': zone.type_flags, } def show_partition(partition): return { 'number': partition.number, 'condition_flags': partition.condition_flags, 'armed': 'Armed' in partition.condition_flags, 'last_user': partition.last_user, } def show_user(user): if all([x > 9 for x in user.pin]): pin = None else: pin = ''.join([str(c) if c < 10 else '' for c in user.pin]) return { 'number': user.number, 'pin': pin, 'authority_flags': user.authority_flags, 'authorized_partitions': user.authorized_partitions, } @app.route('/zones') def index_zones(): try: result = json.dumps({ 'zones': [show_zone(zone) for zone in CONTROLLER.zones.values()]}) return flask.Response(result, mimetype='application/json') except Exception as e: LOG.exception('Failed to index zones') @app.route('/partitions') def index_partitions(): try: result = json.dumps({ 'partitions': [show_partition(partition) for partition in CONTROLLER.partitions.values()]}) return flask.Response(result, mimetype='application/json') except Exception as e: LOG.exception('Failed to index partitions') @app.route('/command') def command(): args = flask.request.args if args.get('cmd') == 'arm': if args.get('type') == 'stay': CONTROLLER.arm_stay(int(args.get('partition', 1))) elif args.get('type') == 'exit': CONTROLLER.arm_exit(int(args.get('partition', 1))) else: CONTROLLER.arm_auto(int(args.get('partition', 1))) elif args.get('cmd') == 'disarm': CONTROLLER.disarm(args.get('master_pin'), int(args.get('partition', 1))) return flask.Response() @app.route('/zones/', methods=['PUT']) def put_zone(zone): zone = CONTROLLER.zones.get(zone) if not zone: flask.abort(404) zonedata = flask.request.json if 'bypassed' in zonedata: want_bypass = zonedata['bypassed'] if want_bypass == zone.bypassed: flask.abort(409) CONTROLLER.zone_bypass_toggle(zone.number) result = json.dumps(show_zone(zone)) return flask.Response(result, mimetype='application/json') @app.route('/users/') def get_user(user): args = flask.request.args master_pin = flask.request.headers.get('Master-Pin') if not master_pin: return 'Master PIN required', 403 if user not in CONTROLLER.users: if 'retry' not in args: CONTROLLER.get_user_info(master_pin, user) return '', 202 else: return 'Not Found', 404 user = CONTROLLER.users[user] result = json.dumps(show_user(user)) return flask.Response(result, mimetype='application/json') @app.route('/users/', methods=['PUT']) def put_user(user): if user == 1: return 'I refuse to let you break your master user', 403 master_pin = flask.request.headers.get('Master-Pin') if not master_pin: return 'Master PIN required', 403 if user not in CONTROLLER.users: CONTROLLER.get_user_info(master_pin, user) return '', 204 user = CONTROLLER.users[user] if 'master' in ''.join(user.authority_flags).lower(): return 'I refuse to let you break a master user', 403 userdata = flask.request.json changed = [] if 'pin' in userdata: pin = userdata['pin'] changed.append('pin') if pin is None: user.pin = [15] * 6 elif len(pin) == 4: user.pin = [int(i) for i in pin] + [15, 15] elif len(pin) == 6: user.pin = [int(i) for i in pin] else: return 'Invalid PIN format', 400 if changed: CONTROLLER.set_user_info(master_pin, user, changed) return flask.Response(json.dumps(show_user(user)), mimetype='application/json') @app.route('/events') def get_events(): index = int(flask.request.args.get('index', 0)) timeout = int(flask.request.args.get('timeout', 10)) events = CONTROLLER.event_queue.get(index, timeout=timeout) if events: index = events[-1].number events = [event.payload for event in events] return flask.Response(json.dumps({'events': events, 'index': index}), mimetype='application/json') @app.route('/version') def get_version(): return flask.Response(json.dumps( {'version': '1.2', 'last_active': int(CONTROLLER.last_active)}), mimetype='application/json') kk7ds-pynx584-d1dc263/nx584/client.py000066400000000000000000000067121464031722600171330ustar00rootroot00000000000000import json import requests import time class Client(object): def __init__(self, url): self._url = url self._session = requests.Session() self._last_event_index = 0 def list_zones(self): r = self._session.get(self._url + '/zones') try: return r.json['zones'] except TypeError: return r.json()['zones'] def list_partitions(self): r = self._session.get(self._url + '/partitions') try: return r.json['partitions'] except TypeError: return r.json()['partitions'] def arm(self, armtype='auto', partition=1): if armtype not in ['stay', 'exit', 'auto']: raise Exception('Invalid arm type') r = self._session.get( self._url + '/command', params={'cmd': 'arm', 'type': armtype, 'partition': partition}) return r.status_code == 200 def disarm(self, master_pin, partition=1): r = self._session.get( self._url + '/command', params={'cmd': 'disarm', 'master_pin': master_pin, 'partition': partition}) return r.status_code == 200 def set_bypass(self, zone, bypass): data = {'bypassed': bypass} r = self._session.put(self._url + '/zones/%i' % zone, data=json.dumps(data), headers={'Content-Type': 'application/json'}) return r.status_code == 200 def get_user(self, master_pin, user_number): params = {} while True: r = self._session.get(self._url + '/users/%i' % user_number, params=params, headers={'Master-Pin': master_pin}) if r.status_code == 202: params['retry'] = 'yes' time.sleep(1) continue if r.status_code == 404: time.sleep(1) continue if r.status_code == 200: return r.json() print('Status code %i' % r.status_code) break def put_user(self, master_pin, user): cur_user = self.get_user(master_pin, user['number']) if not cur_user: return None r = self._session.put(self._url + '/users/%i' % user['number'], headers={'Master-Pin': master_pin, 'Content-Type': 'application/json'}, data=json.dumps(user)) if r.status_code == 200: return r.json() def get_events(self, index=None, timeout=None): if index is None: index = self._last_event_index if timeout is None: timeout = 60 r = self._session.get(self._url + '/events', params={'index': index, 'timeout': timeout}) if r.status_code == 200: data = r.json() self._last_event_index = data['index'] return data['events'] def get_version(self): r = self._session.get(self._url + '/version') if r.status_code == 404: return '1.0' else: return r.json()['version'] def get_info(self): r = self._session.get(self._url + '/version') if r.status_code == 404: return '1.0' else: return r.json() kk7ds-pynx584-d1dc263/nx584/controller.py000066400000000000000000000701271464031722600200410ustar00rootroot00000000000000try: import ConfigParser as configparser except ImportError: import configparser import datetime import logging import serial import socket import time import stevedore.extension from nx584 import event_queue from nx584 import mail from nx584 import model LOG = logging.getLogger('controller') def parse_ascii(data): data_bytes = [] for i in range(0, len(data), 2): data_bytes.append(int(data[i:i + 2], 16)) return data_bytes def make_ascii(data): data_chars = [] for b in data: data_chars.append('%02X' % b) return ''.join(data_chars) def make_pin_buffer(digits): pinbuf = [] for i in range(0, 6, 2): try: pinbuf.append((int(digits[i + 1]) << 4) | int(digits[i])) except (IndexError, TypeError): pinbuf.append(0xFF) return pinbuf def fletcher(data, k=16): if k not in (16, 32, 64): raise ValueError("Valid choices of k are 16, 32 and 64") nbytes = k // 16 mod = 2 ** (8 * nbytes) - 1 s = s2 = 0 for t in data: s += t s2 += s cksum = s % mod + (mod + 1) * (s2 % mod) sum1 = cksum & 0xFF sum2 = (cksum & 0xFF00) >> 8 return sum1, sum2 class NXFrame(object): def __init__(self): self.length = 0 self.msgtype = 0 self.checksum = 0 self.data = [] self.ackreq = False @property def ack_required(self): return self.ackreq @staticmethod def decode_line(line_bytes): self = NXFrame() s1, s2 = fletcher(line_bytes[:-2]) if [s1, s2] != line_bytes[-2:]: raise ReadFailure('Checksum mismatch on received frame') self.length = line_bytes[0] msgtypefield = line_bytes[1] self.checksum = (line_bytes[-2] << 8) & line_bytes[-1] self.data = line_bytes[2:-2] self.ackreq = bool(msgtypefield & 0x80) self.msgtype = msgtypefield & 0x7F return self @property def type_name(self): return model.MSG_TYPES[self.msgtype] class ReadTimeout(Exception): pass class ConnectionLost(Exception): pass class ReadFailure(Exception): pass class NXProtocol(object): """Abstract the act of talking to the control panel.""" def __init__(self, stream): self.stream = stream def read(self, n): """Read bytes from the stream. Does the right thing for sockets and serial ports. :raises: ReadTimeout if there is no data :raises: ConnectionLost if something goes wrong """ if hasattr(self.stream, 'read'): r = self.stream.read(n) if r == b'': raise ReadTimeout() return r elif hasattr(self.stream, 'recv'): try: r = self.stream.recv(n) except socket.timeout: raise ReadTimeout() except (socket.error, OSError): raise ConnectionLost() if r == b'': raise ConnectionLost() return r else: raise ConnectionLost('What is this stream?') def write(self, data): """Write bytes to the stream. :raises: ConnectionLost if something goes wrong """ if hasattr(self.stream, 'write'): self.stream.write(data) elif hasattr(self.stream, 'send'): try: self.stream.send(data) except (socket.error, OSError): raise ConnectionLost() else: raise ConnectionLost('What is this stream?') def discard_until(self, byte): """Reads any unexpected data until we encounter an expected byte. :raises: ReadTimeout (via self.read()) if we never get it. """ while True: c = self.read(1) if c == byte: return c LOG.warning('Seeking (discarded %s %02x)' % (c, c[0])) def read_frame(self): """Read a whole frame from the stream. :returns: An array of int values, inclusive of the length and checksum bytes :raises: ConnectionLost if something goes wrong or the stream cannot be parsed """ return [] def write_frame(self, data): """Write a whole frame to the stream. NOTE: This adds the length and checksum bytes automatically. :param: data is an array of integers """ pass class NXASCII(NXProtocol): def read_frame(self): self.discard_until(b'\n') start = time.time() line = '' while not line.endswith('\r'): try: c = self.read(1).decode() except ReadTimeout: LOG.error('Mid-frame read timeout (got %i: %r)' % ( len(line), line)) raise ConnectionLost() line += c if time.time() - start > 60: LOG.error('Timeout reading a line, killing connection') raise ConnectionLost() LOG.debug('Parsing ASCII frame %r' % line.strip()) try: return parse_ascii(line.strip()) except Exception: LOG.exception('Failed to parse raw ASCII line %r' % line.strip()) raise ConnectionLost() def write_frame(self, data): data = [len(data)] + data data += fletcher(data) raw = '\n%s\r' % make_ascii(data) self.write(raw.encode()) class NXBinary(NXProtocol): def read_frame(self): self.discard_until(b'\x7e') length = self.read(1)[0] buffer = [length] start = time.time() bytestuffed = False i = 1 while (i <= length + 2): try: c = self.read(1)[0] except ReadTimeout: LOG.error('Mid-frame read timeout (expected %i got %i)' % ( length, i)) raise ConnectionLost() if c == 0x7e: raise ConnectionLost('Received start byte mid-frame!') # Adjust any byte stuffed bytes - Skip the current byte if so, # then XOR the following byte with 0x20 if c == 0x7d: bytestuffed = True else: if bytestuffed: c = c ^ 0x20 bytestuffed = False buffer.append(c) i += 1 if time.time() - start > 60: LOG.error('Timeout reading a line, killing connection') raise ConnectionLost() return buffer def write_frame(self, data): data = [len(data)] + data data += fletcher(data) # Byte Stuff Any 0x7d, 0x7e bytes bytestuff = [i for i, x in enumerate(data) if x == 0x7d] for i, index in reversed(list(enumerate(bytestuff))): data[index:index+1] = [0x7d, 0x5d] bytestuff = [i for i, x in enumerate(data) if x == 0x7e] for i, index in reversed(list(enumerate(bytestuff))): data[index:index+1] = [0x7d, 0x5e] # add the start character 0x7e data.insert(0, 0x7e) self.write(bytes(data)) class StreamWrapper(object): """Wraps a connection to the control panel. This mostly just manages connecting, reconnecting, and some error handling, transparent to the protocol (ASCII or Binary) being used. """ def __init__(self, portspec, config): self._portspec = portspec self._config = config try: self._use_binary_protocol = self._config.getboolean( 'config', 'use_binary_protocol') except configparser.NoOptionError: self._use_binary_protocol = False self._s = None self.protocol = None self.connect() def connect(self): sleep_time = 0 while True: connected = self._connect() if connected: if self._use_binary_protocol: self.protocol = NXBinary(self._s) else: self.protocol = NXASCII(self._s) LOG.info('Connected') return True sleep_time = min(60, sleep_time + 5) LOG.debug('Waiting %i sec before retry...' % sleep_time) time.sleep(sleep_time) def reconnect(self): self._s.close() time.sleep(10) self.connect() def read_frame_raw(self): """Read a raw frame from the stream. Returns the raw bytes (inclusive of length and checksum) or None if there is no data to read. """ try: return self.protocol.read_frame() except ConnectionLost as e: LOG.warning('Connection terminated: %s' % e) self.reconnect() return None except ReadTimeout: return None except UnicodeDecodeError as e: LOG.error('Failed to decode a line; reconnecting: %s' % e) return None def write_frame_raw(self, data): """Writes a frame to the stream. NOTE: length and checksum values are added automatically. """ try: self.protocol.write_frame(data) except ConnectionLost: LOG.warning('Failed to send frame; reconnecting') self.reconnect() # Try to re-send if we reconnect so we don't lose this event self.protocol.write(data) class SocketWrapper(StreamWrapper): def _connect(self): if self._s: self._s.close() try: self._s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) LOG.debug('Connecting...') self._s.connect(self._portspec) self._s.settimeout(0.5) return True except (socket.error, OSError) as ex: LOG.error('Failed to connect: %s' % ex) self._s = None self.protocol = None return False class SerialWrapper(StreamWrapper): def _connect(self): port, baudrate = self._portspec self._s = serial.Serial(port, baudrate, timeout=0.25) return self._s.isOpen(); class NXController(object): def __init__(self, portspec, configfile): self._portspec = portspec self._configfile = configfile self._queue_waiting = False self._queue_should_wait = False self._queue = [] self.last_active = 0 self.zones = {} self.partitions = {} self.users = {} self.system = model.System() ext_mgr = stevedore.extension.ExtensionManager( 'pynx584', invoke_on_load=True, invoke_args=(self,)) self.extensions = [ext_mgr[name] for name in ext_mgr.names()] LOG.info('Loaded extensions %s' % ext_mgr.names()) self._load_config() self.event_queue = event_queue.EventQueue(100) try: self.zone_name_update = self._config.getboolean('config', 'zone_name_update') except configparser.NoOptionError: self.zone_name_update = True try: self._idle_time_heartbeat_seconds = self._config.getint( 'config', 'idle_time_heartbeat_seconds') except configparser.NoOptionError: self._idle_time_heartbeat_seconds = 120 def connect(self): if '/' in self._portspec[0] or 'COM' in self._portspec[0]: self._ser = SerialWrapper(self._portspec, self._config) else: self._ser = SocketWrapper(self._portspec, self._config) LOG.info('Connected') def _load_config(self): self._config = configparser.ConfigParser() self._config.read(self._configfile) if not self._config.has_section('config'): self._config.add_section('config') if self._config.has_section('zones'): for opt in self._config.options('zones'): number = int(opt) name = self._config.get('zones', opt) zone = self._get_zone(number) zone.name = name def _write_config(self): if not self._config.has_section('zones'): self._config.add_section('zones') for zone in self.zones.values(): if (not self._config.has_option('zones', str(zone.number)) and zone.name != 'Unknown'): self._config.set('zones', str(zone.number), zone.name) try: with open(self._configfile, 'w') as configfile: self._config.write(configfile) except IOError as ex: LOG.error('Unable to write %s: %s' % (self._configfile, ex)) @property def interior_zones(self): return [x for x in self.zones.values() if 'Interior' in x.type_flags] @property def interior_bypassed(self): return all(['Inhibit' in x.condition_flags for x in self.interior_zones]) def process_next(self): data = self._ser.read_frame_raw() if not data: return None self.last_active = time.time() try: frame = NXFrame.decode_line(data) except ReadFailure as e: LOG.error(str(e)) return None return frame def _send(self, data): try: self._ser.write_frame_raw(data) except Exception: LOG.exception('Failed to send frame %r' % data) def send_ack(self): self._send([0x1D]) def send_nack(self): self._send([0x1E]) def get_zone_name(self, number): self._queue.append([0x23, number - 1]) def get_zone_status(self, number): self._queue.append([0x24, number - 1]) def arm_stay(self, partition): self._queue.append([0x3E, 0x00, partition]) def arm_exit(self, partition): self._queue.append([0x3E, 0x02, partition]) def arm_auto(self, partition): self._queue.append([0x3D, 0x05, 0x01, 0x01]) def disarm(self, master_pin, partition): self._queue.append([0x3C] + make_pin_buffer(master_pin) + [0x01, partition]) def zone_bypass_toggle(self, zone): self._queue.append([0x3F, zone - 1]) def get_system_status(self): self._queue.append([0x28]) def get_partition_status(self, partition): self._queue.append([0x26, partition - 1]) def set_time(self): now = datetime.datetime.now() self._queue.append([0x3B, now.year - 2000, now.month, now.day, now.hour, now.minute, ((now.weekday() + 1) % 7) + 1]) def get_user_info(self, master_pin, user_number): if len(master_pin) < 6: master_pin += '00' if len(master_pin) != 6: LOG.error('Master pin %r incorrect length' % master_pin) return False digits = make_pin_buffer(master_pin) self._queue.append([0x32] + digits + [user_number]) LOG.debug('Sending for user info %s' % digits) return True def set_user_info(self, master_pin, user, changed): if user.number < 1: LOG.error('Unable to set PIN for user %i' % user.number) return False if 'pin' in changed: mstr_digits = make_pin_buffer(master_pin) user_digits = make_pin_buffer(user.pin) LOG.info('Setting user %i PIN to `%s`' % ( user.number, ''.join(str(x) for x in user.pin if x < 10))) self._queue.append( [0x34] + mstr_digits + [user.number] + user_digits) return True def _get_zone(self, number): if number not in self.zones: self.zones[number] = model.Zone(number) return self.zones[number] def _get_partition(self, number): if number not in self.partitions: self.partitions[number] = model.Partition(number) return self.partitions[number] def _get_user(self, number): if number not in self.users: self.users[number] = model.User(number) return self.users[number] def process_msg_3(self, frame): # Zone Name number = frame.data[0] + 1 name = ''.join([chr(x) for x in frame.data[1:]]) LOG.info('Zone %i: %s' % (number, repr(name.strip()))) if self.zone_name_update: self._get_zone(number).name = name.strip() LOG.debug('Zone info from %s' % self.zones.keys()) self._write_config() else: LOG.debug('Zone name not updating') def process_msg_4(self, frame): # Zone Status zone = self._get_zone(frame.data[0] + 1) condition = frame.data[5] types = frame.data[2:5] zone.state = bool(condition & 0x01) zone.condition_flags = [] for index, string in enumerate(model.Zone.STATUS_FLAGS): if condition & (1 << index): zone.condition_flags.append(string) zone.type_flags = [] for byte, flags in enumerate(model.Zone.TYPE_FLAGS): for bit, name in enumerate(flags): if types[byte] & (1 << bit): zone.type_flags.append(name) LOG.info('Zone %i (%s) state is %s' % ( zone.number, zone.name, zone.state and 'FAULT' or 'NORMAL')) LOG.debug('Zone %i (%s) %s %s' % (zone.number, zone.name, zone.condition_flags, zone.type_flags)) event = {'type': 'zone_status', 'timestamp': datetime.datetime.now().isoformat(), 'zone': zone.number, 'zone_state': zone.state, 'zone_flags': zone.condition_flags, } self.event_queue.push(event) for ext in self.extensions: ext.obj.zone_status(zone) def _send_flag_notifications(self, flags_section, flags_key, asserted, deasserted, email_fn): changed = asserted | deasserted try: flags = set(self._config.get(flags_section, flags_key).split(',')) except (configparser.NoOptionError, configparser.NoSectionError): flags = set([]) if any([flag in changed for flag in flags]): if deasserted & flags: status = '(restored)' else: status = '' sub = '%s %s' % (list(changed & flags), status) msg = ('Asserted: %s\n' % (', '.join(asserted)) + 'Deasserted: %s\n' % (', '.join(deasserted))) email_fn(sub, msg) def process_msg_6(self, frame): partition = self._get_partition(frame.data[0] + 1) partition.last_user = frame.data[5] types = frame.data[1:5] + frame.data[6:8] was_armed = partition.armed orig_flags = partition.condition_flags partition.condition_flags = [] for byte, flags in enumerate(model.Partition.CONDITION_FLAGS): for bit, name in enumerate(flags): if types[byte] & (1 << bit): partition.condition_flags.append(name) if was_armed != partition.armed: LOG.info('Partition %i %s armed' % ( partition.number, '' if partition.armed else 'not')) LOG.debug('Partition %i %s' % (partition.number, partition.condition_flags)) for ext in self.extensions: ext.obj.partition_status(partition) deasserted = set(orig_flags) - set(partition.condition_flags) asserted = set(partition.condition_flags) - set(orig_flags) changed = asserted | deasserted event = {'type': 'partition', 'timestamp': datetime.datetime.now().isoformat(), 'partition': partition.number, 'partition_flags_asserted': list(asserted), 'partition_flags': partition.condition_flags, 'partition_was_armed': was_armed, 'partition_is_armed': partition.armed, } self.event_queue.push(event) if changed: mail.send_partition_email(self._config, partition, deasserted, asserted) def email_status(sub, msg): mail.send_partition_status_email(self._config, partition, 'status', sub, msg) def email_alarms(sub, msg): mail.send_partition_status_email(self._config, partition, 'alarms', sub, msg) section = 'partition_%i' % partition.number self._send_flag_notifications(section, 'status_flags', asserted, deasserted, email_status) self._send_flag_notifications(section, 'alarm_flags', asserted, deasserted, email_alarms) def process_msg_8(self, frame): errors = model.System.STATUS_FLAGS[1] + model.System.STATUS_FLAGS[2] status = frame.data[1:10] self.system.panel_id = frame.data[0] orig_flags = self.system.status_flags self.system.status_flags = [] for byte, flags in enumerate(model.System.STATUS_FLAGS): for bit, name in enumerate(flags): if status[byte] & (1 << bit): self.system.status_flags.append(name) LOG.debug('System status received (panel id 0x%02x)' % ( self.system.panel_id)) def _log(flag, asserted): if flag not in errors: fn = LOG.info else: if asserted: fn = LOG.error else: fn = LOG.warn if asserted: pfx = '' else: pfx = 'de-' msg = 'System %sasserts %s' % (pfx, flag) fn(msg) deasserted = set(orig_flags) - set(self.system.status_flags) asserted = set(self.system.status_flags) - set(orig_flags) for flag in deasserted: _log(flag, False) for flag in asserted: _log(flag, True) for ext in self.extensions: ext.obj.system_status(self.system) if asserted or deasserted: mail.send_system_email(self._config, deasserted, asserted) for i in range(1, 9): if ('Valid partition %i' % i) in asserted: LOG.debug('Requesting partition status for %i' % i) self.get_partition_status(i) def process_msg_9(self, frame): commands = {0x28: 'on', 0x38: 'off'} house = chr(ord('A') + frame.data[0]) unit = frame.data[1] cmd = commands.get(frame.data[2], frame.data[2]) LOG.info('Device %s%02i command %s' % (house, unit, cmd)) event = {'type': 'device-command', 'timestamp': datetime.datetime.now().isoformat(), 'device': '%s%02i' % (house, unit), 'command': '%s' % cmd} self.event_queue.push(event) for ext in self.extensions: ext.obj.device_command(house, unit, cmd) def process_msg_10(self, frame): event = model.LogEvent() event.number = frame.data[0] event.log_size = frame.data[1] event.event_type = frame.data[2] & 0x7F event.reportable = bool(frame.data[2] & 0x80) event.zone_user_device = frame.data[3] + 1 event.partition_number = frame.data[4] euro_format = self._config.getboolean('config', 'euro_date_format', fallback=False) if euro_format: month = frame.data[6] day = frame.data[5] else: month = frame.data[5] day = frame.data[6] hour = frame.data[7] minute = frame.data[8] now = datetime.datetime.now() if month > now.month: year = now.year - 1 else: year = now.year try: event.timestamp = datetime.datetime( year=year, month=month, day=day, hour=hour, minute=minute) except ValueError: LOG.error('Log event had invalid date, or format needs to be set') return LOG.info('Log event: %s at %s' % (event.event_string, event.timestamp)) _event = {'type': 'log', 'event': event.event_string, 'timestamp': event.timestamp.isoformat(), } self.event_queue.push(_event) for ext in self.extensions: ext.obj.log_event(event) mail.send_log_event_mail(self._config, event) def process_msg_18(self, frame): user = self._get_user(frame.data[0]) user.pin = [] user.authority_flags = [] user.authorized_partitions = [] for byte in frame.data[1:4]: user.pin.append(byte & 0x0F) user.pin.append((byte & 0xF0) >> 4) authbytetype = frame.data[4] & 0x80 authbyte = frame.data[4] & 0x7F flags = model.User.AUTHORITY_FLAGS[1 if authbytetype else 0] for i, flag in enumerate(flags): if authbyte & (1 << i): user.authority_flags.append(flag) for i in range(0, 8): if frame.data[5] & (1 << i): user.authorized_partitions.append(i + 1) LOG.info('Received information about user %i' % user.number) def _run_queue(self): if not self._queue: return msg = self._queue.pop(0) LOG.debug('Sending queued %s' % msg) self._send(msg) def generate_heartbeat_activity(self): self.get_system_status() def controller_loop(self): self.set_time() self.get_system_status() try: max_zone = self._config.getint('config', 'max_zone') except configparser.NoOptionError: max_zone = 8 self._config.set('config', 'max_zone', str(max_zone)) for i in range(1, max_zone + 1): self.get_zone_status(i) if not self._config.has_option('zones', str(i)): self.get_zone_name(i) watchdog = time.time() while self.running: frame = self.process_next() if frame is None: if time.time() - watchdog < self._idle_time_heartbeat_seconds: self._run_queue() else: # After time with no activity - generate # something to make sure we are still alive LOG.info('No activity for a while, heartbeating') self.generate_heartbeat_activity() watchdog = time.time() continue watchdog = time.time() LOG.debug('Received: %i %s (data %s)' % (frame.msgtype, frame.type_name, frame.data)) if frame.ack_required: LOG.debug('Sending ACK') self.send_ack() else: pass # This is sometimes too fast if we get two responses # from a single command (like time set). Need to keep # track of waiting for replies and re-send things when # we don't hear back. # self._run_queue() name = 'process_msg_%i' % frame.msgtype if hasattr(self, name): try: getattr(self, name)(frame) except Exception as e: LOG.exception('Failed to process message type %i', frame.msgtype) else: LOG.debug('Unsupported frame type %i (0x%02x)' % ( frame.msgtype, frame.msgtype)) def controller_loop_safe(self): self.running = True while self.running: try: self.connect() self.controller_loop() except Exception as e: LOG.exception('Controller loop exited: %s' % e) LOG.warning('Waiting 10s before reconnecting...') time.sleep(10) kk7ds-pynx584-d1dc263/nx584/event_queue.py000066400000000000000000000025151464031722600201770ustar00rootroot00000000000000import threading class Event(object): def __init__(self, number, payload): self.number = number self.payload = payload def __repr__(self): return 'Event<%i>' % self.number class EventQueue(object): def __init__(self, length, start=0): self._queue = [] self._queue_lock = threading.Lock() self._length = length self._index = start self._condition = threading.Condition() self._min = start self._max = start def push(self, thing): self._condition.acquire() self._max += 1 self._queue.append(Event(self._max, thing)) self._queue = self._queue[0 - self._length:] self._min = self._queue[0].number self._condition.notify_all() self._condition.release() @property def current(self): return self._max def get(self, index, timeout=None): self._condition.acquire() data_available = lambda: index < self._min or self._max > index if not data_available(): self._condition.wait(timeout) the_index = index - self._min + 1 if the_index < 0: the_index = 0 if data_available(): result = self._queue[the_index:] else: result = None self._condition.release() return result kk7ds-pynx584-d1dc263/nx584/mail.py000066400000000000000000000101331464031722600165670ustar00rootroot00000000000000try: import ConfigParser as configparser except ImportError: import configparser import email import email.mime import email.mime.text import email.utils import smtplib class MissingEmailConfig(Exception): pass def _send_system_email(config, subject, recips, body): try: fromaddr = config.get('email', 'fromaddr') smtphost = config.get('email', 'smtphost') except (configparser.NoOptionError, configparser.NoSectionError): raise MissingEmailConfig() msg = email.mime.text.MIMEText(body) msg['Subject'] = subject msg['From'] = fromaddr msg['Date'] = email.utils.formatdate() msg['Message-Id'] = email.utils.make_msgid('nx584') for addr in recips: msg['To'] = addr smtp = smtplib.SMTP(smtphost) smtp.sendmail(fromaddr, recips, msg.as_string()) smtp.quit() def send_system_email(config, deasserted, asserted): try: emails = config.get('email', 'system').split(',') except (configparser.NoOptionError, configparser.NoSectionError): return if not emails: return body = ('Security System alert.\n' + '\n' + 'The following new flags have been asserted:\n' + ('%s\n' % ','.join(asserted)) + '\n' + 'The following flags are now de-asserted:\n' + ('%s\n' % ','.join(deasserted))) try: _send_system_email(config, 'Security System Alert', emails, body) except MissingEmailConfig: pass def send_partition_email(config, partition, deasserted, asserted): try: emails = config.get('partition_%i' % partition.number, 'flags').split(',') except (configparser.NoOptionError, configparser.NoSectionError): return try: ignore = set(config.get('partition_%i' % partition.number, 'ignore_flags').split(',')) except configparser.NoOptionError: ignore = set([]) deasserted = deasserted - ignore asserted = asserted - ignore if not asserted and not deasserted: return if not emails: return body = ('Security System partition %i alert.\n' % partition.number + '\n' + 'The following new flags have been asserted:\n' + ('%s\n' % ','.join(asserted)) + '\n' + 'The following flags are now de-asserted:\n' + ('%s\n' % ','.join(deasserted))) try: _send_system_email( config, 'Security System Partition %i Alert' % partition.number, emails, body) except MissingEmailConfig: pass def send_partition_status_email(config, partition, recip_key, sub, message): try: emails = config.get('partition_%i' % partition.number, recip_key).split(',') except (configparser.NoOptionError, configparser.NoSectionError): return if not emails: return body = 'Security System alert:\n%s' % message try: _send_system_email( config, 'Security: %s' % sub, emails, body) except MissingEmailConfig: pass def send_log_event_mail(config, event): try: alarm_emails = set(config.get('email', 'alarms').split(',')) except (configparser.NoOptionError, configparser.NoSectionError): alarm_emails = set([]) try: alarm_events = set(config.get('email', 'alarm_events').split(',')) except (configparser.NoOptionError, configparser.NoSectionError): alarm_events = set(['Alarm', 'Alarm restore', 'Manual fire',]) try: event_emails = set(config.get('email', 'events').split(',')) except (configparser.NoOptionError, configparser.NoSectionError): event_emails = set([]) emails = set(event_emails) if event.event in alarm_events: emails |= alarm_emails if not emails: return body = '%s at %s' % (event.event_string, event.timestamp) _send_system_email( config, 'Security: %s' % event.event, emails, body) kk7ds-pynx584-d1dc263/nx584/main.py000066400000000000000000000064151464031722600166010ustar00rootroot00000000000000import argparse import logging import logging.handlers import os import threading from nx584 import api from nx584 import controller LOG_FORMAT = '%(asctime)-15s %(module)s %(levelname)s %(message)s' def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', default='config.ini', metavar='FILE', help='Path to config file') parser.add_argument('--debug', default=False, action='store_true', help='Enable debug') parser.add_argument('--debug-log', default=None, help='Debug to this log file only') parser.add_argument('--log', default=None, metavar='FILE', help='Path to log file') parser.add_argument('--connect', default=None, metavar='HOST:PORT', help='Host and port to connect for serial stream') parser.add_argument('--serial', default=None, metavar='PORT', help='Serial port to open for stream') parser.add_argument('--baudrate', default=38400, type=int, metavar='BAUD', help='Serial baudrate') parser.add_argument('--listen', default='127.0.0.1', metavar='ADDR', help='Listen address (defaults to 127.0.0.1)') parser.add_argument('--port', default=5007, type=int, help='Listen port (defaults to 5007)') args = parser.parse_args() LOG = logging.getLogger() LOG.setLevel(logging.DEBUG) formatter = logging.Formatter(LOG_FORMAT) istty = os.isatty(0) if (args.debug or args.debug_log) and not istty: debug_handler = logging.handlers.RotatingFileHandler( args.debug_log or 'debug.log', maxBytes=1024*1024*10, backupCount=3) debug_handler.setFormatter(formatter) debug_handler.setLevel(logging.DEBUG) LOG.addHandler(debug_handler) if istty or not args.log: verbose_handler = logging.StreamHandler() verbose_handler.setFormatter(formatter) verbose_handler.setLevel( (args.debug and not args.debug_log) and logging.DEBUG or logging.INFO) LOG.addHandler(verbose_handler) if args.log: log_handler = logging.handlers.RotatingFileHandler( args.log, maxBytes=1024*1024*10, backupCount=3) log_handler.setFormatter(formatter) log_handler.setLevel(logging.INFO) LOG.addHandler(log_handler) LOG.info('Ready') logging.getLogger('connectionpool').setLevel(logging.WARNING) if args.connect: host, port = args.connect.split(':') ctrl = controller.NXController((host, int(port)), args.config) elif args.serial: ctrl = controller.NXController((args.serial, args.baudrate), args.config) else: LOG.error('Either host:port or serial and baudrate are required') return api.CONTROLLER = ctrl t = threading.Thread(target=ctrl.controller_loop_safe) t.daemon = True t.start() api.app.run(debug=False, host=args.listen, port=args.port, threaded=True) kk7ds-pynx584-d1dc263/nx584/model.py000066400000000000000000000237751464031722600167650ustar00rootroot00000000000000MSG_TYPES = [ 'UNUSED', 'Interface Configuration', 'Reserved', 'Zone Name', 'Zone Status', 'Zones Snapshot', 'Partition Status', 'Partitions Snapshot', 'System Status', 'X-10 Message Received', 'Log Event', 'Keypad Message Received', 'Reserved', 'Reserved', 'Reserved', 'Reserved', 'Program Data Reply', 'Reserved', 'User Information Reply', 'Reserved', 'Reserved', 'Reserved', 'Reserved', 'Reserved', 'Reserved', 'Reserved', 'Reserved', 'Reserved', 'Command Failed', 'Positive Acknowledge', 'Negative Acknowledge', 'Message Rejected', # 0x20 'Reserved', 'Interface Configuration Request', 'Reserved', 'Zone Name Request', 'Zone Status Request', 'Zones Snapshot Request', 'Partition Status Request', 'Partitions Snapshot Request', 'System Status Request', 'Send X-10 Message', 'Log Event Request', 'Send Keypad Text Message', 'Keypad Terminal Mode REquest', 'Reserved', 'Reserved', 'Reserved', 'Program Data Request', 'Program Data Command', 'User Information Request with PIN', 'User Information Request without PIN', 'Set User Code Command with PIN', 'Set User Code Command without PIN', 'Set User Authorization Command with PIN', 'Set User Authorization Command without PIN', 'Reserved', 'Reserved', 'Store Communication Event Command', 'Set Clock / Calendar Command', 'Primary Keypad Function with PIN', 'Primary Keypad Function without PIN', 'Secondary Keypad Function', 'Zone Bypass Toggle', ] class Zone(object): STATUS_FLAGS = [ 'Faulted', 'Trouble', 'Bypass', 'Inhibit', 'Low battery', 'Loss of supervision', 'Reserved',] TYPE_FLAGS = [ ['Fire', '24 hour', 'Key-switch', 'Follower', 'Entry / exit delay 1', 'Entry / exit delay 2', 'Interior', 'Local only'], ['Keypad sounder', 'Yelping Siren', 'Steady Siren', 'Chime', 'Bypassable', 'Group bypassable', 'Force armable', 'Entry guard'], ['Fast loop response', 'Double EOL tamper', 'Trouble', 'Cross zone', 'Dialer delay', 'Swinger shutdown', 'Restorable', 'Listen in'], ] def __init__(self, number): self.number = number self.name = 'Unknown' self.state = None self.condition_flags = [] self.type_flags = [] @property def bypassed(self): return ('Inhibit' in self.condition_flags or 'Bypass' in self.condition_flags) class Partition(object): CONDITION_FLAGS = [ ['Bypass code required', 'Fire trouble', 'Fire', 'Pulsing buzzer', 'TLM fault memory', 'reserved', 'Armed', 'Instant'], ['Previous alarm', 'Siren on', 'Steady siren on', 'Alarm memory', 'Tamper', 'Cancel command entered', 'Code entered', 'Cancel pending'], ['Reserved', 'Silent exit enabled', 'Entryguard (stay mode)', 'Chime mode on', 'Entry', 'Delay expiration warning', 'Exit 1', 'Exit 2'], ['LED extinguish', 'Cross timing', 'Recent closing being timed', 'Reserved', 'Exit error triggered', 'Auto home inhibited', 'Sensor low battery', 'Sensor lost supervision'], ['Zone bypassed', 'Force arm triggered by auto arm', 'Ready to arm', 'Ready to force arm', 'Valid PIN accepted', 'Chime on (sounding)', 'Error beep (triple beep)', 'Tone on (activation tone)'], ['Entry 1', 'Open period', 'Alarm sent using phone number 1', 'Alarm sent using phone number 2', 'Alarm sent using phone number 3', 'Cancel report is in the stack', 'Keyswitch armed', 'Delay trip in progress (common zone)'], ] def __init__(self, number): self.number = number self.condition_flags = [] self.last_user = None @property def armed(self): return 'Armed' in self.condition_flags class System(object): STATUS_FLAGS = [ ['Line seizure', 'Off hook', 'Initial handshake received', 'Download in progress', 'Dialer delay in progress', 'Using backup phone', 'Listen in active', 'Two way lockout'], ['Ground fault', 'Phone fault', 'Fail to communicate', 'Fuse fault', 'Box tamper', 'Siren tamper/trouble', 'Low battery', 'AC fail'], ['Expander box tamper', 'Expander AC failure', 'Expander low battery', 'Expander loss of supervision', 'Expander auxiliary output over current', 'Auxiliary communication channel failure', 'Expander bell fault', 'Reserved'], ['6 digit PIN enabled', 'Programming token in use', 'PIN required for local download', 'Global pulsing buzzer', 'Global Siren on', 'Global steady siren', 'Bus device has line seized', 'Bus device has requested sniff mode'], ['Dynamic battery test', 'AC power on', 'Low battery memory', 'Ground fault memory', 'Fire alarm verification being timed', 'Smoke power reset', '50 Hz line power detected', 'Timing a high voltage battery charge'], ['Communication since last autotest', 'Power up delay in progress', 'Walk test mode', 'Loss of system time', 'Enroll requested', 'Test fixture mode', 'Control shutdown mode', 'Timing a cancel window'], ['reserved', 'reserved', 'reserved', 'reserved', 'reserved', 'reserved', 'reserved', 'Call back in progress'], ['Phone line faulted', 'Voltage present interrupt active', 'House phone off hook', 'Phone line monitor enabled', 'Sniffing', 'Last read was off hook', 'Listen in requested', 'Listen in trigger'], ['Valid partition 1', 'Valid partition 2', 'Valid partition 3', 'Valid partition 4', 'Valid partition 5', 'Valid partition 6', 'Valid partition 7', 'Valid partition 8'], ] def __init__(self): self.panel_id = 0 self.status_flags = [] class LogEvent(object): ZONE_EVENT_CODES = { 0: 'Alarm', 1: 'Alarm restore', 2: 'Bypass', 3: 'Bypass restore', 4: 'Tamper', 5: 'Tamper restore', 6: 'Trouble', 7: 'Trouble restore', 8: 'TX low battery', 9: 'TX low battery restore', 10: 'Zone lost', 11: 'Zone lost restore', 12: 'Start of cross time', } NONE_EVENT_CODES = { 17: 'Special expansion event', 18: 'Duress', 19: 'Manual fire', 20: 'Auxiliary 2 panic', 22: 'Panic', 23: 'Keypad tamper', 34: 'Telephone fault', 35: 'Telephone fault restore', 38: 'Fail to communicate', 39: 'Log full', 44: 'Auto-test', 45: 'Start program', 46: 'End program', 47: 'Start download', 48: 'End download', 50: 'Ground fault', 51: 'Ground fault restore', 52: 'Manual test', 54: 'Start of listen in', 55: 'Technician on site', 56: 'Technician left', 57: 'Control power up', 119: 'Time set', 123: 'Begin walk-test', 124: 'End walk-test', 125: 'Re-exit', 127: 'Data lost', } DEVICE_EVENT_CODES = { 24: 'Control box tamper', 25: 'Control box tamper restore', 26: 'AC fail', 27: 'AC fail restore', 28: 'Low battery', 29: 'Low battery restore', 30: 'Over current', 31: 'Over current restore', 32: 'Siren tamper', 33: 'Siren tamper restore', 36: 'Expander trouble', 37: 'Expander trouble restore', } USER_EVENT_CODES = { 40: 'Opening', 41: 'Closing', 42: 'Exit error', 43: 'Recent closing', 49: 'Cancel', 53: 'Closed with zones bypassed', 120: 'First to open', 121: 'Last to close', 122: 'PIN entered with bit 7 set', 126: 'Output trip', } def __init__(self): self.number = 0 self.log_size = 0 self.event_type = 119 self.reportable = None self.zone_user_device = 0 self.partition_number = 0 self.timestamp = None @property def event(self): for codes in (self.ZONE_EVENT_CODES, self.USER_EVENT_CODES, self.DEVICE_EVENT_CODES, self.NONE_EVENT_CODES): if self.event_type in codes: return codes[self.event_type] return 'Unknown event %i' % self.event_type @property def event_string(self): if self.event_type in self.ZONE_EVENT_CODES: return 'Zone %i %s' % (self.zone_user_device, self.event) if self.event_type in self.USER_EVENT_CODES: return 'User %i %s' % (self.zone_user_device, self.event) if self.event_type in self.DEVICE_EVENT_CODES: return 'Device %i %s' % (self.zone_user_device, self.event) if self.event_type in self.NONE_EVENT_CODES: return self.event return 'Unknown event %i for target %i' % (self.event_type, self.zone_user_device) class User(object): AUTHORITY_FLAGS = ( ['Reserved', 'Arm only', 'Arm only (during close window)', 'Master / Program', 'Arm / Disarm', 'Bypass enable', 'Open / close report enable'], ['Output 1 enable', 'Output 2 enable', 'Output 3 enable', 'Output 4 enable', 'Arm / disarm', 'Bypass enable', 'Open / close report enable'], ) def __init__(self, number): self.number = number self.pin = [] self.authority_flags = [] self.authorized_partitions = [] class NX584Extension(object): def __init__(self, controller): self._controller = controller def zone_status(self, zone): pass def partition_status(self, partition): pass def device_command(self, house, unit, command): pass def system_status(self, system): pass def log_event(self, event): pass kk7ds-pynx584-d1dc263/nx584_client000077500000000000000000000125271464031722600165700ustar00rootroot00000000000000#!/usr/bin/env python import argparse import pprint import prettytable import time import sys from nx584 import client def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('command') parser.add_argument('--zone', default=None, type=int, help='Zone number for zone-related commands') parser.add_argument('--partition', default=None, type=int, help='Partition number for partition-related commands') parser.add_argument('--user', default=None, type=int, help='User number for user-related commands') parser.add_argument('--master', default=None, help='Master PIN for commands that require it') parser.add_argument('--pin', default=None, help='User PIN to set (or `x` to disable)') parser.add_argument('--host', default='localhost:5007', help='Host and port (localhost:5007)') args = parser.parse_args() return args def do_list(clnt, args): for zone in clnt.list_zones(): pprint.pprint(zone) def do_list_partitions(clnt, args): for part in clnt.list_partitions(): pprint.pprint(part) def do_arm(clnt, args): if args.command == 'arm-stay': mode = 'stay' elif args.command == 'arm-exit': mode = 'exit' else: mode = 'auto' clnt.arm(mode, int(args.partition or 1)) def do_disarm(clnt, args): if not args.master: print('Master pin required') return clnt.disarm(args.master, args.partition) def do_summary(clnt, args): t = prettytable.PrettyTable(['Zone', 'Name', 'Bypass', 'Status']) for zone in clnt.list_zones(): t.add_row(['%i' % zone['number'], zone['name'], zone['bypassed'] and 'bypass' or '-', '%s' % (zone['state'] or False)]) print(t) for i, part in enumerate(clnt.list_partitions()): status = 'Partition %i %s' % (part['number'], part['armed'] and 'armed' or 'disarmed') if part['armed'] or i == 0: print(status) def do_bypass(clnt, args): if args.command == 'bypass': clnt.set_bypass(args.zone, True) elif args.command == 'unbypass': clnt.set_bypass(args.zone, False) def do_show(clnt, args): if args.zone: for zone in clnt.list_zones(): if zone['number'] == args.zone: pprint.pprint(zone) return print('No such zone `%s\'' % args.zone) elif args.partition: for part in clnt.list_partitions(): if part['number'] == args.partition: pprint.pprint(part) return print('No such partition `%s\'' % args.partition) else: print('Zone or Partition required') def do_get_user(clnt, args): if not (args.user and args.master): print('User number and master pin required') return user = clnt.get_user(args.master, args.user) if user: pprint.pprint(user) else: print('Unable to fetch user information') def do_user_summary(clnt, args): t = prettytable.PrettyTable(['User', 'PIN', 'Master']) if not (args.user and args.master): print('User number (max) and master pin required') return for i in range(0, args.user): user = clnt.get_user(args.master, i + 1) t.add_row([user['number'], user['pin'], 'Master / Program' in user['authority_flags']]) print(t) def do_set_user_pin(clnt, args): if not (args.user and args.master and args.pin): print('User number and master pin and user pin required') return user = { 'number': args.user, 'pin': None if args.pin.lower() == 'x' else args.pin, } user = clnt.put_user(args.master, user) if user: pprint.pprint(user) else: print('Unable to set user information') def do_events(clnt, args): while True: events = clnt.get_events() if events: for event in events: print(event) def do_version(clnt, args): print(clnt.get_version()) def do_alive(clnt, args): info = clnt.get_info() dead = time.time() - info['last_active'] > 300 print(dead and 'Dead' or 'Alive') return dead def main(): args = parse_args() url = 'http://%s:%s' % tuple(args.host.split(':', 1)) clnt = client.Client(url) if args.command == 'list': do_list(clnt, args) elif args.command in ['arm', 'arm-stay', 'arm-exit', 'arm-auto']: do_arm(clnt, args) elif args.command == 'disarm': do_disarm(clnt, args) elif args.command == 'partitions': do_list_partitions(clnt, args) elif args.command == 'summary': do_summary(clnt, args) elif args.command in ['bypass', 'unbypass']: do_bypass(clnt, args) elif args.command == 'show': do_show(clnt, args) elif args.command == 'getuser': do_get_user(clnt, args) elif args.command == 'setuserpin': do_set_user_pin(clnt, args) elif args.command == 'users': do_user_summary(clnt, args) elif args.command == 'events': do_events(clnt, args) elif args.command == 'version': do_version(clnt, args) elif args.command == 'alive': return do_alive(clnt, args) if __name__ == '__main__': sys.exit(main()) kk7ds-pynx584-d1dc263/nx584_server000077500000000000000000000000671464031722600166140ustar00rootroot00000000000000#!/usr/bin/python from nx584 import main main.main() kk7ds-pynx584-d1dc263/setup.py000066400000000000000000000010221464031722600161140ustar00rootroot00000000000000from setuptools import setup setup(name='pynx584', version='0.8.2', description='NX584/NX8E Interface Library and Server', author='Dan Smith', author_email='dsmith+nx584@danplanet.com', url='http://github.com/kk7ds/pynx584', packages=['nx584'], install_requires=['requests', 'stevedore', 'prettytable', 'pyserial', 'flask'], scripts=['nx584_server', 'nx584_client'], classifiers = [ "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", ] ) kk7ds-pynx584-d1dc263/tests/000077500000000000000000000000001464031722600155515ustar00rootroot00000000000000kk7ds-pynx584-d1dc263/tests/__init__.py000066400000000000000000000000001464031722600176500ustar00rootroot00000000000000kk7ds-pynx584-d1dc263/tests/test_controller.py000066400000000000000000000133631464031722600213530ustar00rootroot00000000000000import io import logging import unittest import mock import tempfile from nx584 import controller TESTFRAME = [1, 0x7e, 2, 0x7d, 3] logging.basicConfig(level=logging.DEBUG) class TestProtocols(unittest.TestCase): def test_write_ascii(self): stream = io.BytesIO() proto = controller.NXASCII(stream) # Write a test frame proto.write_frame(TESTFRAME) # Make sure that the stream got the actual bytes expected length = len(TESTFRAME) s1, s2 = controller.fletcher([length] + TESTFRAME) self.assertEqual(b'\n%02x017E027D03%02x%02x\r' % (length, s1, s2), stream.getvalue()) # Reset the stream and read it back stream.seek(0) data = proto.read_frame() # Make sure we got the right length, data, and checksum self.assertEqual(data, [length] + TESTFRAME + [s1, s2]) def test_write_binary(self): stream = io.BytesIO() proto = controller.NXBinary(stream) # Write a test frame proto.write_frame(TESTFRAME) # Make sure that the stream got the actual bytes expected length = len(TESTFRAME) s1, s2 = controller.fletcher([length] + TESTFRAME) self.assertEqual(b'\x7e' + bytes([length]) + b'\x01\x7d\x5e\x02\x7d\x5d\x03' + bytes([s1, s2]), stream.getvalue()) # Reset the stream and read it back stream.seek(0) data = proto.read_frame() # Make sure we got the right length, data, and checksum self.assertEqual(data, [length] + TESTFRAME + [s1, s2]) class SplitIO(io.BytesIO): def __init__(self, r, w): self.r = r self.w = w def read(self, n): return self.r.read(n) def write(self, b): return self.w.write(b) def get_wrapper(config): rio = io.BytesIO() wio = io.BytesIO() class FakeWrapper(controller.StreamWrapper): def _connect(self): self._s = SplitIO(rio, wio) return True return rio, wio, FakeWrapper('fakeport', config) class TestController(unittest.TestCase): def setUp(self): with mock.patch('stevedore.extension.ExtensionManager'): with tempfile.NamedTemporaryFile() as f: self.ctrl = controller.NXController('fakeport', f.name) def _run_until_idle(self): def stop(): self.ctrl.running = False self.ctrl.running = True self.ctrl._idle_time_heartbeat_seconds = 0.1 self.ctrl._config.set('config', 'max_zone', '2') with mock.patch.object(self.ctrl, 'generate_heartbeat_activity', side_effect=stop): self.ctrl.controller_loop() def _test_startup(self, binary): fake_config = mock.MagicMock() fake_config.getboolean.return_value = binary rio, wio, self.ctrl._ser = get_wrapper(fake_config) self._run_until_idle() expected = [ '0128292A', # system status '022400264E', # zone 1 status '022300254C', # zone 1 name '022401274F', # zone 2 status '022301264D', # zone 2 name ] return expected, wio def test_startup_ascii(self): expected, wio = self._test_startup(False) messages = wio.getvalue().split(b'\r') # First message is the time/date, which will vary. Make sure # it looks sane self.assertTrue(messages[0].startswith(b'\n073B')) # Check the rest of the messages to make sure they look like # we expect self.assertEqual([b'\n%s' % m.encode() for m in expected], messages[1:-1]) def test_startup_binary(self): expected, wio = self._test_startup(True) # Use the NXBinary proto adapter to read the stream so we can # compare to the same list of expected messages. wio.seek(0) proto = controller.NXBinary(wio) messages = [] while True: try: frame = proto.read_frame() messages.append(controller.make_ascii(frame)) except controller.ReadTimeout: break # First message is the time/date, which will vary. Make sure # it looks sane self.assertTrue(messages[0].startswith('073B')) # Check the rest of the messages to make sure they look like # we expect self.assertEqual(expected, messages[1:]) def _test_receive(self, binary): fake_config = mock.MagicMock() fake_config.getboolean.return_value = binary rio, wio, self.ctrl._ser = get_wrapper(fake_config) messages = [ # Partitions status [0x87, 0x47, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], # Partitions snapshot [0x86, 0x00, 0x68, 0x00, 0xE0, 0x40, 0x62, 0x04, 0x82, 0x02, 0x07], # Partitions status [0x87, 0x47, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], ] if binary: proto = controller.NXBinary(rio) else: proto = controller.NXASCII(rio) for message in messages: proto.write_frame(message) rio.seek(0) self.ctrl.process_msg_7 = None with mock.patch.object(self.ctrl, 'process_msg_7') as pm: with mock.patch.object(self.ctrl, 'send_ack') as sa: self._run_until_idle() self.assertEqual(2, pm.call_count) sa.assert_has_calls([mock.call(), mock.call()]) return rio.getvalue() def test_receive_ascii(self): buf = self._test_receive(False) print('Test buffer is %r' % buf) def test_receive_binary(self): buf = self._test_receive(True) print('Test buffer is %r' % list(buf)) kk7ds-pynx584-d1dc263/tests/test_event_queue.py000066400000000000000000000036141464031722600215130ustar00rootroot00000000000000import unittest import mock from nx584 import event_queue class TestEventQueue(unittest.TestCase): def test_push(self): eq = event_queue.EventQueue(10) eq.push('a') eq.push('b') self.assertEqual(['a', 'b'], [x.payload for x in eq.get(0)]) c = eq.current eq.push('c') self.assertEqual(['c'], [x.payload for x in eq.get(c)]) def test_trim(self): eq = event_queue.EventQueue(5) for i in range(1, 11): eq.push(i) self.assertEqual(10, eq.current) self.assertEqual([6, 7, 8, 9, 10], [x.payload for x in eq._queue]) self.assertEqual([6, 7, 8, 9, 10], [x.payload for x in eq.get(0)]) self.assertEqual([6, 7, 8, 9, 10], [x.payload for x in eq.get(3)]) self.assertEqual([8, 9, 10], [x.payload for x in eq.get(7)]) def test_get(self): eq = event_queue.EventQueue(10) eq.push(1) cur = eq.current with mock.patch.object(eq, '_condition') as mock_c: eq.get(cur) mock_c.wait.assert_called_once_with(None) with mock.patch.object(eq, '_condition') as mock_c: eq.get(0) self.assertFalse(mock_c.wait.called) def test_get_empty(self): eq = event_queue.EventQueue(10) c = eq.current with mock.patch.object(eq, '_condition') as mock_c: self.assertEqual(None, eq.get(c)) mock_c.wait.assert_called_once_with(None) eq.push(1) with mock.patch.object(eq, '_condition') as mock_c: self.assertEqual(1, eq.get(c)[0].payload) self.assertFalse(mock_c.called) c = eq.current with mock.patch.object(eq, '_condition') as mock_c: self.assertEqual(None, eq.get(c)) mock_c.wait.assert_called_once_with(None)