pax_global_header00006660000000000000000000000064145726113030014514gustar00rootroot0000000000000052 comment=3d1db717ed7d8a6cfba4dc6636527f3dcb98c852 pemmican-1.0.3/000077500000000000000000000000001457261130300133065ustar00rootroot00000000000000pemmican-1.0.3/.github/000077500000000000000000000000001457261130300146465ustar00rootroot00000000000000pemmican-1.0.3/.github/workflows/000077500000000000000000000000001457261130300167035ustar00rootroot00000000000000pemmican-1.0.3/.github/workflows/test.yml000066400000000000000000000022471457261130300204120ustar00rootroot00000000000000name: pemmican-test-suite on: push: branches: - main pull_request: branches: - main jobs: test: strategy: fail-fast: false matrix: include: - os: ubuntu-20.04 python: "3.9" experimental: false - os: ubuntu-22.04 python: "3.10" experimental: false - os: ubuntu-22.04 python: "3.11" experimental: false - os: ubuntu-22.04 python: "3.12" experimental: false runs-on: ${{ matrix.os }} continue-on-error: ${{ matrix.experimental }} steps: - name: Install Python ${{ matrix.python }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python }} - name: Checkout pemmican uses: actions/checkout@v4 - name: Install dependencies run: | sudo sed -i -e '/^deb / {p; s/^deb/deb-src/}' /etc/apt/sources.list sudo apt update sudo apt install -y libglib2.0-dev libdbus-1-dev sudo apt build-dep -y python3-gi make develop - name: Run tests run: | make test pemmican-1.0.3/.gitignore000066400000000000000000000003731457261130300153010ustar00rootroot00000000000000# Python stuff *.py[cdo] # Vim stuff *.vim *.swp # Translations *.mo # Miscellaneous tags # Packages *.egg *.egg-info *.pyc *.whl dist build man # Unit test / coverage reports coverage .cache .coverage .coverage.py* .tox .pytest_cache .env .eggs pemmican-1.0.3/.readthedocs.yaml000066400000000000000000000005151457261130300165360ustar00rootroot00000000000000version: 2 formats: all python: install: - method: pip path: . extra_requirements: - doc - gui build: os: ubuntu-22.04 tools: python: "3.12" apt_packages: - libcairo2-dev - libffi-dev - libgirepository1.0-dev - libglib2.0-dev - libdbus-1-dev - python3-cairo-dev pemmican-1.0.3/LICENSE.txt000066400000000000000000001045571457261130300151450ustar00rootroot00000000000000SPDX-License-Identifier: GPL-3.0 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 . pemmican-1.0.3/Makefile000066400000000000000000000110001457261130300147360ustar00rootroot00000000000000# vim: set noet sw=4 ts=4 fileencoding=utf-8: # External utilities PYTHON=python3 PIP=pip PYTEST=pytest TWINE=twine PYFLAGS= MSGINIT=msginit MSGMERGE=msgmerge MSGFMT=msgfmt XGETTEXT=xgettext DEST_DIR=/ # Find the location of the GObject introspection libs and cairo (required for # the develop target) GI:=$(wildcard /usr/lib/python3/dist-packages/gi) GOBJECT:= GLIB:= # Calculate the base names of the distribution, the location of all source, # documentation, packaging, icon, and executable script files NAME:=$(shell $(PYTHON) $(PYFLAGS) setup.py --name) WHEEL_NAME:=$(subst -,_,$(NAME)) VER:=$(shell $(PYTHON) $(PYFLAGS) setup.py --version) PY_SOURCES:=$(shell \ $(PYTHON) $(PYFLAGS) setup.py egg_info >/dev/null 2>&1 && \ cat $(WHEEL_NAME).egg-info/SOURCES.txt | grep -v "\.egg-info" | grep -v "\.mo$$") DOC_SOURCES:=docs/conf.py \ $(wildcard docs/*.png) \ $(wildcard docs/*.svg) \ $(wildcard docs/*.dot) \ $(wildcard docs/*.mscgen) \ $(wildcard docs/*.gpi) \ $(wildcard docs/*.rst) \ $(wildcard docs/*.pdf) SUBDIRS:= # Calculate the name of all outputs DIST_WHEEL=dist/$(WHEEL_NAME)-$(VER)-py3-none-any.whl DIST_TAR=dist/$(NAME)-$(VER).tar.gz DIST_ZIP=dist/$(NAME)-$(VER).zip POT_FILE=po/$(NAME).pot PO_FILES:=$(wildcard po/*.po) MO_FILES:=$(patsubst po/%.po,po/mo/%/LC_MESSAGES/$(NAME).mo,$(PO_FILES)) MAN_PAGES=\ man/pemmican-cli.1 \ man/pemmican-mon.1 \ man/pemmican-reset.1 # Default target all: @echo "make install - Install on local system" @echo "make develop - Install symlinks for development" @echo "make pot - Update translation template and sources" @echo "make mo - Generate translation files" @echo "make test - Run tests" @echo "make doc - Generate HTML and PDF documentation" @echo "make source - Create source package" @echo "make wheel - Generate a PyPI wheel package" @echo "make zip - Generate a source zip package" @echo "make tar - Generate a source tar package" @echo "make dist - Generate all packages" @echo "make clean - Get rid of all generated files" @echo "make release - Create and tag a new release" @echo "make upload - Upload the new release to repositories" install: $(SUBDIRS) $(PYTHON) $(PYFLAGS) setup.py install --root $(DEST_DIR) doc: $(DOC_SOURCES) $(MAKE) -C docs clean $(MAKE) -C docs html $(MAKE) -C docs epub $(MAKE) -C docs latexpdf $(MAKE) $(MAN_PAGES) preview: $(MAKE) -C docs preview source: $(DIST_TAR) $(DIST_ZIP) wheel: $(DIST_WHEEL) zip: $(DIST_ZIP) tar: $(DIST_TAR) dist: $(DIST_WHEEL) $(DIST_TAR) $(DIST_ZIP) pot: $(POT_FILE) $(PO_FILES) mo: $(MO_FILES) develop: @# These have to be done separately to avoid a cockup... $(PIP) install -U setuptools $(PIP) install -U pip $(PIP) install -U twine $(PIP) install -U tox $(PIP) install -e .[gui,doc,test] @# If we're in a venv, link the system's GObject Introspection (gi) into it ifeq ($(VIRTUAL_ENV),) @echo "Virtualenv not detected! You may need to link gi manually" else ifeq ($(GI),) @echo "ERROR: gi not found. Install the python{,3}-gi packages" else ln -sf $(GI) $(VIRTUAL_ENV)/lib/python*/site-packages/ endif ifneq ($(GLIB),) ln -sf $(GLIB) $(VIRTUAL_ENV)/lib/python*/site-packages/ endif ifneq ($(GOBJECT),) ln -sf $(GOBJECT) $(VIRTUAL_ENV)/lib/python*/site-packages/ endif endif test: $(PYTEST) clean: rm -fr dist/ build/ man/ .pytest_cache/ .mypy_cache/ $(WHEEL_NAME).egg-info/ tags .coverage for dir in $(SUBDIRS); do \ $(MAKE) -C $$dir clean; \ done find $(CURDIR) -name "*.pyc" -delete find $(CURDIR) -name "__pycache__" -delete tags: $(PY_SOURCES) ctags -R --exclude="build/*" --exclude="docs/*" --languages="Python" lint: $(PY_SOURCES) pylint $(WHEEL_NAME) $(SUBDIRS): $(MAKE) -C $@ $(MAN_PAGES): $(DOC_SOURCES) $(MAKE) -C docs man mkdir -p man/ cp build/man/*.[0-9] man/ $(POT_FILE): $(PY_SOURCES) $(XGETTEXT) -o $@ $(filter %.py,$^) $(filter %.ui,$^) po/%.po: $(POT_FILE) $(MSGMERGE) -U $@ $< po/mo/%/LC_MESSAGES/$(NAME).mo: po/%.po mkdir -p $(dir $@) $(MSGFMT) $< -o $@ $(DIST_TAR): $(PY_SOURCES) $(SUBDIRS) $(PYTHON) $(PYFLAGS) setup.py sdist --formats gztar $(DIST_ZIP): $(PY_SOURCES) $(SUBDIRS) $(PYTHON) $(PYFLAGS) setup.py sdist --formats zip $(DIST_WHEEL): $(PY_SOURCES) $(SUBDIRS) $(PYTHON) $(PYFLAGS) setup.py bdist_wheel release: $(MAKE) clean test -z "$(shell git status --porcelain)" git tag -s v$(VER) -m "Release $(VER)" git push origin v$(VER) upload: $(DIST_TAR) $(DIST_WHEEL) $(TWINE) check $(DIST_TAR) $(DIST_WHEEL) $(TWINE) upload $(DIST_TAR) $(DIST_WHEEL) .PHONY: all install develop test doc source wheel zip tar dist clean tags release upload $(SUBDIRS) pemmican-1.0.3/README.rst000066400000000000000000000033661457261130300150050ustar00rootroot00000000000000======== Pemmican ======== Pemmican is a small utility which warns users of power supply issues on the Raspberry Pi 5 platform. It provides a command line utility, intended for use from the `update-motd`_ facility for non-graphical platforms, and two GLib-based applications for use on graphical platforms, which expect to talk to a DBus service implementing the freedesktop `notifications specification`_: * ``pemmican-cli`` -- the command line utility * ``pemmican-reset`` -- the one-shot notification service which warns of brownout reset issues, and failure to negotiate a 5A feed * ``pemmican-mon`` -- the persistent notification service which warns of active undervolt or USB overcurrent events Usage ===== End users should never need to run these directly; distro packaging should integrate these applications into the platform as appropriate (an MOTD plugin for the command line application, and systemd user services activated by ``graphical-session.target`` for the graphical applications). What's in a Name? ================= This project started life as PMICmon (for `Power Management IC`_ monitor), but I kept mis-pronouncing it as as `pemmican`_! Useful Links ============ * `Source code`_ on GitHub * `Issues`_ on GitHub * `Documentation`_ on ReadTheDocs .. _update-motd: https://manpages.ubuntu.com/manpages/noble/en/man5/update-motd.5.html .. _notifications specification: https://specifications.freedesktop.org/notification-spec/latest/ .. _Power Management IC: https://en.wikipedia.org/wiki/Power_management_integrated_circuit .. _pemmican: https://en.wikipedia.org/wiki/Pemmican .. _Source code: https://github.com/waveform80/pemmican .. _Issues: https://github.com/waveform80/pemmican/issues .. _Documentation: https://pemmican.readthedocs.io/ pemmican-1.0.3/docs/000077500000000000000000000000001457261130300142365ustar00rootroot00000000000000pemmican-1.0.3/docs/Makefile000066400000000000000000000126451457261130300157060ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = ../build PY_SOURCES := $(wildcard ../pemmican/*.py) DOT_DIAGRAMS := $(wildcard images/*.dot images/*/*.dot) MSC_DIAGRAMS := $(wildcard images/*.mscgen images/*/*.mscgen) GPI_DIAGRAMS := $(wildcard images/*.gpi images/*/*.gpi) SVG_IMAGES := $(wildcard images/*.svg images/*/*.svg) $(DOT_DIAGRAMS:%.dot=%.svg) $(MSC_DIAGRAMS:%.mscgen=%.svg) PNG_IMAGES := $(wildcard images/*.png images/*/*.png) $(GPI_DIAGRAMS:%.gpi=%.png) $(SVG_IMAGES:%.svg=%.png) PDF_IMAGES := $(SVG_IMAGES:%.svg=%.pdf) $(GPI_DIAGRAMS:%.gpi=%.pdf) $(DOT_DIAGRAMS:%.dot=%.pdf) $(MSC_DIAGRAMS:%.mscgen=%.pdf) INKSCAPE_VER := $(shell inkscape --version | sed -ne '/^Inkscape/ s/^Inkscape \([0-9]\+\)\..*$$/\1/p') # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " preview to start a web-server that watches for file changes" @echo " and re-builds the docs when required" @echo " json to make JSON files" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SVG_IMAGES) $(PNG_IMAGES) $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(PDF_IMAGES) $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(PDF_IMAGES) $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." preview: ../scripts/previewer $(BUILDDIR)/html %.svg: %.mscgen mscgen -T svg -o $@ $< %.svg: %.dot dot -T svg -o $@ $< %.png: %.gpi gnuplot -e "set term pngcairo transparent size 400,400" $< > $@ ifeq ($(INKSCAPE_VER),0) %.png: %.svg inkscape --export-dpi 150 -e $@ $< %.pdf: %.svg inkscape -A $@ $< else %.png: %.svg inkscape --export-dpi 150 --export-type png -o $@ $< %.pdf: %.svg inkscape --export-type pdf -o $@ $< endif %.pdf: %.gpi gnuplot -e "set term pdfcairo size 5cm,5cm" $< > $@ %.pdf: %.mscgen mscgen -T eps -o - $< | ps2pdf -dEPSCrop - $@ .PHONY: help clean html preview json epub latex latexpdf text man changes linkcheck doctest gettext pemmican-1.0.3/docs/api.rst000066400000000000000000000007231457261130300155430ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 === API === Pemmican has a very basic API, which is probably not much use outside of the scripts provided with the package. Nonetheless, it is documented in the following modules: Modules ======= .. toctree:: :maxdepth: 1 api_power api_gui api_cli pemmican-1.0.3/docs/api_cli.rst000066400000000000000000000004401457261130300163660ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 ============ pemmican.cli ============ .. module:: pemmican.cli .. autofunction:: main pemmican-1.0.3/docs/api_gui.rst000066400000000000000000000005701457261130300164070ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 ================ pemmican.gui ================ .. module:: pemmican.gui .. autoclass:: NotifierApplication .. autoclass:: ResetApplication .. autoclass:: MonitorApplication pemmican-1.0.3/docs/api_power.rst000066400000000000000000000005271457261130300167610ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 =============== pemmican.power =============== .. module:: pemmican.power .. autofunction:: reset_brownout .. autofunction:: psu_max_current pemmican-1.0.3/docs/changelog.rst000066400000000000000000000013401457261130300167150ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 ================== Changelog ================== .. currentmodule:: pemmican Release 1.0.3 (2024-03-08) ========================== * Moved translation stuff into the standard locations Release 1.0.2 (2024-02-23) ========================== * Re-license under GPL3 only (not later), according to policy Release 1.0.1 (2024-02-20) ========================== * Mostly documentation changes (PyPI installation, development installation, and minor corrections) Release 1.0 (2024-02-19) ======================== * Initial release pemmican-1.0.3/docs/conf.py000066400000000000000000000067211457261130300155430ustar00rootroot00000000000000#!/usr/bin/env python3 # vim: set fileencoding=utf-8: # # pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 # pemmican: Notify users of Raspberry Pi PMIC (power management IC) issues import sys import os import configparser from pathlib import Path from datetime import datetime from setuptools.config import read_configuration on_rtd = os.environ.get('READTHEDOCS', '').lower() == 'true' config = configparser.ConfigParser() config.read([Path(__file__).parent / '..' / 'setup.cfg']) info = config['metadata'] # -- Project information ----------------------------------------------------- project = info['name'] author = info['author'] now = datetime.now() copyright = ( f'2023-{now:%Y} {author}' if now.year > 2023 else f'2023 {author}') release = info['version'] version = release # -- General configuration ------------------------------------------------ needs_sphinx = '4.0' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.imgmath', ] if on_rtd: tags.add('rtd') root_doc = 'index' templates_path = ['_templates'] exclude_patterns = ['_build'] highlight_language = 'python3' pygments_style = 'sphinx' # -- Autodoc configuration ------------------------------------------------ autodoc_member_order = 'groupwise' autodoc_default_options = { 'members': True, } autodoc_mock_imports = [] # -- Intersphinx configuration -------------------------------------------- intersphinx_mapping = { 'python': ('https://docs.python.org/3.12', None), } # -- Options for HTML output ---------------------------------------------- html_theme = 'sphinx_rtd_theme' html_title = f'{project} {version} Documentation' html_static_path = ['_static'] manpages_url = 'https://manpages.ubuntu.com/manpages/noble/en/man{section}/{page}.{section}.html' # -- Options for LaTeX output --------------------------------------------- latex_engine = 'xelatex' latex_elements = { 'papersize': 'a4paper', 'pointsize': '10pt', 'preamble': r'\def\thempfootnote{\arabic{mpfootnote}}', # workaround sphinx issue #2530 } latex_documents = [ ( 'index', # source start file project + '.tex', # target filename html_title, # title author, # author 'manual', # documentclass True, # documents ref'd from toctree only ), ] latex_show_pagerefs = True latex_show_urls = 'footnote' # -- Options for epub output ---------------------------------------------- epub_basename = project epub_author = author epub_identifier = f'https://{info["name"]}.readthedocs.io/' epub_show_urls = 'no' # -- Options for manual page output --------------------------------------- man_pages = [ ( 'pemmican-cli', 'pemmican-cli', 'pemmican-cli - Check boot-time PMIC issues', info['author'], 1, ), ( 'pemmican-reset', 'pemmican-reset', 'pemmican-reset - Check boot-time PMIC issues', info['author'], 1, ), ( 'pemmican-mon', 'pemmican-mon', 'pemmican-mon - Monitor PMIC notifications at runtime', info['author'], 1, ), ] man_show_urls = True # -- Options for linkcheck builder ---------------------------------------- linkcheck_retries = 3 linkcheck_workers = 20 linkcheck_anchors = True pemmican-1.0.3/docs/development.rst000066400000000000000000000102671457261130300173200ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 =========== Development =========== .. currentmodule:: pemmican The main GitHub repository for the project can be found at: https://github.com/waveform80/pemmican .. _dev_install: Development installation ======================== If you wish to develop pemmican, obtain the source by cloning the GitHub repository and then use the "develop" target of the Makefile which will install the package as a link to the cloned repository allowing in-place development. The following example demonstrates this method within a virtual Python environment: .. code-block:: console $ sudo apt install build-essential git virtualenvwrapper $ sudo apt build-dep python3-gi $ sudo apt build-dep python3-dbus $ sudo apt build-dep python3-pyudev After installing ``virtualenvwrapper`` you'll need to restart your shell before commands like :command:`mkvirtualenv` will operate correctly. Once you've restarted your shell, continue: .. code-block:: console $ cd $ mkvirtualenv pemmican $ workon pemmican (pemmican) $ git clone https://github.com/waveform80/pemmican.git (pemmican) $ cd pemmican (pemmican) $ make develop To pull the latest changes from git into your clone and update your installation: .. code-block:: console $ workon pemmican (pemmican) $ cd ~/pemmican (pemmican) $ git pull (pemmican) $ make develop To remove your installation, destroy the sandbox and the clone: .. code-block:: console (pemmican) $ deactivate $ rmvirtualenv pemmican $ rm -rf ~/pemmican Building the docs ================= If you wish to build the docs, you'll need a few more dependencies. Inkscape is used for conversion of SVGs to other formats, Graphviz is used for rendering certain charts, and TeX Live is required for building PDF output. The following command should install all required dependencies: .. code-block:: console $ sudo apt install texlive-latex-recommended texlive-latex-extra \ texlive-fonts-recommended texlive-xetex graphviz inkscape \ python3-sphinx python3-sphinx-rtd-theme latexmk xindy Once these are installed, you can use the "doc" target to build the documentation in all supported formats (HTML, ePub, and PDF): .. code-block:: console $ workon pemmican (pemmican) $ cd ~/pemmican (pemmican) $ make doc However, the easiest way to develop the documentation is with the "preview" target which will build the HTML version of the docs, and start a web-server to preview the output. The web-server will then watch for source changes (in both the documentation source, and the application's source) and rebuild the HTML automatically as required: .. code-block:: console $ workon pemmican (pemmican) $ cd ~/pemmican (pemmican) $ make preview The HTML output is written to :file:`build/html` while the PDF output goes to :file:`build/latex`. Test suite ========== If you wish to run the pemmican test suite, follow the instructions in :ref:`dev_install` above and then make the "test" target within the sandbox: .. code-block:: console $ workon pemmican (pemmican) $ cd ~/pemmican (pemmican) $ make test The test suite is also setup for usage with the :command:`tox` utility, in which case it will attempt to execute the test suite with all supported versions of Python. If you are developing under Ubuntu you may wish to look into the `Dead Snakes PPA`_ in order to install old/new versions of Python; the tox setup *should* work with the version of tox shipped with Ubuntu Focal, but more features (like parallel test execution) are available with later versions. For example, to execute the test suite under tox: .. code-block:: console $ tox To execute the test suite under all installed interpreter versions in parallel, using as many parallel tasks as there are CPUs, then displaying a combined report of coverage from all environments: .. code-block:: console $ tox -p auto $ coverage combine $ coverage report .. _Dead Snakes PPA: https://launchpad.net/~deadsnakes/%2Barchive/ubuntu/ppa pemmican-1.0.3/docs/index.rst000066400000000000000000000007241457261130300161020ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 .. include:: ../README.rst Contents ======== .. toctree:: :maxdepth: 1 install pemmican-cli pemmican-reset pemmican-mon api development changelog license Indices and tables ================== * :ref:`modindex` * :ref:`genindex` pemmican-1.0.3/docs/install.rst000066400000000000000000000051341457261130300164410ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 =============== Installation =============== Pemmican should be installed by default on all Ubuntu for Raspberry Pi images from the 24.04 release ("Noble Numbat") onwards. However, should you wish to install it manually for whatever reason, there are two primary packages which provide different configurations of the application: * ``pemmican-server`` installs the MOTD ("Message of the Day") plugins only, which check for brownout and power supply negotiation states. As the name suggests, this is intended for usage on server installations which lack any kind of desktop notification service. * ``pemmican-desktop`` installs two globally enabled user services which attempt to communicate with an implementation of the freedesktop notification service. One service warns about brownout and power supply negotiation issues (the same as the MOTD service), the other is runtime monitor for overcurrent and undervolt issues. These both rely on the ``pemmican-common`` package (which is the actual code for both implementations). From PyPI =========== You may also choose to install Pemmican from PyPI: .. code-block:: console $ pip install "pemmican[gui]" The ``[gui]`` option should be included only if you want to include the dependencies for the graphical :program:`pemmican-reset` and :program:`pemmican-mon` applications. Please note that, in this case, you will need to add service definitions to launch the applications yourself. For the graphical applications, the following two service definitions are recommended: .. literalinclude:: ../systemd/pemmican-reset.service :language: ini :caption: /usr/lib/systemd/user/pemmican-reset.service .. literalinclude:: ../systemd/pemmican-monitor.service :language: ini :caption: /usr/lib/systemd/user/pemmican-monitor.service As these are user services, they will either need to be enabled on a per-user basis, or globally like so: .. code-block:: console $ sudo systemctl --global enable pemmican-reset.service $ sudo systemctl --global enable pemmican-monitor.service For the console application (:program:`pemmican-cli`) the following :manpage:`update-motd(5)` script is recommended: .. code-block:: bash :caption: /etc/update-motd.d/90-pemmican #!/bin/sh if [ -x /usr/bin/pemmican-cli ]; then exec /usr/bin/pemmican-cli elif [ -x /usr/local/bin/pemmican-cli ]; then exec /usr/local/bin/pemmican-cli fi pemmican-1.0.3/docs/license.rst000066400000000000000000000011401457261130300164060ustar00rootroot00000000000000======= License ======= This file is part of pemmican. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. 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 . pemmican-1.0.3/docs/pemmican-cli.rst000066400000000000000000000037121457261130300173310ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 ============= pemmican-cli ============= .. include:: subst.rst Synopsis ======== .. code-block:: text usage: pemmican-cli [-h] [--version] .. program:: pemmican-cli Options ======= .. option:: -h, --help show the help message and exit .. option:: --version show program's version number and exit Usage ===== :program:`pemmican-cli` is intended to be a one-shot operation, typically launched by :manpage:`update-motd(5)`. It first checks whether the last reset occurred due to a brownout (undervolt) condition and, if it was, prints a warning to stdout. If you wish to suppress this warning for your user, touch the file |user/brownout.inhibit|. If you wish to suppress this warning system-wide, touch the file |system/brownout.inhibit|. .. warning:: It is strongly recommended that any such notice is heeded, as brownout is very likely to lead to any manner of other (hard to predict or replicate) issues up to and including data corruption. Put simply, suppressing this warning is probably a very bad idea! If the last reset was normal (or there was no last reset), the script further checks if the power supply negotiated a full 5A feed. If it did not, this also results in a warning printed to stdout. The Pi 5 can be reliably operated without a 5A feed, provided the peripherals attached to it are relatively light in their power draw. Depending on circumstance, you may well wish to suppress this warning which can be done for your individual user by touching the file |user/max_current.inhibit| or system-wide by touching |system/max_current.inhibit|. See Also ======== .. only:: not man :doc:`pemmican-reset`, :doc:`pemmican-mon` .. only:: man :manpage:`pemmican-reset(1)`, :manpage:`pemmican-mon(1)` Bugs ==== |bug-link| pemmican-1.0.3/docs/pemmican-mon.rst000066400000000000000000000055151457261130300173560ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 ============ pemmican-mon ============ .. include:: subst.rst Synopsis ======== .. code-block:: text usage: pemmican-mon [-h] [--help-all] [--help-gapplication] [--gapplication-service] .. program:: pemmican-mon Options ======= .. option:: -h, --help show the help message and exit .. option:: --help-all show all available help options and exit .. option:: --help-gapplication show help options specific to GLib.Application and exit .. option:: --gapplication-service run the application in GApplication service mode (for DBus service files) Usage ===== :program:`pemmican-mon` is intended to be a background service, launched as a user-slice systemd service by the "graphical-session" target. It monitors udev for power supply related events, reporting those of interest via the freedesktop `notification service `_. Power supply undervolt (typically reported in the event the supply drops below 4.8V) is likely the most important event the application warns about. If you wish to suppress this warning for your user, touch the file |user/undervolt.inhibit|. If you wish to suppress this warning system-wide, touch the file |system/undervolt.inhibit|. .. warning:: It is strongly recommended that any such notice is heeded, as brownout is very likely to lead to any manner of other (hard to predict or replicate) issues up to and including data corruption. Put simply, suppressing this warning is probably a very bad idea! USB over-current is the other event the application will warn about. This occurs when peripherals attached to the USB ports attempt to draw more current that permitted. If the Pi 5 is being supplied by a PSU that did not negotiate a 5A feed at boot time, the USB ports will be limited in their supply and this warning is more likely. If you wish to suppress this warning for your individual user, touch the file |user/overcurrent.inhibit|. To suppress this warning system-wide, touch |system/overcurrent.inhibit|. Environment =========== Because the notifications generated by this application are capable of launching a web-browser (via the "More Information" action), the script will also bail with an error in the event that ``DISPLAY`` or ``WAYLAND_DISPLAY`` are not found in the environment at startup. See Also ======== .. only:: not man :doc:`pemmican-cli`, :doc:`pemmican-reset` .. only:: man :manpage:`pemmican-cli(1)`, :manpage:`pemmican-reset(1)` The freedesktop `notifications specification `_. .. _notification service: https://specifications.freedesktop.org/notification-spec/latest/ Bugs ==== |bug-link| pemmican-1.0.3/docs/pemmican-reset.rst000066400000000000000000000055271457261130300177120ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 ============== pemmican-reset ============== .. include:: subst.rst Synopsis ======== .. code-block:: text usage: pemmican-reset [-h] [--help-all] [--help-gapplication] [--gapplication-service] .. program:: pemmican-reset Options ======= .. option:: -h, --help show the help message and exit .. option:: --help-all show all available help options and exit .. option:: --help-gapplication show help options specific to GLib.Application and exit .. option:: --gapplication-service run the application in GApplication service mode (for DBus service files) Usage ===== :program:`pemmican-reset` is intended to be a one-shot operation, launched as a user-slice systemd service by the "graphical-session" target. Its operation is in essence identical to :program:`pemmican-cli`, but rather than printing to stdout, it reports warnings via the freedesktop `notification service `_. It first checks whether the last reset occurred due to a brownout (undervolt) condition and, if it was, sends a critical notification to the notification service. If you wish to suppress this warning for your user, touch the file |user/brownout.inhibit|. If you wish to suppress this warning system-wide, touch the file |system/brownout.inhibit|. .. warning:: It is strongly recommended that any such notice is heeded, as brownout is very likely to lead to any manner of other (hard to predict or replicate) issues up to and including data corruption. Put simply, suppressing this warning is probably a very bad idea! If the last reset was normal (or there was no last reset), the script further checks if the power supply negotiated a full 5A feed. If it did not, this also results in a warning printed to stdout. The Pi 5 can be reliably operated without a 5A feed, provided the peripherals attached to it are relatively light in their power draw. Depending on circumstance, you may well wish to suppress this warning which can be done for your individual user by touching the file |user/max_current.inhibit| or system-wide by touching |system/max_current.inhibit|. Environment =========== Because the notifications generated by this application are capable of launching a web-browser (via the "More Information" action), the script will also bail with an error in the event that ``DISPLAY`` or ``WAYLAND_DISPLAY`` are not found in the environment at startup. See Also ======== .. only:: not man :doc:`pemmican-cli`, :doc:`pemmican-mon` .. only:: man :manpage:`pemmican-cli(1)`, :manpage:`pemmican-mon(1)` The freedesktop `notifications specification `_. Bugs ==== |bug-link| pemmican-1.0.3/docs/subst.rst000066400000000000000000000021141457261130300161260ustar00rootroot00000000000000.. pemmican: notifies users of Raspberry Pi 5 power issues .. .. Copyright (c) 2024 Dave Jones .. Copyright (c) 2024 Canonical Ltd. .. .. SPDX-License-Identifier: GPL-3.0 .. |bug-link| replace:: Please report bugs at: https://github.com/waveform80/pemmican/issues .. _notifications-spec: https://specifications.freedesktop.org/notification-spec/latest/ .. |user/brownout.inhibit| replace:: :file:`~/.config/pemmican/brownout.inhibit` .. |system/brownout.inhibit| replace:: :file:`/etc/xdg/pemmican/brownout.inhibit` .. |user/max_current.inhibit| replace:: :file:`~/.config/pemmican/max_current.inhibit` .. |system/max_current.inhibit| replace:: :file:`/etc/xdg/pemmican/max_current.inhibit` .. |user/undervolt.inhibit| replace:: :file:`~/.config/pemmican/undervolt.inhibit` .. |system/undervolt.inhibit| replace:: :file:`/etc/xdg/pemmican/undervolt.inhibit` .. |user/overcurrent.inhibit| replace:: :file:`~/.config/pemmican/overcurrent.inhibit` .. |system/overcurrent.inhibit| replace:: :file:`/etc/xdg/pemmican/overcurrent.inhibit` pemmican-1.0.3/pemmican/000077500000000000000000000000001457261130300150775ustar00rootroot00000000000000pemmican-1.0.3/pemmican/__init__.py000066400000000000000000000000001457261130300171760ustar00rootroot00000000000000pemmican-1.0.3/pemmican/cli.py000066400000000000000000000054031457261130300162220ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 """ This module contains the "main" entry point for the :program:`pemmican-cli` application. This is a trivial console script, intended to be run from the :manpage:`update-motd(5)` mechanism. All output is written to stdout. """ import os import argparse from pathlib import Path from importlib import metadata from textwrap import fill from . import lang from .power import reset_brownout, psu_max_current from .const import ( XDG_CONFIG_HOME, XDG_CONFIG_DIRS, RPI_PSU_URL, BROWNOUT_INHIBIT, MAX_CURRENT_INHIBIT, ) def main(args=None): """ The entry-point for the :program:`pemmican-cli` application. Takes the command line *args* as its only parameter and returns the exit code of the application. """ lang.init() parser = argparse.ArgumentParser(description=lang._( """ Checks the Raspberry Pi 5's power status and reports if the last reset occurred due to a brownout (undervolt) situation, or if the current power supply failed to negotiate a 5A supply. This script is intended to be run as part of the man:update-motd(5) process. If you wish to suppress the warnings generated by this script, please refer to man:pemmican-cli(1) for more information. """)) parser.add_argument( '--version', action='version', version=metadata.version(__package__)) parser.parse_args(args) try: brownout = reset_brownout() and not any( (p / __package__ / BROWNOUT_INHIBIT).exists() for p in [XDG_CONFIG_HOME] + XDG_CONFIG_DIRS) max_current = (psu_max_current() < 5000) and not any( (p / __package__ / MAX_CURRENT_INHIBIT).exists() for p in [XDG_CONFIG_HOME] + XDG_CONFIG_DIRS) except OSError: # We're probably not on a Pi 5; just exit return 0 # Check for brownout initially. If brownout caused a reset, don't # bother double-warning about an inadequate PSU if brownout: print() print(fill(lang._( 'Reset due to low power; please check your power supply'))) elif max_current: print() print(fill(lang._( 'This power supply is not capable of supplying 5A; power ' 'to peripherals will be restricted'))) if brownout or max_current: print() print(fill(lang._( 'See man:pemmican-cli(1) for information on suppressing ' 'this warning, or {RPI_PSU_URL} for more information on the ' 'Raspberry Pi 5 power supply'.format(RPI_PSU_URL=RPI_PSU_URL) ))) return 0 pemmican-1.0.3/pemmican/const.py000066400000000000000000000012561457261130300166030ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 import os from pathlib import Path XDG_CONFIG_HOME = Path(os.environ.get( 'XDG_CONFIG_HOME', os.path.expanduser('~/.config'))) XDG_CONFIG_DIRS = [ Path(p) for p in os.environ.get( 'XDG_CONFIG_DIRS', f'{XDG_CONFIG_HOME}:/etc/xdg').split(':') ] RPI_PSU_URL = 'https://rptl.io/rpi5-power-supply-info' BROWNOUT_INHIBIT = 'brownout.inhibit' MAX_CURRENT_INHIBIT = 'max_current.inhibit' UNDERVOLT_INHIBIT = 'undervolt.inhibit' OVERCURRENT_INHIBIT = 'overcurrent.inhibit' pemmican-1.0.3/pemmican/gui.py000066400000000000000000000426721457261130300162500ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 """ This module contains the "main" entry points for the :program:`pemmican-reset` and :program:`pemmican-mon` applications, :class:`ResetApplication` and :class:`MonitorApplication`, respectively. Both are derived from an abstract base class, :class:`NotifierApplication` containing the logic common to both. """ import os import sys import html import webbrowser from time import monotonic, sleep from abc import ABC, abstractmethod import gi gi.require_version('Gio', '2.0') gi.require_version('GLib', '2.0') from gi.repository import Gio, GLib from dbus.mainloop.glib import DBusGMainLoop from dbus.exceptions import DBusException from pyudev import Context, Monitor from pyudev.glib import MonitorObserver from . import lang from .power import reset_brownout, psu_max_current from .notify import Notifications from .const import ( XDG_CONFIG_DIRS, XDG_CONFIG_HOME, RPI_PSU_URL, BROWNOUT_INHIBIT, MAX_CURRENT_INHIBIT, UNDERVOLT_INHIBIT, OVERCURRENT_INHIBIT, ) class NotifierApplication(ABC): """ Base class for a GLib GApplication which needs to talk to the freedestkop `notification service`_. An instance of this class can be called as a "main" function, optionally passing in the command line parameters. As a GApplication with an identifier (see :attr:`APP_ID`), only one instance is typically permitted to run. Additional instances will exit before activation, but will signal the original instance to activate instead. The XDG directories, particularly those related to configuration (:envvar:`XDG_CONFIG_HOME` and :envvar:`XDG_CONFIG_DIRS`) are expected in the environment. The application will terminate early with a non-zero exit code if :envvar:`DISPLAY` or :envvar:`WAYLAND_DISPLAY` are missing from the environment. Finally, if the freedesktop notification service does not show up within 1 minute of the application starting, the application will also terminate with a non-zero exit code. This is an abstract class; descendents need to implement the :meth:`run` method. .. attribute:: APP_ID The application's identifier, in the typical form of a reverse domain-name. This should be overridden at the class-level in each descendent. .. _notification service: https://specifications.freedesktop.org/notification-spec/ """ APP_ID = 'com.canonical.pemmican' def __init__(self): super().__init__() self.title = '' self.app = None self.main_loop = None self.notifier = None self._run_start = None def __call__(self, args=None): # Bail if we don't have DISPLAY or WAYLAND_DISPLAY set in the # environment (which are required to launch the browser on "more # information"); the service will retry us later (when hopefully # they've shown up...) if not os.environ.keys() & {'DISPLAY', 'WAYLAND_DISPLAY'}: print('Missing DISPLAY / WAYLAND_DISPLAY', file=sys.stderr, flush=True) return 1 # Integrate dbus-python with GLib; the set_as_default parameter means # we don't have to pass around the NativeMainLoop object this returns # whenever connecting to a bus -- it'll be the default anyway DBusGMainLoop(set_as_default=True) # Yes, it's unconventional to use GApplication instead of # GtkApplication but we've no need of any GUI stuff here; we just want # to talk to DBus notifications (if necessary) and quit self.app = Gio.Application() self.app.set_application_id(self.APP_ID) self.app.connect('activate', self.do_activate) lang.init() self.title = lang._('Raspberry Pi PMIC Monitor') return self.app.run(sys.argv if args is None else args) def do_activate(self, user_data): """ Application activation. This starts the GLib main loop; any set up which should be performed before entering the main loop should be done here. The application's main logic (in the abstract :meth:`run` method) is ultimately executed as a one-shot idle handler from the GLib main loop, configured here. """ self.main_loop = GLib.MainLoop() GLib.idle_add(self._call_run) self._run_start = monotonic() self.main_loop.run() def _call_run(self): """ This method is run as an idle handler from the GLib main loop. If the freedesktop notification service is available, this executes the abstract :meth:`run` method. Otherwise, provided we haven't yet timed out, it schedules a future retry. """ try: self.notifier = Notifications() except DBusException as err: if err.get_dbus_name() in ( 'org.freedesktop.DBus.Error.NameHasNoOwner', 'org.freedesktop.DBus.Error.ServiceUnknown', ): if monotonic() - self._run_start > 60: raise else: sleep(1) return True else: raise self._run_id = None self.run() return False @abstractmethod def run(self): """ This abstract method should be overridden in descendents to provide the main logic of the application. """ raise NotImplementedError() class ResetApplication(NotifierApplication): """ Checks the Raspberry Pi 5's power status and reports, via the freedesktop notification mechanism, if the last reset occurred due to a brownout (undervolt) situation, or if the current power supply failed to negotiate a 5A supply. This script is intended to be run from a systemd user slice as part of the :file:`graphical-session.target`. """ APP_ID = 'com.canonical.pemmican.ResetGui' def __init__(self): super().__init__() self.inhibit = None def run(self): self.notifier.on_closed = self.do_notification_closed self.notifier.on_action = self.do_notification_action self.do_check() def do_notification_closed(self, msg_id, reason): """ Callback executed when the user dismisses a notification by any mechanism (explicit close, timeout, action activation, etc). As a oneshot application, which can only ever show one notification, we just quit if it's closed. """ self.main_loop.quit() def do_notification_action(self, msg_id, action_key): """ Callback executed when the user activates an action on one of our pending notifications. This launches the web-browser for the "More information" action, or touches the appropriate file for the "Don't show again" action. """ if action_key == 'moreinfo': webbrowser.open_new_tab(RPI_PSU_URL) else: # action_key == 'suppress' inhibit_path = XDG_CONFIG_HOME / __package__ / self.inhibit inhibit_path.parent.mkdir(parents=True, exist_ok=True) inhibit_path.touch() def do_check(self): """ This method is the bulk of the :program:`pemmican-reset` application. It runs the checks on the device-tree nodes and, if notifications are required, queries the notification service's capabilities to format the notifications accordingly. """ try: brownout = reset_brownout() and not any( (p / __package__ / BROWNOUT_INHIBIT).exists() for p in [XDG_CONFIG_HOME] + XDG_CONFIG_DIRS) max_current = (psu_max_current() < 5000) and not any( (p / __package__ / MAX_CURRENT_INHIBIT).exists() for p in [XDG_CONFIG_HOME] + XDG_CONFIG_DIRS) except OSError: # We're probably not on a Pi 5; just exit brownout = max_current = False if not brownout and not max_current: self.main_loop.quit() return caps = self.notifier.get_capabilities() escape = html.escape if 'body-markup' in caps else lambda s: s # Customize what we notify based on the notification system's # capabilities; if we have actions, use them, otherwise tack "more # info" URLs onto the notification itself, using hyperlinks if capable if 'actions' in caps: actions = [ ('moreinfo', lang._('More information')), ('suppress', lang._("Don't show again")), ] suffix = '' elif 'body-hyperlinks' in caps: actions = [] suffix = ( f'' + escape(lang._("More information")) + '') else: actions = [] suffix = escape(lang._('See {RPI_PSU_URL} for more information') .format(RPI_PSU_URL=RPI_PSU_URL)) # Check for brownout initially. If brownout caused a reset, don't # bother double-warning about an inadequate PSU if brownout: self.inhibit = BROWNOUT_INHIBIT body=escape(lang._( 'Reset due to low power; please check your power supply')) + ( '. ' + suffix if suffix else '') self.notifier.notify( self.title, body=body, hints={'urgency': 2}, actions=actions) else: # max_current self.inhibit = MAX_CURRENT_INHIBIT body=escape(lang._( 'This power supply is not capable of supplying 5A; power ' 'to peripherals will be restricted')) + ( '. ' + suffix if suffix else '') self.notifier.notify( self.title, body=body, hints={'urgency': 1}, actions=actions) # If nothing is pending (already!), just exit immediately if not self.notifier.pending: self.main_loop.quit() class MonitorApplication(NotifierApplication): """ Monitors the Raspberry Pi 5's power supply for reports of undervolt (deficient power supply), or overcurrent (excessive draw by USB peripherals). Issues are reported via the freedesktop notification mechanism. This script is intended to be run from a systemd user slice as part of the :file:`graphical-session.target`. """ APP_ID = 'com.canonical.pemmican.MonitorGui' def __init__(self): super().__init__() self.overcurrent_monitor = None self.overcurrent_observer = None self.overcurrent_handle = None self.overcurrent_msg_id = 0 self.overcurrent_counts = {} self.undervolt_monitor = None self.undervolt_observer = None self.undervolt_handle = None self.undervolt_msg_id = 0 def run(self): check_undervolt = not any( (p / __package__ / UNDERVOLT_INHIBIT).exists() for p in [XDG_CONFIG_HOME] + XDG_CONFIG_DIRS) check_overcurrent = not any( (p / __package__ / OVERCURRENT_INHIBIT).exists() for p in [XDG_CONFIG_HOME] + XDG_CONFIG_DIRS) if not check_undervolt and not check_overcurrent: self.main_loop.quit() return self.notifier.on_closed = self.do_notification_closed self.notifier.on_action = self.do_notification_action context = Context() if check_overcurrent: self.overcurrent_monitor = Monitor.from_netlink(context) self.overcurrent_monitor.filter_by(subsystem='usb') self.overcurrent_observer = MonitorObserver(self.overcurrent_monitor) self.overcurrent_handle = self.overcurrent_observer.connect( 'device-event', self.do_usb_device) self.overcurrent_monitor.start() if check_undervolt: self.undervolt_monitor = Monitor.from_netlink(context) self.undervolt_monitor.filter_by(subsystem='hwmon') self.undervolt_observer = MonitorObserver(self.undervolt_monitor) self.undervolt_handle = self.undervolt_observer.connect( 'device-event', self.do_hwmon_device) self.undervolt_monitor.start() def do_usb_device(self, observer, device): """ Callback registered for USB device events. This method performs further filtering to determine if this is actually an overcurrent event, and dispatches a notification if it is. """ try: if device.action == 'change': port = device.properties['OVER_CURRENT_PORT'] count = int(device.properties['OVER_CURRENT_COUNT']) else: return except KeyError: return if ( # Only display a notification if there's no active notification # already; this works around an issue in GNOME that replacing a # notification loses its actions self.overcurrent_msg_id == 0 and port and count > self.overcurrent_counts.get(port, 0) ): self.overcurrent_counts[port] = count self.overcurrent_msg_id = self.notify( 'overcurrent', lang._('USB overcurrent; please check your connected USB devices'), replaces_id=self.overcurrent_msg_id) def do_hwmon_device(self, observer, device): """ Callback registered for hardware monitoring events. This performs further filtering to determine if this is actually an undervolt event, and dispatches a notification if it is. """ try: if device.action == 'change': name = device.attributes.asstring('name') alarm = device.attributes.asint('in0_lcrit_alarm') else: return except KeyError: return # See note in method above if self.undervolt_msg_id == 0 and name == 'rpi_volt' and alarm: self.undervolt_msg_id = self.notify( 'undervolt', lang._('Low voltage warning; please check your power supply'), replaces_id=self.undervolt_msg_id) def notify(self, key, msg, *, replaces_id=0): """ This method is called by the monitoring callbacks (:meth:`do_usb_device` and :meth:`do_hwmon_device`) to format and dispatch a notification according to the capabilities of the system's notification mechanism. """ caps = self.notifier.get_capabilities() escape = html.escape if 'body-markup' in caps else lambda s: s # Customize what we notify based on the notification system's # capabilities; if we have actions, use them, otherwise tack "more # info" URLs onto the notification itself, using hyperlinks if capable if 'actions' in caps: actions = [ ('moreinfo', lang._('More information')), (f'suppress_{key}', lang._("Don't show again")), ] suffix = '' elif 'body-hyperlinks' in caps: actions = [] suffix = ( f'' + escape(lang._("More information")) + '') else: actions = [] suffix = escape(lang._('See {RPI_PSU_URL} for more information') .format(RPI_PSU_URL=RPI_PSU_URL)) return self.notifier.notify( self.title, body=escape(msg) + ('. ' + suffix if suffix else ''), hints={'urgency': 2}, actions=actions, replaces_id=replaces_id) def do_notification_closed(self, msg_id, reason): """ Callback executed when the user dismisses a notification by any mechanism (explicit close, timeout, action activation, etc). """ if msg_id == self.undervolt_msg_id: self.undervolt_msg_id = 0 elif msg_id == self.overcurrent_msg_id: self.overcurrent_msg_id = 0 def do_notification_action(self, msg_id, action_key): """ Callback executed when the user activates an action on one of our pending notifications. This launches the web-browser for the "More information" action, or touches the appropriate file for the "Don't show again" action. """ if action_key == 'suppress_undervolt': inhibit = XDG_CONFIG_HOME / __package__ / UNDERVOLT_INHIBIT inhibit.parent.mkdir(parents=True, exist_ok=True) inhibit.touch() self.undervolt_observer.disconnect(self.undervolt_handle) self.undervolt_handle = None self.undervolt_observer = None self.undervolt_monitor = None elif action_key == 'suppress_overcurrent': inhibit = XDG_CONFIG_HOME / __package__ / OVERCURRENT_INHIBIT inhibit.parent.mkdir(parents=True, exist_ok=True) inhibit.touch() self.overcurrent_observer.disconnect(self.overcurrent_handle) self.overcurrent_handle = None self.overcurrent_observer = None self.overcurrent_monitor = None else: # action_key == 'moreinfo' webbrowser.open_new_tab(RPI_PSU_URL) if self.undervolt_monitor is None and self.overcurrent_monitor is None: self.main_loop.quit() reset_main = ResetApplication() monitor_main = MonitorApplication() pemmican-1.0.3/pemmican/lang.py000066400000000000000000000006411457261130300163730ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 import locale import gettext _ = gettext.gettext def init(): try: locale.setlocale(locale.LC_ALL, '') except locale.Error: locale.setlocale(locale.LC_ALL, 'C') gettext.textdomain(__package__) pemmican-1.0.3/pemmican/notify.py000066400000000000000000000130361457261130300167640ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 import dbus class Notifications: """ Wraps the methods of the DBus Notifications freedesktop service. If *bus* is not specified, it defaults to the DBus :class:`~dbus.SessionBus`. As the instance needs to receive signals, the bus must be associated with a "main loop", e.g. :class:`DBusGMainLoop`. """ SERVICE_NAME = 'org.freedesktop.Notifications' OBJECT_PATH = '/org/freedesktop/Notifications' def __init__(self, bus=None): if bus is None: bus = dbus.SessionBus() server = bus.get_object(self.SERVICE_NAME, self.OBJECT_PATH) self._intf = dbus.Interface(server, dbus_interface=self.SERVICE_NAME) self._pending = set() self.on_closed = None self.on_action = None bus.add_signal_receiver( self._notification_closed, 'NotificationClosed', self.SERVICE_NAME) bus.add_signal_receiver( self._action_invoked, 'ActionInvoked', self.SERVICE_NAME) def get_server_info(self): """ Returns a :class:`dict` with keys "name", "vendor", "version", and "spec_version" mapped to the values returned by the service. """ return { key: value for key, value in zip( ('name', 'vendor', 'version', 'spec_version'), self._intf.GetServerInformation() ) } def get_capabilities(self): """ Return a :class:`list` of :class:`str` detailing the capabilities of the notification service. Typical values include "actions", the server will display specified actions to the user, "body", the server supports notification bodies, "body-markup", the server supports limited markup in the notification body, and "persistence", the server supports persistence of notifications. See the `Desktop Notifications Specification`_ for all possible return values. .. _Desktop Notifications Specification: https://specifications.freedesktop.org/notification-spec/latest/ """ return self._intf.GetCapabilities() def notify(self, summary, *, body='', app_name='', app_icon='', replaces_id=0, actions=None, hints=None, timeout=-1): """ Send a notification to the service. The *summary*, a brief :class:`str` summarizing the message, must be included. The *body* is the full message which may optionally contain a limited form of XML markup, if "body-markup" is included in the result of :meth:`get_capabilities`. The optional *app_name* and *app_icon* strings identify the application sending the notification. The *actions* parameter specifies a :class:`list` of ``(id, label)`` tuples where *id* is the action identifier, and *label* is the string to display for the action. This is only supported if "actions" is included in the result of :meth:`get_capabilities`. The *hints* parameter is a :class:`dict` of optional hints passed to the notification service. A common hint is "urgency" which takes the value 0 (low), 1 (normal), or 2 (critical). The *timeout* specifies how long the notification will remain displayed. The default of -1 is system-dependent. 0 indicates a notification never times out. The return value is the ID of the displayed notification. This may be used in future calls with the *replaces_id* parameter to replace prior notifications. """ if actions is None: actions = [] else: actions = [item for (id, label) in actions for item in (id, label)] if hints is None: hints = {} msg_id = self._intf.Notify( app_name, replaces_id, app_icon, summary, body, actions, hints, timeout) if msg_id: self._pending.add(msg_id) return msg_id def remove(self, msg_id): """ Forces the notification identified by *msg_id* (an :class:`int` as returned by :meth:`notify`) to be removed from display. """ self._intf.CloseNotification(msg_id) @property def pending(self): """ Returns the set of pending message identifiers, as returned by :meth:`notify`. """ return frozenset(self._pending) def _action_invoked(self, msg_id, action_id): """ If *msg_id* is a message we sent, call :attr:`on_action` with the identifier, and the *action_id* (one of the ids passed as the *actions* parameter to :meth:`notify`) that was invoked by the user. """ if msg_id in self._pending: if self.on_action is not None: self.on_action(msg_id, action_id) def _notification_closed(self, msg_id, reason): """ If *msg_id* is a message we sent, call :attr:`on_closed` with the identifier and the *reason* for closing. See the `Desktop Notifications Specification`_ for valid reason codes. .. _Desktop Notifications Specification: https://specifications.freedesktop.org/notification-spec/latest/ """ try: self._pending.remove(msg_id) except KeyError: pass else: if self.on_closed is not None: self.on_closed(msg_id, reason) pemmican-1.0.3/pemmican/power.py000066400000000000000000000024241457261130300166070ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 import struct from pathlib import Path DT_POWER = Path('/proc/device-tree/chosen/power') def reset_brownout(): """ Returns :data:`True` if the device-tree reports that a power brownout (undervolt condition) was the cause of the last reset. Raises :exc:`OSError` if the reset condition cannot be queried (e.g. if this is executed on a non-Raspberry Pi). """ # D-T values are big-endian (hence the > prefix) fmt = struct.Struct('>I') with (DT_POWER / 'power_reset').open('rb') as f: value, = fmt.unpack(f.read(fmt.size)) return bool(value & 0x02) def psu_max_current(): """ Returns the maximum current negotiated with the PSU by the power supply in mA. Ideally this should be 5000 (indicating a power supply capable of 5V at 5A), but may be 3000 or lower. Raises :exc:`OSError` if the maximum current could not be queried (e.g. if this is executed on a non-Raspberry Pi). """ fmt = struct.Struct('>I') with (DT_POWER / 'max_current').open('rb') as f: value, = fmt.unpack(f.read(fmt.size)) return value pemmican-1.0.3/po/000077500000000000000000000000001457261130300137245ustar00rootroot00000000000000pemmican-1.0.3/po/en_GB.po000066400000000000000000000043411457261130300152400ustar00rootroot00000000000000# British English translations for pemmican 1.0.2 # Copyright (C) 2024 Canonical Ltd. # This file is distributed under the same license as the pemmican package. # msgid "" msgstr "" "Project-Id-Version: pemmican 1.0.2\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-03-01 20:31+0000\n" "PO-Revision-Date: 2024-03-01 20:40+0000\n" "Last-Translator: Dave Jones \n" "Language-Team: Dave Jones \n" "Language: en_GB\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "X-Generator: Poedit 3.0.1\n" "X-Poedit-SourceCharset: UTF-8\n" #: pemmican/cli.py:40 msgid "" "\n" " Checks the Raspberry Pi 5's power status and reports if the last\n" " reset occurred due to a brownout (undervolt) situation, or if the\n" " current power supply failed to negotiate a 5A supply. This script\n" " is intended to be run as part of the man:update-motd(5) process. " "If\n" " you wish to suppress the warnings generated by this script, please\n" " refer to man:pemmican-cli(1) for more information.\n" " " msgstr "" #: pemmican/cli.py:69 pemmican/gui.py:247 msgid "Reset due to low power; please check your power supply" msgstr "" #: pemmican/cli.py:73 pemmican/gui.py:255 msgid "" "This power supply is not capable of supplying 5A; power to peripherals will " "be restricted" msgstr "" #: pemmican/cli.py:78 #, python-brace-format msgid "" "See man:pemmican-cli(1) for information on suppressing this warning, or " "{RPI_PSU_URL} for more information on the Raspberry Pi 5 power supply" msgstr "" #: pemmican/gui.py:106 msgid "Raspberry Pi PMIC Monitor" msgstr "" #: pemmican/gui.py:228 pemmican/gui.py:236 pemmican/gui.py:379 #: pemmican/gui.py:387 msgid "More information" msgstr "" #: pemmican/gui.py:229 pemmican/gui.py:380 msgid "Don't show again" msgstr "" #: pemmican/gui.py:240 pemmican/gui.py:391 #, python-brace-format msgid "See {RPI_PSU_URL} for more information" msgstr "" #: pemmican/gui.py:341 msgid "USB overcurrent; please check your connected USB devices" msgstr "" #: pemmican/gui.py:362 msgid "Low voltage warning; please check your power supply" msgstr "" pemmican-1.0.3/po/pemmican.pot000066400000000000000000000041661457261130300162500ustar00rootroot00000000000000# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-03-01 20:31+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" #: pemmican/cli.py:40 msgid "" "\n" " Checks the Raspberry Pi 5's power status and reports if the last\n" " reset occurred due to a brownout (undervolt) situation, or if the\n" " current power supply failed to negotiate a 5A supply. This script\n" " is intended to be run as part of the man:update-motd(5) process. If\n" " you wish to suppress the warnings generated by this script, please\n" " refer to man:pemmican-cli(1) for more information.\n" " " msgstr "" #: pemmican/cli.py:69 pemmican/gui.py:247 msgid "Reset due to low power; please check your power supply" msgstr "" #: pemmican/cli.py:73 pemmican/gui.py:255 msgid "" "This power supply is not capable of supplying 5A; power to peripherals will " "be restricted" msgstr "" #: pemmican/cli.py:78 #, python-brace-format msgid "" "See man:pemmican-cli(1) for information on suppressing this warning, or " "{RPI_PSU_URL} for more information on the Raspberry Pi 5 power supply" msgstr "" #: pemmican/gui.py:106 msgid "Raspberry Pi PMIC Monitor" msgstr "" #: pemmican/gui.py:228 pemmican/gui.py:236 pemmican/gui.py:379 #: pemmican/gui.py:387 msgid "More information" msgstr "" #: pemmican/gui.py:229 pemmican/gui.py:380 msgid "Don't show again" msgstr "" #: pemmican/gui.py:240 pemmican/gui.py:391 #, python-brace-format msgid "See {RPI_PSU_URL} for more information" msgstr "" #: pemmican/gui.py:341 msgid "USB overcurrent; please check your connected USB devices" msgstr "" #: pemmican/gui.py:362 msgid "Low voltage warning; please check your power supply" msgstr "" pemmican-1.0.3/scripts/000077500000000000000000000000001457261130300147755ustar00rootroot00000000000000pemmican-1.0.3/scripts/copyrights000077500000000000000000000407421457261130300171250ustar00rootroot00000000000000#!/usr/bin/python3 """ This script updates the copyright headers on all files project-wide. It derives the authorship and copyright years information from the git history of the project; hence, this script must be run within a git clone of the project's repository. Options are available to specify the license text file, the files to edit, and files to exclude. Default options can be specified in the containing project's setup.cfg under [{SETUP_SECTION}] """ from __future__ import annotations import os import re import sys assert sys.version_info >= (3, 6), 'Script requires Python 3.6+' import tempfile import typing as t from argparse import ArgumentParser, Namespace from configparser import ConfigParser from operator import attrgetter from itertools import groupby from datetime import datetime from subprocess import Popen, PIPE, DEVNULL from pathlib import Path from fnmatch import fnmatch PROJECT_ROOT: Path = (Path(__file__).parent / '..').resolve() SETUP_SECTION: str = str(Path(__file__).name) + ':settings' SPDX_PREFIX: str = 'SPDX-License-Identifier:' COPYRIGHT_PREFIX: str = 'Copyright (c)' def main(args: t.Optional[t.List[str]]=None): if args is None: args = sys.argv[1:] config = get_config(args) writer = CopyWriter.from_config(config) for path, copyrights in get_copyrights( config.include, config.exclude, config.additional ): print(f'Re-writing {path}...') copyrights = sorted( copyrights, reverse=True, key=lambda c: (max(c.years), c.author)) with ( AtomicReplaceFile(path, encoding='utf-8') as target, path.open('r') as source ): for chunk in writer.transform(source, copyrights): target.write(chunk) def get_config(args: t.List[str]) -> Namespace: config = ConfigParser( defaults={ 'additional': '', 'include': '**/*', 'exclude': '', 'license': 'LICENSE.txt', 'preamble': '', 'strip_preamble': 'false', 'spdx_prefix': SPDX_PREFIX, 'copy_prefix': COPYRIGHT_PREFIX, }, delimiters=('=',), default_section=SETUP_SECTION, empty_lines_in_values=False, interpolation=None, converters={'list': lambda s: s.strip().splitlines()}) config.read(PROJECT_ROOT / 'setup.cfg') sect = config[SETUP_SECTION] # Resolve license default relative to setup.cfg if sect['license']: sect['license'] = str(PROJECT_ROOT / sect['license']) parser = ArgumentParser(description=__doc__.format(**globals())) parser.add_argument( '-a', '--additional', action='append', metavar='STR', default=sect.getlist('additional'), help="An additional copyright owner to add to all files. This is " "typically used to specify a corporate owner which never appears " "directly in commits, but which ultimately owns a project. If an " "e-mail contact should be included, format the string as " '"name "') parser.add_argument( '-i', '--include', action='append', metavar='GLOB', default=sect.getlist('include'), help="The set of patterns that a file must match to be included in " "the set of files to re-write. Can be specified multiple times to " "add several patterns. Default: %(default)r") parser.add_argument( '-e', '--exclude', action='append', metavar='GLOB', default=sect.getlist('exclude'), help="The set of patterns that a file must *not* match to be included " "in the set of files to re-write. Can be specified multiple times to " "add several patterns. Default: %(default)r") parser.add_argument( '-l', '--license', action='store', type=Path, metavar='PATH', default=sect['license'], help="The file containing the project's license text. If this file " "contains a SPDX-License-Identifier line (in addition to the license " "text itself), then matching license text found in source files will " "be replaced by the SPDX-License-Identifier line (appropriately " "commented). Default: %(default)s") parser.add_argument( '-p', '--preamble', action='append', metavar='STR', default=sect.getlist('preamble'), help="The line(s) of text to insert before the copyright attributions " "in source files. This is typically a brief description of the " "project. Can be specified multiple times to add several lines. " "Default: %(default)r") parser.add_argument( '-S', '--spdx-prefix', action='store', metavar='STR', default=sect['spdx_prefix'], help="The prefix on the line in the license file, and within comments " "of source files that identifies the appropriate license from the " "SPDX list. Default: %(default)r") parser.add_argument( '-C', '--copy-prefix', action='store', metavar='STR', default=sect['copy_prefix'], help="The prefix before copyright attributions in source files. " "Default: %(default)r") parser.add_argument( '--no-strip-preamble', action='store_false', dest='strip_preamble') parser.add_argument( '--strip-preamble', action='store_true', default=sect.getboolean('strip-preamble'), help="If enabled, any existing preamble matching that specified " "by --preamble will be removed. This can be used to change the " "preamble text in files by first specifying the old preamble with " "this option, then running a second time with the new preamble") ns = parser.parse_args(args) ns.include = set(ns.include) ns.exclude = set(ns.exclude) ns.additional = [name_and_email(s) for s in ns.additional] return ns def name_and_email(s: str) -> t.Tuple[str, str]: """ Parse the :class:`str` *s* into a :class:`tuple` of ``(name, email)`` when *s* is formatted as "name ", or ``(name, '')`` otherwise. """ m = re.match(r'^(?P.*) +<(?P.+)>$', s) if m: return m.group('name'), m.group('email') else: return s, '' class Copyright(t.NamedTuple): author: str email: str years: t.Set[int] def __str__(self): if len(self.years) > 1: years = f'{min(self.years)}-{max(self.years)}' else: years = f'{min(self.years)}' if self.email: return f'{years} {self.author} <{self.email}>' else: return f'{years} {self.author}' def get_copyrights(include: t.Set[str], exclude: t.Set[str], additional: t.Set[t.Tuple[str, str]] ) -> t.Iterator[t.Tuple[Path, t.Iterable[Copyright]]]: sorted_blame = sorted( get_contributions(include, exclude), key=lambda c: (c.path, c.author, c.email) ) blame_by_file = { path: list(file_contributions) for path, file_contributions in groupby( sorted_blame, key=attrgetter('path') ) } for path, file_contributors in blame_by_file.items(): it = groupby(file_contributors, key=lambda c: (c.author, c.email)) copyrights = [ Copyright(author, email, {y.year for y in years}) for (author, email), years in it ] years = {year for c in copyrights for year in c.years} copyrights.extend([ Copyright(author, email, years) for author, email in additional ]) yield path, copyrights class Contribution(t.NamedTuple): author: str email: str year: int path: Path def get_contributions(include: t.Set[str], exclude: t.Set[str])\ -> t.Iterator[Contribution]: for path in get_source_paths(include, exclude): blame = Popen( ['git', 'blame', '--line-porcelain', 'HEAD', '--', str(path)], stdout=PIPE, stderr=PIPE, universal_newlines=True ) author = email = year = None if blame.stdout is not None: for line in blame.stdout: if line.startswith('author '): author = line.split(' ', 1)[1].rstrip() elif line.startswith('author-mail '): email = line.split(' ', 1)[1].rstrip() email = email.lstrip('<').rstrip('>') elif line.startswith('author-time '): # Forget the timezone; we only want the year anyway timestamp = int(line.split(' ', 1)[1].strip()) year = datetime.fromtimestamp(timestamp).year elif line.startswith('filename '): assert author is not None assert email is not None assert year is not None yield Contribution( author=author, email=email, year=year, path=path) author = email = year = None blame.wait() assert blame.returncode == 0 def get_source_paths(include: t.Set[str], exclude: t.Set[str])\ -> t.Iterator[Path]: ls_tree = Popen( ['git', 'ls-tree', '-r', '--name-only', 'HEAD'], stdout=PIPE, stderr=DEVNULL, universal_newlines=True) if not include: include = {'*'} if ls_tree.stdout is not None: for filename in ls_tree.stdout: filename = filename.strip() if any(fnmatch(filename, pattern) for pattern in exclude): continue if any(fnmatch(filename, pattern) for pattern in include): yield Path(filename) ls_tree.wait() assert ls_tree.returncode == 0 class License(t.NamedTuple): ident: t.Optional[str] text: t.List[str] def get_license(path: Path, *, spdx_prefix: str = SPDX_PREFIX) -> License: with open(path, 'r') as f: lines = f.read().splitlines() idents = [ line.rstrip() for line in lines if line.startswith(spdx_prefix) ] ident = None if len(idents) > 1: raise RuntimeError(f'More than one {spdx_prefix} line in {path}!') elif len(idents) == 1: ident = idents[0] body = [ line.rstrip() for line in lines if not line.startswith(spdx_prefix) ] while not body[0]: del body[0] while not body[-1]: del body[-1] return License(ident, body) class CopyWriter: """ Transformer for the copyright header in source files. The :meth:`transform` method can be called with a file-like object as the *source* and will yield chunks of replacement data to be written to the replacement. """ # The script's kinda dumb at this point - only handles straight-forward # line-based comments, not multi-line delimited styles like /*..*/ COMMENTS = { '': '#', '.c': '//', '.cpp': '//', '.js': '//', '.py': '#', '.rst': '..', '.sh': '#', '.sql': '--', } def __init__(self, license: Path=Path('LICENSE.txt'), preamble: t.Optional[t.List[str]]=None, spdx_prefix: str=SPDX_PREFIX, copy_prefix: str=COPYRIGHT_PREFIX): if preamble is None: preamble = [] self.license = get_license(license, spdx_prefix=spdx_prefix) self.preamble = preamble self.spdx_prefix = spdx_prefix self.copy_prefix = copy_prefix @classmethod def from_config(cls, config: Namespace) -> CopyWriter: return cls( config.license, config.preamble, config.spdx_prefix, config.copy_prefix) def transform(self, source: t.TextIO, copyrights: t.List[Copyright], *, comment_prefix: t.Optional[str]=None) -> t.Iterator[str]: if comment_prefix is None: comment_prefix = self.COMMENTS[Path(source.name).suffix] license_start = self.license.text[0] license_end = self.license.text[-1] state = 'header' empty = True for linenum, line in enumerate(source, start=1): if state == 'header': if linenum == 1 and line.startswith('#!'): yield line empty = False elif linenum < 3 and ( 'fileencoding=' in line or '-*- coding:' in line): yield line empty = False elif line.rstrip() == comment_prefix: pass # skip blank comment lines elif line.startswith(f'{comment_prefix} {self.spdx_prefix}'): pass # skip existing SPDX ident elif line.startswith(f'{comment_prefix} {self.copy_prefix}'): pass # skip existing copyright lines elif any(line.startswith(f'{comment_prefix} {pre_line}') for pre_line in self.preamble): pass # skip existing preamble elif line.startswith(f'{comment_prefix} {license_start}'): state = 'license' # skip existing license lines else: yield from self._generate_header( copyrights, comment_prefix, empty) state = 'blank' elif state == 'license': if line.startswith(f'{comment_prefix} {license_end}'): yield from self._generate_header( copyrights, comment_prefix, empty) state = 'blank' continue if state == 'blank': # Ensure there's a blank line between license and start of the # source body if line.strip(): yield '\n' yield line state = 'body' elif state == 'body': yield line def _generate_header(self, copyrights: t.Iterable[Copyright], comment_prefix: str, empty: bool) -> t.Iterator[str]: if not empty: yield comment_prefix + '\n' for line in self.preamble: yield f'{comment_prefix} {line}\n' if self.preamble: yield comment_prefix + '\n' for copyright in copyrights: yield f'{comment_prefix} {self.copy_prefix} {copyright!s}\n' yield comment_prefix + '\n' if self.license.ident: yield f'{comment_prefix} {self.license.ident}\n' else: for line in self.license.text: if line: yield f'{comment_prefix} {line}\n' else: yield comment_prefix + '\n' class AtomicReplaceFile: """ A context manager for atomically replacing a target file. Uses :class:`tempfile.NamedTemporaryFile` to construct a temporary file in the same directory as the target file. The associated file-like object is returned as the context manager's variable; you should write the content you wish to this object. When the context manager exits, if no exception has occurred, the temporary file will be renamed over the target file atomically (after copying permissions from the target file). If an exception occurs during the context manager's block, the temporary file will be deleted leaving the original target file unaffected and the exception will be re-raised. :param pathlib.Path path: The full path and filename of the target file. This is expected to be an absolute path. :param str encoding: If ``None`` (the default), the temporary file will be opened in binary mode. Otherwise, this specifies the encoding to use with text mode. """ def __init__(self, path: t.Union[str, Path], encoding: t.Optional[str]=None): if isinstance(path, str): path = Path(path) self._path = path self._tempfile = tempfile.NamedTemporaryFile( mode='wb' if encoding is None else 'w', dir=str(self._path.parent), encoding=encoding, delete=False) self._withfile = None def __enter__(self): self._withfile = self._tempfile.__enter__() return self._withfile def __exit__(self, exc_type, exc_value, exc_tb): os.fchmod(self._withfile.file.fileno(), self._path.stat().st_mode) result = self._tempfile.__exit__(exc_type, exc_value, exc_tb) if exc_type is None: os.rename(self._withfile.name, str(self._path)) else: os.unlink(self._withfile.name) return result if __name__ == '__main__': sys.exit(main()) pemmican-1.0.3/scripts/previewer000077500000000000000000000166441457261130300167460ustar00rootroot00000000000000#!/usr/bin/python3 """ This script builds the HTML documentation of the containing project, and serves it from a trivial built-in web-server. It then watches the project source code for changes, and rebuilds the documentation as necessary. Options are available to specify the build output directory, the build command, and the paths to watch for changes. Default options can be specified in the containing project's setup.cfg under [{SETUP_SECTION}] """ from __future__ import annotations import os import sys assert sys.version_info >= (3, 6), 'Script requires Python 3.6+' import time import shlex import socket import traceback import typing as t import subprocess as sp import multiprocessing as mp from pathlib import Path from functools import partial from configparser import ConfigParser from argparse import ArgumentParser, Namespace from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler PROJECT_ROOT: Path = Path(__file__).parent / '..' SETUP_SECTION: str = str(Path(__file__).name) + ':settings' def main(args: t.Optional[t.List[str]]=None): if args is None: args = sys.argv[1:] config = get_config(args) queue: mp.Queue = mp.Queue() builder_proc = mp.Process(target=builder, args=(config, queue), daemon=True) server_proc = mp.Process(target=server, args=(config, queue), daemon=True) builder_proc.start() server_proc.start() exc, value, tb = queue.get() server_proc.terminate() builder_proc.terminate() traceback.print_exception(exc, value, tb) def get_config(args: t.List[str]) -> Namespace: config = ConfigParser( defaults={ 'command': 'make doc', 'html': 'build/html', 'watch': '', 'ignore': '\n'.join(['*.swp', '*.bak', '*~', '.*']), 'bind': '0.0.0.0', 'port': '8000', }, delimiters=('=',), default_section=SETUP_SECTION, empty_lines_in_values=False, interpolation=None, converters={'list': lambda s: s.strip().splitlines()}) config.read(PROJECT_ROOT / 'setup.cfg') sect = config[SETUP_SECTION] # Resolve html and watch defaults relative to setup.cfg if sect['html']: sect['html'] = str(PROJECT_ROOT / sect['html']) if sect['watch']: sect['watch'] = '\n'.join( str(PROJECT_ROOT / watch) for watch in sect.getlist('watch') ) parser = ArgumentParser(description=__doc__.format(**globals())) parser.add_argument( 'html', default=sect['html'], type=Path, nargs='?', help="The base directory (relative to the project's root) which you " "wish to server over HTTP. Default: %(default)s") parser.add_argument( '-c', '--command', default=sect['command'], help="The command to run (relative to the project root) to regenerate " "the HTML documentation. Default: %(default)s") parser.add_argument( '-w', '--watch', action='append', default=sect.getlist('watch'), help="Can be specified multiple times to append to the list of source " "patterns (relative to the project's root) to watch for changes. " "Default: %(default)s") parser.add_argument( '-i', '--ignore', action='append', default=sect.getlist('ignore'), help="Can be specified multiple times to append to the list of " "patterns to ignore. Default: %(default)s") parser.add_argument( '--bind', metavar='ADDR', default=sect['bind'], help="The address to listen on. Default: %(default)s") parser.add_argument( '--port', metavar='PORT', default=sect['port'], help="The port to listen on. Default: %(default)s") ns = parser.parse_args(args) ns.command = shlex.split(ns.command) if not ns.watch: parser.error('You must specify at least one --watch') ns.watch = [ str(Path(watch).relative_to(Path.cwd())) for watch in ns.watch ] return ns class DevRequestHandler(SimpleHTTPRequestHandler): server_version = 'DocsPreview/1.0' protocol_version = 'HTTP/1.0' class DevServer(ThreadingHTTPServer): allow_reuse_address = True base_path = None def get_best_family(host: t.Optional[str], port: t.Union[str, int, None])\ -> t.Tuple[ socket.AddressFamily, t.Union[t.Tuple[str, int], t.Tuple[str, int, int, int]] ]: infos = socket.getaddrinfo( host, port, type=socket.SOCK_STREAM, flags=socket.AI_PASSIVE) for family, type, proto, canonname, sockaddr in infos: return family, sockaddr raise ValueError(f'No family found for {host}:{port}') def server(config: Namespace, queue: t.Optional[mp.Queue]=None): try: DevServer.address_family, addr = get_best_family(config.bind, config.port) handler = partial(DevRequestHandler, directory=str(config.html)) with DevServer(addr[:2], handler) as httpd: host, port = httpd.socket.getsockname()[:2] hostname = socket.gethostname() print(f'Serving {config.html} HTTP on {host} port {port}') print(f'http://{hostname}:{port}/ ...') # XXX Wait for queue message to indicate time to start? httpd.serve_forever() except: if queue is not None: queue.put(sys.exc_info()) raise def get_stats(config: Namespace) -> t.Dict[Path, os.stat_result]: return { path: path.stat() for watch_pattern in config.watch for path in Path('.').glob(watch_pattern) if not any(path.match(ignore_pattern) for ignore_pattern in config.ignore) } def get_changes(old_stats: t.Dict[Path, os.stat_result], new_stats: t.Dict[Path, os.stat_result])\ -> t.Tuple[t.Set[Path], t.Set[Path], t.Set[Path]]: # Yes, this is crude and could be more efficient but it's fast enough on a # Pi so it'll be fast enough on anything else return ( new_stats.keys() - old_stats.keys(), # new old_stats.keys() - new_stats.keys(), # deleted { # modified filepath for filepath in old_stats.keys() & new_stats.keys() if new_stats[filepath].st_mtime > old_stats[filepath].st_mtime } ) def rebuild(config: Namespace) -> t.Dict[Path, os.stat_result]: print('Rebuilding...') sp.run(config.command, cwd=PROJECT_ROOT) return get_stats(config) def builder(config: Namespace, queue: t.Optional[mp.Queue]=None): try: old_stats = rebuild(config) print('Watching for changes in:') print('\n'.join(config.watch)) # XXX Add some message to the queue to indicate first build done and # webserver can start? And maybe launch webbrowser too? while True: new_stats = get_stats(config) created, deleted, modified = get_changes(old_stats, new_stats) if created or deleted or modified: for filepath in created: print(f'New file, {filepath}') for filepath in deleted: print(f'Deleted file, {filepath}') for filepath in modified: print(f'Changed detected in {filepath}') old_stats = rebuild(config) else: time.sleep(0.5) # make sure we're not a busy loop except: if queue is not None: queue.put(sys.exc_info()) raise if __name__ == '__main__': sys.exit(main()) pemmican-1.0.3/setup.cfg000066400000000000000000000037551457261130300151410ustar00rootroot00000000000000# coding: utf-8 [metadata] name = pemmican version = 1.0.3 description = Notify users of Raspberry Pi 5 power issues long_description = file: README.rst author = Dave Jones author_email = dave.jones@canonical.com project_urls = Documentation = https://pemmican.readthedocs.io/ Source Code = https://github.com/waveform80/pemmican Issue Tracker = https://github.com/waveform80/pemmican/issues keywords = raspberry pi pmic notify classifiers = Development Status :: 4 - Beta Environment :: Console Intended Audience :: System Administrators License :: OSI Approved :: GNU General Public License v3 (GPLv3) Operating System :: POSIX :: Linux Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 Programming Language :: Python :: 3.12 Topic :: System :: Boot [options] packages = find: python_requires = >=3.9 install_requires = setuptools [options.extras_require] gui = dbus-python pyudev pygobject test = pytest pytest-cov doc = sphinx sphinx-rtd-theme [options.entry_points] console_scripts = pemmican-reset = pemmican.gui:reset_main pemmican-mon = pemmican.gui:monitor_main pemmican-cli = pemmican.cli:main [tool:pytest] addopts = -rsx --cov --tb=short testpaths = tests filterwarnings = ignore:GObject\.SIGNAL_RUN_LAST is deprecated:DeprecationWarning [coverage:run] source = pemmican branch = true [coverage:report] show_missing = true exclude_lines = raise NotImplementedError assert False [copyrights:settings] include = **/*.py **/*.rst exclude = docs/examples/*.py docs/license.rst additional = Canonical Ltd. license = LICENSE.txt preamble = pemmican: notifies users of Raspberry Pi 5 power issues strip-preamble = false [previewer:settings] command = make -C docs html html = build/html watch = pemmican/*.py docs/*.rst README.rst pemmican-1.0.3/setup.py000066400000000000000000000000461457261130300150200ustar00rootroot00000000000000from setuptools import setup setup() pemmican-1.0.3/systemd/000077500000000000000000000000001457261130300147765ustar00rootroot00000000000000pemmican-1.0.3/systemd/pemmican-monitor.service000066400000000000000000000006331457261130300216400ustar00rootroot00000000000000[Unit] Description=Check the Raspberry Pi PMIC for power supply issues ConditionPathExists=/proc/device-tree/chosen/power ConditionPathExists=|!%E/pemmican/overcurrent.inhibit ConditionPathExists=|!%E/pemmican/undervolt.inhibit Requires=dbus.socket After=dbus.socket [Service] Slice=session.slice Type=simple ExecStart=pemmican-mon Restart=on-failure RestartSec=1s [Install] WantedBy=graphical-session.target pemmican-1.0.3/systemd/pemmican-reset.service000066400000000000000000000006351457261130300212750ustar00rootroot00000000000000[Unit] Description=Check the Raspberry Pi PMIC for reset notifications ConditionPathExists=/proc/device-tree/chosen/power ConditionPathExists=|!%E/pemmican/brownout.inhibit ConditionPathExists=|!%E/pemmican/max_current.inhibit Requires=dbus.socket After=dbus.socket [Service] Slice=session.slice Type=oneshot ExecStart=pemmican-reset Restart=on-failure RestartSec=1s [Install] WantedBy=graphical-session.target pemmican-1.0.3/tests/000077500000000000000000000000001457261130300144505ustar00rootroot00000000000000pemmican-1.0.3/tests/conftest.py000066400000000000000000000056141457261130300166550ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 from unittest import mock import pytest @pytest.fixture() def dbus(): with mock.patch('pemmican.notify.dbus') as mock_dbus: yield mock_dbus @pytest.fixture() def dbus_mainloop(dbus): with mock.patch('pemmican.gui.DBusGMainLoop') as mock_dbus_mainloop: yield mock_dbus_mainloop @pytest.fixture() def dbus_exception(dbus): class DBusException(Exception): def __init__(self, name, msg=''): self._name = name super().__init__(msg) def get_dbus_name(self): return self._name with mock.patch('pemmican.gui.DBusException', DBusException) as mock_exc: yield mock_exc @pytest.fixture() def notify_intf(dbus): return dbus.Interface() @pytest.fixture() def udev_context(): with mock.patch('pemmican.gui.Context') as context: yield context @pytest.fixture() def udev_monitor(udev_context): with mock.patch('pemmican.gui.Monitor') as monitor: yield monitor @pytest.fixture() def udev_observer(udev_monitor): class MonitorObserver: def __init__(self, monitor): self.monitor = monitor self._handle_id = 0 self._handlers = {} def connect(self, event, handler): self._handle_id += 1 self._handlers[self._handle_id] = (event, handler) return self._handle_id def disconnect(self, handler_id): del self._handlers[handler_id] def event(self, event, device): for h_event, handler in self._handlers.values(): if h_event == event: handler(self, device) with mock.patch('pemmican.gui.MonitorObserver', MonitorObserver) as observer: yield observer @pytest.fixture() def gio(): with mock.patch('pemmican.gui.Gio') as Gio: handlers = {} app = Gio.Application() def connect(signal, handler, data=None): handlers[signal] = (handler, data) def run(args): handler, data = handlers['activate'] handler(data) return 0 app.connect.side_effect = connect app.run.side_effect = run yield Gio @pytest.fixture() def glib(): with mock.patch('pemmican.gui.GLib') as GLib: handlers = {} loop = GLib.MainLoop() loop._quit = False def idle_add(handler): handlers['idle_add'] = handler def run(): handler = handlers['idle_add'] # TODO timeout while handler() and not loop._quit: pass def quit(): loop._quit = True GLib.idle_add.side_effect = idle_add loop.run.side_effect = run loop.quit.side_effect = quit yield GLib pemmican-1.0.3/tests/test_cli.py000066400000000000000000000061101457261130300166260ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 from unittest import mock import pytest from pemmican.cli import * def test_help(capsys): with pytest.raises(SystemExit) as err: main(['--version']) assert err.value.code == 0 capture = capsys.readouterr() assert capture.out.strip() == '1.0.3' with pytest.raises(SystemExit) as err: main(['--help']) assert err.value.code == 0 capture = capsys.readouterr() assert capture.out.strip().startswith('usage:') def test_lang_fallback(capsys): import locale with mock.patch('pemmican.lang.locale.setlocale') as setlocale: setlocale.side_effect = [locale.Error, None] with pytest.raises(SystemExit) as err: main(['--version']) assert err.value.code == 0 # Ensure we fell back to C locale on initial failure assert setlocale.call_count == 2 assert setlocale.call_args.args == (locale.LC_ALL, 'C') def test_regular_operation(capsys): with ( mock.patch('pemmican.cli.reset_brownout') as reset_brownout, mock.patch('pemmican.cli.psu_max_current') as psu_max_current, ): reset_brownout.return_value = False psu_max_current.return_value = 5000 assert main([]) == 0 capture = capsys.readouterr() assert capture.out.strip() == '' def test_non_pi_operation(capsys): with ( mock.patch('pemmican.cli.reset_brownout') as reset_brownout, mock.patch('pemmican.cli.psu_max_current') as psu_max_current, ): reset_brownout.side_effect = FileNotFoundError('no such file or directory') psu_max_current.return_value = 5000 assert main([]) == 0 capture = capsys.readouterr() assert capture.out.strip() == '' def test_brownout(capsys): with ( mock.patch('pemmican.cli.reset_brownout') as reset_brownout, mock.patch('pemmican.cli.psu_max_current') as psu_max_current, ): reset_brownout.return_value = True psu_max_current.return_value = 3000 assert main([]) == 0 capture = capsys.readouterr() out = capture.out.strip() assert out.startswith('Reset due to low power') assert 'man:pemmican-cli(1)' in out assert RPI_PSU_URL in out # Note: PSU max current is also reported low (3A), but this doesn't # result in output assert '5A' not in out def test_max_current(capsys): with ( mock.patch('pemmican.cli.reset_brownout') as reset_brownout, mock.patch('pemmican.cli.psu_max_current') as psu_max_current, ): reset_brownout.return_value = False psu_max_current.return_value = 3000 assert main([]) == 0 capture = capsys.readouterr() out = capture.out.strip() assert out.startswith('This power supply is not capable') assert 'man:pemmican-cli(1)' in out assert RPI_PSU_URL in out assert 'Reset due to low power' not in out pemmican-1.0.3/tests/test_monitor_gui.py000066400000000000000000000313061457261130300204170ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 from unittest import mock import pytest from pemmican.const import RPI_PSU_URL from pemmican.gui import MonitorApplication @pytest.fixture() def conf_dir(tmp_path): with ( mock.patch('pemmican.gui.XDG_CONFIG_HOME', tmp_path), mock.patch('pemmican.gui.XDG_CONFIG_DIRS', [tmp_path]), ): yield tmp_path @pytest.fixture() def main( gio, glib, dbus, notify_intf, udev_context, udev_monitor, udev_observer, conf_dir, monkeypatch ): with ( monkeypatch.context() as m, ): m.setenv('DISPLAY', ':0') yield MonitorApplication() def test_main(main, glib, notify_intf): assert main() == 0 assert notify_intf.Notify.call_count == 0 assert glib.MainLoop().quit.call_count == 0 assert main.overcurrent_monitor is not None assert main.undervolt_monitor is not None def test_both_inhibited(main, conf_dir, glib, notify_intf): (conf_dir / 'pemmican').mkdir() (conf_dir / 'pemmican' / 'undervolt.inhibit').touch() (conf_dir / 'pemmican' / 'overcurrent.inhibit').touch() assert main() == 0 assert notify_intf.Notify.call_count == 0 assert glib.MainLoop().quit.call_count == 1 def test_undervolt_inhibited(main, conf_dir, glib, notify_intf): (conf_dir / 'pemmican').mkdir() (conf_dir / 'pemmican' / 'undervolt.inhibit').touch() assert main() == 0 assert notify_intf.Notify.call_count == 0 assert glib.MainLoop().quit.call_count == 0 assert main.overcurrent_monitor is not None assert main.undervolt_monitor is None def test_overcurrent_inhibited(main, conf_dir, glib, notify_intf): (conf_dir / 'pemmican').mkdir() (conf_dir / 'pemmican' / 'overcurrent.inhibit').touch() assert main() == 0 assert notify_intf.Notify.call_count == 0 assert glib.MainLoop().quit.call_count == 0 assert main.overcurrent_monitor is None assert main.undervolt_monitor is not None def test_missing_display(main, monkeypatch, capsys): with monkeypatch.context() as m: m.delenv('DISPLAY', raising=False) m.delenv('WAYLAND_DISPLAY', raising=False) assert main() == 1 capture = capsys.readouterr() assert capture.err.strip().startswith('Missing DISPLAY') def test_missing_notifier(main, dbus, dbus_exception): with ( mock.patch('pemmican.gui.sleep') as sleep, mock.patch('pemmican.gui.monotonic') as monotonic, ): dbus.Interface.side_effect = dbus_exception( 'org.freedesktop.DBus.Error.ServiceUnknown') monotonic.side_effect = list(range(100)) with pytest.raises(dbus_exception): main() assert sleep.call_count == 60 def test_broken_notifier(main, dbus, dbus_exception): with mock.patch('pemmican.gui.sleep') as sleep: dbus.Interface.side_effect = dbus_exception( 'org.freedesktop.DBus.Error.SomeOtherError') with pytest.raises(dbus_exception): main() assert sleep.call_count == 0 def test_usb_overcurrent(main, notify_intf): assert main() == 0 assert notify_intf.Notify.call_count == 0 device = mock.Mock() device.action = 'change' device.properties = {} device.properties['OVER_CURRENT_PORT'] = '4-2-port1' device.properties['OVER_CURRENT_COUNT'] = 1 main.overcurrent_observer.event('device-event', device) assert notify_intf.Notify.call_count == 1 # Re-send the same event, observe the call-count doesn't change because # the notification is still active main.overcurrent_observer.event('device-event', device) assert notify_intf.Notify.call_count == 1 def test_usb_other(main, notify_intf): notify_intf.Notify.return_value = 1 assert main() == 0 assert notify_intf.Notify.call_count == 0 device = mock.Mock() device.action = 'add' device.properties = {} main.overcurrent_observer.event('device-event', device) assert notify_intf.Notify.call_count == 0 device = mock.Mock() device.action = 'change' device.properties = {} # No OVER_CURRENT_PORT... device.properties['OVER_CURRENT_COUNT'] = 1 main.overcurrent_observer.event('device-event', device) assert notify_intf.Notify.call_count == 0 def test_undervolt(main, notify_intf): notify_intf.Notify.return_value = 1 assert main() == 0 assert notify_intf.Notify.call_count == 0 device = mock.Mock() device.action = 'change' device.attributes.asstring.side_effect = ( lambda s: 'rpi_volt' if s == 'name' else 'foo') device.attributes.asint.side_effect = ( lambda s: '1' if s == 'in0_lcrit_alarm' else '0') main.undervolt_observer.event('device-event', device) assert notify_intf.Notify.call_count == 1 # Re-send the same event, observe the call-count doesn't change because # the original notification is still active main.undervolt_observer.event('device-event', device) assert notify_intf.Notify.call_count == 1 def test_not_undervolt(main, notify_intf): assert main() == 0 assert notify_intf.Notify.call_count == 0 device = mock.Mock() # Wrong action device.action = 'add' main.undervolt_observer.event('device-event', device) assert notify_intf.Notify.call_count == 0 # No in0_lcrit_alarm attribute device = mock.Mock() device.action = 'change' device.attributes.asstring.side_effect = ( lambda s: 'rpi_volt' if s == 'name' else 'foo') device.attributes.asint.side_effect = KeyError('in0_lcrit_alarm') main.undervolt_observer.event('device-event', device) assert notify_intf.Notify.call_count == 0 # Wrong name device = mock.Mock() device.action = 'change' device.attributes.asstring.side_effect = ( lambda s: 'foo' if s == 'name' else 'rpi_volt') device.attributes.asint.side_effect = ( lambda s: '1' if s == 'in0_lcrit_alarm' else '0') main.undervolt_observer.event('device-event', device) assert notify_intf.Notify.call_count == 0 def test_undervolt_basic(main, notify_intf): notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = [] assert main() == 0 assert notify_intf.Notify.call_count == 0 device = mock.Mock() device.action = 'change' device.attributes.asstring.side_effect = ( lambda s: 'rpi_volt' if s == 'name' else 'foo') device.attributes.asint.side_effect = ( lambda s: '1' if s == 'in0_lcrit_alarm' else '0') main.undervolt_observer.event('device-event', device) assert notify_intf.Notify.call_count == 1 assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Raspberry Pi PMIC Monitor', 'Low voltage warning; please check your power supply. ' f'See {RPI_PSU_URL} for more information', [], {'urgency': 2}, -1) def test_undervolt_hyperlinks(main, notify_intf): notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['body-hyperlinks'] assert main() == 0 assert notify_intf.Notify.call_count == 0 device = mock.Mock() device.action = 'change' device.attributes.asstring.side_effect = ( lambda s: 'rpi_volt' if s == 'name' else 'foo') device.attributes.asint.side_effect = ( lambda s: '1' if s == 'in0_lcrit_alarm' else '0') main.undervolt_observer.event('device-event', device) assert notify_intf.Notify.call_count == 1 assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Raspberry Pi PMIC Monitor', 'Low voltage warning; please check your power supply. ' f'More information', [], {'urgency': 2}, -1) def test_undervolt_actions(main, notify_intf): notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['actions', 'body-hyperlinks'] assert main() == 0 assert notify_intf.Notify.call_count == 0 device = mock.Mock() device.action = 'change' device.attributes.asstring.side_effect = ( lambda s: 'rpi_volt' if s == 'name' else 'foo') device.attributes.asint.side_effect = ( lambda s: '1' if s == 'in0_lcrit_alarm' else '0') main.undervolt_observer.event('device-event', device) assert notify_intf.Notify.call_count == 1 assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Raspberry Pi PMIC Monitor', 'Low voltage warning; please check your power supply', ['moreinfo', 'More information', 'suppress_undervolt', "Don't show again"], {'urgency': 2}, -1) def test_more_info(main, glib, notify_intf): with mock.patch('pemmican.gui.webbrowser') as webbrowser: notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['actions'] assert main() == 0 assert notify_intf.Notify.call_count == 0 device = mock.Mock() device.action = 'change' device.attributes.asstring.side_effect = ( lambda s: 'rpi_volt' if s == 'name' else 'foo') device.attributes.asint.side_effect = ( lambda s: '1' if s == 'in0_lcrit_alarm' else '0') main.undervolt_observer.event('device-event', device) assert notify_intf.Notify.call_count == 1 assert main.undervolt_msg_id == 1 main.notifier._action_invoked(1, 'moreinfo') assert webbrowser.open_new_tab.call_count == 1 assert webbrowser.open_new_tab.call_args.args == (RPI_PSU_URL,) main.notifier._notification_closed(1, 2) assert main.undervolt_msg_id == 0 assert glib.MainLoop().quit.call_count == 0 def test_inhibit_overcurrent(main, conf_dir, glib, notify_intf): notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['actions'] assert main() == 0 assert notify_intf.Notify.call_count == 0 device = mock.Mock() device.action = 'change' device.properties = {} device.properties['OVER_CURRENT_PORT'] = '4-2-port1' device.properties['OVER_CURRENT_COUNT'] = 1 main.overcurrent_observer.event('device-event', device) assert notify_intf.Notify.call_count == 1 assert main.overcurrent_msg_id == 1 assert not (conf_dir / 'pemmican' / 'overcurrent.inhibit').exists() main.notifier._action_invoked(1, 'suppress_overcurrent') assert (conf_dir / 'pemmican' / 'overcurrent.inhibit').exists() main.notifier._notification_closed(1, 2) assert main.overcurrent_msg_id == 0 # Close an unrelated message id, just for coverage main.do_notification_closed(2, 2) assert main.overcurrent_msg_id == 0 assert glib.MainLoop().quit.call_count == 0 def test_inhibit_undervolt(main, conf_dir, glib, notify_intf): notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['actions'] assert main() == 0 assert notify_intf.Notify.call_count == 0 device = mock.Mock() device.action = 'change' device.attributes.asstring.side_effect = ( lambda s: 'rpi_volt' if s == 'name' else 'foo') device.attributes.asint.side_effect = ( lambda s: '1' if s == 'in0_lcrit_alarm' else '0') main.undervolt_observer.event('device-event', device) assert notify_intf.Notify.call_count == 1 assert main.undervolt_msg_id == 1 assert not (conf_dir / 'pemmican' / 'undervolt.inhibit').exists() main.notifier._action_invoked(1, 'suppress_undervolt') assert (conf_dir / 'pemmican' / 'undervolt.inhibit').exists() main.notifier._notification_closed(1, 2) assert main.undervolt_msg_id == 0 # Close an unrelated message id, just for coverage main.do_notification_closed(2, 2) assert main.undervolt_msg_id == 0 assert glib.MainLoop().quit.call_count == 0 def test_inhibit_quits(main, conf_dir, glib, notify_intf): # Pre-inhibit the undervolt warning (conf_dir / 'pemmican').mkdir() (conf_dir / 'pemmican' / 'undervolt.inhibit').touch() notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['actions'] assert main() == 0 assert notify_intf.Notify.call_count == 0 device = mock.Mock() device.action = 'change' device.properties = {} device.properties['OVER_CURRENT_PORT'] = '4-2-port1' device.properties['OVER_CURRENT_COUNT'] = 1 main.overcurrent_observer.event('device-event', device) assert notify_intf.Notify.call_count == 1 assert main.overcurrent_msg_id == 1 assert not (conf_dir / 'pemmican' / 'overcurrent.inhibit').exists() main.notifier._action_invoked(1, 'suppress_overcurrent') assert (conf_dir / 'pemmican' / 'overcurrent.inhibit').exists() main.notifier._notification_closed(1, 2) assert main.overcurrent_msg_id == 0 # Because both are now inhibited, check quit was called assert glib.MainLoop().quit.call_count == 1 pemmican-1.0.3/tests/test_notify.py000066400000000000000000000122631457261130300173750ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 import pytest from unittest import mock from pemmican.notify import Notifications def test_notifications_init(dbus): notifier = Notifications() assert notifier.on_closed is None assert notifier.on_action is None assert notifier.pending == frozenset() assert dbus.SessionBus().add_signal_receiver.call_count == 2 def test_notifications_init_with_bus(dbus): my_bus = dbus.SessionBus() notifier = Notifications(my_bus) assert notifier.on_closed is None assert notifier.on_action is None assert notifier.pending == frozenset() assert my_bus.add_signal_receiver.call_count == 2 def test_notifications_info(notify_intf): notifier = Notifications() notify_intf.GetServerInformation.return_value = ( 'foo-shell', 'FOO', '1.0', '1.2') assert notifier.get_server_info() == { 'name': 'foo-shell', 'vendor': 'FOO', 'version': '1.0', 'spec_version': '1.2', } def test_notifications_caps(notify_intf): notifier = Notifications() caps = ['persistence', 'body', 'body-hyperlink'] notify_intf.GetCapabilities.return_value = caps assert notifier.get_capabilities() == caps def test_notifications_notify(notify_intf): notifier = Notifications() notify_intf.Notify.return_value = 9 assert notifier.notify('Foo Info', body='The foo has started') == 9 assert notifier.pending == {9} assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Foo Info', 'The foo has started', [], {}, -1) assert notify_intf.Notify.call_args.kwargs == {} notify_intf.Notify.return_value = 10 assert notifier.notify( 'Foo Error', body='The foo is on fire!', actions=[('put-it-out', 'Extinguish!'), ('let-it-burn', 'Leave It')], hints={'urgency': 2}) == 10 assert notifier.pending == {9, 10} assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Foo Error', 'The foo is on fire!', ['put-it-out', 'Extinguish!', 'let-it-burn', 'Leave It'], {'urgency': 2}, -1) assert notify_intf.Notify.call_args.kwargs == {} def test_notifications_not_pending(notify_intf): notifier = Notifications() notify_intf.Notify.return_value = 0 assert notifier.notify('Foo Info', body='The foo has started') == 0 # Ensure we don't set 0 (which is not a valid message ID) as a pending # identity assert notifier.pending == set() def test_notifications_remove(notify_intf): notifier = Notifications() notifier.remove(10) assert notify_intf.CloseNotification.call_args.args == (10,) assert notify_intf.CloseNotification.call_args.kwargs == {} def test_notifications_action(notify_intf): notifier = Notifications() notifier.on_action = mock.Mock() notifier._action_invoked(9, 'put-it-out') assert notifier.on_action.call_count == 0 notify_intf.Notify.return_value = 10 assert notifier.notify( 'Foo Error', body='The foo is on fire!', actions=[('put-it-out', 'Extinguish!'), ('let-it-burn', 'Leave It')], hints={'urgency': 2}) == 10 notifier._action_invoked(10, 'put-it-out') assert notifier.on_action.call_count == 1 assert notifier.on_action.call_args.args == (10, 'put-it-out') notifier._action_invoked(11, 'put-it-out') assert notifier.on_action.call_count == 1 def test_notifications_no_action(notify_intf): notifier = Notifications() notifier.on_action = None notify_intf.Notify.return_value = 11 assert notifier.notify( 'Foo Error', body='The foo is on fire!', actions=[('put-it-out', 'Extinguish!'), ('let-it-burn', 'Leave It')], hints={'urgency': 2}) == 11 # Ensure if on_action is None, the _action_invoked handler does not raise # an exception, even if the ID is pending and everything else is valid notifier._action_invoked(11, 'put-it-out') def test_notifications_closed(notify_intf): notifier = Notifications() notifier.on_closed = mock.Mock() notifier._notification_closed(9, 2) assert notifier.on_closed.call_count == 0 notify_intf.Notify.return_value = 10 assert notifier.notify( 'Foo Error', body='The foo is on fire!', actions=[('put-it-out', 'Extinguish!'), ('let-it-burn', 'Leave It')], hints={'urgency': 2}) == 10 notifier._notification_closed(10, 2) assert notifier.on_closed.call_count == 1 assert notifier.on_closed.call_args.args == (10, 2) notifier._notification_closed(11, 2) assert notifier.on_closed.call_count == 1 def test_notifications_closed_but_none(notify_intf): notifier = Notifications() notifier.on_closed = None notify_intf.Notify.return_value = 11 assert notifier.notify( 'Foo Error', body='The foo is on fire!', actions=[('put-it-out', 'Extinguish!'), ('let-it-burn', 'Leave It')], hints={'urgency': 2}) == 11 # Ensure if on_closed is None, the _notification_closed handler does not # raise an exception, even if the ID is pending and everything else is # valid notifier._notification_closed(11, 2) pemmican-1.0.3/tests/test_power.py000066400000000000000000000016661457261130300172260ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 import struct from unittest import mock import pytest from pemmican.power import * @pytest.fixture() def dt_power(tmp_path): dt_power = tmp_path / 'power' with mock.patch('pemmican.power.DT_POWER', dt_power) as p: dt_power.mkdir() (dt_power / 'power_reset').write_bytes(struct.pack('>I', 0)) (dt_power / 'max_current').write_bytes(struct.pack('>I', 5000)) yield dt_power def test_reset_brownout(dt_power): assert not reset_brownout() (dt_power / 'power_reset').write_bytes(struct.pack('>I', 2)) assert reset_brownout() def test_psu_max_current(dt_power): assert psu_max_current() == 5000 (dt_power / 'max_current').write_bytes(struct.pack('>I', 3000)) assert psu_max_current() == 3000 pemmican-1.0.3/tests/test_reset_gui.py000066400000000000000000000215671457261130300200620ustar00rootroot00000000000000# pemmican: notifies users of Raspberry Pi 5 power issues # # Copyright (c) 2024 Dave Jones # Copyright (c) 2024 Canonical Ltd. # # SPDX-License-Identifier: GPL-3.0 from unittest import mock import pytest from pemmican.const import RPI_PSU_URL from pemmican.gui import ResetApplication @pytest.fixture() def conf_dir(tmp_path): with ( mock.patch('pemmican.gui.XDG_CONFIG_HOME', tmp_path), mock.patch('pemmican.gui.XDG_CONFIG_DIRS', [tmp_path]), ): yield tmp_path @pytest.fixture() def main(gio, glib, dbus, notify_intf, conf_dir, monkeypatch): with ( monkeypatch.context() as m, ): m.setenv('DISPLAY', ':0') yield ResetApplication() def test_main(main, glib, notify_intf): with ( mock.patch('pemmican.gui.reset_brownout') as reset_brownout, mock.patch('pemmican.gui.psu_max_current') as psu_max_current, ): reset_brownout.return_value = False psu_max_current.return_value = 5000 notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['actions', 'body-hyperlinks'] assert main() == 0 assert notify_intf.Notify.call_count == 0 assert glib.MainLoop().quit.call_count == 1 def test_missing_display(main, monkeypatch, capsys): with monkeypatch.context() as m: m.delenv('DISPLAY', raising=False) m.delenv('WAYLAND_DISPLAY', raising=False) assert main() == 1 capture = capsys.readouterr() assert capture.err.strip().startswith('Missing DISPLAY') def test_missing_notifier(main, dbus, dbus_exception): with ( mock.patch('pemmican.gui.sleep') as sleep, mock.patch('pemmican.gui.monotonic') as monotonic, ): dbus.Interface.side_effect = dbus_exception( 'org.freedesktop.DBus.Error.ServiceUnknown') monotonic.side_effect = list(range(100)) with pytest.raises(dbus_exception): main() assert sleep.call_count == 60 def test_broken_notifier(main, dbus, dbus_exception): with mock.patch('pemmican.gui.sleep') as sleep: dbus.Interface.side_effect = dbus_exception( 'org.freedesktop.DBus.Error.SomeOtherError') with pytest.raises(dbus_exception): main() assert sleep.call_count == 0 def test_brownout_basic(main, glib, notify_intf): with ( mock.patch('pemmican.gui.reset_brownout') as reset_brownout, mock.patch('pemmican.gui.psu_max_current') as psu_max_current, ): reset_brownout.return_value = True psu_max_current.return_value = 5000 notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = [] assert main() == 0 assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Raspberry Pi PMIC Monitor', 'Reset due to low power; please check your power supply. ' f'See {RPI_PSU_URL} for more information', [], {'urgency': 2}, -1) assert glib.MainLoop().quit.call_count == 0 def test_brownout_hyperlinks(main, glib, notify_intf): with ( mock.patch('pemmican.gui.reset_brownout') as reset_brownout, mock.patch('pemmican.gui.psu_max_current') as psu_max_current, ): reset_brownout.return_value = True psu_max_current.return_value = 5000 notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['body-hyperlinks'] assert main() == 0 assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Raspberry Pi PMIC Monitor', 'Reset due to low power; please check your power supply. ' f'More information', [], {'urgency': 2}, -1) assert glib.MainLoop().quit.call_count == 0 def test_brownout_actions(main, glib, notify_intf): with ( mock.patch('pemmican.gui.reset_brownout') as reset_brownout, mock.patch('pemmican.gui.psu_max_current') as psu_max_current, ): reset_brownout.return_value = True psu_max_current.return_value = 3000 notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['actions', 'body-hyperlinks'] assert main() == 0 assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Raspberry Pi PMIC Monitor', 'Reset due to low power; please check your power supply', ['moreinfo', 'More information', 'suppress', "Don't show again"], {'urgency': 2}, -1) assert glib.MainLoop().quit.call_count == 0 def test_max_current_actions(main, glib, notify_intf): with ( mock.patch('pemmican.gui.reset_brownout') as reset_brownout, mock.patch('pemmican.gui.psu_max_current') as psu_max_current, ): reset_brownout.return_value = False psu_max_current.return_value = 3000 notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['actions', 'body-hyperlinks'] assert main() == 0 assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Raspberry Pi PMIC Monitor', 'This power supply is not capable of supplying 5A; power to ' 'peripherals will be restricted', ['moreinfo', 'More information', 'suppress', "Don't show again"], {'urgency': 1}, -1) assert glib.MainLoop().quit.call_count == 0 def test_max_current_no_message_id(main, glib, notify_intf): with ( mock.patch('pemmican.gui.reset_brownout') as reset_brownout, mock.patch('pemmican.gui.psu_max_current') as psu_max_current, ): reset_brownout.return_value = False psu_max_current.return_value = 3000 # Notify will return 0 (which it mustn't according to the spec, but # just in case there's a dedficient implementation...) notify_intf.Notify.return_value = 0 notify_intf.GetCapabilities.return_value = ['actions', 'body-hyperlinks'] assert main() == 0 assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Raspberry Pi PMIC Monitor', 'This power supply is not capable of supplying 5A; power to ' 'peripherals will be restricted', ['moreinfo', 'More information', 'suppress', "Don't show again"], {'urgency': 1}, -1) assert glib.MainLoop().quit.call_count == 1 def test_non_pi(main, glib): with ( mock.patch('pemmican.gui.reset_brownout') as reset_brownout, mock.patch('pemmican.gui.psu_max_current') as psu_max_current, ): reset_brownout.side_effect = FileNotFoundError() psu_max_current.return_value = 3000 assert main() == 0 assert glib.MainLoop().quit.call_count == 1 def test_more_info(main, glib, notify_intf): with ( mock.patch('pemmican.gui.reset_brownout') as reset_brownout, mock.patch('pemmican.gui.psu_max_current') as psu_max_current, mock.patch('pemmican.gui.webbrowser') as webbrowser, ): reset_brownout.return_value = True psu_max_current.return_value = 3000 notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['actions', 'body-hyperlinks'] assert main() == 0 assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Raspberry Pi PMIC Monitor', 'Reset due to low power; please check your power supply', ['moreinfo', 'More information', 'suppress', "Don't show again"], {'urgency': 2}, -1) assert glib.MainLoop().quit.call_count == 0 main.notifier._action_invoked(1, 'moreinfo') assert webbrowser.open_new_tab.call_count == 1 assert webbrowser.open_new_tab.call_args.args == (RPI_PSU_URL,) main.notifier._notification_closed(1, 2) assert glib.MainLoop().quit.call_count == 1 def test_inhibit(main, conf_dir, glib, notify_intf, tmp_path): with ( mock.patch('pemmican.gui.reset_brownout') as reset_brownout, mock.patch('pemmican.gui.psu_max_current') as psu_max_current, ): reset_brownout.return_value = True psu_max_current.return_value = 5000 notify_intf.Notify.return_value = 1 notify_intf.GetCapabilities.return_value = ['actions', 'body-hyperlinks'] assert main() == 0 assert notify_intf.Notify.call_args.args == ( '', 0, '', 'Raspberry Pi PMIC Monitor', 'Reset due to low power; please check your power supply', ['moreinfo', 'More information', 'suppress', "Don't show again"], {'urgency': 2}, -1) assert glib.MainLoop().quit.call_count == 0 assert not (conf_dir / 'pemmican' / 'brownout.inhibit').exists() main.notifier._action_invoked(1, 'suppress') assert (conf_dir / 'pemmican' / 'brownout.inhibit').exists() main.notifier._notification_closed(1, 2) assert glib.MainLoop().quit.call_count == 1 pemmican-1.0.3/tox.ini000066400000000000000000000004331457261130300146210ustar00rootroot00000000000000[tox] envlist = {py39,py310,py311,py312} [testenv] basepython = py39: python3.9 py310: python3.10 py311: python3.11 py312: python3.12 deps = .[gui,test] usedevelop = true commands = make test setenv = COVERAGE_FILE=.coverage.{envname} allowlist_externals = make