Repository: philippelt/netatmo-api-python Branch: master Commit: 1d87aac44a3a Files: 18 Total size: 156.1 KB Directory structure: gitextract_rkwnjby9/ ├── .github/ │ └── workflows/ │ └── lint_python.yml ├── .gitignore ├── .netatmo.credentials ├── LICENSE.txt ├── README.md ├── lnetatmo.py ├── samples/ │ ├── get_direct_camera_snapshot │ ├── graphLast3Days │ ├── printAllLastData.py │ ├── printThermostat.py │ ├── rawAPIsample.py │ ├── simpleLastData.py │ ├── smsAlarm.py │ ├── weather2file.md │ └── weather2file.py ├── setup.cfg ├── setup.py └── usage.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/lint_python.yml ================================================ name: lint_python on: [pull_request, push] jobs: lint_python: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install black codespell flake8 isort pytest pyupgrade - run: black --check . || true - run: codespell --quiet-level=2 || true # --ignore-words-list="" --skip="" - run: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics - run: isort --profile black . || true - run: pip install -r requirements.txt || true - run: pytest . || true - run: shopt -s globstar && pyupgrade --py36-plus **/*.py || true ================================================ FILE: .gitignore ================================================ build/ dist/ lnetatmo.egg-info/ *.pyc __pycache__/ MANIFEST* *.csv *.h5 *.feather *.json *.parquet *.pkl *.xlsx ================================================ FILE: .netatmo.credentials ================================================ { "CLIENT_ID" : "", "CLIENT_SECRET" : "", "REFRESH_TOKEN" : "" } ================================================ FILE: LICENSE.txt ================================================ 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 . ================================================ FILE: README.md ================================================ netatmo-api-python ================== Simple API to access Netatmo weather station data from any python script For more detailed information see http://dev.netatmo.com I have no relation with the netatmo company, I wrote this because I needed it myself, and published it to save time to anyone who would have same needs. There is no longer credential load at library import, credentials are loaded at `ClientAuth` class initialization and a new parameter `credentialFile` allow to specify private name and location for the credential file. It is recommended to use this parameter to specify the location of the credential file using absolute path to be able to be independant of the account used to run the program. >[!CAUTION] > Remember that the program using the library **must** be able to rewrite the credential file to be able to save the new refresh token that netatmo may provide at the authentication step. Check the file permission according to the account the program is running. >[!NOTE] > Several users reported that Netatmo is now asking for a DPO (Data Protection Officer) mail address to deliver application credentials. Netatmo is requesting this to comply with RGPD European regulation for the case of your application would be able to access other customers account and you would hold responsibility to protect others potentially confidential informations. > For most users (if not all) of this library, this is totally useless as we are accessing only OUR devices thus are not concerned by RGPD. You can then put your netatmo account email address, just in case some mail would be sent to it. > It is only an information for the Netatmo records, there is absolutely no use of this information by the library. >[!CAUTION] > There are currently frequent authentication failures with Netatmo servers, returning exception ranging from 500 errors to invalid scope. Please check that you are not facing a transient failure by retrying your code some minutes later before reporting an issue. ### Install ### To install lnetatmo simply run: python setup.py install or pip install lnetatmo Depending on your permissions you might be required to use sudo. It is a single file module, on platforms where you have limited access, you just have to clone the repo and take the lnetatmo.py in the same directory than your main program. Once installed you can simple add lnetatmo to your python scripts by including: import lnetatmo For documentation, see usage ================================================ FILE: lnetatmo.py ================================================ # Published Jan 2013 # Author : Philippe Larduinat, ph.larduinat@wanadoo.fr # Multiple contributors : see https://github.com/philippelt/netatmo-api-python # License : GPL V3 """ This API provides access to the Netatmo weather station or/and other installed devices This package can be used with Python2 or Python3 applications and do not require anything else than standard libraries PythonAPI Netatmo REST data access coding=utf-8 """ import warnings if __name__ == "__main__": warnings.filterwarnings("ignore") # For installation test only from sys import version_info from os import getenv from os.path import expanduser import json, time import logging # Just in case method could change PYTHON3 = version_info.major > 2 # HTTP libraries depends upon Python 2 or 3 if PYTHON3 : import urllib.parse, urllib.request else: from urllib import urlencode import urllib2 ######################## AUTHENTICATION INFORMATION ###################### # To be able to have a program accessing your netatmo data, you have to register your program as # a Netatmo app in your Netatmo account. All you have to do is to give it a name (whatever) and you will be # returned a client_id and secret that your app has to supply to access netatmo servers. # To ease Docker packaging of your application, you can setup your authentication parameters through env variables # Authentication: # 1 - Values defined in environment variables : CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN # 2 - Parameters passed to ClientAuth initialization # 3 - The .netatmo.credentials file in JSON format in your home directory (now mandatory for regular use) # Note that the refresh token being short lived, using envvar will be restricted to speific testing use case ######################################################################### # Common definitions _BASE_URL = "https://api.netatmo.com/" _AUTH_REQ = _BASE_URL + "oauth2/token" _GETMEASURE_REQ = _BASE_URL + "api/getmeasure" _GETSTATIONDATA_REQ = _BASE_URL + "api/getstationsdata" _GETTHERMOSTATDATA_REQ = _BASE_URL + "api/getthermostatsdata" _GETHOMEDATA_REQ = _BASE_URL + "api/gethomedata" _GETCAMERAPICTURE_REQ = _BASE_URL + "api/getcamerapicture" _GETEVENTSUNTIL_REQ = _BASE_URL + "api/geteventsuntil" _HOME_STATUS = _BASE_URL + "api/homestatus" # Used for Home+ Control Devices _GETHOMES_DATA = _BASE_URL + "api/homesdata" # New API _GETHOMECOACH = _BASE_URL + "api/gethomecoachsdata" # #TODO# Undocumented (but would be very usefull) API : Access currently forbidden (403) _POST_UPDATE_HOME_REQ = _BASE_URL + "/api/updatehome" # For presence setting (POST BODY): # _PRES_BODY_REC_SET = "home_id=%s&presence_settings[presence_record_%s]=%s" # (HomeId, DetectionKind, DetectionSetup.index) _PRES_DETECTION_KIND = ("humans", "animals", "vehicles", "movements") _PRES_DETECTION_SETUP = ("ignore", "record", "record & notify") # _PRES_BODY_ALERT_TIME = "home_id=%s&presence_settings[presence_notify_%s]=%s" # (HomeID, "from"|"to", "hh:mm") # Regular (documented) commands (both cameras) _PRES_CDE_GET_SNAP = "/live/snapshot_720.jpg" #TODO# Undocumented (taken from https://github.com/KiboOst/php-NetatmoCameraAPI/blob/master/class/NetatmoCameraAPI.php) # Work with local_url only (undocumented scope control probably) # For Presence camera _PRES_CDE_GET_LIGHT = "/command/floodlight_get_config" # Not working yet, probably due to scope restriction #_PRES_CDE_SET_LIGHT = "/command/floodlight_set_config?config=mode:%s" # "auto"|"on"|"off" # For all cameras _CAM_CHANGE_STATUS = "/command/changestatus?status=%s" # "on"|"off" # Not working yet #_CAM_FTP_ACTIVE = "/command/ftp_set_config?config=on_off:%s" # "on"|"off" #Known TYPE used by Netatmo services + API, there can be more types possible TYPES = { 'BFII' : ["Bticino IP Indoor unit", 'Home + Security'], 'BFIC' : ["Bticino IP Guard station", 'Home + Security'], 'BFIO' : ["Bticino IP Entrance panel", 'Home + Security'], 'BFIS' : ["Bticino Server DES", 'Home + Security'], 'BN3L' : ["Bticino 3rd party light", 'Home+Control'], 'BNAB' : ["Bticino module automatic blind", 'Home+Control'], 'BNAS' : ["Bticino module automatic shutter", 'Home+Control'], 'BNS' : ["Smarther with Netatmo Thermostat", 'Home+Control'], 'BNCU' : ["Bticino Bticino Alarm Central Unit", 'Home + Security'], 'BNCS' : ["Bticino module Controlled Socket", 'Home+Control'], 'BNCX' : ["Bticino Class 300 EOS", 'Home + Security'], 'BNDL' : ["Bticino Doorlock", 'Home + Security'], 'BNEU' : ["Bticino external unit", 'Home + Security'], 'BNFC' : ["Bticino Thermostat", 'Home+Control'], 'BNIL' : ["Bticino intelligent light", 'Home+Control'], 'BNLD' : ["Bticino module lighting dimmer", 'Home+Control'], 'BNMH' : ["Bticino My Home Server 1", 'Home + Security'], # also API Home+Control GATEWAY 'BNMS' : ["Bticino module motorized shade", 'Home+Control'], 'BNSE' : ["Bticino Alarm Sensor", 'Home + Security'], 'BNSL' : ["Bticino Staircase Light", 'Home + Security'], 'BNTH' : ["Bticino Thermostat", 'Home+Control'], 'BNTR' : ["Bticino module towel rail", 'Home+Control'], 'BNXM' : ["Bticino X meter", 'Home+Control'], 'NACamera' : ["indoor camera", 'Home + Security'], 'NACamDoorTag' : ["door tag", 'Home + Security'], 'NAMain' : ["weather station", 'Weather'], 'NAModule1' : ["outdoor unit", 'Weather'], 'NAModule2' : ["wind unit", 'Weather'], 'NAModule3' : ["rain unit", 'Weather'], 'NAModule4' : ["indoor unit", 'Weather'], 'NAPlug' : ["thermostat relais station", 'Energy'], # A smart thermostat exist of a thermostat module and a Relay device # The relay device is also the bridge for thermostat and Valves 'NATherm1' : ["thermostat", 'Energy'], 'NCO' : ["co2 sensor", 'Home + Security'], # The same API as smoke sensor 'NDB' : ["doorbell", 'Home + Security'], 'NOC' : ["outdoor camera", 'Home + Security'], 'NRV' : ["thermostat valves", 'Energy'], # also API Home+Control 'NSD' : ["smoke sensor", 'Home + Security'], 'NHC' : ["home coach", 'Aircare'], 'NIS' : ["indoor sirene", 'Home + Security'], 'NDL' : ["Doorlock", 'Home + Security'], 'NLAO' : ["Magellan Green power remote control on-off", 'Home+Control'], 'NLAS' : ["Magellan Green Power Remote control scenarios", 'Home+Control'], 'NLAV' : ["Wireless Batteryless Shutter Switch", 'Home+Control'], 'NLC' : ["Cable Outlet", 'Home+Control'], 'NLD' : ["Wireless 2 button switch light", 'Home+Control'], 'NLDP' : ["Magellan Pocket Remote", 'Home+Control'], 'NLE' : ["Ecometer", 'Home+Control'], 'NLF' : ["Dimmer Light Switch", 'Home+Control'], 'NLFE' : ["Dimmer Light Switch Evolution", 'Home+Control'], 'NLFN' : ["Dimmer Light with Neutral", 'Home+Control'], 'NLG' : ["Gateway", 'Home+Control'], 'NLGS' : ["Standard DIN Gateway", 'Home+Control'], 'NLIS' : ["Double Switch with Neutral", 'Home+Control'], 'NLIV' : ["1/2 Gangs Shutter Switch", 'Home+Control'], 'NLL' : ["Light Switch with Neutral", 'Home+Control'], 'NLLF' : ["Centralized Ventilation Control", 'Home+Control'], 'NLLV' : ["Roller Shutter Switch with level detection", 'Home+Control'], 'NLM' : ["Light Micromodule", 'Home+Control'], 'NLP' : ["Power Outlet", 'Home+Control'], 'NLPS' : ["Smart Load Shedder", 'Home+Control'], 'NLPC' : ["DIN Energy meter", 'Home+Control'], 'NLPD' : ["Dry contact", 'Home+Control'], 'NLPM' : ["Mobile Socket", 'Home+Control'], 'NLPO' : ["Contactor", 'Home+Control'], 'NLPT' : ["Teleruptor", 'Home+Control'], 'NLT' : ["Magellan Remote Control", 'Home+Control'], 'NLTS' : ["Magellan Remote Motion Sensor", 'Home+Control'], 'NLV' : ["Roller Shutter Switch", 'Home+Control'], 'OTH' : ["Opentherm Thermostat Relay", 'Home+Control'], 'OTM' : ["Smart modulating Thermostat", 'Home+Control'], 'Z3L' : ["Zigbee 3rd party light", 'Home+Control'], 'Z3V' : ["Generic window covering", 'Home+Control'] } # UNITS used by Netatmo services UNITS = { "unit" : { 0: "metric", 1: "imperial" }, "windunit" : { 0: "kph", 1: "mph", 2: "ms", 3: "beaufort", 4: "knot" }, "pressureunit" : { 0: "mbar", 1: "inHg", 2: "mmHg" }, "Health index" : { # Homecoach 0: "Healthy", 1: "Fine", 2: "Fair", 3: "Poor", 4: "Unhealthy" }, "Wifi status" : { # Wifi Signal quality 86: "Bad", 71: "Average", 56: "Good" } } # Logger context logger = logging.getLogger("lnetatmo") class NoDevice( Exception ): """No device available in the user account""" class NoHome( Exception ): """No home defined in the user account""" class AuthFailure( Exception ): """Credentials where rejected by Netatmo (or netatmo server unavailability)""" class OutOfScope( Exception ): """Your current auth scope do not allow access to this resource""" class ClientAuth: """ Request authentication and keep access token available through token method. Renew it automatically if necessary Args: clientId (str): Application clientId delivered by Netatmo on dev.netatmo.com clientSecret (str): Application Secret key delivered by Netatmo on dev.netatmo.com refreshToken (str) : Scoped refresh token """ def __init__(self, clientId=None, clientSecret=None, refreshToken=None, credentialFile=None): # replace values with content of env variables if defined clientId = getenv("CLIENT_ID", clientId) clientSecret = getenv("CLIENT_SECRET", clientSecret) refreshToken = getenv("REFRESH_TOKEN", refreshToken) # Look for credentials in file if not already provided # Note: this file will be rewritten by the library to record refresh_token change # If you run your application in container, remember to persist this file if not (clientId and clientSecret and refreshToken): self._credentialFile = credentialFile or expanduser("~/.netatmo.credentials") with open(self._credentialFile, "r", encoding="utf-8") as f: cred = {k.upper():v for k,v in json.loads(f.read()).items()} else: # Calling program will need to handle the returned refresh_token for futur call # by getting refreshToken property of the ClientAuth instance and persist it somewhere self._credentialFile = None self._clientId = clientId or cred["CLIENT_ID"] self._clientSecret = clientSecret or cred["CLIENT_SECRET"] self._accessToken = None # Will be refreshed before any use self.refreshToken = refreshToken or cred["REFRESH_TOKEN"] self.expiration = 0 # Force refresh token @property def accessToken(self): if self.expiration < time.time() : self.renew_token() return self._accessToken def renew_token(self): postParams = { "grant_type" : "refresh_token", "refresh_token" : self.refreshToken, "client_id" : self._clientId, "client_secret" : self._clientSecret } resp = postRequest("authentication", _AUTH_REQ, postParams) if self.refreshToken != resp['refresh_token']: self.refreshToken = resp['refresh_token'] cred = {"CLIENT_ID":self._clientId, "CLIENT_SECRET":self._clientSecret, "REFRESH_TOKEN":self.refreshToken } if self._credentialFile: with open(self._credentialFile, "w", encoding="utf-8") as f: f.write(json.dumps(cred, indent=True)) self._accessToken = resp['access_token'] self.expiration = int(resp['expire_in'] + time.time()) class User: """ This class returns basic information about the user Args: authData (ClientAuth): Authentication information with a working access Token """ warnings.warn("The 'User' class is no longer maintained by Netatmo", DeprecationWarning ) def __init__(self, authData): postParams = { "access_token" : authData.accessToken } resp = postRequest("Weather station", _GETSTATIONDATA_REQ, postParams) self.rawData = resp['body'] self.devList = self.rawData['devices'] self.ownerMail = self.rawData['user']['mail'] class UserInfo: """ This class is dynamicaly populated with data from various Netatmo requests to provide complimentary data (eg Units for Weatherdata) """ class HomeStatus: """ List all Home+Control devices (Smarther thermostat, Socket, Cable Output, Centralized fan, Micromodules, ......) Args: authData (clientAuth): Authentication information with a working access Token home : Home name or id of the home who's thermostat belongs to """ def __init__(self, authData, home_id): self.getAuthToken = authData.accessToken postParams = { "access_token" : self.getAuthToken, "home_id": home_id } resp = postRequest("home_status", _HOME_STATUS, postParams) self.resp = resp self.rawData = resp['body']['home'] if not self.rawData : raise NoHome("No home %s found" % home_id) self.rooms = self.rawData['rooms'] self.modules = self.rawData['modules'] def getRoomsId(self): return [room['id'] for room in self.rooms] def getListRoomParam(self, room_id): for room in self.rooms: if room['id'] == room_id: return list(room) return None def getRoomParam(self, room_id, param): for room in self.rooms: if(room['id'] == room_id and param in room): return room[param] return None def getModulesId(self): return [module['id'] for module in self.modules] def getListModuleParam(self, module_id): for module in self.modules: if module['id'] == module_id: return list(module) return None def getModuleParam(self, module_id, param): for module in self.modules: if module['id'] == module_id and param in module: return module[param] return None class ThermostatData: """ List the Relay station and Thermostat modules Valves are controlled by HomesData and HomeStatus in new API Args: authData (clientAuth): Authentication information with a working access Token home : Home name or id of the home who's thermostat belongs to """ def __init__(self, authData, home=None): # I don't own a thermostat thus I am not able to test the Thermostat support warnings.warn("The Thermostat code is not tested due to the lack of test environment.\n" \ "As Netatmo is continuously breaking API compatibility, risk that current bindings are wrong is high.\n" \ "Please report found issues (https://github.com/philippelt/netatmo-api-python/issues)", RuntimeWarning ) self.getAuthToken = authData.accessToken postParams = { "access_token" : self.getAuthToken } resp = postRequest("Thermostat", _GETTHERMOSTATDATA_REQ, postParams) self.rawData = resp['body']['devices'] if not self.rawData : raise NoDevice("No thermostat available") # # keeping OLD code for Reference # self.thermostatData = filter_home_data(self.rawData, home) # if not self.thermostatData : raise NoHome("No home %s found" % home) # self.thermostatData['name'] = self.thermostatData['home_name'] # New key = 'station_name' # for m in self.thermostatData['modules']: # m['name'] = m['module_name'] # self.defaultThermostat = self.thermostatData['home_name'] # New key = 'station_name' # self.defaultThermostatId = self.thermostatData['_id'] # self.defaultModule = self.thermostatData['modules'][0] # Standard the first Relaystation and Thermostat is returned # self.rawData is list all stations # if no ID is given the Relaystation at index 0 is returned def Relay_Plug(self, Rid=""): for Relay in self.rawData: if Rid in Relay['_id']: print ('Relay ', Rid, 'in rawData') #print (Relay.keys()) #print (Relay['_id']) return Relay #dict_keys(['_id', 'applications', 'cipher_id', 'command', 'config_version', 'd_amount', 'date_creation', 'dev_has_init', 'device_group', 'firmware', 'firmware_private', 'homekit_nb_pairing', 'last_bilan', 'last_day_extremum', 'last_fw_update', 'last_measure_stored', 'last_setup', 'last_status_store', 'last_sync_asked', 'last_time_boiler_on', 'mg_station_name', 'migration_date', 'module_history', 'netcom_transport', 'new_historic_data', 'place', 'plug_connected_boiler', 'recompute_outdoor_time', 'record_storage', 'rf_amb_status', 'setpoint_order_history', 'skip_module_history_creation', 'subtype', 'type', 'u_amount', 'update_device', 'upgrade_record_ts', 'wifi_status', 'room', 'modules', 'station_name', 'udp_conn', 'last_plug_seen']) # if no ID is given the Thermostatmodule at index 0 is returned def Thermostat_Data(self, tid=""): for Relay in self.rawData: for thermostat in Relay['modules']: if tid in thermostat['_id']: print ('Thermostat ',tid, 'in Relay', Relay['_id'], Relay['station_name']) #print (thermostat['_id']) #print (thermostat.keys()) return thermostat #dict_keys(['_id', 'module_name', 'type', 'firmware', 'last_message', 'rf_status', 'battery_vp', 'therm_orientation', 'therm_relay_cmd', 'anticipating', 'battery_percent', 'event_history', 'last_therm_seen', 'setpoint', 'therm_program_list', 'measured']) def getThermostat(self, name=None, id=""): for Relay in self.rawData: for module in Relay['modules']: if id == Relay['_id']: print ('Relay ', id, 'found') return Relay elif name == Relay['station_name']: print ('Relay ', name, 'found') return Relay elif id == module['_id']: print ('Thermostat ', id, 'found in Relay', Relay['_id'], Relay['station_name']) return module elif name == module['module_name']: print ('Thermostat ', name, 'found in Relay', Relay['_id'], Relay['station_name']) return module else: #print ('Device NOT Found') pass def moduleNamesList(self, name=None, tid=None): l = [] for Relay in self.rawData: if id == Relay['_id'] or name == Relay['station_name']: RL = [] for module in Relay['modules']: RL.append(module['module_name']) return RL else: #print ("Cloud Data") for module in Relay['modules']: l.append(module['module_name']) #This return a list off all connected Thermostat in the cloud. return l def getModuleByName(self, name, tid=""): for Relay in self.rawData: for module in Relay['modules']: #print (module['module_name'], module['_id']) if module['module_name'] == name: return module elif module['_id'] == tid: return module else: pass class WeatherStationData: """ List the Weather Station devices (stations and modules) Args: authData (ClientAuth): Authentication information with a working access Token """ def __init__(self, authData, home=None, station=None): self.getAuthToken = authData.accessToken postParams = { "access_token" : self.getAuthToken } resp = postRequest("Weather station", _GETSTATIONDATA_REQ, postParams) self.rawData = resp['body']['devices'] # Weather data if not self.rawData : raise NoDevice("No weather station in any homes") # Stations are no longer in the Netatmo API, keeping them for compatibility self.stations = { d['station_name'] : d for d in self.rawData } self.stationIds = { d['_id'] : d for d in self.rawData } self.homes = { d['home_name'] : d["station_name"] for d in self.rawData } # Keeping the old behavior for default station name if home and home not in self.homes : raise NoHome("No home with name %s" % home) self.default_home = home or list(self.homes.keys())[0] if station: if station not in self.stations: # May be a station_id convert it to corresponding station name s = self.stationById(station) if s : station = s["station_name"] else: raise NoDevice("No station with name or id %s" % station) self.default_station = station else: self.default_station = [v["station_name"] for k,v in self.stations.items() if v["home_name"] == self.default_home][0] self.modules = {} self.default_station_data = self.stationByName(self.default_station) if 'modules' in self.default_station_data: for m in self.default_station_data['modules']: self.modules[ m['_id'] ] = m # User data userData = resp['body']['user'] self.user = UserInfo() setattr(self.user, "mail", userData['mail']) for k,v in userData['administrative'].items(): if k in UNITS: setattr(self.user, k, UNITS[k][v]) else: setattr(self.user, k, v) def modulesNamesList(self, station=None): s = self.getStation(station) if not s: raise NoDevice("No station with name or id %s" % station) self.default_station = station self.default_station_data = s self.modules = {} if 'modules' in self.default_station_data: for m in self.default_station_data['modules']: self.modules[ m['_id'] ] = m res = [m['module_name'] for m in self.modules.values()] res.append(s['module_name']) return res # Both functions (byName and byStation) are here for historical reason, # considering that chances are low that a station name could be confused with a station ID, # there should be in fact a single function for getting station data def getStation(self, station=None): if not station : station = self.default_station if station in self.stations : return self.stations[station] if station in self.stationIds : return self.stationIds[station] return None def getModule(self, module): if module in self.modules: return self.modules[module] for m in self.modules.values(): if m['module_name'] == module : return m return None # Functions for compatibility with previous versions def stationByName(self, station=None): return self.getStation(station) def stationById(self, sid): return self.getStation(sid) def moduleByName(self, module): return self.getModule(module) def moduleById(self, mid): return self.getModule(mid) def lastData(self, station=None, exclude=0): s = self.stationByName(station) or self.stationById(station) # Breaking change from Netatmo : dashboard_data no longer available if station lost if not s or 'dashboard_data' not in s : return None lastD = {} # Define oldest acceptable sensor measure event limit = (time.time() - exclude) if exclude else 0 ds = s['dashboard_data'] if ds.get('time_utc',limit+10) > limit : lastD[s['module_name']] = ds.copy() lastD[s['module_name']]['When'] = lastD[s['module_name']].pop("time_utc") if 'time_utc' in lastD[s['module_name']] else time.time() lastD[s['module_name']]['wifi_status'] = s['wifi_status'] if 'modules' in s: for module in s["modules"]: # Skip lost modules that no longer have dashboard data available if 'dashboard_data' not in module : continue ds = module['dashboard_data'] if ds.get('time_utc',limit+10) > limit : # If no module_name has been setup, use _id by default if "module_name" not in module : module['module_name'] = module["_id"] lastD[module['module_name']] = ds.copy() lastD[module['module_name']]['When'] = lastD[module['module_name']].pop("time_utc") if 'time_utc' in lastD[module['module_name']] else time.time() # For potential use, add battery and radio coverage information to module data if present for i in ('battery_vp', 'battery_percent', 'rf_status') : if i in module : lastD[module['module_name']][i] = module[i] return lastD def checkNotUpdated(self, delay=3600): res = self.lastData() ret = [] for mn,v in res.items(): if time.time()-v['When'] > delay : ret.append(mn) return ret if ret else None def checkUpdated(self, delay=3600): res = self.lastData() ret = [] for mn,v in res.items(): if time.time()-v['When'] < delay : ret.append(mn) return ret if ret else None def getMeasure(self, device_id, scale, mtype, module_id=None, date_begin=None, date_end=None, limit=None, optimize=False, real_time=False): postParams = { "access_token" : self.getAuthToken } postParams['device_id'] = device_id if module_id : postParams['module_id'] = module_id postParams['scale'] = scale postParams['type'] = mtype if date_begin : postParams['date_begin'] = date_begin if date_end : postParams['date_end'] = date_end if limit : postParams['limit'] = limit postParams['optimize'] = "true" if optimize else "false" postParams['real_time'] = "true" if real_time else "false" return postRequest("Weather station", _GETMEASURE_REQ, postParams) def MinMaxTH(self, module=None, frame="last24"): s = self.default_station_data if frame == "last24": end = time.time() start = end - 24*3600 # 24 hours ago elif frame == "day": start, end = todayStamps() if module and module != s['module_name']: m = self.moduleById(module) or self.moduleByName(module) if not m : raise NoDevice("Can't find module %s" % module) # retrieve module's data resp = self.getMeasure( device_id = s['_id'], module_id = m['_id'], scale = "max", mtype = "Temperature,Humidity", date_begin = start, date_end = end) else : # retrieve station's data resp = self.getMeasure( device_id = s['_id'], scale = "max", mtype = "Temperature,Humidity", date_begin = start, date_end = end) if resp and resp['body']: T = [v[0] for v in resp['body'].values()] H = [v[1] for v in resp['body'].values()] return min(T), max(T), min(H), max(H) return None class DeviceList(WeatherStationData): """ This class is now deprecated. Use WeatherStationData directly instead """ warnings.warn("The 'DeviceList' class was renamed 'WeatherStationData'", DeprecationWarning ) class HomeData: """ List the Netatmo home informations (Homes, cameras, events, persons) Args: authData (ClientAuth): Authentication information with a working access Token home : Home name of the home where's devices are installed """ def __init__(self, authData, home=None): warnings.warn("The 'HomeData' class is deprecated'", DeprecationWarning ) self.getAuthToken = authData.accessToken postParams = { "access_token" : self.getAuthToken } resp = postRequest("Home data", _GETHOMEDATA_REQ, postParams) self.rawData = resp['body'] # Collect homes self.homes = self.rawData['homes'][0] for d in self.rawData['homes'] : if home == d['name']: self.homes = d else: pass # #print (self.homes.keys()) #dict_keys(['id', 'name', 'persons', 'place', 'cameras', 'smokedetectors', 'events']) self.homeid = self.homes['id'] C = self.homes['cameras'] P = self.homes['persons'] S = self.homes['smokedetectors'] E = None # events not always in self.homes if 'events' in self.homes.keys(): E = self.homes['events'] # if not S: logger.warning('No smoke detector found') if not C: logger.warning('No Cameras found') if not P: logger.warning('No Persons found') if not E: logger.warning('No events found') # if not (C or P or S or E): # raise NoDevice("No device found in home %s" % k) if S or C or P or E: self.default_home = home or self.homes['name'] # Split homes data by category self.persons = {} self.events = {} self.cameras = {} self.lastEvent = {} for i in range(len(self.rawData['homes'])): curHome = self.rawData['homes'][i] nameHome = curHome['name'] if nameHome not in self.cameras: self.cameras[nameHome] = {} if 'persons' in curHome: for p in curHome['persons']: self.persons[ p['id'] ] = p if 'events' in curHome: for e in curHome['events']: if e['camera_id'] not in self.events: self.events[ e['camera_id'] ] = {} self.events[ e['camera_id'] ][ e['time'] ] = e if 'cameras' in curHome: for c in curHome['cameras']: self.cameras[nameHome][ c['id'] ] = c c["home_id"] = curHome['id'] for camera,e in self.events.items(): self.lastEvent[camera] = e[sorted(e)[-1]] #self.default_home has no key homeId use homeName instead! if not self.cameras[self.default_home] : raise NoDevice("No camera available in default home") self.default_camera = list(self.cameras[self.default_home].values())[0] else: pass # raise NoDevice("No Devices available") def homeById(self, hid): return None if hid not in self.homes else self.homes[hid] def homeByName(self, home=None): if not home: home = self.default_home for key,value in self.homes.items(): if value['name'] == home: return self.homes[key] def cameraById(self, cid): for cam in self.cameras.values(): if cid in cam: return cam[cid] return None def cameraByName(self, camera=None, home=None): if not camera and not home: return self.default_camera elif home and camera: if home not in self.cameras: return None for cam_id in self.cameras[home]: if self.cameras[home][cam_id]['name'] == camera: return self.cameras[home][cam_id] elif not home and camera: for h, cam_ids in self.cameras.items(): for cam_id in cam_ids: if self.cameras[h][cam_id]['name'] == camera: return self.cameras[h][cam_id] else: return list(self.cameras[self.default_home].values())[0] return None def cameraUrls(self, camera=None, home=None, cid=None): """ Return the vpn_url and the local_url (if available) of a given camera in order to access to its live feed Can't use the is_local property which is mostly false in case of operator dynamic IP change after presence start sequence """ local_url = None vpn_url = None if cid: camera_data=self.cameraById(cid) else: camera_data=self.cameraByName(camera=camera, home=home) if camera_data: vpn_url = camera_data['vpn_url'] resp = postRequest("Camera", vpn_url + '/command/ping') temp_local_url=resp['local_url'] try: resp = postRequest("Camera", temp_local_url + '/command/ping',timeout=1) if resp and temp_local_url == resp['local_url']: local_url = temp_local_url except: # On this particular request, vithout errors from previous requests, error is timeout local_url = None return vpn_url, local_url def url(self, camera=None, home=None, cid=None): vpn_url, local_url = self.cameraUrls(camera, home, cid) # Return local if available else vpn return local_url or vpn_url def personsAtHome(self, home=None): """ Return the list of known persons who are currently at home """ if not home: home = self.default_home home_data = self.homeByName(home) atHome = [] for p in home_data['persons']: #Only check known persons if 'pseudo' in p: if not p["out_of_sight"]: atHome.append(p['pseudo']) return atHome def getCameraPicture(self, image_id, key): """ Download a specific image (of an event or user face) from the camera """ postParams = { "access_token" : self.getAuthToken, "image_id" : image_id, "key" : key } resp = postRequest("Camera", _GETCAMERAPICTURE_REQ, postParams) return resp, "jpeg" def getProfileImage(self, name): """ Retrieve the face of a given person """ for p in self.persons.values(): if 'pseudo' in p: if name == p['pseudo']: image_id = p['face']['id'] key = p['face']['key'] return self.getCameraPicture(image_id, key) return None, None def updateEvent(self, event=None, home=None): """ Update the list of event with the latest ones """ if not home: home=self.default_home if not event: #If not event is provided we need to retrieve the oldest of the last event seen by each camera listEvent = {} for e in self.lastEvent.values(): listEvent[e['time']] = e event = listEvent[sorted(listEvent)[0]] home_data = self.homeByName(home) postParams = { "access_token" : self.getAuthToken, "home_id" : home_data['id'], "event_id" : event['id'] } resp = postRequest("Camera", _GETEVENTSUNTIL_REQ, postParams) eventList = resp['body']['events_list'] for e in eventList: self.events[ e['camera_id'] ][ e['time'] ] = e for camera,v in self.events.items(): self.lastEvent[camera]=v[sorted(v)[-1]] def personSeenByCamera(self, name, home=None, camera=None): """ Return True if a specific person has been seen by a camera """ try: cam_id = self.cameraByName(camera=camera, home=home)['id'] except TypeError: logger.warning("personSeenByCamera: Camera name or home is unknown") return False #Check in the last event is someone known has been seen if self.lastEvent[cam_id]['type'] == 'person': person_id = self.lastEvent[cam_id]['person_id'] if 'pseudo' in self.persons[person_id]: if self.persons[person_id]['pseudo'] == name: return True return False def _knownPersons(self): known_persons = {} for p_id,p in self.persons.items(): if 'pseudo' in p: known_persons[ p_id ] = p return known_persons def someoneKnownSeen(self, home=None, camera=None): """ Return True if someone known has been seen """ try: cam_id = self.cameraByName(camera=camera, home=home)['id'] except TypeError: logger.warning("personSeenByCamera: Camera name or home is unknown") return False #Check in the last event is someone known has been seen if self.lastEvent[cam_id]['type'] == 'person': if self.lastEvent[cam_id]['person_id'] in self._knownPersons(): return True return False def someoneUnknownSeen(self, home=None, camera=None): """ Return True if someone unknown has been seen """ try: cam_id = self.cameraByName(camera=camera, home=home)['id'] except TypeError: logger.warning("personSeenByCamera: Camera name or home is unknown") return False #Check in the last event is someone known has been seen if self.lastEvent[cam_id]['type'] == 'person': if self.lastEvent[cam_id]['person_id'] not in self._knownPersons(): return True return False def motionDetected(self, home=None, camera=None): """ Return True if movement has been detected """ try: cam_id = self.cameraByName(camera=camera, home=home)['id'] except TypeError: logger.warning("personSeenByCamera: Camera name or home is unknown") return False if self.lastEvent[cam_id]['type'] == 'movement': return True return False def presenceUrl(self, camera=None, home=None, cid=None): camera = self.cameraByName(home=home, camera=camera) or self.cameraById(cid=cid) if camera["type"] != "NOC": return None # Not a presence camera vpnUrl, localUrl = self.cameraUrls(cid=camera["id"]) return localUrl or vpnUrl def presenceLight(self, camera=None, home=None, cid=None, setting=None): url = self.presenceUrl(home=home, camera=camera) or self.cameraById(cid=cid) if not url or setting not in ("on", "off", "auto"): return None if setting : return "Currently unsupported" return cameraCommand(url, _PRES_CDE_GET_LIGHT)["mode"] # Not yet supported #if not setting: return cameraCommand(url, _PRES_CDE_GET_LIGHT)["mode"] #else: return cameraCommand(url, _PRES_CDE_SET_LIGHT, setting) def presenceStatus(self, mode, camera=None, home=None, cid=None): url = self.presenceUrl(home=home, camera=camera) or self.cameraById(cid=cid) if not url or mode not in ("on", "off") : return None r = cameraCommand(url, _CAM_CHANGE_STATUS, mode) return mode if r["status"] == "ok" else None def presenceSetAction(self, camera=None, home=None, cid=None, eventType=_PRES_DETECTION_KIND[0], action=2): raise NotImplementedError # if eventType not in _PRES_DETECTION_KIND or \ # action not in _PRES_DETECTION_SETUP : return None # camera = self.cameraByName(home=home, camera=camera) or self.cameraById(cid=cid) # postParams = { "access_token" : self.getAuthToken, # "home_id" : camera["home_id"], # "presence_settings[presence_record_%s]" % eventType : _PRES_DETECTION_SETUP.index(action) # } # resp = postRequest("Camera", _POST_UPDATE_HOME_REQ, postParams) # self.rawData = resp['body'] def getLiveSnapshot(self, camera=None, home=None, cid=None): camera = self.cameraByName(home=home, camera=camera) or self.cameraById(cid=cid) vpnUrl, localUrl = self.cameraUrls(cid=camera["id"]) url = localUrl or vpnUrl return cameraCommand(url, _PRES_CDE_GET_SNAP) class WelcomeData(HomeData): """ This class is now deprecated. Use HomeData instead Home can handle many devices, not only Welcome cameras """ warnings.warn("The 'WelcomeData' class was renamed 'HomeData' to handle new Netatmo Home capabilities", DeprecationWarning ) class HomesData: """ List the Netatmo actual topology and static information of all devices present into a user account. It is also possible to specify a home_id to focus on one home. Args: authData (clientAuth): Authentication information with a working access Token home : Home name or id of the home who's module belongs to """ def __init__(self, authData, home=None): # self.getAuthToken = authData.accessToken postParams = { "access_token" : self.getAuthToken, "home_id": home } # resp = postRequest("Module", _GETHOMES_DATA, postParams) # self.rawData = resp['body']['devices'] self.rawData = resp['body']['homes'] if not self.rawData : raise NoHome("No home %s found" % home) # if home: # Find a home who's home id or name is the one requested for h in self.rawData: #print (h.keys()) if home in (h["name"], h["id"]): self.Homes_Data = h else: self.Homes_Data = self.rawData[0] self.homeid = self.Homes_Data['id'] if not self.Homes_Data : raise NoDevice("No Devices available") class HomeCoach: """ List the HomeCoach modules Args: authData (clientAuth): Authentication information with a working access Token home : Home name or id of the home who's HomeCoach belongs to """ def __init__(self, authData): # I don't own a HomeCoach thus I am not able to test the HomeCoach support # Homecoach does not need or use HomeID parameter # warnings.warn("The HomeCoach code is not tested due to the lack of test environment.\n", RuntimeWarning ) # "As Netatmo is continuously breaking API compatibility, risk that current bindings are wrong is high.\n" \ # "Please report found issues (https://github.com/philippelt/netatmo-api-python/issues)" self.getAuthToken = authData.accessToken postParams = { "access_token" : self.getAuthToken } resp = postRequest("HomeCoach", _GETHOMECOACH, postParams) self.rawData = resp['body']['devices'] # homecoach data if not self.rawData : raise NoDevice("No HomeCoach available") def HomecoachDevice(self, hid=""): for device in self.rawData: if hid == device['_id']: return device return None def Dashboard(self, hid=""): #D = self.HomecoachDevice['dashboard_data'] for device in self.rawData: if hid == device['_id']: D = device['dashboard_data'] return D def lastData(self, hid=None, exclude=0): for device in self.rawData: if hid == device['_id']: # LastData in HomeCoach #s = self.HomecoachDevice['dashboard_data']['time_utc'] # Define oldest acceptable sensor measure event limit = (time.time() - exclude) if exclude else 0 ds = device['dashboard_data']['time_utc'] return { '_id': hid, 'When': ds if device.get('time_utc',limit+10) > limit else 0} else: pass def checkNotUpdated(self, res, hid, delay=3600): ret = [] if time.time()-res['When'] > delay : ret.append({hid: 'Device Not Updated'}) return ret if ret else None def checkUpdated(self, res, hid, delay=3600): ret = [] if time.time()-res['When'] < delay : ret.append({hid: 'Device up-to-date'}) return ret if ret else None # Utilities routines def rawAPI(authData, url, parameters=None): fullUrl = _BASE_URL + "api/" + url if parameters is None: parameters = {} parameters["access_token"] = authData.accessToken resp = postRequest("rawAPI", fullUrl, parameters) return resp["body"] if "body" in resp else resp def filter_home_data(rawData, home): if home: # Find a home who's home id or name is the one requested for h in rawData: if home in (h['home_name'], h['home_id']): return h return None # By default, the first home is returned return rawData[0] def cameraCommand(cameraUrl, commande, parameters=None, timeout=3): url = cameraUrl + ( commande % parameters if parameters else commande) return postRequest("Camera", url, timeout=timeout) def processErrorResp(resp): try: error_detail = json.loads(resp.fp.read().decode("utf-8"))["error"] logger.error("Netatmo response error 403 : %s" % repr(error_detail)) except Exception as e: logger.error("Error getting body of 403 HTTP error from Netatmo : %s" % e) def postRequest(topic, url, params=None, timeout=10): if PYTHON3: req = urllib.request.Request(url) if params: req.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8") if "access_token" in params: req.add_header("Authorization","Bearer %s" % params.pop("access_token")) params = urllib.parse.urlencode(params).encode('utf-8') try: resp = urllib.request.urlopen(req, params, timeout=timeout) if params else urllib.request.urlopen(req, timeout=timeout) except urllib.error.HTTPError as err: if err.code == 403: processErrorResp(err) else: logger.error("code=%s, reason=%s, body=%s" % (err.code, err.reason, err.fp.read())) return None else: if params: token = params.pop("access_token") if "access_token" in params else None params = urlencode(params) headers = {"Content-Type" : "application/x-www-form-urlencoded;charset=utf-8"} if token: headers["Authorization"] = "Bearer %s" % token req = urllib2.Request(url=url, data=params, headers=headers) if params else urllib2.Request(url=url, headers=headers) try: resp = urllib2.urlopen(req, timeout=timeout) except urllib2.HTTPError as err: logger.error("code=%s, reason=%s" % (err.code, err.reason)) return None data = b"" for buff in iter(lambda: resp.read(65535), b''): data += buff # Return values in bytes if not json data to handle properly camera images returnedContentType = resp.getheader("Content-Type") if PYTHON3 else resp.info()["Content-Type"] return json.loads(data.decode("utf-8")) if "application/json" in returnedContentType else data def toTimeString(value): return time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime(int(value))) def toEpoch(value): return int(time.mktime(time.strptime(value,"%Y-%m-%d_%H:%M:%S"))) def todayStamps(): today = time.strftime("%Y-%m-%d") today = int(time.mktime(time.strptime(today,"%Y-%m-%d"))) return today, today+3600*24 # Global shortcut def getStationMinMaxTH(station=None, module=None, home=None): authorization = ClientAuth() devList = WeatherStationData(authorization, station=station, home=home) if module == "*": pass elif module: module = devList.moduleById(module) or devList.moduleByName(module) if not module: raise NoDevice("No such module %s" % module) module = module["module_name"] else: module = list(devList.modules.values())[0]["module_name"] lastD = devList.lastData() if module == "*": result = {} for m,v in lastD.items(): if time.time()-v['When'] > 3600 : continue r = devList.MinMaxTH(module=m) if r: result[m] = (r[0], v['Temperature'], r[1]) else: if time.time()-lastD[module]['When'] > 3600 : result = ["-", "-"] else : result = [lastD[module]['Temperature'], lastD[module]['Humidity']] result.extend(devList.MinMaxTH(module)) return result # auto-test when executed directly if __name__ == "__main__": logging.basicConfig(format='%(name)s - %(levelname)s: %(message)s', level=logging.INFO) authorization = ClientAuth() # Test authentication method try: try: weatherStation = WeatherStationData(authorization) # Test DEVICELIST except NoDevice: logger.warning("No weather station available for testing") else: weatherStation.MinMaxTH() # Test GETMEASUR try: homes = HomeData(authorization) except NoDevice : logger.warning("No home available for testing") try: thermostat = ThermostatData(authorization) Default_relay = thermostat.Relay_Plug() Default_thermostat = thermostat.Thermostat_Data() thermostat.getThermostat() print (thermostat.moduleNamesList()) #print (thermostat.getModuleByName(name)) except NoDevice: logger.warning("No thermostat avaible for testing") try: print (' ') logger.info("Homes Data") #homesdata = HomesData(authorization, homeid) homesdata = HomesData(authorization) homeid = homesdata.homeid except NoDevice: logger.warning("No HomesData avaible for testing") try: print (' ') logger.info("Home Status") HomeStatus(authorization, homeid) except NoDevice: logger.warning("No Home available for testing") try: print (' ') logger.info("HomeCoach") Homecoach = HomeCoach(authorization) except NoDevice: logger.warning("No HomeCoach avaible for testing") except OutOfScope: logger.warning("Your current scope do not allow such access") # If we reach this line, all is OK logger.info("OK") exit(0) ================================================ FILE: samples/get_direct_camera_snapshot ================================================ #!/usr/bin/python3 # Locate the camera name "MyCam" IP on the local LAN # to collect a snapshot of what the camera sees # If available use a local connection to save internet bandwith from sys import exit import lnetatmo # The name I gave the camera in the Netatmo Security App MY_CAMERA = "MyCam" # Authenticate (see authentication in documentation) # Note you will need the appropriate scope (read_welcome access_welcome or read_presence access_presence) # depending of the camera you are trying to reach # The default library scope ask for all aceess to all cameras authorization = lnetatmo.ClientAuth() # Gather Home information (available cameras and other infos) homeData = lnetatmo.HomeData(authorization) # Request a snapshot from the camera snapshot = homeData.getLiveSnapshot( camera=MY_CAMERA ) # If all was Ok, I should have an image, if None there was an error if not snapshot : # Decide what to do with an error situation (alert, log, ...) exit(1) # You can then archive the snapshot, send it by mail, message App, ... # Example : Save the snapshot in a file with open("MyCamSnap.jpg", "wb") as f: f.write(snapshot) exit(0) ================================================ FILE: samples/graphLast3Days ================================================ #!/usr/bin/python # coding=utf-8 # 2013-01 : philippelt@users.sourceforge.net # This is an example of graphing Temperature and Humidity from a module on the last 3 days # The Matplotlib library is used and should be installed before running this sample program import datetime, time import lnetatmo from matplotlib import pyplot as plt from matplotlib import dates from matplotlib.ticker import FormatStrFormatter # Access to the sensors auth = lnetatmo.ClientAuth() dev = lnetatmo.DeviceList(auth) # Time of information collection : 3*24hours windows to now now = time.time() start = now - 3 * 24 * 3600 # Get Temperature and Humidity with GETMEASURE web service (1 sample every 30min) resp = dev.getMeasure( device_id='xxxx', # Replace with your values module_id='xxxx', # " " " " scale="30min", mtype="Temperature,Humidity", date_begin=start, date_end=now) # Extract the timestamp, temperature and humidity from the more complex response structure result = [(int(k),v[0],v[1]) for k,v in resp['body'].items()] # Sort samples by timestamps (Warning, they are NOT sorted by default) result.sort() # Split in 3 lists for use with Matplotlib (timestamp on x, temperature and humidity on two y axis) xval, ytemp, yhum = zip(*result) # Convert the x axis values from Netatmo timestamp to matplotlib timestamp... xval = [dates.date2num(datetime.datetime.fromtimestamp(x)) for x in xval] # Build the two curves graph (check Matplotlib documentation for details) fig = plt.figure() plt.xticks(rotation='vertical') graph1 = fig.add_subplot(111) graph1.plot(xval, ytemp, color='r', linewidth=3) graph1.set_ylabel(u'Température', color='r') graph1.set_ylim(0, 25) graph1.yaxis.grid(color='gray', linestyle='dashed') for t in graph1.get_yticklabels() : t.set_color('r') graph1.yaxis.set_major_formatter(FormatStrFormatter(u'%2.0f °C')) graph2 = graph1.twinx() graph2.plot(xval, yhum, color='b', linewidth=3) graph2.set_ylabel(u'Humidité',color='b') graph2.set_ylim(50,100) for t in graph2.get_yticklabels(): t.set_color('b') graph2.yaxis.set_major_formatter(FormatStrFormatter(u'%2i %%')) graph1.xaxis.set_major_locator(dates.HourLocator(interval=6)) graph1.xaxis.set_minor_locator(dates.HourLocator()) graph1.xaxis.set_major_formatter(dates.DateFormatter("%d-%Hh")) graph1.xaxis.grid(color='gray') graph1.set_xlabel(u'Jour et heure de la journée') # X display the resulting graph (you could generate a PDF/PNG/... in place of display). # The display provides a minimal interface that notably allows you to save your graph plt.show() ================================================ FILE: samples/printAllLastData.py ================================================ #!/usr/bin/python3 # encoding=utf-8 # 2014-01 : philippelt@users.sourceforge.net # Just connect to a Netatmo account, and print all last informations available for # station(s) and modules of the user account # (except if module data is more than one hour old that usually means module lost # wether out of radio range or battery exhausted thus information is no longer # significant) import time import lnetatmo authorization = lnetatmo.ClientAuth() weather = lnetatmo.WeatherStationData(authorization) user = weather.user print("Station owner : ", user.mail) print("Data units : ", user.unit) # For each station in the account for station in weather.stations: print("\nSTATION : %s\n" % weather.stations[station]["station_name"]) # For each available module in the returned data of the specified station # that should not be older than one hour (3600 s) from now for module, moduleData in weather.lastData(station=station, exclude=3600).items() : # Name of the module (or station embedded module) # You setup this name in the web netatmo account station management print(module) # List key/values pair of sensor information (eg Humidity, Temperature, etc...) for sensor, value in moduleData.items() : # To ease reading, print measurement event in readable text (hh:mm:ss) if sensor == "When" : value = time.strftime("%H:%M:%S",time.localtime(value)) print("%30s : %s" % (sensor, value)) # OUTPUT SAMPLE : # # $ printAllLastData # #Station owner : ph.larduinat@wanadoo.fr #Data units : metric # # #STATION : TEST-STATION-1 # #Office # AbsolutePressure : 988.7 # CO2 : 726 # date_max_temp : 1400760301 # date_min_temp : 1400736146 # Humidity : 60 # max_temp : 19.6 # min_temp : 17.9 # Noise : 46 # Particle : 12768 # Pressure : 988.7 # Temperature : 19.6 # When : 14:10:01 #Outdoor # battery_vp : 5200 # CO2 : 555 # date_max_temp : 1400759951 # date_min_temp : 1400732524 # Humidity : 75 # max_temp : 17.9 # min_temp : 10.3 # rf_status : 57 # Temperature : 17.9 # When : 14:09:25 #Greenhouse # date_min_temp : 1400732204 # Humidity : 89 # max_temp : 19.9 # min_temp : 9.1 # rf_status : 83 # Temperature : 19.9 # When : 14:09:12 ================================================ FILE: samples/printThermostat.py ================================================ #!/usr/bin/python3 # encoding=utf-8 # 2018-02 : ph.larduinat@wanadoo.fr # Thermostat basic sample import sys import lnetatmo authorization = lnetatmo.ClientAuth() thermostat = lnetatmo.ThermostatData(authorization) defaultThermostat = thermostat.getThermostat() if not defaultThermostat : sys.exit(1) defaultModule = thermostat.defaultModule print('Thermostat name :', defaultThermostat['name']) print('Default module :', defaultModule['name']) print('Module measured temp :', defaultModule['measured']['temperature']) print('Module set point :', defaultModule['measured']['setpoint_temp']) print('Module battery : %s%%' % defaultModule['battery_percent']) for p in defaultModule['therm_program_list']: print("\tProgram: ", p['name']) for z in p['zones']: name = z['name'] if 'name' in z else '' print("\t%15s : %s" % (name, z['temp'])) ================================================ FILE: samples/rawAPIsample.py ================================================ #!/usr/bin/python3 # 2023-07 : ph.larduinat@wanadoo.fr # Library 3.2.0 # Direct call of Netatmo API with authentication token # Return a dictionary of body of Netatmo response import lnetatmo authorization = lnetatmo.ClientAuth() rawData = lnetatmo.rawAPI(authorization, "gethomesdata") print("Home name : home_id") for h in rawData["homes"]: print(f"{h['name']} : {h['id']}") print("Radio communication strength by home") for h in rawData["homes"]: print(f"\nFor {h['name']}:") modules = lnetatmo.rawAPI(authorization, "homestatus", {"home_id" : h['id']})['home'] if not 'modules' in modules: print("No modules available") else: print([(m['id'],m['rf_strength']) for m in modules['modules'] if 'rf_strength' in m]) ================================================ FILE: samples/simpleLastData.py ================================================ #!/usr/bin/python3 # encoding=utf-8 # 2013-01 : philippelt@users.sourceforge.net # Just connect to a Netatmo account, and print internal and external temperature of the default (or single) station # In this case, sensors of the station and the external module have been named 'internal' and 'external' in the # Account station settings. import lnetatmo authorization = lnetatmo.ClientAuth() devList = lnetatmo.WeatherStationData(authorization) print ("Current temperature (inside/outside): %s / %s °C" % ( devList.lastData()['internal']['Temperature'], devList.lastData()['external']['Temperature']) ) ================================================ FILE: samples/smsAlarm.py ================================================ #!/usr/bin/python3 # encoding=utf-8 # 2013-01 : philippelt@users.sourceforge.net # Simple example run in a cron job (every 30' for example) to send an alarm SMS if some condition is reached # and an other SMS when condition returned to normal. In both case, a single SMS is emitted to multiple # peoples (here phone1 and phone2 are two mobile phone numbers) # Note : lsms is my personnal library to send SMS using a GSM modem, you have to use your method/library import sys, os import lnetatmo,lsms MARKER_FILE = "//TempAlarm" # This flag file will be used to avoid sending multiple SMS on the same event # Remember that the user who run the cron job must have the rights to create the file # Access the station authorization = lnetatmo.ClientAuth() devList = lnetatmo.WeatherStationData(authorization) message = [] # Condition 1 : the external temperature is below our limit curT = devList.lastData()['external']['Temperature'] if curT < 5 : message.append("Temperature going below 5°C") # Condition 2 : The external temperature data is older that 1 hour someLost = devList.checkNotUpdated() if someLost and 'external' in someLost : message.append("Sensor is no longer active") # Condition 3 : The outdoor module battery is dying volts = devList.lastData()['external']['battery_vp'] # I suspect that this is the total Voltage in mV if volts < 5000 : message.append("External module battery needs replacement") # I will adjust the threshold over time # If one condition is present, at least, send an alarm by SMS if message : if not os.path.exists(MARKER_FILE) : message = "WEATHER ALERT\n" + "\n".join(message) for p in ('', '') : lsms.sendSMS(p, message, flash=True) open(MARKER_FILE,"w").close() # Just to create the empty marker file and avoid to resend the same alert else : if os.path.exists(MARKER_FILE) : os.remove(MARKER_FILE) for p in ('', '') : lsms.sendSMS(p, "END of WEATHER alert, current temperature is %s°C" % curT) sys.exit(0) ================================================ FILE: samples/weather2file.md ================================================ # weather2file The script [weather2file](https://github.com/philippelt/netatmo-api-python/blob/master/samples/weather2file) can be used to save data from [Netatmo](https://www.netatmo.com) to file. The data is extracted through the Netatmo api and is aggregated into a pandas DataFrame which is then saved into one of the possible output formats (-f flag). Each sample/row in the dataframe consists of common columns such as utc_time (int), timestamp (datetime including timezone if supported by output format), type, module_name, module_mac, station_name, station_mac. There are also a number of columns corresponding to the module data such as Temperature, CO2, Humidity, Noise and Pressure. All samples/rows will contain all data columns, however the non-relevant columns (such as pressure for an indoor module) will be set to NaN. When run, it will check if a data file already exists. If it exists, it will be loaded and only new data will be extracted from Netatmo. It will thus not download duplicates. In case of certain types of errors, it will exit data collection for the current module and save whatever it managed to collect, and then continue with the next module until data has been collected from all modules. This means that even if the data collection fails, you will not have to download that data again, but will continue from whatever data it already has. The script also handles user specific rate limits such as 50 requests per 10s and 500 requests per hour, by logging the time of the requests and make sure that those are never exceeded by waiting, if necessary. You can specify lower rate limits than the maximum as to not eat up all resources such that other services might not work. This is done with the -hlr flag for the hour limit and the -t flag for the 10 seconds limit. The script does however not keep track of requests between different runs. In such cases, one kan use the -p flag to specify the number of assumed previous requests. The default name of the output is "weatherdata" followed by the file format ending, but you can change the name with the -n flag. The default output directory is the curent directory. You can change this value with the -o flag (also supports ~). # How to run 1. Clone or download the repository. 2. Enter credential information according one of the alternatives in [lnetatmo.py](https://github.com/philippelt/netatmo-api-python/blob/master/lnetatmo.py) 3. Enter the directory and run: ```PYTHONPATH=. ./samples/weather2file --format csv``` (change --format if you prefer a different format, and use any of the optional flags) ```sh $ PYTHONPATH=. ./samples/weather2file -h usage: weather2file [-h] -f {json,csv,pickle,hdf,feather,parquet,excel} [-e END_DATETIME] [-v {debug,info,warning,error,quiet}] [-n FILE_NAME] [-o OUTPUT_PATH] [-p PREVIOUS_REQUESTS] [-hrl HOUR_RATE_LIMIT] [-t TEN_SECOND_RATE_LIMIT] Save historical information for all weather modules from Netatmo to file optional arguments: -h, --help show this help message and exit -f {json,csv,pickle,hdf,feather,parquet,excel}, --format {json,csv,pickle,hdf,feather,parquet,excel} Format for which the data is to be saved -e END_DATETIME, --end-datetime END_DATETIME The end datetime of data to be saved, in the format YYYY-MM-DD_hh:mm (default: now) -v {debug,info,warning,error,quiet}, --verbose {debug,info,warning,error,quiet} Verbose level (default: info) -n FILE_NAME, --file-name FILE_NAME Name of the output file (default: weatherdata) -o OUTPUT_PATH, --output-path OUTPUT_PATH Output location (default: current folder) -p PREVIOUS_REQUESTS, --previous-requests PREVIOUS_REQUESTS Assumes this many previous requests has been done, so that the rate limit is not exceeded (default: 0) -hrl HOUR_RATE_LIMIT, --hour-rate-limit HOUR_RATE_LIMIT Specify the rate limit per hour (default: 400, max: 500) -t TEN_SECOND_RATE_LIMIT, --ten-second-rate-limit TEN_SECOND_RATE_LIMIT Specify the rate limit per ten seconds (default: 30, max: 50) ``` ================================================ FILE: samples/weather2file.py ================================================ #!/usr/bin/env python3 # Copyright (c) 2020 Joel Berglund # # 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, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA import lnetatmo import pandas as pd import numpy as np import argparse import logging import time import socket from datetime import date, datetime, timedelta from pytz import timezone from os.path import expanduser, join from pathlib import Path def valid_datetime_type(arg_datetime_str): try: return datetime.strptime(arg_datetime_str, "%Y-%m-%d_%H:%M") except ValueError: msg = f"Given Date {arg_datetime_str} not valid! Expected format, YYYY-MM-DD_hh:mm!" raise argparse.ArgumentTypeError(msg) def valid_hour_limit(hour_limit): hour_limit = int(hour_limit) if hour_limit <= 0: msg = "Hour limit must be larger than 0" raise argparse.ArgumentTypeError(msg) elif hour_limit > 500: msg = "Hour limit cannot be more than 500" raise argparse.ArgumentTypeError(msg) return hour_limit def valid_ten_seconds_limit(ten_sec_limit): ten_sec_limit = int(ten_sec_limit) if ten_sec_limit <= 0: msg = "Ten seconds limit must be larger than 0" raise argparse.ArgumentTypeError(msg) elif ten_sec_limit > 50: msg = "Ten seconds limit cannot be more than 50" raise argparse.ArgumentTypeError(msg) return ten_sec_limit verbose_dict = { 'debug':logging.DEBUG, 'info':logging.INFO, 'warning':logging.WARNING, 'error':logging.ERROR } def userexpanded_path_str(path_str): return expanduser(path_str) class DataFrameHandler: def __init__(self, file_name, output_path, file_format, kwargs={}): logging.debug(f'Initiating {self.__class__.__name__}') self.file_name = file_name self.kwargs = kwargs try: Path(output_path).resolve(strict=True) except FileNotFoundError as error: logging.error(f'Output path {output_path} does not exist') raise error self.output_path = output_path self.file_extension = self.file_extension_dict[file_format] self._set_df() # Specify the column formats here dtype_dict = { 'Pressure':np.float32, 'CO2':np.float32, 'Temperature':np.float32, 'Humidity':pd.Int8Dtype(), 'Noise':pd.Int16Dtype(), 'utc_time':np.uint32} file_extension_dict = { "json": "json", "pickle": "pkl", "csv": "csv", "hdf": "h5", "feather": "feather", "parquet": "parquet", "excel": "xlsx", } def _set_df(self): # If the file exists, load it. Otherwise, set empty DataFrame file_path = self._get_complete_file_name() p = Path(file_path) try: abs_path = p.resolve(strict=True) except FileNotFoundError: logging.info(f'Previous file {file_path} not found. Setting empty DataFrame') self.df = pd.DataFrame([]) else: logging.info(f'Previous file {file_path} found. Loading DataFrame.') self.df = self._read_file(abs_path).astype(self.dtype_dict) def _get_complete_file_name(self): return join(self.output_path, f"{self.file_name}.{self.file_extension}") def _read_file(self, file_path): pass def _write_file(self, file_path): pass def save_to_file(self): if self.df.empty: logging.debug("Empty DataFrame. Nothing to save...") return full_file_path = self._get_complete_file_name() logging.debug(f"Saving to file {full_file_path} ({self.df.shape[0]} samples)") self._write_file(full_file_path) logging.debug(f"{full_file_path} saved") def append(self, df): self.df = pd.concat([self.df, df], ignore_index=True) def get_newest_timestamp(self,module_mac): if ('module_mac' in self.df.columns): module_utc_time = self.df.loc[self.df['module_mac']==module_mac,'utc_time'] if module_utc_time.size: return module_utc_time.max() return None def _remove_timezone(self): if 'timestamp' in self.df.columns: self.df['timestamp'] = self.df['timestamp'].apply(lambda x: x.replace(tzinfo=None)) logging.debug (f'Timezone was removed for {self.__class__.__name__}') class PickleHandler(DataFrameHandler): def __init__(self, file_name, output_path): super().__init__(file_name, output_path, file_format="pickle") def _read_file(self, file_path): return pd.read_pickle(file_path, **self.kwargs) def _write_file(self, file_path): self.df.to_pickle(file_path, **self.kwargs) class JSONHandler(DataFrameHandler): def __init__(self, file_name, output_path): self.dtype_dict['Humidity'] = np.float64 self.dtype_dict['Noise'] = np.float64 super().__init__(file_name, output_path, file_format="json", kwargs = {"orient": "table"}) def _read_file(self, file_path): return pd.read_json(file_path, convert_dates=False, **self.kwargs) def _write_file(self, file_path): logging.debug('JSON orient table does not support timezones. Removing timezone information...') self._remove_timezone() self.df.to_json(file_path, index=False, **self.kwargs) class CSVHandler(DataFrameHandler): def __init__(self, file_name, output_path): super().__init__(file_name, output_path, file_format="csv") def _read_file(self, file_path): return pd.read_csv(file_path, parse_dates=["timestamp"], **self.kwargs) def _write_file(self, file_path): self.df.to_csv(file_path, index=False, **self.kwargs) class HDFHandler(DataFrameHandler): def __init__(self, file_name, output_path): self.dtype_dict['Humidity'] = np.float64 self.dtype_dict['Noise'] = np.float64 super().__init__(file_name, output_path, file_format="hdf", kwargs={"key": "df"}) def _read_file(self, file_path): return pd.read_hdf(file_path, **self.kwargs) def _write_file(self, file_path): self.df.to_hdf(file_path, mode="w", **self.kwargs) class ParquetHandler(DataFrameHandler): def __init__(self, file_name, output_path): self.dtype_dict['Noise'] = np.float64 super().__init__(file_name, output_path, file_format="parquet") def _read_file(self, file_path): return pd.read_parquet(file_path, **self.kwargs) def _write_file(self, file_path): self.df.to_parquet(file_path, **self.kwargs) class SQLHandler(DataFrameHandler): def __init__(self, file_name, output_path): raise NotImplementedError("sql details not setup") #from sqlalchemy import create_engine #super().__init__(file_name, output_path, file_format="sql", kwargs={"con": self.engine}) #self.engine = create_engine("sqlite://", echo=False) def _read_file(self, file_path): return pd.read_sql(file_path, **self.kwargs) def _write_file(self, file_path): raise NotImplementedError("sql details not setup") self.df.to_sql(file_path, index=False, **self.kwargs) class FeatherHandler(DataFrameHandler): def __init__(self, file_name, output_path): self.dtype_dict['Noise'] = np.float64 super().__init__(file_name, output_path, file_format="feather") def _read_file(self, file_path): return pd.read_feather(file_path, **self.kwargs) def _write_file(self, file_path): self.df.to_feather(file_path, **self.kwargs) class ExcelHandler(DataFrameHandler): def __init__(self, file_name, output_path): super().__init__(file_name, output_path, file_format="excel") def _read_file(self, file_path): return pd.read_excel(file_path, **self.kwargs) def _write_file(self, file_path): logging.debug('Excel does not support timezones. Removing timezone information...') self._remove_timezone() self.df.to_excel(file_path, index=False, **self.kwargs) df_handler_dict = { "json": JSONHandler, "pickle": PickleHandler, "csv": CSVHandler, "hdf": HDFHandler, "feather": FeatherHandler, "sql": SQLHandler, "parquet": ParquetHandler, "excel": ExcelHandler, } class RateLimitHandler: def __init__(self, user_request_limit_per_ten_seconds=50, user_request_limit_per_hour=500, nr_previous_requests=0): self._USER_REQUEST_LIMIT_PER_TEN_SECONDS = user_request_limit_per_ten_seconds logging.debug(f'Ten second rate limit was set to {user_request_limit_per_ten_seconds}') self._USER_REQUST_LIMIT_PER_HOUR = user_request_limit_per_hour logging.debug(f'Hour rate limit was set to {user_request_limit_per_hour}') self._TEN_SECOND_TIMEDELTA = timedelta(seconds=10) self._HOUR_TIMEDELTA = timedelta(hours=1) self._SECOND_TIMEDELTA = timedelta(seconds=1) # Keep track of when we have done requests if nr_previous_requests: logging.debug(f'{nr_previous_requests} previous requests has been assumed') self.requests_series = pd.Series( data=1, index=[datetime.now()], name='request_logger', dtype=np.uint16).repeat(nr_previous_requests) else: logging.debug('No previous requests has been assumed. Creating empty request logger') self.requests_series = pd.Series(name='request_logger',dtype=np.uint16) self._set_authorization() self._set_weather_data() def _get_masked_series(self, time_d): return self.requests_series[self.requests_series.index >= (datetime.now() - time_d)] def _log_request(self): self.requests_series[datetime.now()] = 1 def _set_authorization(self): self._check_rate_limit_and_wait() self.authorization = lnetatmo.ClientAuth() self._log_request() def _set_weather_data(self): self._check_rate_limit_and_wait() self.weather_data = lnetatmo.WeatherStationData(self.authorization) self._log_request() def _sleep(self, until_time): sleep = True tot_seconds = (until_time - datetime.now())/self._SECOND_TIMEDELTA while(sleep): time_left = (until_time - datetime.now())/self._SECOND_TIMEDELTA if(time_left>0): if logging.getLogger().isEnabledFor(logging.INFO): print(f'\t{time_left:.1f}/{tot_seconds:.1f} seconds left',end='\r') time.sleep(1) else: sleep = False def _check_rate_limit_and_wait(self): # Check the 10 second limit ten_sec_series = self._get_masked_series(self._TEN_SECOND_TIMEDELTA) if(ten_sec_series.size >= self._USER_REQUEST_LIMIT_PER_TEN_SECONDS): # Wait until there is at least room for one more request until_time = (ten_sec_series.index[-self._USER_REQUEST_LIMIT_PER_TEN_SECONDS] + self._TEN_SECOND_TIMEDELTA) logging.info(f'10 second limit. Waiting for {(until_time - datetime.now())/self._SECOND_TIMEDELTA:.1f} seconds...') self._sleep(until_time) # Check the 500 second limit hour_series = self._get_masked_series(self._HOUR_TIMEDELTA) if(hour_series.size >= self._USER_REQUST_LIMIT_PER_HOUR): # Wait until there is at least room for one more request until_time = (hour_series.index[-self._USER_REQUST_LIMIT_PER_HOUR] + self._HOUR_TIMEDELTA) logging.info(f'Hour limit hit ({self._USER_REQUST_LIMIT_PER_HOUR} per hour). Waiting for {(until_time - datetime.now())/self._SECOND_TIMEDELTA:.1f} seconds...') self._sleep(until_time) def _get_measurement(self, input_dict): # Check that we don't exceed the user rate limit self._check_rate_limit_and_wait() # Log this request self._log_request() try: return self.weather_data.getMeasure(**input_dict) except socket.timeout as socket_timeout: logging.error(socket_timeout) return None def get_stations(self): return self.weather_data.stations.items() def _get_field_dict(self, station_id,module_id,data_type,start_date,end_date): """Returns a dict to be used when requesting data through the Netatmo API""" return {'device_id':station_id, 'scale':'max', 'mtype':','.join(data_type), 'module_id':module_id, 'date_begin':start_date, 'date_end':end_date} def _get_date_from_timestamp(self, ts, tz=None): return datetime.fromtimestamp(ts,tz).date() def _get_timestamp_from_date(self, d, tz=None): """Returns the timetamp corresponding to the end of the day d""" # Create datetime from date combined_datetime = datetime.combine(d, datetime.max.time(), tzinfo=tz) return np.floor(datetime.timestamp(combined_datetime)) def _get_common_elements(self, keys, column_names): return list(set(keys).intersection(column_names)) def _to_dataframe(self, module_data_body, module_data, station_name, station_mac, dtype={}, time_z=None): """Convert the dict to a pandas DataFrame""" df = pd.DataFrame.from_dict(module_data_body,orient='index',columns=module_data['data_type']) df['type'] = module_data['type'] df['module_name'] = module_data['module_name'] df['module_mac'] = module_data['_id'] df['station_name'] = station_name df['station_mac'] = station_mac df.index.set_names('utc_time',inplace=True) df.reset_index(inplace=True) df['timestamp'] = df['utc_time'].apply(lambda x: datetime.fromtimestamp(np.uint32(x), tz=time_z)) common_names = self._get_common_elements(dtype.keys(), df.columns) dtypes = {k: dtype[k] for k in common_names} return df.astype(dtypes) def get_module_df(self, newest_utctime, station_name, station_mac, module_data_overview, end_date_timestamp, dtype={}, time_z=None): logging.info(f'Processing {module_data_overview["module_name"]}...') module_name = module_data_overview["module_name"] # We start by collecting new data keep_collecting_module_data = True # Start with the oldest timestamp module_start_date_timestamp = module_data_overview['last_setup'] # Fill array with data data = [] if(newest_utctime): # Found newer data! Change start time according to the newest value if(newest_utctime > module_start_date_timestamp): module_start_date_timestamp = newest_utctime + 1 logging.info(f'Newer data found for {module_name}. Setting new start date to {self._get_date_from_timestamp(module_start_date_timestamp, tz=time_z)}') else: logging.debug(f'No newer data found for module {module_name}, starting from last setup.') if(end_date_timestamp < module_start_date_timestamp): logging.info('Start date is after end date. Nothing to do...') keep_collecting_module_data = False else: logging.info(f'Collecting data for {module_name}...') while(keep_collecting_module_data): # Get new data from Netatmo d = self._get_field_dict(station_mac, module_data_overview['_id'], module_data_overview['data_type'], module_start_date_timestamp, end_date_timestamp) retreived_module_data = self._get_measurement(d) if retreived_module_data is None: logging.warning(f'None received. Aborting data collection from module {module_name}') keep_collecting_module_data = False else: try: # Was there any data? if(retreived_module_data['body']): new_df = self._to_dataframe(retreived_module_data['body'], module_data_overview, station_name, station_mac, dtype, time_z) data.append(new_df) new_df['utc_time'].min() logging.debug(f'{len(retreived_module_data["body"])} samples found for {module_data_overview["module_name"]}. {new_df["timestamp"].iloc[0]} - {new_df["timestamp"].iloc[-1]}') # Now change the start_time module_start_date_timestamp = new_df['utc_time'].max() + 1 else: keep_collecting_module_data = False logging.debug(f'Data not found for {module_name}. Proceeding...') except Exception as e: logging.error(e) keep_collecting_module_data = False logging.error(f'Something fishy is going on... Aborting collection for module {module_name}') if data: df_module = pd.concat(data,ignore_index=True) else: df_module = pd.DataFrame([]) logging.info(f'Collected data from {module_name} contains {df_module.shape[0]} samples.') return df_module def main(): parser = argparse.ArgumentParser( description="Save historical information for all weather modules from Netatmo to file" ) parser.add_argument( "-f", "--format", choices=["json", "csv", "pickle", "hdf", "feather", "parquet", "excel"], required=True, help="Format for which the data is to be saved", ) parser.add_argument( "-e", "--end-datetime", type=valid_datetime_type, default=datetime.now(), required=False, help="The end datetime of data to be saved, in the format YYYY-MM-DD_hh:mm (default: now)", ) parser.add_argument( "-v", "--verbose", choices=["debug", "info", "warning", "error", "quiet"], default="info", required=False, help="Verbose level (default: info)") parser.add_argument( "-n", "--file-name", default="weatherdata", required=False, help="Name of the output file (default: weatherdata)") parser.add_argument( "-o", "--output-path", type=userexpanded_path_str, default=".", required=False, help="Output location (default: current folder)") parser.add_argument( "-p", "--previous-requests", type=np.uint16, default=np.uint8(0), required=False, help="Assumes this many previous requests has been done, so that the rate limit is not exceeded (default: 0)") parser.add_argument( "-hrl", "--hour-rate-limit", type=valid_hour_limit, default=400, required=False, help="Specify the rate limit per hour (default: 400, max: 500)") parser.add_argument( "-t", "--ten-second-rate-limit", type=valid_ten_seconds_limit, default=30, required=False, help="Specify the rate limit per ten seconds (default: 30, max: 50)") args = parser.parse_args() if(args.verbose == 'quiet'): logging.disable(logging.DEBUG) else: logging.basicConfig(format=" %(levelname)s: %(message)s", level=verbose_dict[args.verbose]) # Handle dataframes (loading, appending, saving). df_handler = df_handler_dict[args.format](file_name=args.file_name, output_path=args.output_path) # Rate handler to make sure that we don't exceed Netatmos user rate limits rate_limit_handler = RateLimitHandler( user_request_limit_per_ten_seconds=args.ten_second_rate_limit, user_request_limit_per_hour=args.hour_rate_limit, nr_previous_requests=args.previous_requests) for station_name, station_data_overview in rate_limit_handler.get_stations(): station_mac = station_data_overview['_id'] station_timezone = timezone(station_data_overview['place']['timezone']) logging.info(f'Timezone {station_timezone} extracted from data.') end_datetime_timestamp = np.floor(datetime.timestamp(station_timezone.localize(args.end_datetime))) newest_utc = df_handler.get_newest_timestamp(station_data_overview['_id']) df_handler.append( rate_limit_handler.get_module_df( newest_utc, station_name, station_mac, station_data_overview, end_datetime_timestamp, df_handler.dtype_dict, station_timezone)) for module_data_overview in station_data_overview['modules']: df_handler.append( rate_limit_handler.get_module_df( df_handler.get_newest_timestamp(module_data_overview['_id']), station_name, station_mac, module_data_overview, end_datetime_timestamp, df_handler.dtype_dict, station_timezone)) # Save the data after the collection df_handler.save_to_file() if __name__ == "__main__": main() ================================================ FILE: setup.cfg ================================================ [metadata] description-file = README.md ================================================ FILE: setup.py ================================================ # python setup.py --dry-run --verbose install from distutils.core import setup setup( name='lnetatmo', version='4.2.1', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3' ], author='Philippe Larduinat', author_email='ph.larduinat@wanadoo.fr', py_modules=['lnetatmo'], scripts=[], data_files=[], url='https://github.com/philippelt/netatmo-api-python', download_url='https://github.com/philippelt/netatmo-api-python/archive/v4.2.1.tar.gz', license='GPL V3', description='Simple API to access Netatmo weather station data from any python script.' ) ================================================ FILE: usage.md ================================================ Python Netatmo API programmers guide ------------------------------------ >2013-01-21, philippelt@users.sourceforge.net >2014-01-13, Revision to include new modules additionnal informations >2016-06-25, Update documentation for Netatmo Welcome >2017-01-09, Minor updates to packaging info >2020-12-07, Breaking changes due to removal of direct access to devices, "home" being now required (Netatmo redesign) >2023-07-12, Breaking changes due to deprecation of grant_type "password" for ALL apps >2023-07-24, Adding rawAPI call to direct access the netatmo API when no additional support is provided by the library >2023-12-04, New update to Netatmo authentication rules, no longer long lived refresh token -> credentials MUST be writable, Hard coding credentials in the library no longer possible (bad luck for small home automation device) >2024-01-03, New authentication method priorities, credential file as a parameter No additional library other than standard Python library is required. Both Python V2.7x and V3.x.x are supported without change. More information about the Netatmo REST API can be obtained from http://dev.netatmo.com/doc/ This package support only preauthenticated scoped tokens created along apps. ### 1 Setup your environment from Netatmo Web interface ### Before being able to use the module you will need : * A Netatmo user account having access to, at least, one station * An application registered from the user account (see http://dev.netatmo.com/dev/createapp) to obtain application credentials. * Create a couple access_token/refresh_token at the same time with your required scope (depending of your intents on library use) In the netatmo philosophy, both the application itself and the user have to be registered thus have authentication credentials to be able to access any station. Registration is free for both. Possible NETATMO_SCOPES ; read_station read_smarther write_smarther read_thermostat write_thermostat read_camera write_camera read_doorbell read_presence write_precense read_homecoach read_carbonmonoxidedetector read_smokedetector read_magellen write_magellan read_bubendorff write_bubendorff read_mx write_mx read_mhs1 write_mhs1 ### 2 Setup your authentication information ### Copy the lnetatmo.py file in your work directory (or use pip install lnetatmo). Authentication data can be supplied with 3 different methods (each method override any settings of previous methods) : 1. Some or all values can be defined by explicit call to initializer of ClientAuth class ̀```bash # Example: REFRESH_TOKEN supposed to be defined by an other method authData = lnetatmo.ClientAuth( clientId="netatmo-client-id", clientSecret="secret" ) ``` 2. Some or all values can stored in ~/.netatmo.credentials (in your platform home directory) or a file path specified using the ̀`credentialFile` parameter. The file containing the keys in JSON format ̀̀```bash $ cat .netatmo.credentials # Here all values are defined but it is not mandatory { "CLIENT_ID" : "`xxx", "CLIENT_SECRET" : "xxx", "REFRESH_TOKEN" : "xxx" } $ ̀̀``` 3. Some or all values can be overriden by environment variables. This is the easiest method if your are packaging your application with Docker. ̀̀```bash $ export REFRESH_TOKEN="yyy" $ python3 MyCodeUsingLnetatmo.py ̀̀``` > Due to Netatmo continuous changes, the credential file is the recommended method for production use as the refresh token will be frequently refreshed and this file MUST be writable by the library to keep a usable refresh token. You can also recover the `authorization.refreshToken` before your program termination and save it to be able to pass it back when your program restart. If you provide all the values in a credential file, you can test that everything is working properly by simply running the package as a standalone program. This will run a full access test to the account and stations and return 0 as return code if everything works well. If run interactively, it will also display an OK message. ```bash $ python3 lnetatmo.py # or python2 as well lnetatmo.py : OK $ echo $? 0 ``` Whatever is your choice for the library authentication setup, your application code if you were using previous library version, will not be affected. ### 3 Package guide ### Most of the time, the sequence of operations will be : 1. Authenticate your program against Netatmo web server 2. Get the device list accessible to the user 3. Request data on one of these devices or directly access last data sent by the station Example : ```python #!/usr/bin/python3 # encoding=utf-8 import lnetatmo # 1 : Authenticate authorization = lnetatmo.ClientAuth() # 2 : Get devices list weatherData = lnetatmo.WeatherStationData(authorization) # 3 : Access most fresh data directly print ("Current temperature (inside/outside): %s / %s °C" % ( weatherData.lastData()['indoor']['Temperature'], weatherData.lastData()['outdoor']['Temperature']) ) ``` In this example, no init parameters are supplied to ClientAuth, the library is supposed to have been customized with the required values (see §2). The user must have nammed the sensors indoor and outdoor through the Web interface (or any other name as long as the program is requesting the same name). The Netatmo design is based on stations (usually the in-house module) and modules (radio sensors reporting to a station, usually an outdoor sensor). Sensor design is not exactly the same for station and external modules and they are not addressed the same way wether in the station or an external module. This is a design issue of the API that restrict the ability to write generic code that could work for station sensor the same way than other modules sensors. The station role (the reporting device) and module role (getting environmental data) should not have been mixed. The fact that a sensor is physically built in the station should not interfere with this two distincts objects. The consequence is that, for the API, we will use terms of station data (for the sensors inside the station) and module data (for external(s) module). Lookup methods like moduleByName look for external modules and **NOT station modules**. Having two roles, the station has a 'station_name' property as well as a 'module_name' for its internal sensor. >Exception : to reflect again the API structure, the last data uploaded by the station is indexed by module_name (wether it is a station module or an external module). Sensors (stations and modules) are managed in the API using ID's (network hardware adresses). The Netatmo web account management gives you the capability to associate names to station sensor and module (and to the station itself). This is by far more comfortable and the interface provides service to locate a station or a module by name or by Id depending of your taste. Module lookup by name includes the optional station name in case multiple stations would have similar module names (if you monitor multiple stations/locations, it would not be a surprise that each of them would have an 'outdoor' module). This is a benefit in the sense it give you the ability to write generic code (for exemple, collect all 'outdoor' temperatures for all your stations). The results are Python data structures, mostly dictionaries as they mirror easily the JSON returned data. All supplied classes provides simple properties to use as well as access to full data returned by the netatmo web services (rawData property for most classes). ### 4 Package classes and functions ### #### 4-1 Global variables #### ```python _CLIENT_ID, _CLIENT_SECRET = Application ID and secret provided by Netatmo application registration in your user account _REFRESH_TOKEN : Refresh token created along the app client credentials _BASE_URL and _*_REQ : Various URL to access Netatmo web services. They are documented in http://dev.netatmo.com/doc/ They should not be changed unless Netatmo API changes. ``` #### 4-2 ClientAuth class #### Constructor ```python authorization = lnetatmo.ClientAuth( clientId = _CLIENT_ID, clientSecret = _CLIENT_SECRET, refreshToken = _REFRESH_TOKEN, credentialFile = "~/.netatmo.credentials" ) ``` Requires : Application and User credentials to access Netatmo API. if all this parameters are put in global variables they are not required (in library source code or in the main program through lnetatmo._CLIENT_ID = …) Return : an authorization object that will supply the access token required by other web services. This class will handle the renewal of the access token if expiration is reached. Properties, all properties are read-only unless specified : * **accessToken** : Retrieve a valid access token (renewed if necessary) * **refreshToken** : The token used to renew the access token (normally should not be used explicitely) * **expiration** : The expiration time (epoch) of the current token #### 4-3 User class #### Constructor ```python user = lnetatmo.User( authorization ) ``` Requires : an authorization object (ClientAuth instance) Return : a User object. This object provides multiple informations on the user account such as the mail address of the user, the preferred language, … Properties, all properties are read-only unless specified : * **rawData** : Full dictionary of the returned JSON GETUSER Netatmo API service * **ownerMail** : eMail address associated to the user account * **devList** : List of Station's id accessible to the user account In most cases, you will not need to use this class that is oriented toward an application that would use the other authentication method to an unknown user and then get information about him. #### 4-4 WeatherStationData class #### Constructor ```python weatherData = lnetatmo.WeatherStationData( authorization, home=None, station=None ) ``` * Input : an authorization object (ClientAuth instance), an optional home name, an optional station name or id Return : a WeatherStationData object. This object contains most administration properties of stations and modules accessible to the user and the last data pushed by the station to the Netatmo servers. Raise a lnetatmo.NoDevice exception if no weather station is available for the given account. If no home is specified, the first returned home will be set as default home. Same apply to station. If you have only one home and one station, you can safely ignore these new parameters. Note that return order is undefined. If you have multiple homes and a weather station in only one, the default home may be the one without station and the call will fail. >**Breaking change:** If you used the station name in the past in any method call, you should be aware that Netatmo decided to rename your station with their own value thus your existing code will have to be updated. Properties, all properties are read-only unless specified: * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service * **default_station** : Name of the first station returned by the web service (warning, this is mainly for the ease of use of peoples having only 1 station). * **stations** : Dictionary of stations (indexed by ID) accessible to this user account * **modules** : Dictionary of modules (indexed by ID) accessible to the user account (whatever station there are plugged in) Methods : * **getStation** (station=None) : Find a station by it's station name or station ID * Input : Station name or ID to lookup (str) * Output : station dictionary or None * **stationByName** (station=None) : Find a station by it's station name * Input : Station name to lookup (str) * Output : station dictionary or None * **stationById** (sid) : Find a station by it's Netatmo ID (mac address) * Input : Station ID * Output : station dictionary or None * **moduleByName** (module, station=None) : Find a module by it's module name * Input : module name and optional station name * Output : module dictionary or None The station name parameter, if provided, is used to check wether the module belongs to the appropriate station (in case multiple stations would have same module name). * **moduleById** (mid, sid=None) : Find a module by it's ID and belonging station's ID * Input : module ID and optional Station ID * Output : module dictionary or None * **modulesNamesList** (station=None) : Get the list of modules names, including the station module name. Each of them should have a corrsponding entry in lastData. It is an equivalent (at lower cost) for lastData.keys() * **lastData** (station=None, exclude=0) : Get the last data uploaded by the station, exclude sensors with measurement older than given value (default return all) * Input : station name OR id. If not provided default_station is used. Exclude is the delay in seconds from now to filter sensor readings. * Output : Sensors data dictionary (Key is sensor name) AT the time of this document, Available measures types are : * a full or subset of Temperature, Pressure, Noise, Co2, Humidity, Rain (mm of precipitation during the last 5 minutes, or since the previous data upload), When (measurement timestamp) for modules including station module * battery_vp : likely to be total battery voltage for external sensors (running on batteries) in mV (undocumented) * rf_status : likely to be the % of radio signal between the station and a module (undocumented) See Netatmo API documentation for units of regular measurements If you named the internal sensor 'indoor' and the outdoor one 'outdoor' (simple is'n it ?) for your station in the user Web account station properties, you will access the data by : ```python # Last data access example theData = weatherData.lastData() print('Available modules : ', theData.keys() ) print('In-house CO2 level : ', theData['indoor']['Co2'] ) print('Outside temperature : ', theData['outdoor']['Temperature'] ) print('External module battery : ', "OK" if int(theData['outdoor']['battery_vp']) > 5000 \ else "NEEDS TO BE REPLACED" ) ``` * **checkNotUpdated** (station=None, delay=3600) : * Input : optional station name (else default_station is used) * Output : list of modules name for which last data update is older than specified delay (default 1 hour). If the station itself is lost, the module_name of the station will be returned (the key item of lastData information). For example (following the previous one) ```python # Ensure data sanity for m in weatherData.checkNotUpdated(""): print("Warning, sensor %s information is obsolete" % m) if moduleByName(m) == None : # Sensor is not an external module print("The station is lost") ``` * **checkUpdated** (station=None, delay=3600) : * Input : optional station name (else default_station is used) * Output : list of modules name for which last data update is newer than specified delay (default 1 hour). Complement of the previous service * **getMeasure** (device_id, scale, mtype, module_id=None, date_begin=None, date_end=None, limit=None, optimize=False) : * Input : All parameters specified in the Netatmo API service GETMEASURE (type being a python reserved word as been replaced by mtype). * Output : A python dictionary reflecting the full service response. No transformation is applied. * **MinMaxTH** (station=None, module=None, frame="last24") : Return min and max temperature and humidity for the given station/module in the given timeframe * Input : * An optional station Name or ID, default_station is used if not supplied, * An optional module name or ID, default : station sensor data is used * A time frame that can be : * "last24" : For a shifting window of the last 24 hours * "day" : For all available data in the current day * Output : * A 4 values tuple (Temp mini, Temp maxi, Humid mini, Humid maxi) >Note : I have been oblliged to determine the min and max manually, the built-in service in the API doesn't always provide the actual min and max. The double parameter (scale) and aggregation request (min, max) is not satisfying at all if you slip over two days as required in a shifting 24 hours window. #### 4-5 HomeData class #### Constructor ```python homeData = lnetatmo.HomeData( authorization ) ``` Requires : an authorization object (ClientAuth instance) Return : a homeData object. This object contains most administration properties of home security products and notably Welcome & Presence cameras. Note : the is_local property of camera is most of the time unusable if your IP changes, use cameraUrls to try to get a local IP as a replacement. Properties, all properties are read-only unless specified: * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service * **default_home** : Name of the first home returned by the web service (warning, this is mainly for the ease of use of peoples having cameras in only 1 house). * **default_camera** : Data of the first camera in the default home returned by the web service (warning, this is mainly for the ease of use of peoples having only 1 camera). * **homes** : Dictionary of homes (indexed by ID) accessible to this user account * **cameras** : Dictionnary of cameras (indexed by home name and cameraID) accessible to this user * **persons** : Dictionary of persons (indexed by ID) accessible to the user account * **events** : Dictionary of events (indexed by cameraID and timestamp) seen by cameras Methods : * **homeById** (hid) : Find a home by its Netatmo ID * Input : Home ID * Output : home dictionary or None * **homeByName** (home=None) : Find a home by it's home name * Input : home name to lookup (str) * Output : home dictionary or None * **cameraById** (hid) : Find a camera by its Netatmo ID * Input : camera ID * Output : camera dictionary or None * **cameraByName** (camera=None, home=None) : Find a camera by it's camera name * Input : camera name and home name to lookup (str) * Output : camera dictionary or None * **cameraUrls** (camera=None, home=None, cid=None) : return Urls to access camera live feed * Input : camera name and optional home name or cameraID to lookup (str) * Output : tuple with the vpn_url (for remote access) and local url to access the camera (commands) * **url** (camera=None, home=None, cid=None) : return the best url to access camera live feed * Input : camera name and optional home name or cameraID to lookup (str) * Output : the local url if available to reduce internet bandwith usage else the vpn url * **personsAtHome** (home=None) : return the list of known persons who are at home * Input : home name to lookup (str) * Output : list of persons seen * **getCameraPicture** (image_id, key): Download a specific image (of an event or user face) from the camera * Input : image_id and key of an events or person face * Output: Tuple with image data (to be stored in a file) and image type (jpg, png...) * **getProfileImage** (name) : Retreive the face of a given person * Input : person name (str) * Output: **getCameraPicture** data * **updateEvent** (event=None, home=None): Update the list of events * Input: Id of the latest event and home name to update event list * **personSeenByCamera** (name, home=None, camera=None): Return true is a specific person has been seen by the camera in the last event * **someoneKnownSeen** (home=None, camera=None) : Return true is a known person has been in the last event * **someoneUnknownSeen** (home=None, camera=None) : Return true is an unknown person has been seen in the last event * **motionDetected** (home=None, camera=None) : Return true is a movement has been detected in the last event * **presenceLight** (camera=None, home=None, cid=None, setting=None) : return or set the Presence camera lighting mode * Input : camera name and optional home name or cameraID to lookup (str), setting must be None|auto|on|off. *currently not supported* * Output : setting requested if supplied else current camera setting * **presenceStatus** (mode, camera=None, home=None, cid=None) : set the camera on or off (current status in camera properties) * Input : mode (on|off) (str), camera name and optional home name or cameraID to lookup (str) * Output : requested mode if changed else None * **getLiveSnapshot** (camera=None, home=None, cid=None) : Get a jpeg of current live view of the camera * Input : camera name and optional home name or cameraID to lookup (str) * Output : jpeg binary content ``` homedata = lnetatmo.HomeData(authorization) for k, v in homedata.homes.items(): homeid = k S = v.get('smokedetectors') C = v.get('cameras') P = v.get('persons') E = v.get('events') if S or C or P or E: print ('devices in HomeData') for smokedetector in homedata.homes[homeid].get('smokedetectors'): print (smokedetector['name']) for camera in homedata.homes[homeid].get('cameras'): print (camera['name']) for persons in homedata.homes[homeid].get('persons'): print (persons['name']) for events in homedata.homes[homeid].get('events'): print (events['name']) return homeid else: homeid = k return homeid ``` #### 4-6 HomeStatus class #### Constructor ``` homeStatus = lnetatmo.HomeStatus( authorization, home_id ) ``` Requires : - an authorization object (ClientAuth instance) - home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using "class homedata" Return : a homeStatus object. This object contains most administration properties of Home+ Control devices such as Smarther thermostat, Socket, Cable Output, Centralized fan, Micromodules, ... Methods : * **getRoomsId** : return all room ID * Output : list of IDs of every single room (only the one with Smarther thermostat) * **getListRoomParam** : return every parameters of a room * Input : room ID * Output : list of parameters of a room * **getRoomParam** : return a specific parameter for a specific room * Input : room ID and parameter * Output : value * **getModulesId** : return all module IDs * Output : list of IDs of every single module (socket, cable outlet, ...) * **getListModuleParam** : return every parameters of a module * Input : module ID * Output : list of parameters of a module * **getModuleParam** : return a specific parameter for a specific module * Input : module ID and parameter * Output : value ``` homestatus = lnetatmo.HomeStatus(authorization, homeid) print ('Rooms in Homestatus') for r in homestatus.rooms: print (r) print ('Persons in Homestatus') if 'persons' in homestatus.rawData.keys(): for pp in homestatus.rawData['persons']: print (pp) print ('Modules in Homestatus') for m in homestatus.modules: for kt, vt in m.items(): if kt == 'type': print (m['type']) print (m['id']) print (lnetatmo.TYPES[vt]) print (m.keys()) ``` #### 4-7 ThermostatData class #### Constructor ``` device = lnetatmo.ThermostatData ( authorization, home_id ) ``` Requires : - an authorization object (ClientAuth instance) - home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using "class homedata" Return : a device object. This object contains the Relay_Plug with Thermostat and temperature modules. Methods : * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service * Output : list of IDs of every relay_plug * **Relay_Plug** : * Output : Dictionairy of First Relay object * **Thermostat_Data** : * Output : Dictionairy of Thermostat object in First Relay[Modules]. Example : ``` device = lnetatmo.ThermostatData(authorization, homeid) for i in device.rawData: print ('rawData') print (i['_id']) print (i['station_name']) print (dir(i)) print ('modules in rawData') print (i['modules'][0]['_id']) print (i['modules'][0]['module_name']) print (' ') print ('Relay Data') Relay = device.Relay_Plug() print (Relay.keys()) print ('Thermostat Data') TH = device.Thermostat_Data() print (TH.keys()) ``` #### 4-8 HomesData class #### Constructor ```python homesData = lnetatmo.HomesData ( authorization, home_id ) ``` Requires : - an authorization object (ClientAuth instance) - home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using "class homedata" Return : a homesdata object. This object contains the Netatmo actual topology and static information of all devices present into a user account. It is also possible to specify a home_id to focus on one home. Methods : * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service * Output : list of IDs of every devices Example : ``` homesData = lnetatmo.HomesData ( authorization, home_id ) print (homesdata.Homes_Data['name']) print (homesdata.Homes_Data['altitude']) print (homesdata.Homes_Data['coordinates']) print (homesdata.Homes_Data['country']) print (homesdata.Homes_Data['timezone']) print ('rooms in HomesData') for r in homesdata.Homes_Data.get('rooms'): print (r) print ('Devices in HomesData') for m in homesdata.Homes_Data.get('modules'): print (m) print ('Persons in HomesData') if 'persons' in homesdata.Homes_Data.keys(): for P in homesdata.Homes_Data.get('persons'): print (P) print ('Schedules in HomesData') print (homesdata.Homes_Data['schedules'][0].keys()) ``` #### 4-9 Homecoach class #### Constructor ```python homecoach = lnetatmo.HomeCoach(authorization, home_id ) ``` Requires : - an authorization object (ClientAuth instance) - home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using "class homedata" Return : a homecoach object. This object contains all Homecoach Data. Methods : * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service * Output : list of all Homecoach in user account * **checkNotUpdated** : * Output : list of modules name for which last data update is older than specified delay (default 1 hour). * **checkUpdated** : * Output : list of modules name for which last data update is newer than specified delay (default 1 hour). Example : ``` homecoach = lnetatmo.HomeCoach(authorization, homeid) # Not_updated = [] updated = [] d = {} for device in homecoach.rawData: _id = device['_id'] d.update({'When': device['dashboard_data']['time_utc']}) a = homecoach.checkNotUpdated(d, _id) b = homecoach.checkUpdated(d, _id) print (device['station_name']) print (device['date_setup']) print (device['last_setup']) print (device['type']) print (device['last_status_store']) print (device['firmware']) print (device['last_upgrade']) print (device['wifi_status']) print (device['reachable']) print (device['co2_calibrating']) print (device['data_type']) print (device['place']) print (device['dashboard_data']) Not_updated.append(a) updated.append(b) D = homecoach.HomecoachDevice['dashboard_data'] print (D.keys()) # dict_keys(['time_utc', 'Temperature', 'CO2', 'Humidity', 'Noise', 'Pressure', 'AbsolutePressure', 'health_idx', 'min_temp', 'max_temp', 'date_max_temp', 'date_min_temp']) print (Not_updated) print (updated) ``` #### 4-10 Utilities functions #### * **rawAPI** (authentication, APIkeyword, parameters) : Direct call an APIkeyword from Netatmo and return a dictionary with the raw response the APIkeywork is the path without the / before as specified in the documentation (eg. "gethomesdata" or "homestatus") * **toTimeString** (timestamp) : Convert a Netatmo time stamp to a readable date/time format. * **toEpoch**( dateString) : Convert a date string (form YYYY-MM-DD_HH:MM:SS) to timestamp * **todayStamps**() : Return a couple of epoch time (start, end) for the current day #### 4-11 All-in-One function #### If you just need the current temperature and humidity reported by a sensor with associated min and max values on the last 24 hours, you can get it all with only one call that handle all required steps including authentication : **getStationMinMaxTH**(station=None, module=None, home=None) : * Input : optional station name and/or module name (if no station name is provided, default_station will be used, if no module name is provided, station sensor will be reported). if no home is specified, first returned home will be used * Output : A tuple of 6 values (Temperature, Humidity, minT, MaxT, minH, maxH) ```python >>> import lnetatmo >>> print(lnetatmo.getStationMinMaxTH()) [20, 33, 18.1, 20, 30, 34] >>> >>> print(lnetatmo.getStationMinMaxTH(module='outdoor')) [2, 53, 1.2, 5.4, 51, 74]