pax_global_header00006660000000000000000000000064145411355700014517gustar00rootroot0000000000000052 comment=67d544dcf1bfa46726f88fe3cba2936cf7842029 padelt-temper-python-67d544d/000077500000000000000000000000001454113557000161445ustar00rootroot00000000000000padelt-temper-python-67d544d/.devcontainer/000077500000000000000000000000001454113557000207035ustar00rootroot00000000000000padelt-temper-python-67d544d/.devcontainer/Dockerfile000066400000000000000000000001751454113557000227000ustar00rootroot00000000000000FROM mcr.microsoft.com/devcontainers/base:alpine-3.18 RUN apk add --no-cache \ libusb=1.0.26-r2 \ py3-pip=23.1.2-r0 padelt-temper-python-67d544d/.devcontainer/devcontainer.json000066400000000000000000000022401454113557000242550ustar00rootroot00000000000000// For format details, see https://aka.ms/devcontainer.json. For config options, see the // README at: https://github.com/devcontainers/templates/tree/main/src/alpine { "name": "Python Alpine", // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile "build": { "dockerfile": "Dockerfile", "context": ".." }, // Features to add to the dev container. More info: https://containers.dev/features. // "features": {}, // Use 'forwardPorts' to make a list of ports inside the container available locally. // "forwardPorts": [], // Use 'postCreateCommand' to run commands after the container is created. "postCreateCommand": "pip3 install --user -r requirements.txt -r requirements_test.txt", // Priviledged mode is necessary to get access to usb "runArgs": ["--privileged"], // Configure tool-specific properties. // "customizations": {}, // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. //"remoteUser": "root" // Access local .pypi api keys "mounts": [ "source=${localEnv:HOME}${localEnv:USERPROFILE}/.pypirc,target=/home/vscode/.pypirc,type=bind,consistency=cached" ] } padelt-temper-python-67d544d/.github/000077500000000000000000000000001454113557000175045ustar00rootroot00000000000000padelt-temper-python-67d544d/.github/workflows/000077500000000000000000000000001454113557000215415ustar00rootroot00000000000000padelt-temper-python-67d544d/.github/workflows/ci.yml000066400000000000000000000011221454113557000226530ustar00rootroot00000000000000name: CI on: [push, pull_request] jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements_test.txt - name: Run unit tests run: python -m pytest --import-mode=append tests/ padelt-temper-python-67d544d/.gitignore000066400000000000000000000005151454113557000201350ustar00rootroot00000000000000*.swp *.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # virtualenv _/ .idea/ padelt-temper-python-67d544d/.vscode/000077500000000000000000000000001454113557000175055ustar00rootroot00000000000000padelt-temper-python-67d544d/.vscode/settings.json000066400000000000000000000004451454113557000222430ustar00rootroot00000000000000{ "python.envFile": "${workspaceFolder}/.env", "python.testing.pytestArgs": [ "tests" ], "python.testing.unittestEnabled": false, "python.testing.nosetestsEnabled": false, "python.testing.pytestEnabled": true, "python.pythonPath": "/usr/local/bin/python", }padelt-temper-python-67d544d/CHANGELOG.md000066400000000000000000000035471454113557000177660ustar00rootroot00000000000000# Change log All notable changes to this project will be documented in this file. * This project adheres to [Semantic Versioning](http://semver.org/). * This project follows the guidelines outlined on [keepachangelog.com](http://keepachangelog.com/). ## [Unreleased] No changes yet. ## [1.6.1] - 2023-12-19 ### Added - Support for TEMPer2V1.3 - Support for TEMPerHumiV1.1 - Support for TEMPerHumiV1.0 - Experimental support for TEMPer2_V3.7 - get_product() function to get product name - Updates to documentation ## [1.6.0] - 2021-11-03 ### Added - A new architecture for supporting different device types. - Tests using pytest ### Added - Add support for 3 sensor tempers and TEMPerNTC1.O - Add support for TemperHUM with si7021 type sensor - Add support for TEMPer1V1.4 ### Fixed - Fixes for the munin plugin - Report TEMPerV1.2 devices as having a single sensor - Fix error message about USB permissions to display correctly on Python 3.6 ## [1.5.3] - 2017-04-03 - Commit ID: 4da8be1 ### Added - Support for 0c45:7402 (RDing TEMPer1F_H1_V1.4) including humidity - Hints for local development - Add release documentation to `DEVELOPMENT.md`. ### Fixed - Negative temperature readings incorrectly wrapped around to very high temperatures - Fixed format string error in the munin plugin (PR#71) ## [1.5.2] - 2016-09-07 - Commit ID: e904dbe ### Fixed - Clarification of install documentation from eric-s-raymond. - Workaround for misleading error message when at least one TEMPer USB device node has insufficient permissions. (#63) ## [1.5.1] - 2016-06-12 - Commit ID: ceb0617 ### Added - Support for `TEMPer1F_V1.3`'s behaviour: Only one sensor, data is at offset 4 from ps-jay. ### Fixed - Comparing only port without bus may lead to calibration being applied to multiple devices instead of one from ps-jay. ## [1.5.0] - 2016-04-20 - Commit ID: 8752b14 ### Added - Changelog file. padelt-temper-python-67d544d/DEVELOPMENT.md000066400000000000000000000125031454113557000202510ustar00rootroot00000000000000For development purposes, you will sometimes need to change some code and try it. This should happen without changing the main installation of `temper-python`. Here is how to do it. You will need these tools installed: - `git` - `python` (if you don't know which, grab Python 3) - `virtualenv` for the Python version (see below) # Clone the repository This will clone into a directory named `temper-dev`: ``` pa@plug2:~/temper$ git clone https://github.com/padelt/temper-python.git temper-dev Cloning into 'temper-dev'... remote: Counting objects: 544, done. Receiving objects: 100% (544/544), 118.51 KiB, done. remote: Total 544 (delta 0), reused 0 (delta 0), pack-reused 544 Resolving deltas: 100% (329/329), done. pa@plug2:~/temper$ cd temper-dev/ pa@plug2:~/temper/temper-dev$ ``` # How to find `virtualenv` A virtualenv basically isolates all the package installation we are going to do in a subdirectory instead of the global python repository. Unfortunately, availability of virtualenv differs greatly between Python versions. In Python 2 and until 3.3, this is a seperate tool, usually installed from your distribution packages and available as a binary named `virtualenv` (check availability using `which virtualenv`). In Python 3.4+, we finally reached a sane solution: Virtualenv is a module in the standard Python distribution and is called using `python -m venv` followed by your desire virtualenv directory. # Setting up a `virtualenv` and activating it Check which python binary is available and what you want by entering `python` and hitting the Tab key twice to have your shell suggest some: ``` pa@plug2:~/temper/temper-dev$ python python python2.7 python3 python3.2mu python-config python2 python2.7-config python3.2 python3mu ``` I will choose `python3.2`. To have it set up in the subdirectory `venv` (the name could be any valid directory name), try this: ``` pa@plug2:~/temper/temper-dev$ virtualenv -p python3.2 venv Running virtualenv with interpreter /usr/bin/python3.2 New python executable in venv/bin/python3.2 Also creating executable in venv/bin/python Installing setuptools, pip, wheel...done. pa@plug2:~/temper/temper-dev$ ll venv/bin/ insgesamt 2792 -rw-r--r-- 1 pa pa 2242 Dez 5 11:34 activate -rw-r--r-- 1 pa pa 1268 Dez 5 11:34 activate.csh -rw-r--r-- 1 pa pa 2481 Dez 5 11:34 activate.fish -rw-r--r-- 1 pa pa 1137 Dez 5 11:34 activate_this.py -rwxr-xr-x 1 pa pa 262 Dez 5 11:34 easy_install -rwxr-xr-x 1 pa pa 262 Dez 5 11:34 easy_install-3.2 -rwxr-xr-x 1 pa pa 234 Dez 5 11:34 pip -rwxr-xr-x 1 pa pa 234 Dez 5 11:34 pip3 -rwxr-xr-x 1 pa pa 234 Dez 5 11:34 pip3.2 lrwxrwxrwx 1 pa pa 9 Dez 5 11:34 python -> python3.2 lrwxrwxrwx 1 pa pa 9 Dez 5 11:34 python3 -> python3.2 -rwxr-xr-x 1 pa pa 2814320 Dez 5 11:34 python3.2 -rwxr-xr-x 1 pa pa 241 Dez 5 11:34 wheel pa@plug2:~/temper/temper-dev$ ``` Now activate it: ``` pa@plug2:~/temper/temper-dev$ . venv/bin/activate (venv)pa@plug2:~/temper/temper-dev$ ``` What this does is prepend your PATH environment variable to prefer the python executable in the virtualenv. All the installations using `pip` will now go there and not into your global python repo. To later deactivate it, run `deactivate` (which is a function set into your running `bash` by `activate`). Check that the right python binary will be called: ``` (venv)pa@plug2:~/temper/temper-dev$ which python /home/pa/temper/temper-dev/venv/bin/python ``` Great! # Install `temper-python` into the virtualenv ``` (venv)pa@plug2:~/temper/temper-dev$ python setup.py install running install ... Installing temper-poll script to /home/pa/temper/temper-dev/venv/bin ... Finished processing dependencies for temperusb==1.5.2 (venv)pa@plug2:~/temper/temper-dev$ ``` Now we can run `temper-poll` for testing. Since the virtualenv is active, our fresh install is found first: ``` (venv)pa@plug2:~/temper/temper-dev$ which temper-poll /home/pa/temper/temper-dev/venv/bin/temper-poll (venv)pa@plug2:~/temper/temper-dev$ temper-poll Found 2 devices Device #0: 30.9°C 87.7°F Device #1: 17.1°C 62.8°F (venv)pa@plug2:~/temper/temper-dev$ ``` # Development/testing workflow To test a change, you need to follow this workflow: - Make your changes to e.g. `temperusb/temper.py` - Run `python setup.py install --force` (the `--force` will have it reinstalled despite the package version in `setup.py` not changing). - Run `temper-poll` This is a simple and surefire way to deal with module names and dependencies. # Release workflow 1. Edit `setup.py` to reflect the new version. 1. Edit `CHANGELOG.md` to document the new version (without commit ID). 1. Setup your `~.pypirc`: ``` [distutils] index-servers = pypi pypitest [pypi] repository=https://pypi.python.org/pypi username=myusername password=mypass [pypitest] repository=https://testpypi.python.org/pypi username=myusername password=mypass ```` 1. Test-Upload: `python setup.py sdist upload -r pypitest` 1. Check if https://testpypi.python.org/pypi/temperusb looks good. 1. Commit changes and note commit ID. 1. Tag the revision and push the tag to Github: `git tag v1.5.3 && git push origin v1.5.3` 1. Edit `CHANGELOG.md` noting the commit ID you just tagged. 1. Commit and push that change. 1. Live PyPI upload: `python setup.py sdist upload -r pypi` padelt-temper-python-67d544d/LICENSE.md000066400000000000000000000775441454113557000175710ustar00rootroot00000000000000This software is released unter the GNU Public License (GPL). A copy of the text from http://www.gnu.org/licenses/gpl.txt is copied below. 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 padelt-temper-python-67d544d/MANIFEST.in000066400000000000000000000000221454113557000176740ustar00rootroot00000000000000include README.md padelt-temper-python-67d544d/README.md000066400000000000000000000442161454113557000174320ustar00rootroot00000000000000This is a rewrite of a userspace USB driver for TEMPer devices presenting a USB ID like this: `0c45:7401 Microdia` My device came from [M-Ware ID7747](http://www.m-ware.de/m-ware-usb-thermometer-40--120-c-emailbenachrichtigung-id7747/a-7747/) and also reports itself as 'RDing TEMPerV1.2'. Also provides a passpersist-module for NetSNMP (as found in the `snmpd` packages of Debian and Ubuntu) to present the temperature of 1-3 USB devices via SNMP. ### Reported working devices | USB ID | Name Reported | Notes | | ------------------------------------------------------------ | ------------------------ | ----------------------- | | `0c45:7401 Microdia` | `RDing TEMPerV1.2` | First supported device | | `0c45:7401 Microdia TEMPer Temperature Sensor` | `RDing TEMPer2_M12_V1.3` | Two sensor device | | `0c45:7401 Microdia` | `RDing TEMPer1F_V1.3` | Single external sensor, but better precision is possible by using "sensor 2" | | `0c45:7401 Microdia` | `RDing TEMPerV1.4` | | | `0c45:7402 Microdia TEMPerHUM Temperature & Humidity Sensor` | `RDing TEMPer1F_H1_V1.4` | Single sensor which reports both temperature and relative-humidity | # Requirements Basically, `libusb` bindings for python (PyUSB) and `snmp-passpersist` from PyPI. Under Debian/Ubuntu, treat yourself to some package goodness: sudo apt-get install python-usb python-setuptools snmpd # The latter is only necessary for SNMP-usage. sudo easy_install snmp-passpersist # Installation and usage To install using pip, run pip install temperusb To install from source, clone the repository, cd into its top-level directory, and run sudo python setup.py install you should end up with two scripts conveniently installed: /usr/local/bin/temper-poll /usr/local/bin/temper-snmp If your system does not provide access as a normal user to the USB device, you need to run them as root. See "USB device permissions" section for more on this. temper-poll accepts -p option now, which adds the USB bus and port information each device is plugged on. without -p option $ temper-poll Found 1 devices Device #0: 22.5°C 72.5°F with -p option $ temper-poll -p Found 1 devices Device #0 (bus 1 - port 1.3): 22.4°C 72.3°F Which tells you there is a USB hub plugged (internally or externally) on the port 1 of the bus 1 of the host, and your TEMPer device is on the port 3 of that hub. ## Tell kernel to leave TEMPer alone Regarding errors: - `usb.core.USBError: [Errno 16] Resource busy` - `Unknown error` By default, the Linux kernel claims (e.g. opens/uses) the TEMPer device as a keyboard (HID device). When that happens, this script is not able to set the configuration and communicate with it. You will see one of those two errors when running `sudo temper-poll`. Your `dmesg` log will show something similar to this: usb 1-1.3: usbfs: interface 0 claimed by usbhid while 'temper-poll' sets config #1 To prevent this, add this to the kernel command line: usbhid.quirks=0x0c45:0x7401:0x4 On Raspbian, this will be `/boot/cmdline.txt`. Reboot after saving and retry. Hat tip to and more information from [AndiDog here](http://unix.stackexchange.com/questions/55495/prevent-usbhid-from-claiming-usb-device). # Serving via SNMP Using [NetSNMP](http://www.net-snmp.org/), you can use `temper/snmp.py` as a `pass_persist` module. You can choose one of two OIDs to be emulated: [APC's typical](http://www.oidview.com/mibs/318/PowerNet-MIB.html) internal/battery temperature (.1.3.6.1.4.1.318.1.1.1.2.2.2.0) or [Cisco's typical temperature OIDs](http://tools.cisco.com/Support/SNMP/do/BrowseOID.do?local=en&translate=Translate&objectInput=1.3.6.1.4.1.9.9.13.1.3.1.3) (.1.3.6.1.4.1.9.9.13.1.3.1.3.1 - 3.3). Note that you _should not activate both_ modes at the same time. The reason for this limitation is that the script will keep running for each `pass_persist` entry and they will interfere with each other when updating the temperature. This typically leads to syslog entries like this: temper-python: Exception while updating data: could not release intf 1: Invalid argument ## USB device permissions At least on Debian Wheezy, the default USB device node has permissions to only allow access for root. In the same case, `snmpd` is running as the user `snmpd`. Bam. No access. You might find a corresponding note in syslog. To solve that, the file `99-tempsensor.rules` is a udev rule that allows access to the specific USB devices (with matching VID/PID) by anyone. Install like this: sudo cp etc/99-tempsensor.rules /etc/udev/rules.d/ Then restart. To check for success, find the bus and device IDs of the devices like this: pi@raspi-temper1 ~ $ lsusb | grep "0c45:7401" Bus 001 Device 004: ID 0c45:7401 Microdia Bus 001 Device 005: ID 0c45:7401 Microdia pi@raspi-temper1 ~ $ ls -l /dev/usb* crw------- 1 root root 189, 0 Jan 1 1970 /dev/usbdev1.1 crw------- 1 root root 189, 1 Jan 1 1970 /dev/usbdev1.2 crw------- 1 root root 189, 2 Jan 1 1970 /dev/usbdev1.3 crw-rw-rwT 1 root root 189, 3 Jan 1 1970 /dev/usbdev1.4 crw-rw-rwT 1 root root 189, 4 Jan 1 1970 /dev/usbdev1.5 pi@raspi-temper1 ~ $ Note that `/dev/usbdev1.4` and `/dev/usbdev1.5` have permissions for read/write for anyone, including `snmp`. This will work for the passpersist-module running along with `snmpd`. ## What to add to snmpd.conf To emulate an APC Battery/Internal temperature value, add something like this to snmpd.conf. The highest of all measured temperatures in degrees Celsius as an integer is reported. pass_persist .1.3.6.1.4.1.318.1.1.1.2.2.2 /usr/local/bin/temper-snmp Alternatively, emulate a Cisco device's temperature information with the following. The first three detected devices will be reported as ..13.1.3.1.3.1, ..3.2 and ..3.3 . The value is the temperature in degree Celsius as an integer. pass_persist .1.3.6.1.4.1.9.9.13.1.3 /usr/local/bin/temper-snmp Add `--testmode` to the line (as an option to `snmp.py` to enable a mode where APC reports 99°C and Cisco OIDs report 97, 98 and 99°C respectively. No actual devices need to be installed but `libusb` and its Python bindings are still required. The path `/usr/local/bin/` is correct if the installation using `python setup.py install` did install the scripts there. If you prefer not to install them, find and use the `temper/snmp.py` file. ## Troubleshooting NetSNMP-interaction The error reporting of NetSNMP is underwhelming to say the least. Expect every error to fail silently without a chance to find the source. `snmp.py` reports some simple information to syslog with an ident string of `temper-python` and a facility of `LOG_DAEMON`. So this should give you the available debug information: sudo tail -f /var/log/syslog | grep temper-python Try stopping the snmpd daemon and starting it with logging to the console: sudo service snmpd stop sudo snmpd -f It will _not_ start the passpersist-process for `snmp.py` immediately but on the first request for the activated OIDs. This also means that the first `snmpget` you try may fail like this: iso.3.6.1.4.1.9.9.13.1.3.1.3.2 = No Such Instance currently exists at this OID To test the reporting, try this (twice if it first reports No Such Instance): snmpget -c public -v 2c localhost .1.3.6.1.4.1.9.9.13.1.3.1.3.1 # Cisco #1 snmpget -c public -v 2c localhost .1.3.6.1.4.1.9.9.13.1.3.1.3.2 # Cisco #2 snmpget -c public -v 2c localhost .1.3.6.1.4.1.9.9.13.1.3.1.3.3 # Cisco #3 snmpget -c public -v 2c localhost .1.3.6.1.4.1.318.1.1.1.2.2.2.0 # APC When NetSNMP starts the instance (upon first `snmpget`), you should see something like this in syslog: Jan 6 16:01:51 raspi-temper1 temper-python: Found 2 thermometer devices. Jan 6 16:01:51 raspi-temper1 temper-python: Initial temperature of device #0: 22.2 degree celsius Jan 6 16:01:51 raspi-temper1 temper-python: Initial temperature of device #1: 10.9 degree celsius If you don't even see this, maybe the script has a problem and quits with an exception. Try running it manually and mimik a passpersist-request (`->` means you should enter the rest of the line): -> sudo temper/snmp.py -> PING <- PONG -> get -> .1.3.6.1.4.1.318.1.1.1.2.2.2.0 <- .1.3.6.1.4.1.318.1.1.1.2.2.2.0 <- INTEGER <- 22.25 If you have a problem with the USB side and want to test SNMP, run the script with `--testmode`. # Using MQTT While temper-python does not directly support MQTT, it is fairly straightforeward to push the temperature values collected to a MQTT broker periodically, so they may be integrated in for example Home-Assistant. In the below example we will show how to push data to a Mosquitto MQTT broker using a small bash script and a CRON job. The setup was tested with temper-python installed on a RaspberryPi running Rasbian Buster and a Mosquitto MQTT broker installed as part of Home-Assistant. In this example we will publish one specific temperature value for one specific device, for example the temperatue in Celcius for device 0 To test this, type on your console: $ /usr/local/bin/temper-poll -c -s 0 1.9 As you can see because of the "-c" option, temper-poll will present a single temperature value in degrees Celcius. To get degrees Farenheit, use option "-f" The "-s 0" option makes sure temper-poll only looks at Device #0 We now need to install the Mosquitto client on the device where you installed temper-python. This will provide the mosquitto_pub client which we will use to push towards the MQTT broker sudo apt-get install mosquitto-clients To start pushing a value to your MQTT broker, you also need to know the MQTT server IP adress and optionally a username and password. A mosquitto_pub command looks something like this: /usr/bin/mosquitto_pub -h MQTT_IP -m "Some message" -t MQTT_TOPIC -u MQTT_USERNAME -P MQTT_PASSWORD If you need more paramaters, have a look at the output of mosquitto_pub --help If needed, use the "-d" option for mosquitto_pub, which will print debug output about the connection. A successful connection debug print should look like: pi@raspberrypi:~ $ /usr/bin/mosquitto_pub -h 10.0.0.* -m "foobar" -t home-assistant/temper_schuur/temperature -u ****** -P ****** -d Client mosqpub|2107-raspberryp sending CONNECT Client mosqpub|2107-raspberryp received CONNACK (0) Client mosqpub|2107-raspberryp sending PUBLISH (d0, q0, r0, m1, 'home-assistant/temper_schuur/temperature', ... (0 bytes)) Client mosqpub|2107-raspberryp sending DISCONNECT We will now combine the two using a small bash script called "temper-push-mqtt". First create the script, then make it executable. sudo touch /usr/local/bin/temper-push-mqtt sudo chmod a+x /usr/local/bin/temper-push-mqtt sudo nano /usr/local/bin/temper-push-mqtt The script should contain: #! /bin/bash T=$(/usr/local/bin/temper-poll -c -s 0) /usr/bin/mosquitto_pub -h MQTT_IP -m "${T}" -t MQTT_TOPIC -u MQTT_USER -P MQTT_PASSWORD If you need other parameters for temper-poll, replace them here. Also replace all MQTT_* values with proper values for you local setup. If you are using Home-Assistant you should add a sensor to you setup by defining it in configuration.yaml: sensor: - platform: mqtt name: "Temperatuur Schuur" state_topic: "home-assistant/temper_schuur/temperature" unit_of_measurement: "°C" Make sure the state_topic value matches the MQTT_TOPIC value in the temper-push-mqtt script Finally, to make sure we get periodic data, we create a cron job to run the script every 5 minutes sudo crontab -e To start a new crontab, which should contain */5 * * * * /usr/local/bin/temper-push-mqtt > /var/log/cron_temper-push-mqtt.log 2>&1 The above cronjob will run the temper-push-mqtt script every 5 minutes and will log any issues to a logfile /var/log/cron_temper-push-mqtt.log # Note on multiple device usage The devices I have seen do not have any way to identify them. The serial number is 0. There is no way (and this driver does not make any attempt) to present a persistent ordering among the USB devices. The effective order is the one that `libusb` presents. That seems to be based on the enumeration order of the devices. That in turn [seems to be](http://osr507doc.sco.com/en/man/html.HW/usb.HW.html#USBdevID) based primarily on the physical ordering in the root hub -> hub port hierarchy on bootup. But if you unplug and replug the device (or it gets detached due to a glitch and is redetected) then the order of the devices may be changed. If that happens, your temperature readings will change and you cannot say which device belongs to what OID if you are using SNMP. Long story short: Only use the device order if the USB bus is stable and you reboot after any plugging on the device. Even then, you are not safe. Sorry. ## Note by GM3D Since calibration parameters must be set per each device, we need some way to identify them physically. As mentioned above, the serial number for all TEMPer devices is zero, so there is no true way to tell which is which programmatically. The USB device number does not work either since it changes every time you reboot the machine or plug/unplug the device. The way that possibly can work is identifying them by the combination of the bus number and the USB port (possibly a chain of ports, if you have hubs in between), which is what I am doing for now. This information is basically the same with what you can get with `lsusb -t` and is based on the information in the sysfs directory `/sys/bus/usb/devices` (see below). So far I am assuming this scheme is persistent enough for regular use cases, but even the bus number may change in some cases like - for example - if your machine is a tablet like machine and you hotplug it to a keyboard dock with a USB root hub in it. In such case you will need to re-run `lsusb` and adjust the bus-port numbers in the configuration file accordingly. At the moment I have no clue about SNMP OID persistence. # Calibration parameters You can have parameters in the configuration file `/etc/temper.conf` for each of your TEMPer device to calibrate its value with simple linear formula. If there is not this file on your machine it's fine, calibration is just skipped. The same if the program can't find a matching line with the actual device on the system. Format of calibration lines in `/etc/temper.conf` is: n-m(.m)* : scale = a, offset = b where `n` is the USB bus number and `m` is (possibly a chain of) the USB port(s) which your TEMPer device is plugged on. `a` and `b` are some floating values decided by experiment, we will come back to this later, first let me describe how n and m can be decided for your device. You will need to use `lsusb` command in usbutils package to decide `n` and `m`. Use `lsusb` with and without `-t` option. For example, assume the following outputs; $ lsusb Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 016: ID 0c45:7401 Microdia Bus 001 Device 015: ID 1a40:0101 TERMINUS TECHNOLOGY INC. USB-2.0 4-Port HUB Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub $ lsusb -t /: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=orion-ehci/1p, 480M /: Bus 01.Port 1: Dev 1, Class=root_hub, Driver=orion-ehci/1p, 480M |__ Port 4: Dev 15, If 0, Class=hub, Driver=hub/4p, 12M |__ Port 3: Dev 16, If 0, Class=HID, Driver=usbhid, 1.5M |__ Port 3: Dev 16, If 1, Class=HID, Driver=usbhid, 1.5M First output tells you your TEMPer device (0c45:7401 Microdia) is on the bus 1 and has (just currently, it may change time to time, even if you don't move it around) device ID = 16. Now look at the second output. Looking at this tree, your TEMPer device (Dev 16) on the bus 01 is connected to your pc through two ports, port 4 and port 3. Don't worry about two devices having the same Dev ID = 16, they both belong to a single TEMPer device (it uses two USB interfaces by default, which is normal). So in this example, `n = 1` and `m = 4.3`; thus the config file should be like 1-4.3: scale = a, offset = b with `a` and `b` replaced with the actual values which you will need to measure and calculate for your own TEMPer device. These values are used in the formula y = a * x + b where * `y`: calibrated temperature (in Celsius), * `x`: raw temperature read from your TEMPer device (in Celsius). You will need to find appropriate values for `a` and `b` for your TEMPer device by doing some experiment and basic math. Either comparing it with another thermometer which you can rely on or measuring two temperatures which you already know ... like iced water and boiling water, but make sure in the latter case that you seal your TEMPer device firmly in a plastic bag or something, since it is NOT waterproof! To find out bus and port numbers, you can also try running temper-poll with -p option, which will contain information in the form (bus 1 - port 4.3) in the above example. This might be actually easier than looking at the `lsusb` outputs, as long as it works. # Origins The USB interaction pattern is extracted from [here](http://www.isp-sl.com/pcsensor-1.0.0.tgz) as seen on [Google+](https://plus.google.com/105569853186899442987/posts/N9T7xAjEtyF). # Compatibility with Python versions This should work on Python 3.7 and above. It was tested with Python 3.7, 3.8, 3.9, 3.10, 3.11, 3.12. # Authors * Original rewrite by Philipp Adelt * Additional work by Brian Cline * Calibration code by Joji Monma (@GM3D on Github) * Munin plugin by Alexander Schier (@allo- on Github) * PyPI package work and rewrite to `libusb1` by James Stewart (@amorphic on Github) * Reduced kernel messages, support multiple sensors, and support TEMPer1F_V1.3 by Philip Jay (@ps-jay on Github) * Python 3 compatibility and rewrite of cli.py to use argparse by Will Furnass (@willfurnass on Github) * TEMPerV1.4 support by Christian von Roques (@roques on Github) * Pytest and architecture improvement by Dave Thompson (@davet2001 on Github). padelt-temper-python-67d544d/etc/000077500000000000000000000000001454113557000167175ustar00rootroot00000000000000padelt-temper-python-67d544d/etc/99-tempsensor.rules000066400000000000000000000004401454113557000224270ustar00rootroot00000000000000SUBSYSTEMS=="usb", ACTION=="add", ATTRS{idVendor}=="0c45", ATTRS{idProduct}=="7401", MODE="666" SUBSYSTEMS=="usb", ACTION=="add", ATTRS{idVendor}=="0c45", ATTRS{idProduct}=="7402", MODE="666" SUBSYSTEMS=="usb", ACTION=="add", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="e025", MODE="666" padelt-temper-python-67d544d/etc/munin-temperature000077500000000000000000000031411454113557000223250ustar00rootroot00000000000000#!/usr/bin/python # encoding: utf-8 # # munin-plugin for temper # # Copyright 2013 Alexander Schier # # This code is licensed under the GNU public license (GPL). See LICENSE.md for details. #%# capabilities=autoconf from __future__ import print_function import sys def get_handler(): from temperusb.temper import TemperHandler return TemperHandler() def autoconf(): try: handler = get_handler() except ImportError: print ("no (temper-python package is not installed)") else: if len(handler.get_devices()): print ("yes") else: print ("no (No devices found)") def config(): handler = get_handler() print ("graph_title Temperature") print ("graph_vlabel Degrees Celsius") print ("graph_category sensors") for device in handler.get_devices(): port = device.get_ports() port_name = str(port).replace('.', '_') print ("temp_" + port_name + ".label Port {0:s} Temperature".format(str(port))) def fetch(): handler = get_handler() for device in handler.get_devices(): port = device.get_ports() port_name = str(port).replace('.', '_') try: temp = device.get_temperature() except Exception: temp = 'U' print ("temp_" + port_name + ".value {0:f}".format(temp)) def main(): if len(sys.argv) == 2: arg = sys.argv[1] if arg == 'autoconf': autoconf() elif arg == 'config': config() else: fetch() sys.exit(0) if __name__ == '__main__': main() padelt-temper-python-67d544d/requirements.txt000066400000000000000000000000151454113557000214240ustar00rootroot00000000000000pyusb==1.2.1 padelt-temper-python-67d544d/requirements_test.txt000066400000000000000000000000761454113557000224720ustar00rootroot00000000000000# Dependencies for running tests. pyusb==1.2.1 pytest==7.4.3 padelt-temper-python-67d544d/scripts/000077500000000000000000000000001454113557000176335ustar00rootroot00000000000000padelt-temper-python-67d544d/scripts/publish_to_pypi.sh000077500000000000000000000017051454113557000234060ustar00rootroot00000000000000#!/bin/bash # Script to automate publishing to pypi # Dave T 2023-12-21 pypi_config_file=~/.pypirc pip install twine if [ ! -f dist/*.tar.gz ]; then echo "No releases found. Please run python3 -m setup.py sdist" exit fi twine check dist/* echo "Ready to publish." echo "Default is publishing to testpypi." read -r -p "If you are fully ready, please publish to pypi by typing 'thisisnotatest': " response echo "response=$response" if [ "$response" = "thisisnotatest" ]; then repository=pypi else repository=testpypi fi if [ -f $pypi_config_file ]; then echo "Using $pypi_config_file for API keys" else echo "$pypi_config_file not found, please paste pypi API token below:" read twine_api_key export TWINE_USERNAME=__token__ export TWINE_PASSWORD=$twine_api_key fi echo "Publishing to $repository..." twine upload --repository $repository dist/* echo "Publishing complete!" echo echo "Don't forget to tag this release!"padelt-temper-python-67d544d/setup.py000066400000000000000000000016161454113557000176620ustar00rootroot00000000000000from io import open from setuptools import setup setup( name='temperusb', author='Philipp Adelt', author_email='autosort-github@philipp.adelt.net ', url='https://github.com/padelt/temper-python', version='1.6.1', description='Reads temperature from TEMPerV1 devices (USB 0c45:7401)', long_description=open('README.md', encoding='utf-8').read(), long_description_content_type='text/markdown', packages=['temperusb'], install_requires=[ 'pyusb>=1.0.0rc1', ], entry_points={ 'console_scripts': [ 'temper-poll = temperusb.cli:main', 'temper-snmp = temperusb.snmp:main' ] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Programming Language :: Python :: 3', ], ) padelt-temper-python-67d544d/temperusb/000077500000000000000000000000001454113557000201525ustar00rootroot00000000000000padelt-temper-python-67d544d/temperusb/__init__.py000066400000000000000000000000601454113557000222570ustar00rootroot00000000000000from .temper import TemperDevice, TemperHandler padelt-temper-python-67d544d/temperusb/cli.py000066400000000000000000000074401454113557000213000ustar00rootroot00000000000000# encoding: utf-8 from __future__ import print_function, absolute_import import argparse import logging from .temper import TemperHandler def parse_args(): descr = "Temperature data from a TEMPer v1.2/v1.3 sensor." parser = argparse.ArgumentParser(description=descr) parser.add_argument("-p", "--disp_ports", action='store_true', help="Display ports") units = parser.add_mutually_exclusive_group(required=False) units.add_argument("-c", "--celsius", action='store_true', help="Quiet: just degrees celcius as decimal") units.add_argument("-f", "--fahrenheit", action='store_true', help="Quiet: just degrees fahrenheit as decimal") units.add_argument("-H", "--humidity", action='store_true', help="Quiet: just percentage relative humidity as decimal") parser.add_argument("-s", "--sensor_ids", choices=['0', '1', 'all'], help="IDs of sensors to use on the device " + "(multisensor devices only)", default='0') parser.add_argument("-S", "--sensor_count", type=int, help="Override auto-detected number of sensors on the device") parser.add_argument("-v", "--verbose", action='store_true', help="Verbose: display all debug information") args = parser.parse_args() return args def main(): args = parse_args() quiet = args.celsius or args.fahrenheit or args.humidity lvl = logging.ERROR if quiet else logging.WARNING if args.verbose: lvl = logging.DEBUG logging.basicConfig(level = lvl) th = TemperHandler() devs = th.get_devices() if not quiet: print("Found %i devices" % len(devs)) readings = [] for dev in devs: if args.sensor_count is not None: # Override auto-detection from args dev.set_sensor_count(int(args.sensor_count)) if args.sensor_ids == 'all': sensors = range(dev.get_sensor_count()) else: sensors = [int(args.sensor_ids)] temperatures = dev.get_temperatures(sensors=sensors) humidities = dev.get_humidity(sensors=sensors) combinations = {} for k, v in temperatures.items(): c = v.copy() try: c.update(humidities[k]) except: pass combinations[k] = c readings.append(combinations) for i, reading in enumerate(readings): output = '' if quiet: if args.celsius: dict_key = 'temperature_c' elif args.fahrenheit: dict_key = 'temperature_f' elif args.humidity: dict_key = 'humidity_pc' for sensor in sorted(reading): output += '%0.1f; ' % reading[sensor][dict_key] output = output[0:len(output) - 2] else: portinfo = '' tempinfo = '' huminfo = '' for sensor in sorted(reading): if args.disp_ports and portinfo == '': portinfo = " (bus %(bus)s - port %(ports)s)" % reading[sensor] try: tempinfo += '%0.1f°C %0.1f°F; ' % ( reading[sensor]['temperature_c'], reading[sensor]['temperature_f'], ) except: pass try: huminfo += '%0.1f%%RH; ' % (reading[sensor]['humidity_pc']) except: pass tempinfo = tempinfo[0:len(output) - 2] huminfo = huminfo[0:len(output) - 2] output = 'Device #%i%s: %s %s' % (i, portinfo, tempinfo, huminfo) print(output) if __name__ == '__main__': main() padelt-temper-python-67d544d/temperusb/device_library.py000066400000000000000000000055741454113557000235220ustar00rootroot00000000000000# encoding: utf-8 # # TEMPer USB temperature/humidty sensor device driver settings. # Handles devices reporting themselves as USB VID/PID 0C45:7401 (mine also says # RDing TEMPerV1.2). # # Copyright 2012-2020 Philipp Adelt and contributors. # # This code is licensed under the GNU public license (GPL). See LICENSE.md for # details. from enum import Enum class TemperType(Enum): FM75 = 0 SI7021 = 1 class TemperConfig: def __init__( self, temp_sens_offsets: list, hum_sens_offsets: list = None, type: TemperType = TemperType.FM75, ): self.temp_sens_offsets = temp_sens_offsets self.hum_sens_offsets = hum_sens_offsets self.type = type DEVICE_LIBRARY = { "TEMPer2V1.3": TemperConfig( temp_sens_offsets=[2, 4], hum_sens_offsets=None, type=TemperType.FM75, ), "TEMPerV1.2": TemperConfig( temp_sens_offsets=[2], hum_sens_offsets=None, type=TemperType.FM75, ), "TEMPerV1.4": TemperConfig( temp_sens_offsets=[2], hum_sens_offsets=None, type=TemperType.FM75, ), "TEMPer1F_V1.3": TemperConfig( # Has only 1 sensor at offset 4 temp_sens_offsets=[4], hum_sens_offsets=None, type=TemperType.FM75, ), "TEMPERHUM1V1.2": TemperConfig( temp_sens_offsets=[2], hum_sens_offsets=[4], type=TemperType.SI7021, ), "TEMPERHUM1V1.3": TemperConfig( temp_sens_offsets=[2], hum_sens_offsets=[4], type=TemperType.SI7021, ), "TEMPerHumiV1.0": TemperConfig( temp_sens_offsets=[2], hum_sens_offsets=[4], type=TemperType.FM75, ), "TEMPerHumiV1.1": TemperConfig( temp_sens_offsets=[2], hum_sens_offsets=[4], type=TemperType.FM75, ), "TEMPer1F_H1_V1.4": TemperConfig( temp_sens_offsets=[2], hum_sens_offsets=[4], type=TemperType.FM75, ), "TEMPerNTC1.O": TemperConfig( temp_sens_offsets=[2, 4, 6], hum_sens_offsets=None, type=TemperType.FM75, ), "TEMPer1V1.4": TemperConfig( temp_sens_offsets=[2], hum_sens_offsets=None, type=TemperType.FM75, ), "TEMPer2_V3.7": TemperConfig( temp_sens_offsets=[2, 10], hum_sens_offsets=None, type=TemperType.FM75, ), "TEMPer2V1.4": TemperConfig( temp_sens_offsets=[2], hum_sens_offsets=None, type=TemperType.FM75, ), # The config used if the sensor type is not recognised. # If your sensor is working but showing as unrecognised, please # add a new entry above based on "generic_fm75" below, and submit # a PR to https://github.com/padelt/temper-python/pulls "generic_fm75": TemperConfig( temp_sens_offsets=[2, 4], hum_sens_offsets=None, type=TemperType.FM75, ), } padelt-temper-python-67d544d/temperusb/snmp.py000066400000000000000000000070341454113557000215050ustar00rootroot00000000000000# encoding: utf-8 # # Run snmp_temper.py as a pass-persist module for NetSNMP. # See README.md for instructions. # # Copyright 2012-2020 Philipp Adelt # # This code is licensed under the GNU public license (GPL). See LICENSE.md for details. import os import sys import syslog import threading import snmp_passpersist as snmp from temperusb.temper import TemperHandler, TemperDevice ERROR_TEMPERATURE = 9999 def _unbuffered_handle(fd): return os.fdopen(fd.fileno(), 'w', 0) class LogWriter(): def __init__(self, ident='temper-python', facility=syslog.LOG_DAEMON): syslog.openlog(ident, 0, facility) def write_log(self, message, prio=syslog.LOG_INFO): syslog.syslog(prio, message) class Updater(): def __init__(self, pp, logger, testmode=False): self.logger = logger self.pp = pp self.testmode = testmode self.usb_lock = threading.Lock() # used to stop reinitialization interfering with update-thread self._initialize() def _initialize(self): with self.usb_lock: try: self.th = TemperHandler() self.devs = self.th.get_devices() self.logger.write_log('Found %i thermometer devices.' % len(self.devs)) for i, d in enumerate(self.devs): self.logger.write_log('Initial temperature of device #%i: %0.1f degree celsius' % (i, d.get_temperature())) except Exception as e: self.logger.write_log('Exception while initializing: %s' % str(e)) def _reinitialize(self): # Tries to close all known devices and starts over. self.logger.write_log('Reinitializing devices') with self.usb_lock: for i,d in enumerate(self.devs): try: d.close() except Exception as e: self.logger.write_log('Exception closing device #%i: %s' % (i, str(e))) self._initialize() def update(self): if self.testmode: # APC Internal/Battery Temperature self.pp.add_int('318.1.1.1.2.2.2.0', 99) # Cisco devices temperature OIDs self.pp.add_int('9.9.13.1.3.1.3.1', 97) self.pp.add_int('9.9.13.1.3.1.3.2', 98) self.pp.add_int('9.9.13.1.3.1.3.3', 99) else: try: with self.usb_lock: temperatures = [d.get_temperature() for d in self.devs] self.pp.add_int('318.1.1.1.2.2.2.0', int(max(temperatures))) for i, temperature in enumerate(temperatures[:3]): # use max. first 3 devices self.pp.add_int('9.9.13.1.3.1.3.%i' % (i+1), int(temperature)) except Exception as e: self.logger.write_log('Exception while updating data: %s' % str(e)) # Report an exceptionally large temperature to set off all alarms. # snmp_passpersist does not expose an API to remove an OID. for oid in ('318.1.1.1.2.2.2.0', '9.9.13.1.3.1.3.1', '9.9.13.1.3.1.3.2', '9.9.13.1.3.1.3.3'): self.pp.add_int(oid, ERROR_TEMPERATURE) self.logger.write_log('Starting reinitialize after error on update') self._reinitialize() def main(): sys.stdout = _unbuffered_handle(sys.stdout) pp = snmp.PassPersist(".1.3.6.1.4.1") logger = LogWriter() upd = Updater(pp, logger, testmode=('--testmode' in sys.argv)) pp.start(upd.update, 5) # update every 5s if __name__ == '__main__': main() padelt-temper-python-67d544d/temperusb/temper.conf.sample000066400000000000000000000014761454113557000236050ustar00rootroot00000000000000# configuration for calibrating your TEMPer device. # example line: #1-1.2: scale = 0.95, offset = -2.2 # the above example indicates the output y of temper-poll and SNMP for # your TEMPer device which is on USB bus 1 through port 1 and port 2 will be # calculated with y = 0.95 * x - 2.2, where x is the raw uncalibrated output # from the device (in Celsius). # Default values are scale = 1.0 and offset = 0.0, which simply means y = x. # Using this bus-(chain of)port(s) combination, you can uniquely specify your # device. Also you can have lines for multiple TEMPer device since they are # distinguishable with this scheme. # Don't just uncomment the example line, you need the specific correct values # for yourself. # To decide what these numbers will be in your case, see calibration # parameters section in README.md. padelt-temper-python-67d544d/temperusb/temper.py000066400000000000000000000363461454113557000220340ustar00rootroot00000000000000# encoding: utf-8 # # Handles devices reporting themselves as USB VID/PID 0C45:7401 (mine also says # RDing TEMPerV1.2). # # Copyright 2012-2020 Philipp Adelt and contributors. # # This code is licensed under the GNU public license (GPL). See LICENSE.md for # details. import usb import os import re import logging import struct from .device_library import DEVICE_LIBRARY, TemperType, TemperConfig VIDPIDS = [ (0x0c45, 0x7401), (0x0c45, 0x7402), (0x1a86, 0xe025), ] REQ_INT_LEN = 8 ENDPOINT = 0x82 INTERFACE = 1 CONFIG_NO = 1 TIMEOUT = 5000 USB_PORTS_STR = r'^\s*(\d+)-(\d+(?:\.\d+)*)' CALIB_LINE_STR = USB_PORTS_STR +\ r'\s*:\s*scale\s*=\s*([+|-]?\d*\.\d+)\s*,\s*offset\s*=\s*([+|-]?\d*\.\d+)' USB_SYS_PREFIX = '/sys/bus/usb/devices/' COMMANDS = { 'temp': b'\x01\x80\x33\x01\x00\x00\x00\x00', 'ini1': b'\x01\x82\x77\x01\x00\x00\x00\x00', 'ini2': b'\x01\x86\xff\x01\x00\x00\x00\x00', } LOGGER = logging.getLogger(__name__) CONTRIBUTE_URL = "https://github.com/padelt/temper-python/issues" def readattr(path, name): """ Read attribute from sysfs and return as string """ try: f = open(USB_SYS_PREFIX + path + "/" + name) return f.readline().rstrip("\n") except IOError: return None def find_ports(device): """ Find the port chain a device is plugged on. This is done by searching sysfs for a device that matches the device bus/address combination. Useful when the underlying usb lib does not return device.port_number for whatever reason. """ bus_id = device.bus dev_id = device.address for dirent in os.listdir(USB_SYS_PREFIX): matches = re.match(USB_PORTS_STR + '$', dirent) if matches: bus_str = readattr(dirent, 'busnum') if bus_str: busnum = float(bus_str) else: busnum = None dev_str = readattr(dirent, 'devnum') if dev_str: devnum = float(dev_str) else: devnum = None if busnum == bus_id and devnum == dev_id: return str(matches.groups()[1]) class TemperDevice(object): """ A TEMPer USB thermometer. """ def __init__(self, device, sensor_count=1): self.set_sensor_count(sensor_count) self._device = device self._bus = device.bus self._ports = getattr(device, 'port_number', None) if self._ports == None: self._ports = find_ports(device) self.set_calibration_data() try: # Try to trigger a USB permission issue early so the # user is not presented with seemingly unrelated error message. # https://github.com/padelt/temper-python/issues/63 productname = self._device.product except ValueError as e: if 'langid' in str(e): raise usb.core.USBError("Error reading langids from device. "+ "This might be a permission issue. Please check that the device "+ "node for your TEMPer devices can be read and written by the "+ "user running this code. The temperusb README.md contains hints "+ "about how to fix this. Search for 'USB device permissions'.") config = DEVICE_LIBRARY.get(productname) if config is None: LOGGER.warning( "Unrecognised sensor type '%s'. " "Trying to guess communication format. " "Please add the configuration to 'device_library.py' " "and submit to %s to benefit other users." % (self._device.product, CONTRIBUTE_URL) ) config = DEVICE_LIBRARY["generic_fm75"] self.temp_sens_offsets = config.temp_sens_offsets self.hum_sens_offsets = config.hum_sens_offsets self.type = config.type self.set_sensor_count(self.lookup_sensor_count()) LOGGER.debug('Found device | Bus:{0} Ports:{1} SensorCount:{2}'.format( self._bus, self._ports, self._sensor_count)) def set_calibration_data(self, scale=None, offset=None): """ Set device calibration data based on settings in /etc/temper.conf. """ if scale is not None and offset is not None: self._scale = scale self._offset = offset elif scale is None and offset is None: self._scale = 1.0 self._offset = 0.0 try: f = open('/etc/temper.conf', 'r') except IOError: f = None if f: lines = f.read().split('\n') f.close() for line in lines: matches = re.match(CALIB_LINE_STR, line) if matches: bus = int(matches.groups()[0]) ports = matches.groups()[1] scale = float(matches.groups()[2]) offset = float(matches.groups()[3]) if (str(ports) == str(self._ports)) and (str(bus) == str(self._bus)): self._scale = scale self._offset = offset else: raise RuntimeError("Must set both scale and offset, or neither") def lookup_offset(self, sensor): """ Lookup the number of sensors on the device by product name. """ return self.temp_sens_offsets[sensor] def lookup_humidity_offset(self, sensor): """ Get the offset of the humidity data. """ if self.hum_sens_offsets: return self.hum_sens_offsets[sensor] else: return None def lookup_sensor_count(self): """ Lookup the number of sensors on the device by product name. """ return len(self.temp_sens_offsets) def get_sensor_count(self): """ Get number of sensors on the device. """ return self._sensor_count def set_sensor_count(self, count): """ Set number of sensors on the device. To do: revamp /etc/temper.conf file to include this data. """ # Currently this only supports 1 and 2 sensor models. # If you have the 8 sensor model, please contribute to the # discussion here: https://github.com/padelt/temper-python/issues if count not in [1, 2, 3]: raise ValueError('Only sensor_count of 1-3 supported') self._sensor_count = int(count) def get_product(self): """ Get device product name. """ return self._device.product def get_ports(self): """ Get device USB ports. """ if self._ports: return self._ports return '' def get_bus(self): """ Get device USB bus. """ if self._bus: return self._bus return '' def get_data(self, reset_device=False): """ Get data from the USB device. """ try: if reset_device: self._device.reset() # detach kernel driver from both interfaces if attached, so we can set_configuration() for interface in [0,1]: if self._device.is_kernel_driver_active(interface): LOGGER.debug('Detaching kernel driver for interface %d ' 'of %r on ports %r', interface, self._device, self._ports) self._device.detach_kernel_driver(interface) self._device.set_configuration() # Prevent kernel message: # "usbfs: process (python) did not claim interface x before use" # This will become unnecessary once pull-request #124 for # PyUSB has been accepted and we depend on a fixed release # of PyUSB. Until then, and even with the fix applied, it # does not hurt to explicitly claim the interface. usb.util.claim_interface(self._device, INTERFACE) # Turns out we don't actually need that ctrl_transfer. # Disabling this reduces number of USBErrors from ~7/30 to 0! #self._device.ctrl_transfer(bmRequestType=0x21, bRequest=0x09, # wValue=0x0201, wIndex=0x00, data_or_wLength='\x01\x01', # timeout=TIMEOUT) # Magic: Our TEMPerV1.4 likes to be asked twice. When # only asked once, it get's stuck on the next access and # requires a reset. self._control_transfer(COMMANDS['temp']) self._interrupt_read() # Turns out a whole lot of that magic seems unnecessary. #self._control_transfer(COMMANDS['ini1']) #self._interrupt_read() #self._control_transfer(COMMANDS['ini2']) #self._interrupt_read() #self._interrupt_read() # Get temperature self._control_transfer(COMMANDS['temp']) temp_data = self._interrupt_read() # Get humidity LOGGER.debug("ID='%s'" % self._device.product) if self.hum_sens_offsets: humidity_data = temp_data else: humidity_data = None # Combine temperature and humidity data data = {'temp_data': temp_data, 'humidity_data': humidity_data} # Be a nice citizen and undo potential interface claiming. # Also see: https://github.com/walac/pyusb/blob/master/docs/tutorial.rst#dont-be-selfish usb.util.dispose_resources(self._device) return data except usb.USBError as err: if not reset_device: LOGGER.warning("Encountered %s, resetting %r and trying again.", err, self._device) return self.get_data(True) # Catch the permissions exception and add our message if "not permitted" in str(err): raise Exception( "Permission problem accessing USB. " "Maybe I need to run as root?") else: LOGGER.error(err) raise def get_temperature(self, format='celsius', sensor=0): """ Get device temperature reading. """ results = self.get_temperatures(sensors=[sensor,]) if format == 'celsius': return results[sensor]['temperature_c'] elif format == 'fahrenheit': return results[sensor]['temperature_f'] elif format == 'millicelsius': return results[sensor]['temperature_mc'] else: raise ValueError("Unknown format") def get_temperatures(self, sensors=None): """ Get device temperature reading. Params: - sensors: optional list of sensors to get a reading for, examples: [0,] - get reading for sensor 0 [0, 1,] - get reading for sensors 0 and 1 None - get readings for all sensors """ _sensors = sensors if _sensors is None: _sensors = list(range(0, self._sensor_count)) if not set(_sensors).issubset(list(range(0, self._sensor_count))): raise ValueError( 'Some or all of the sensors in the list %s are out of range ' 'given a sensor_count of %d. Valid range: %s' % ( _sensors, self._sensor_count, list(range(0, self._sensor_count)), ) ) data = self.get_data() data = data['temp_data'] results = {} # Interpret device response for sensor in _sensors: offset = self.lookup_offset(sensor) if self.type == TemperType.SI7021: celsius = struct.unpack_from('>h', data, offset)[0] * 175.72 / 65536 - 46.85 else: # fm75 (?) type device celsius = struct.unpack_from('>h', data, offset)[0] / 256.0 # Apply scaling and offset (if any) celsius = celsius * self._scale + self._offset LOGGER.debug("T=%.5fC" % celsius) results[sensor] = { 'ports': self.get_ports(), 'bus': self.get_bus(), 'sensor': sensor, 'temperature_f': celsius * 1.8 + 32.0, 'temperature_c': celsius, 'temperature_mc': celsius * 1000, 'temperature_k': celsius + 273.15, } return results def get_humidity(self, sensors=None): """ Get device humidity reading. Params: - sensors: optional list of sensors to get a reading for, examples: [0,] - get reading for sensor 0 [0, 1,] - get reading for sensors 0 and 1 None - get readings for all sensors """ _sensors = sensors if _sensors is None: _sensors = list(range(0, self._sensor_count)) if not set(_sensors).issubset(list(range(0, self._sensor_count))): raise ValueError( 'Some or all of the sensors in the list %s are out of range ' 'given a sensor_count of %d. Valid range: %s' % ( _sensors, self._sensor_count, list(range(0, self._sensor_count)), ) ) data = self.get_data() data = data['humidity_data'] results = {} # Interpret device response for sensor in _sensors: offset = self.lookup_humidity_offset(sensor) if offset is None: continue if self.type == TemperType.SI7021: humidity = (struct.unpack_from('>H', data, offset)[0] * 125) / 65536 -6 else: #fm75 (?) type device humidity = (struct.unpack_from('>H', data, offset)[0] * 32) / 1000.0 LOGGER.debug("RH=%.5f%%" % humidity) results[sensor] = { 'ports': self.get_ports(), 'bus': self.get_bus(), 'sensor': sensor, 'humidity_pc': humidity, } return results def _control_transfer(self, data): """ Send device a control request with standard parameters and as payload. """ LOGGER.debug('Ctrl transfer: %r', data) self._device.ctrl_transfer(bmRequestType=0x21, bRequest=0x09, wValue=0x0200, wIndex=0x01, data_or_wLength=data, timeout=TIMEOUT) def _interrupt_read(self): """ Read data from device. """ data = self._device.read(ENDPOINT, REQ_INT_LEN, timeout=TIMEOUT) LOGGER.debug('Read data: %r', ' '.join('{:02x}'.format(x) for x in data)) return data def close(self): """Does nothing in this device. Other device types may need to do cleanup here.""" pass class TemperHandler(object): """ Handler for TEMPer USB thermometers. """ def __init__(self): self._devices = [] for vid, pid in VIDPIDS: self._devices += [TemperDevice(device) for device in \ usb.core.find(find_all=True, idVendor=vid, idProduct=pid)] LOGGER.info('Found {0} TEMPer devices'.format(len(self._devices))) def get_devices(self): """ Get a list of all devices attached to this handler """ return self._devices padelt-temper-python-67d544d/tests/000077500000000000000000000000001454113557000173065ustar00rootroot00000000000000padelt-temper-python-67d544d/tests/__init__.py000066400000000000000000000000001454113557000214050ustar00rootroot00000000000000padelt-temper-python-67d544d/tests/test_temper.py000066400000000000000000000134541454113557000222220ustar00rootroot00000000000000""" pytests for temperusb run from the project root with: pytest --cov=temperusb --cov-report term-missing """ import os import pytest import usb from unittest.mock import MagicMock, patch, Mock import temperusb from temperusb.temper import TIMEOUT @pytest.mark.parametrize( [ "productname", # the faked usb device product name "vid", # faked vendor ID "pid", # faked vendor ID "count", # number of sensors we expect to be reported "ctrl_data_in_expected", # the ctrl data we expect to be sent to the (faked) usb device "data_out_raw", # the bytes that the usb device will return (our encoded temps/RHs need to be in here) "temperature_out_expected", # array of temperatures that we are expecting to see decoded. "humidity_out_expected", # array of humidities that we are expecting to see decoded ], [ [ "generic_unmatched", # Default is to assume 2 fm75 style temperature sensors 0x0C45, 0x7401, 2, b"\x01\x80\x33\x01\x00\x00\x00\x00", b"\x00\x00\x20\x1A\x2B\x33", # 0x201A,0x2B33 converts to 32.1C, 43.2C (fm75) [32.1, 43.2], None, ], [ 'TEMPer2V1.3', 0x0c45, 0x7401, 2, b"\x01\x80\x33\x01\x00\x00\x00\x00", b"\x80\x04\x0a\xe0\x15\x00\x1d\x15", # 0x0AE0, 0x1500 converts to 10.9C, 21.0C (fm75) [10.9, 21.0], None, ], [ "TEMPerV1.2", 0x0C45, 0x7401, 1, b"\x01\x80\x33\x01\x00\x00\x00\x00", b"\x00\x00\x20\x1A", # 0x201A converts to 32.1C (fm75) [32.1], None, ], [ "TEMPerV1.4", 0x0C45, 0x7401, 1, b"\x01\x80\x33\x01\x00\x00\x00\x00", b"\x00\x00\x20\x1A", # 0x201A converts to 32.1C (fm75) [32.1], None, ], [ "TEMPer1F_V1.3", # Has 1 sensor at offset 4 0x0C45, 0x7401, 1, b"\x01\x80\x33\x01\x00\x00\x00\x00", b"\x00\x00\x00\x00\x20\x1A", # 0x201A converts to 32.1C (fm75) [32.1], None, ], [ "TEMPERHUM1V1.3", 0x0C45, 0x7401, 1, b"\x01\x80\x33\x01\x00\x00\x00\x00", b"\x00\x00\x56\x2C\xBF\xB1", # 0x562C,0xBFB1 converts to 12.3C,87.6% (si7021) [12.3], [87.6], ], [ "TEMPerHumiV1.0", 0x0C45, 0x7401, 1, b"\x01\x80\x33\x01\x00\x00\x00\x00", b"\x00\x00\x20\x1A\x0C\x0C", # 0x201A,0x0C0C converts to 32.1C,98.7% (fm75) [32.1], [98.7], ], [ "TEMPerHumiV1.1", 0x0C45, 0x7401, 1, b"\x01\x80\x33\x01\x00\x00\x00\x00", b"\x00\x00\x20\x1A\x0C\x0C", # 0x201A,0x0C0C converts to 32.1C,98.7% (fm75) [32.1], [98.7], ], [ "TEMPer1F_H1_V1.4", 0x0C45, 0x7401, 1, b"\x01\x80\x33\x01\x00\x00\x00\x00", b"\x00\x00\x20\x1A\x0C\x0C", # 0x201A,0x0C0C converts to 32.1C,98.7% (fm75) [32.1], [98.7], ], [ "TEMPerNTC1.O", 0x0C45, 0x7401, 3, b"\x01\x80\x33\x01\x00\x00\x00\x00", b"\x00\x00\x20\x1A\x2B\x33\x36\x4D", # 0x201A,0x2B33,0x364D converts to 32.1,43.2,54.3C (fm75) [32.1, 43.2, 54.3], None, ], ], ) def test_TemperDevice( productname, vid, pid, count, ctrl_data_in_expected, data_out_raw, temperature_out_expected, humidity_out_expected, ): """ Patches the underlying usb port call to allow us to verify the data we would be sending, and fake the return data so that we can test the conversion coming back. """ usbdev = Mock(bus="fakebus", product=productname) usbdev.is_kernel_driver_active = MagicMock(return_value=False) def ctrl_transfer_dummy( bmRequestType, bRequest, wValue, wIndex, data_or_wLength, timeout ): assert data_or_wLength == ctrl_data_in_expected assert timeout == TIMEOUT usbdev.ctrl_transfer = MagicMock( bmRequestType=0x21, bRequest=0x09, wValue=0x0200, wIndex=0x01, data_or_wLength=None, timeout=None, side_effect=ctrl_transfer_dummy, ) usbdev.read = Mock(return_value=data_out_raw) def match_pids(find_all, idVendor, idProduct): if idVendor == vid and idProduct == pid: return [usbdev] else: return [] with patch("usb.core.find", side_effect=match_pids, return_value=[usbdev]): th = temperusb.TemperHandler() devs = th.get_devices() # Check that we actually got any devices assert devs != None # Check that we only found one sensor assert len(devs) == 1, "Should be only one sensor type matching" dev = devs[0] # check that the sensor count reported is what we expect assert dev.get_sensor_count() == count # read a temperature results = dev.get_temperatures(None) for i, temperature in enumerate(temperature_out_expected): # check the temperature is what we were expecting. assert results[i]["temperature_c"] == pytest.approx(temperature, 0.01) # if the device is expected to also report humidty if humidity_out_expected: for i, humidity in enumerate(humidity_out_expected): results_h = dev.get_humidity(None) assert results_h[i]["humidity_pc"] == pytest.approx(humidity, 0.1)