[
  {
    "path": ".github/workflows/lint_python.yml",
    "content": "name: lint_python\non: [pull_request, push]\njobs:\n  lint_python:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v2\n      - uses: actions/setup-python@v2\n      - run: pip install black codespell flake8 isort pytest pyupgrade\n      - run: black --check . || true\n      - run: codespell --quiet-level=2 || true  # --ignore-words-list=\"\" --skip=\"\"\n      - run: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics\n      - run: isort --profile black . || true\n      - run: pip install -r requirements.txt || true\n      - run: pytest . || true\n      - run: shopt -s globstar && pyupgrade --py36-plus **/*.py || true\n"
  },
  {
    "path": ".gitignore",
    "content": "\nbuild/\n\ndist/\n\nlnetatmo.egg-info/\n\n*.pyc\n\n__pycache__/\n\nMANIFEST*\n\n*.csv\n*.h5\n*.feather\n*.json\n*.parquet\n*.pkl\n*.xlsx\n\n"
  },
  {
    "path": ".netatmo.credentials",
    "content": "{\n    \"CLIENT_ID\" : \"\",\n    \"CLIENT_SECRET\" : \"\",\n    \"REFRESH_TOKEN\" : \"\"\n}\n\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "netatmo-api-python\n==================\n\nSimple API to access Netatmo weather station data from any python script\nFor more detailed information see http://dev.netatmo.com\n\nI have no relation with the netatmo company, I wrote this because I needed it myself,\nand published it to save time to anyone who would have same needs.\n\nThere 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.\n>[!CAUTION]\n> 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.\n\n>[!NOTE]\n> 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.  \n> 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.  \n> It is only an information for the Netatmo records, there is absolutely no use of this information by the library.\n\n>[!CAUTION]\n> 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.\n\n### Install ###\n\nTo install lnetatmo simply run:\n\n    python setup.py install\n\n  or\n\n    pip install lnetatmo\n\nDepending on your permissions you might be required to use sudo.\n\nIt 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.\n\nOnce installed you can simple add lnetatmo to your python scripts by including:\n\n    import lnetatmo\n\nFor documentation, see usage\n"
  },
  {
    "path": "lnetatmo.py",
    "content": "# Published Jan 2013\n# Author : Philippe Larduinat, ph.larduinat@wanadoo.fr\n# Multiple contributors : see https://github.com/philippelt/netatmo-api-python\n# License : GPL V3\n\"\"\"\nThis API provides access to the Netatmo weather station or/and other installed devices\nThis package can be used with Python2 or Python3 applications and do not\nrequire anything else than standard libraries\n\nPythonAPI Netatmo REST data access\ncoding=utf-8\n\"\"\"\n\nimport warnings\nif __name__ == \"__main__\": warnings.filterwarnings(\"ignore\")                              # For installation test only\n\nfrom sys import version_info\nfrom os import getenv\nfrom os.path import expanduser\nimport json, time\nimport logging\n\n# Just in case method could change\nPYTHON3 = version_info.major > 2\n\n# HTTP libraries depends upon Python 2 or 3\nif PYTHON3 :\n    import urllib.parse, urllib.request\nelse:\n    from urllib import urlencode\n    import urllib2\n\n\n######################## AUTHENTICATION INFORMATION ######################\n\n# To be able to have a program accessing your netatmo data, you have to register your program as\n# a Netatmo app in your Netatmo account. All you have to do is to give it a name (whatever) and you will be\n# returned a client_id and secret that your app has to supply to access netatmo servers.\n\n# To ease Docker packaging of your application, you can setup your authentication parameters through env variables\n\n# Authentication:\n#  1 - Values defined in environment variables : CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN\n#  2 - Parameters passed to ClientAuth initialization\n#  3 - The .netatmo.credentials file in JSON format in your home directory (now mandatory for regular use)\n\n# Note that the refresh token being short lived, using envvar will be restricted to speific testing use case\n\n#########################################################################\n\n\n# Common definitions\n\n_BASE_URL = \"https://api.netatmo.com/\"\n_AUTH_REQ              = _BASE_URL + \"oauth2/token\"\n_GETMEASURE_REQ        = _BASE_URL + \"api/getmeasure\"\n_GETSTATIONDATA_REQ    = _BASE_URL + \"api/getstationsdata\"\n_GETTHERMOSTATDATA_REQ = _BASE_URL + \"api/getthermostatsdata\"\n_GETHOMEDATA_REQ       = _BASE_URL + \"api/gethomedata\"\n_GETCAMERAPICTURE_REQ  = _BASE_URL + \"api/getcamerapicture\"\n_GETEVENTSUNTIL_REQ    = _BASE_URL + \"api/geteventsuntil\"\n_HOME_STATUS           = _BASE_URL + \"api/homestatus\"                                     # Used for Home+ Control Devices\n_GETHOMES_DATA         = _BASE_URL + \"api/homesdata\"                                      # New API\n_GETHOMECOACH          = _BASE_URL + \"api/gethomecoachsdata\"                              #\n\n#TODO# Undocumented (but would be very usefull) API : Access currently forbidden (403)\n\n_POST_UPDATE_HOME_REQ  = _BASE_URL + \"/api/updatehome\"\n\n# For presence setting (POST BODY):\n# _PRES_BODY_REC_SET     = \"home_id=%s&presence_settings[presence_record_%s]=%s\"          # (HomeId, DetectionKind, DetectionSetup.index)\n_PRES_DETECTION_KIND   = (\"humans\", \"animals\", \"vehicles\", \"movements\")\n_PRES_DETECTION_SETUP  = (\"ignore\", \"record\", \"record & notify\")\n\n# _PRES_BODY_ALERT_TIME  = \"home_id=%s&presence_settings[presence_notify_%s]=%s\"          # (HomeID, \"from\"|\"to\", \"hh:mm\")\n\n# Regular (documented) commands (both cameras)\n\n_PRES_CDE_GET_SNAP     = \"/live/snapshot_720.jpg\"\n\n#TODO# Undocumented (taken from https://github.com/KiboOst/php-NetatmoCameraAPI/blob/master/class/NetatmoCameraAPI.php)\n# Work with local_url only (undocumented scope control probably)\n\n# For Presence camera\n\n_PRES_CDE_GET_LIGHT    = \"/command/floodlight_get_config\"\n# Not working yet, probably due to scope restriction\n#_PRES_CDE_SET_LIGHT    = \"/command/floodlight_set_config?config=mode:%s\"                 # \"auto\"|\"on\"|\"off\"\n\n\n# For all cameras\n\n_CAM_CHANGE_STATUS     = \"/command/changestatus?status=%s\"                                # \"on\"|\"off\"\n# Not working yet\n#_CAM_FTP_ACTIVE        = \"/command/ftp_set_config?config=on_off:%s\"                      # \"on\"|\"off\"\n\n#Known TYPE used by Netatmo services + API,      there can be more types possible\nTYPES = {\n    'BFII'         : [\"Bticino IP Indoor unit\", 'Home + Security'],\n    'BFIC'         : [\"Bticino IP Guard station\", 'Home + Security'],\n    'BFIO'         : [\"Bticino IP Entrance panel\", 'Home + Security'],\n    'BFIS'         : [\"Bticino Server DES\", 'Home + Security'],\n    'BN3L'         : [\"Bticino 3rd party light\", 'Home+Control'],\n    'BNAB'         : [\"Bticino module automatic blind\", 'Home+Control'],\n    'BNAS'         : [\"Bticino module automatic shutter\", 'Home+Control'],\n    'BNS'          : [\"Smarther with Netatmo Thermostat\", 'Home+Control'],\n    'BNCU'         : [\"Bticino Bticino Alarm Central Unit\", 'Home + Security'],\n    'BNCS'         : [\"Bticino module Controlled Socket\", 'Home+Control'],\n    'BNCX'         : [\"Bticino Class 300 EOS\", 'Home + Security'],\n    'BNDL'         : [\"Bticino Doorlock\", 'Home + Security'],\n    'BNEU'         : [\"Bticino external unit\", 'Home + Security'],\n    'BNFC'         : [\"Bticino Thermostat\", 'Home+Control'],\n    'BNIL'         : [\"Bticino intelligent light\", 'Home+Control'],\n    'BNLD'         : [\"Bticino module lighting dimmer\", 'Home+Control'],\n    'BNMH'         : [\"Bticino My Home Server 1\", 'Home + Security'],                     # also API Home+Control  GATEWAY\n    'BNMS'         : [\"Bticino module motorized shade\", 'Home+Control'],\n    'BNSE'         : [\"Bticino Alarm Sensor\", 'Home + Security'],\n    'BNSL'         : [\"Bticino Staircase Light\", 'Home + Security'],\n    'BNTH'         : [\"Bticino Thermostat\", 'Home+Control'],\n    'BNTR'         : [\"Bticino module towel rail\", 'Home+Control'],\n    'BNXM'         : [\"Bticino X meter\", 'Home+Control'],\n\n    'NACamera'     : [\"indoor camera\", 'Home + Security'],\n    'NACamDoorTag' : [\"door tag\", 'Home + Security'],\n    'NAMain'       : [\"weather station\", 'Weather'],\n    'NAModule1'    : [\"outdoor unit\", 'Weather'],\n    'NAModule2'    : [\"wind unit\", 'Weather'],\n    'NAModule3'    : [\"rain unit\", 'Weather'],\n    'NAModule4'    : [\"indoor unit\", 'Weather'],\n    'NAPlug'       : [\"thermostat relais station\", 'Energy'],                             # A smart thermostat exist of a thermostat module and a Relay device\n                                                                                          # The relay device is also the bridge for thermostat and Valves\n    'NATherm1'     : [\"thermostat\",  'Energy'],\n    'NCO'          : [\"co2 sensor\", 'Home + Security'],                                   # The same API as smoke sensor\n    'NDB'          : [\"doorbell\", 'Home + Security'],\n    'NOC'          : [\"outdoor camera\", 'Home + Security'],\n    'NRV'          : [\"thermostat valves\", 'Energy'],                                     # also API Home+Control\n    'NSD'          : [\"smoke sensor\", 'Home + Security'],\n    'NHC'          : [\"home coach\", 'Aircare'],\n    'NIS'          : [\"indoor sirene\", 'Home + Security'],\n    'NDL'          : [\"Doorlock\", 'Home + Security'],\n\n    'NLAO'         : [\"Magellan Green power remote control on-off\", 'Home+Control'],\n    'NLAS'         : [\"Magellan Green Power Remote control scenarios\", 'Home+Control'],\n    'NLAV'         : [\"Wireless Batteryless Shutter Switch\", 'Home+Control'],\n    'NLC'          : [\"Cable Outlet\", 'Home+Control'],\n    'NLD'          : [\"Wireless 2 button switch light\", 'Home+Control'],\n    'NLDP'         : [\"Magellan Pocket Remote\", 'Home+Control'],\n    'NLE'          : [\"Ecometer\", 'Home+Control'],\n    'NLF'          : [\"Dimmer Light Switch\", 'Home+Control'],\n    'NLFE'         : [\"Dimmer Light Switch Evolution\", 'Home+Control'],\n    'NLFN'         : [\"Dimmer Light with Neutral\", 'Home+Control'],\n    'NLG'          : [\"Gateway\", 'Home+Control'],\n    'NLGS'         : [\"Standard DIN Gateway\", 'Home+Control'],\n    'NLIS'         : [\"Double Switch with Neutral\", 'Home+Control'],\n    'NLIV'         : [\"1/2 Gangs Shutter Switch\", 'Home+Control'],\n    'NLL'          : [\"Light Switch with Neutral\", 'Home+Control'],\n    'NLLF'         : [\"Centralized Ventilation Control\", 'Home+Control'],\n    'NLLV'         : [\"Roller Shutter Switch with level detection\", 'Home+Control'],\n    'NLM'          : [\"Light Micromodule\", 'Home+Control'],\n    'NLP'          : [\"Power Outlet\", 'Home+Control'],\n    'NLPS'         : [\"Smart Load Shedder\", 'Home+Control'],\n    'NLPC'         : [\"DIN Energy meter\", 'Home+Control'],\n    'NLPD'         : [\"Dry contact\", 'Home+Control'],\n    'NLPM'         : [\"Mobile Socket\", 'Home+Control'],\n    'NLPO'         : [\"Contactor\", 'Home+Control'],\n    'NLPT'         : [\"Teleruptor\", 'Home+Control'],\n    'NLT'          : [\"Magellan Remote Control\", 'Home+Control'],\n    'NLTS'         : [\"Magellan Remote Motion Sensor\", 'Home+Control'],\n    'NLV'          : [\"Roller Shutter Switch\", 'Home+Control'],\n\n    'OTH'          : [\"Opentherm Thermostat Relay\", 'Home+Control'],\n    'OTM'          : [\"Smart modulating Thermostat\", 'Home+Control'],\n\n    'Z3L'          : [\"Zigbee 3rd party light\", 'Home+Control'],\n    'Z3V'          : [\"Generic window covering\", 'Home+Control']\n    }\n\n# UNITS used by Netatmo services\nUNITS = {\n    \"unit\" : {\n        0: \"metric\",\n        1: \"imperial\"\n    },\n    \"windunit\" : {\n        0: \"kph\",\n        1: \"mph\",\n        2: \"ms\",\n        3: \"beaufort\",\n        4: \"knot\"\n    },\n    \"pressureunit\" : {\n        0: \"mbar\",\n        1: \"inHg\",\n        2: \"mmHg\"\n    },\n    \"Health index\" : {                                                                    # Homecoach\n        0: \"Healthy\",\n        1: \"Fine\",\n        2: \"Fair\",\n        3: \"Poor\",\n        4: \"Unhealthy\"\n    },\n    \"Wifi status\" : {                                                                     # Wifi Signal quality\n        86: \"Bad\",\n        71: \"Average\",\n        56: \"Good\"\n    }\n}\n\n# Logger context\nlogger = logging.getLogger(\"lnetatmo\")\n\n\nclass NoDevice( Exception ):\n    \"\"\"No device available in the user account\"\"\"\n\n\nclass NoHome( Exception ):\n    \"\"\"No home defined in the user account\"\"\"\n\n\nclass AuthFailure( Exception ):\n    \"\"\"Credentials where rejected by Netatmo (or netatmo server unavailability)\"\"\"\n\nclass OutOfScope( Exception ):\n    \"\"\"Your current auth scope do not allow access to this resource\"\"\"\n\nclass ClientAuth:\n    \"\"\"\n    Request authentication and keep access token available through token method. Renew it automatically if necessary\n\n    Args:\n        clientId (str): Application clientId delivered by Netatmo on dev.netatmo.com\n        clientSecret (str): Application Secret key delivered by Netatmo on dev.netatmo.com\n        refreshToken (str) : Scoped refresh token\n    \"\"\"\n\n    def __init__(self, clientId=None,\n                       clientSecret=None,\n                       refreshToken=None,\n                       credentialFile=None):\n\n        # replace values with content of env variables if defined\n        clientId = getenv(\"CLIENT_ID\", clientId)\n        clientSecret = getenv(\"CLIENT_SECRET\", clientSecret)\n        refreshToken = getenv(\"REFRESH_TOKEN\", refreshToken)\n\n        # Look for credentials in file if not already provided\n        # Note: this file will be rewritten by the library to record refresh_token change\n        # If you run your application in container, remember to persist this file\n        if not (clientId and clientSecret and refreshToken):\n            self._credentialFile = credentialFile or expanduser(\"~/.netatmo.credentials\")\n            with open(self._credentialFile, \"r\", encoding=\"utf-8\") as f:\n                cred = {k.upper():v for k,v in json.loads(f.read()).items()}\n        else:\n            # Calling program will need to handle the returned refresh_token for futur call\n            # by getting refreshToken property of the ClientAuth instance and persist it somewhere\n            self._credentialFile = None\n\n        self._clientId = clientId or cred[\"CLIENT_ID\"]\n        self._clientSecret = clientSecret or cred[\"CLIENT_SECRET\"]\n        self._accessToken = None # Will be refreshed before any use\n        self.refreshToken = refreshToken or cred[\"REFRESH_TOKEN\"]\n        self.expiration = 0 # Force refresh token\n\n    @property\n    def accessToken(self):\n        if self.expiration < time.time() : self.renew_token()\n        return self._accessToken\n\n    def renew_token(self):\n        postParams = {\n                \"grant_type\" : \"refresh_token\",\n                \"refresh_token\" : self.refreshToken,\n                \"client_id\" : self._clientId,\n                \"client_secret\" : self._clientSecret\n                }\n        resp = postRequest(\"authentication\", _AUTH_REQ, postParams)\n        if self.refreshToken != resp['refresh_token']:\n            self.refreshToken = resp['refresh_token']\n            cred = {\"CLIENT_ID\":self._clientId,\n                    \"CLIENT_SECRET\":self._clientSecret,\n                    \"REFRESH_TOKEN\":self.refreshToken }\n            if self._credentialFile:\n                with open(self._credentialFile, \"w\", encoding=\"utf-8\") as f:\n                    f.write(json.dumps(cred, indent=True))\n        self._accessToken = resp['access_token']\n        self.expiration = int(resp['expire_in'] + time.time())\n\n\nclass User:\n    \"\"\"\n    This class returns basic information about the user\n\n    Args:\n        authData (ClientAuth): Authentication information with a working access Token\n    \"\"\"\n    warnings.warn(\"The 'User' class is no longer maintained by Netatmo\",\n            DeprecationWarning )\n    def __init__(self, authData):\n        postParams = {\n                \"access_token\" : authData.accessToken\n                }\n        resp = postRequest(\"Weather station\", _GETSTATIONDATA_REQ, postParams)\n        self.rawData = resp['body']\n        self.devList = self.rawData['devices']\n        self.ownerMail = self.rawData['user']['mail']\n\n\nclass UserInfo:\n    \"\"\"\n    This class is dynamicaly populated with data from various Netatmo requests to provide\n    complimentary data (eg Units for Weatherdata)\n    \"\"\"\n\n\nclass HomeStatus:\n    \"\"\"\n    List all Home+Control devices (Smarther thermostat, Socket, Cable Output, Centralized fan, Micromodules, ......)\n\n    Args:\n        authData (clientAuth): Authentication information with a working access Token\n        home : Home name or id of the home who's thermostat belongs to\n    \"\"\"\n    def __init__(self, authData, home_id):\n\n        self.getAuthToken = authData.accessToken\n        postParams = {\n                \"access_token\" : self.getAuthToken,\n                \"home_id\": home_id\n                }\n        resp = postRequest(\"home_status\", _HOME_STATUS, postParams)\n        self.resp = resp\n        self.rawData = resp['body']['home']\n        if not self.rawData : raise NoHome(\"No home %s found\" % home_id)\n        self.rooms = self.rawData['rooms']\n        self.modules = self.rawData['modules']\n\n    def getRoomsId(self):\n        return [room['id'] for room in self.rooms]\n\n    def getListRoomParam(self, room_id):\n        for room in self.rooms:\n            if room['id'] == room_id:\n                return list(room)\n        return None\n\n    def getRoomParam(self, room_id, param):\n        for room in self.rooms:\n            if(room['id'] == room_id and param in room):\n                return room[param]\n        return None\n\n    def getModulesId(self):\n        return [module['id'] for module in self.modules]\n\n    def getListModuleParam(self, module_id):\n        for module in self.modules:\n            if module['id'] == module_id:\n                return list(module)\n        return None\n\n    def getModuleParam(self, module_id, param):\n        for module in self.modules:\n            if module['id'] == module_id and param in module:\n                return module[param]\n        return None\n\n\nclass ThermostatData:\n    \"\"\"\n    List the Relay station and Thermostat modules\n    Valves are controlled by HomesData and HomeStatus in new API\n    Args:\n        authData (clientAuth): Authentication information with a working access Token\n        home : Home name or id of the home who's thermostat belongs to\n    \"\"\"\n    def __init__(self, authData, home=None):\n\n        # I don't own a thermostat thus I am not able to test the Thermostat support\n        warnings.warn(\"The Thermostat code is not tested due to the lack of test environment.\\n\" \\\n                      \"As Netatmo is continuously breaking API compatibility, risk that current bindings are wrong is high.\\n\" \\\n                      \"Please report found issues (https://github.com/philippelt/netatmo-api-python/issues)\",\n                       RuntimeWarning )\n\n        self.getAuthToken = authData.accessToken\n        postParams = {\n                \"access_token\" : self.getAuthToken\n                }\n        resp = postRequest(\"Thermostat\", _GETTHERMOSTATDATA_REQ, postParams)\n        self.rawData = resp['body']['devices']\n        if not self.rawData : raise NoDevice(\"No thermostat available\")\n        #\n        # keeping OLD code for Reference\n#        self.thermostatData = filter_home_data(self.rawData, home)\n#        if not self.thermostatData : raise NoHome(\"No home %s found\" % home)\n#        self.thermostatData['name'] = self.thermostatData['home_name']                    # New key = 'station_name'\n#        for m in self.thermostatData['modules']:\n#            m['name'] = m['module_name']\n#        self.defaultThermostat = self.thermostatData['home_name']                         # New key = 'station_name'\n#        self.defaultThermostatId = self.thermostatData['_id']\n#        self.defaultModule = self.thermostatData['modules'][0]\n        # Standard the first Relaystation and Thermostat is returned\n        # self.rawData is list all stations\n\n# if no ID is given the Relaystation at index 0 is returned\n    def Relay_Plug(self, Rid=\"\"):\n        for Relay in self.rawData:\n            if Rid in Relay['_id']:\n                print ('Relay ', Rid, 'in rawData')\n                #print (Relay.keys())\n                #print (Relay['_id'])\n                return Relay\n#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'])\n\n# if no ID is given the Thermostatmodule at index 0 is returned\n    def Thermostat_Data(self, tid=\"\"):\n        for Relay in self.rawData:\n            for thermostat in Relay['modules']:\n                if tid in thermostat['_id']:\n                    print ('Thermostat ',tid, 'in Relay', Relay['_id'], Relay['station_name'])\n                    #print (thermostat['_id'])\n                    #print (thermostat.keys())\n                    return thermostat\n#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'])\n\n\n    def getThermostat(self, name=None, id=\"\"):\n        for Relay in self.rawData:\n            for module in Relay['modules']:\n                if id == Relay['_id']:\n                        print ('Relay ', id, 'found')\n                        return Relay\n                elif name == Relay['station_name']:\n                        print ('Relay ', name, 'found')\n                        return Relay\n                elif id == module['_id']:\n                        print ('Thermostat ', id, 'found in Relay', Relay['_id'], Relay['station_name'])\n                        return module\n                elif name == module['module_name']:\n                        print ('Thermostat ', name, 'found in Relay', Relay['_id'], Relay['station_name'])\n                        return module\n                else:\n                    #print ('Device NOT Found')\n                    pass\n\n    def moduleNamesList(self, name=None, tid=None):\n        l = []\n        for Relay in self.rawData:\n            if id == Relay['_id'] or name == Relay['station_name']:\n                RL = []\n                for module in Relay['modules']:\n                    RL.append(module['module_name'])\n                return RL\n            else:\n                #print (\"Cloud Data\")\n                for module in Relay['modules']:\n                    l.append(module['module_name'])\n                    #This return a list off all connected Thermostat in the cloud.\n        return l\n\n    def getModuleByName(self, name, tid=\"\"):\n        for Relay in self.rawData:\n            for module in Relay['modules']:\n                #print (module['module_name'], module['_id'])\n                if module['module_name'] == name:\n                    return module\n                elif module['_id'] == tid:\n                    return module\n                else:\n                    pass\n\n\nclass WeatherStationData:\n    \"\"\"\n    List the Weather Station devices (stations and modules)\n\n    Args:\n        authData (ClientAuth): Authentication information with a working access Token\n    \"\"\"\n    def __init__(self, authData, home=None, station=None):\n        self.getAuthToken = authData.accessToken\n        postParams = {\n                \"access_token\" : self.getAuthToken\n                }\n        resp = postRequest(\"Weather station\", _GETSTATIONDATA_REQ, postParams)\n        self.rawData = resp['body']['devices']\n        # Weather data\n        if not self.rawData : raise NoDevice(\"No weather station in any homes\")\n        # Stations are no longer in the Netatmo API, keeping them for compatibility\n        self.stations = { d['station_name'] : d for d in self.rawData }\n        self.stationIds = { d['_id'] : d for d in self.rawData }\n        self.homes = { d['home_name'] : d[\"station_name\"] for d in self.rawData }\n        # Keeping the old behavior for default station name\n        if home and home not in self.homes : raise NoHome(\"No home with name %s\" % home)\n        self.default_home = home or list(self.homes.keys())[0]\n        if station:\n            if station not in self.stations:\n                # May be a station_id convert it to corresponding station name\n                s = self.stationById(station)\n                if s :\n                    station = s[\"station_name\"]\n                else:\n                    raise NoDevice(\"No station with name or id %s\" % station)\n            self.default_station = station\n        else:\n            self.default_station =  [v[\"station_name\"] for k,v in self.stations.items() if v[\"home_name\"] == self.default_home][0]\n        self.modules = {}\n        self.default_station_data = self.stationByName(self.default_station)\n        if 'modules' in self.default_station_data:\n            for m in self.default_station_data['modules']:\n                self.modules[ m['_id'] ] = m\n        # User data\n        userData = resp['body']['user']\n        self.user = UserInfo()\n        setattr(self.user, \"mail\", userData['mail'])\n        for k,v in userData['administrative'].items():\n            if k in UNITS:\n                setattr(self.user, k, UNITS[k][v])\n            else:\n                setattr(self.user, k, v)\n\n    def modulesNamesList(self, station=None):\n        s = self.getStation(station)\n        if not s: raise NoDevice(\"No station with name or id %s\" % station)\n        self.default_station = station\n        self.default_station_data = s\n        self.modules = {}\n        if 'modules' in self.default_station_data:\n            for m in self.default_station_data['modules']:\n                self.modules[ m['_id'] ] = m\n        res = [m['module_name'] for m in self.modules.values()]\n        res.append(s['module_name'])\n        return res\n\n    # Both functions (byName and byStation) are here for historical reason,\n    # considering that chances are low that a station name could be confused with a station ID,\n    # there should be in fact a single function for getting station data\n\n    def getStation(self, station=None):\n        if not station : station = self.default_station\n        if station in self.stations : return self.stations[station]\n        if station in self.stationIds : return self.stationIds[station]\n        return None\n\n    def getModule(self, module):\n        if module in self.modules: return self.modules[module]\n        for m in self.modules.values():\n            if m['module_name'] == module : return m\n        return None\n\n    # Functions for compatibility with previous versions\n    def stationByName(self, station=None):\n        return self.getStation(station)\n    def stationById(self, sid):\n        return self.getStation(sid)\n    def moduleByName(self, module):\n        return self.getModule(module)\n    def moduleById(self, mid):\n        return self.getModule(mid)\n\n    def lastData(self, station=None, exclude=0):\n        s = self.stationByName(station) or self.stationById(station)\n        # Breaking change from Netatmo : dashboard_data no longer available if station lost\n        if not s or 'dashboard_data' not in s : return None\n        lastD = {}\n        # Define oldest acceptable sensor measure event\n        limit = (time.time() - exclude) if exclude else 0\n        ds = s['dashboard_data']\n        if ds.get('time_utc',limit+10) > limit :\n            lastD[s['module_name']] = ds.copy()\n            lastD[s['module_name']]['When'] = lastD[s['module_name']].pop(\"time_utc\") if 'time_utc' in lastD[s['module_name']] else time.time()\n            lastD[s['module_name']]['wifi_status'] = s['wifi_status']\n        if 'modules' in s:\n            for module in s[\"modules\"]:\n                # Skip lost modules that no longer have dashboard data available\n                if 'dashboard_data' not in module : continue\n                ds = module['dashboard_data']\n                if ds.get('time_utc',limit+10) > limit :\n                    # If no module_name has been setup, use _id by default\n                    if \"module_name\" not in module : module['module_name'] = module[\"_id\"]\n                    lastD[module['module_name']] = ds.copy()\n                    lastD[module['module_name']]['When'] = lastD[module['module_name']].pop(\"time_utc\") if 'time_utc' in lastD[module['module_name']] else time.time()\n                    # For potential use, add battery and radio coverage information to module data if present\n                    for i in ('battery_vp', 'battery_percent', 'rf_status') :\n                        if i in module : lastD[module['module_name']][i] = module[i]\n        return lastD\n\n    def checkNotUpdated(self, delay=3600):\n        res = self.lastData()\n        ret = []\n        for mn,v in res.items():\n            if time.time()-v['When'] > delay : ret.append(mn)\n        return ret if ret else None\n\n    def checkUpdated(self, delay=3600):\n        res = self.lastData()\n        ret = []\n        for mn,v in res.items():\n            if time.time()-v['When'] < delay : ret.append(mn)\n        return ret if ret else None\n\n    def getMeasure(self, device_id, scale, mtype, module_id=None, date_begin=None, date_end=None, limit=None, optimize=False, real_time=False):\n        postParams = { \"access_token\" : self.getAuthToken }\n        postParams['device_id']  = device_id\n        if module_id : postParams['module_id'] = module_id\n        postParams['scale']      = scale\n        postParams['type']       = mtype\n        if date_begin : postParams['date_begin'] = date_begin\n        if date_end : postParams['date_end'] = date_end\n        if limit : postParams['limit'] = limit\n        postParams['optimize'] = \"true\" if optimize else \"false\"\n        postParams['real_time'] = \"true\" if real_time else \"false\"\n        return postRequest(\"Weather station\", _GETMEASURE_REQ, postParams)\n\n    def MinMaxTH(self, module=None, frame=\"last24\"):\n        s = self.default_station_data\n        if frame == \"last24\":\n            end = time.time()\n            start = end - 24*3600 # 24 hours ago\n        elif frame == \"day\":\n            start, end = todayStamps()\n        if module and module != s['module_name']:\n            m = self.moduleById(module) or self.moduleByName(module)\n            if not m : raise NoDevice(\"Can't find module %s\" % module)\n            # retrieve module's data\n            resp = self.getMeasure(\n                    device_id  = s['_id'],\n                    module_id  = m['_id'],\n                    scale      = \"max\",\n                    mtype      = \"Temperature,Humidity\",\n                    date_begin = start,\n                    date_end   = end)\n        else : # retrieve station's data\n            resp = self.getMeasure(\n                    device_id  = s['_id'],\n                    scale      = \"max\",\n                    mtype      = \"Temperature,Humidity\",\n                    date_begin = start,\n                    date_end   = end)\n        if resp and resp['body']:\n            T = [v[0] for v in resp['body'].values()]\n            H = [v[1] for v in resp['body'].values()]\n            return min(T), max(T), min(H), max(H)\n        return None\n\n\nclass DeviceList(WeatherStationData):\n    \"\"\"\n    This class is now deprecated. Use WeatherStationData directly instead\n    \"\"\"\n    warnings.warn(\"The 'DeviceList' class was renamed 'WeatherStationData'\",\n            DeprecationWarning )\n\n\nclass HomeData:\n    \"\"\"\n    List the Netatmo home informations (Homes, cameras, events, persons)\n\n    Args:\n        authData (ClientAuth): Authentication information with a working access Token\n        home : Home name of the home where's devices are installed\n    \"\"\"\n    def __init__(self, authData, home=None):\n        warnings.warn(\"The 'HomeData' class is deprecated'\",\n            DeprecationWarning )\n        self.getAuthToken = authData.accessToken\n        postParams = {\n            \"access_token\" : self.getAuthToken\n            }\n        resp = postRequest(\"Home data\", _GETHOMEDATA_REQ, postParams)\n        self.rawData = resp['body']\n        # Collect homes\n        self.homes = self.rawData['homes'][0]\n        for d in self.rawData['homes'] :\n            if home == d['name']:\n                self.homes = d\n            else:\n                pass\n        #\n        #print (self.homes.keys())\n        #dict_keys(['id', 'name', 'persons', 'place', 'cameras', 'smokedetectors', 'events'])\n        self.homeid = self.homes['id']\n        C = self.homes['cameras']\n        P = self.homes['persons']\n        S = self.homes['smokedetectors']\n        E = None\n        # events not always in self.homes\n        if 'events' in self.homes.keys():\n            E = self.homes['events']\n        #\n        if not S:\n            logger.warning('No smoke detector found')\n        if not C:\n            logger.warning('No Cameras found')\n        if not P:\n            logger.warning('No Persons found')\n        if not E:\n            logger.warning('No events found')\n        #    if not (C or P or S or E):\n        #        raise NoDevice(\"No device found in home %s\" % k)\n        if S or C or P or E:\n            self.default_home = home or self.homes['name']\n            # Split homes data by category\n            self.persons = {}\n            self.events = {}\n            self.cameras = {}\n            self.lastEvent = {}\n            for i in range(len(self.rawData['homes'])):\n                curHome = self.rawData['homes'][i]\n                nameHome = curHome['name']\n                if nameHome not in self.cameras:\n                    self.cameras[nameHome] = {}\n                if 'persons' in curHome:\n                    for p in curHome['persons']:\n                        self.persons[ p['id'] ] = p\n                if 'events' in curHome:\n                    for e in curHome['events']:\n                        if e['camera_id'] not in self.events:\n                            self.events[ e['camera_id'] ] = {}\n                        self.events[ e['camera_id'] ][ e['time'] ] = e\n                if 'cameras' in curHome:\n                    for c in curHome['cameras']:\n                        self.cameras[nameHome][ c['id'] ] = c\n                        c[\"home_id\"] = curHome['id']\n            for camera,e in self.events.items():\n                self.lastEvent[camera] = e[sorted(e)[-1]]\n            #self.default_home has no key homeId use homeName instead!\n            if not self.cameras[self.default_home] : raise NoDevice(\"No camera available in default home\")\n            self.default_camera = list(self.cameras[self.default_home].values())[0]\n        else:\n            pass\n#            raise NoDevice(\"No Devices available\")\n\n    def homeById(self, hid):\n        return None if hid not in self.homes else self.homes[hid]\n\n    def homeByName(self, home=None):\n        if not home: home = self.default_home\n        for key,value in self.homes.items():\n            if value['name'] == home:\n                return self.homes[key]\n\n    def cameraById(self, cid):\n        for cam in self.cameras.values():\n            if cid in cam:\n                return cam[cid]\n        return None\n\n    def cameraByName(self, camera=None, home=None):\n        if not camera and not home:\n            return self.default_camera\n        elif home and camera:\n            if home not in self.cameras:\n                return None\n            for cam_id in self.cameras[home]:\n                if self.cameras[home][cam_id]['name'] == camera:\n                    return self.cameras[home][cam_id]\n        elif not home and camera:\n            for h, cam_ids in self.cameras.items():\n                for cam_id in cam_ids:\n                    if self.cameras[h][cam_id]['name'] == camera:\n                        return self.cameras[h][cam_id]\n        else:\n            return list(self.cameras[self.default_home].values())[0]\n        return None\n\n    def cameraUrls(self, camera=None, home=None, cid=None):\n        \"\"\"\n        Return the vpn_url and the local_url (if available) of a given camera\n        in order to access to its live feed\n        Can't use the is_local property which is mostly false in case of operator\n        dynamic IP change after presence start sequence\n        \"\"\"\n        local_url = None\n        vpn_url = None\n        if cid:\n            camera_data=self.cameraById(cid)\n        else:\n            camera_data=self.cameraByName(camera=camera, home=home)\n        if camera_data:\n            vpn_url = camera_data['vpn_url']\n            resp = postRequest(\"Camera\", vpn_url + '/command/ping')\n            temp_local_url=resp['local_url']\n            try:\n                resp = postRequest(\"Camera\", temp_local_url + '/command/ping',timeout=1)\n                if resp and temp_local_url == resp['local_url']:\n                    local_url = temp_local_url\n            except:  # On this particular request, vithout errors from previous requests, error is timeout\n                local_url = None\n        return vpn_url, local_url\n\n    def url(self, camera=None, home=None, cid=None):\n        vpn_url, local_url = self.cameraUrls(camera, home, cid)\n        # Return local if available else vpn\n        return local_url or vpn_url\n\n    def personsAtHome(self, home=None):\n        \"\"\"\n        Return the list of known persons who are currently at home\n        \"\"\"\n        if not home: home = self.default_home\n        home_data = self.homeByName(home)\n        atHome = []\n        for p in home_data['persons']:\n            #Only check known persons\n            if 'pseudo' in p:\n                if not p[\"out_of_sight\"]:\n                    atHome.append(p['pseudo'])\n        return atHome\n\n    def getCameraPicture(self, image_id, key):\n        \"\"\"\n        Download a specific image (of an event or user face) from the camera\n        \"\"\"\n        postParams = {\n            \"access_token\" : self.getAuthToken,\n            \"image_id\" : image_id,\n            \"key\" : key\n            }\n        resp = postRequest(\"Camera\", _GETCAMERAPICTURE_REQ, postParams)\n        return resp, \"jpeg\"\n\n    def getProfileImage(self, name):\n        \"\"\"\n        Retrieve the face of a given person\n        \"\"\"\n        for p in self.persons.values():\n            if 'pseudo' in p:\n                if name == p['pseudo']:\n                    image_id = p['face']['id']\n                    key = p['face']['key']\n                    return self.getCameraPicture(image_id, key)\n        return None, None\n\n    def updateEvent(self, event=None, home=None):\n        \"\"\"\n        Update the list of event with the latest ones\n        \"\"\"\n        if not home: home=self.default_home\n        if not event:\n            #If not event is provided we need to retrieve the oldest of the last event seen by each camera\n            listEvent = {}\n            for e in self.lastEvent.values():\n                listEvent[e['time']] = e\n            event = listEvent[sorted(listEvent)[0]]\n\n        home_data = self.homeByName(home)\n        postParams = {\n            \"access_token\" : self.getAuthToken,\n            \"home_id\" : home_data['id'],\n            \"event_id\" : event['id']\n        }\n        resp = postRequest(\"Camera\", _GETEVENTSUNTIL_REQ, postParams)\n        eventList = resp['body']['events_list']\n        for e in eventList:\n            self.events[ e['camera_id'] ][ e['time'] ] = e\n        for camera,v in self.events.items():\n            self.lastEvent[camera]=v[sorted(v)[-1]]\n\n    def personSeenByCamera(self, name, home=None, camera=None):\n        \"\"\"\n        Return True if a specific person has been seen by a camera\n        \"\"\"\n        try:\n            cam_id = self.cameraByName(camera=camera, home=home)['id']\n        except TypeError:\n            logger.warning(\"personSeenByCamera: Camera name or home is unknown\")\n            return False\n        #Check in the last event is someone known has been seen\n        if self.lastEvent[cam_id]['type'] == 'person':\n            person_id = self.lastEvent[cam_id]['person_id']\n            if 'pseudo' in self.persons[person_id]:\n                if self.persons[person_id]['pseudo'] == name:\n                    return True\n        return False\n\n    def _knownPersons(self):\n        known_persons = {}\n        for p_id,p in self.persons.items():\n            if 'pseudo' in p:\n                known_persons[ p_id ] = p\n        return known_persons\n\n    def someoneKnownSeen(self, home=None, camera=None):\n        \"\"\"\n        Return True if someone known has been seen\n        \"\"\"\n        try:\n            cam_id = self.cameraByName(camera=camera, home=home)['id']\n        except TypeError:\n            logger.warning(\"personSeenByCamera: Camera name or home is unknown\")\n            return False\n        #Check in the last event is someone known has been seen\n        if self.lastEvent[cam_id]['type'] == 'person':\n            if self.lastEvent[cam_id]['person_id'] in self._knownPersons():\n                return True\n        return False\n\n    def someoneUnknownSeen(self, home=None, camera=None):\n        \"\"\"\n        Return True if someone unknown has been seen\n        \"\"\"\n        try:\n            cam_id = self.cameraByName(camera=camera, home=home)['id']\n        except TypeError:\n            logger.warning(\"personSeenByCamera: Camera name or home is unknown\")\n            return False\n        #Check in the last event is someone known has been seen\n        if self.lastEvent[cam_id]['type'] == 'person':\n            if self.lastEvent[cam_id]['person_id'] not in self._knownPersons():\n                return True\n        return False\n\n    def motionDetected(self, home=None, camera=None):\n        \"\"\"\n        Return True if movement has been detected\n        \"\"\"\n        try:\n            cam_id = self.cameraByName(camera=camera, home=home)['id']\n        except TypeError:\n            logger.warning(\"personSeenByCamera: Camera name or home is unknown\")\n            return False\n        if self.lastEvent[cam_id]['type'] == 'movement':\n            return True\n        return False\n\n    def presenceUrl(self, camera=None, home=None, cid=None):\n        camera = self.cameraByName(home=home, camera=camera) or self.cameraById(cid=cid)\n        if camera[\"type\"] != \"NOC\": return None # Not a presence camera\n        vpnUrl, localUrl = self.cameraUrls(cid=camera[\"id\"])\n        return localUrl or vpnUrl\n\n    def presenceLight(self, camera=None, home=None, cid=None, setting=None):\n        url = self.presenceUrl(home=home, camera=camera) or self.cameraById(cid=cid)\n        if not url or setting not in (\"on\", \"off\", \"auto\"): return None\n        if setting : return \"Currently unsupported\"\n        return cameraCommand(url, _PRES_CDE_GET_LIGHT)[\"mode\"]\n        # Not yet supported\n        #if not setting: return cameraCommand(url, _PRES_CDE_GET_LIGHT)[\"mode\"]\n        #else: return cameraCommand(url, _PRES_CDE_SET_LIGHT, setting)\n\n    def presenceStatus(self, mode, camera=None, home=None, cid=None):\n        url = self.presenceUrl(home=home, camera=camera) or self.cameraById(cid=cid)\n        if not url or mode not in (\"on\", \"off\") : return None\n        r = cameraCommand(url, _CAM_CHANGE_STATUS, mode)\n        return mode if r[\"status\"] == \"ok\" else None\n\n    def presenceSetAction(self, camera=None, home=None, cid=None,\n                          eventType=_PRES_DETECTION_KIND[0], action=2):\n        raise NotImplementedError\n        # if eventType not in _PRES_DETECTION_KIND or \\\n        #    action not in _PRES_DETECTION_SETUP : return None\n        # camera = self.cameraByName(home=home, camera=camera) or self.cameraById(cid=cid)\n        # postParams = { \"access_token\" : self.getAuthToken,\n        #                \"home_id\" : camera[\"home_id\"],\n        #                \"presence_settings[presence_record_%s]\" % eventType : _PRES_DETECTION_SETUP.index(action)\n        #              }\n        # resp = postRequest(\"Camera\", _POST_UPDATE_HOME_REQ, postParams)\n        # self.rawData = resp['body']\n\n    def getLiveSnapshot(self, camera=None, home=None, cid=None):\n        camera = self.cameraByName(home=home, camera=camera) or self.cameraById(cid=cid)\n        vpnUrl, localUrl = self.cameraUrls(cid=camera[\"id\"])\n        url = localUrl or vpnUrl\n        return cameraCommand(url, _PRES_CDE_GET_SNAP)\n\n\nclass WelcomeData(HomeData):\n    \"\"\"\n    This class is now deprecated. Use HomeData instead\n    Home can handle many devices, not only Welcome cameras\n    \"\"\"\n    warnings.warn(\"The 'WelcomeData' class was renamed 'HomeData' to handle new Netatmo Home capabilities\",\n            DeprecationWarning )\n\n\nclass HomesData:\n    \"\"\"\n    List the Netatmo actual topology and static information of all devices present\n    into a user account. It is also possible to specify a home_id to focus on one home.\n\n    Args:\n        authData (clientAuth): Authentication information with a working access Token\n        home : Home name or id of the home who's module belongs to\n    \"\"\"\n    def __init__(self, authData, home=None):\n        #\n        self.getAuthToken = authData.accessToken\n        postParams = {\n                \"access_token\" : self.getAuthToken,\n                \"home_id\": home\n                }\n        #\n        resp = postRequest(\"Module\", _GETHOMES_DATA, postParams)\n#        self.rawData = resp['body']['devices']\n        self.rawData = resp['body']['homes']\n        if not self.rawData : raise NoHome(\"No home %s found\" % home)\n        #\n        if home:\n            # Find a home who's home id or name is the one requested\n            for h in self.rawData:\n                #print (h.keys())\n                if home in (h[\"name\"], h[\"id\"]):\n                    self.Homes_Data = h\n        else:\n            self.Homes_Data = self.rawData[0]\n        self.homeid = self.Homes_Data['id']\n        if not self.Homes_Data : raise NoDevice(\"No Devices available\")\n\n\nclass HomeCoach:\n    \"\"\"\n    List the HomeCoach modules\n        \n    Args:\n        authData (clientAuth): Authentication information with a working access Token\n        home : Home name or id of the home who's HomeCoach belongs to\n    \"\"\"\n\n    def __init__(self, authData):\n        # I don't own a HomeCoach thus I am not able to test the HomeCoach support\n        # Homecoach does not need or use HomeID parameter\n#        warnings.warn(\"The HomeCoach code is not tested due to the lack of test environment.\\n\",  RuntimeWarning )\n#                      \"As Netatmo is continuously breaking API compatibility, risk that current bindings are wrong is high.\\n\" \\\n#                      \"Please report found issues (https://github.com/philippelt/netatmo-api-python/issues)\"\n\n        self.getAuthToken = authData.accessToken\n        postParams = {\n                \"access_token\" : self.getAuthToken\n                }\n        resp = postRequest(\"HomeCoach\", _GETHOMECOACH, postParams)\n        self.rawData = resp['body']['devices']\n        # homecoach data\n        if not self.rawData : raise NoDevice(\"No HomeCoach available\")\n\n    def HomecoachDevice(self, hid=\"\"):\n        for device in self.rawData:\n           if hid == device['_id']:\n                return device\n           return None\n\n    def Dashboard(self, hid=\"\"):\n        #D = self.HomecoachDevice['dashboard_data']\n        for device in self.rawData:\n            if hid == device['_id']:\n                D = device['dashboard_data']\n                return D\n\n    def lastData(self, hid=None, exclude=0):\n        for device in self.rawData:\n            if hid == device['_id']:\n                # LastData in HomeCoach\n                #s = self.HomecoachDevice['dashboard_data']['time_utc']\n                # Define oldest acceptable sensor measure event\n                limit = (time.time() - exclude) if exclude else 0\n                ds = device['dashboard_data']['time_utc']\n                return { '_id': hid, 'When': ds if device.get('time_utc',limit+10) > limit else 0}\n            else:\n                pass\n\n    def checkNotUpdated(self, res, hid, delay=3600):\n        ret = []\n        if time.time()-res['When'] > delay : ret.append({hid: 'Device Not Updated'})\n        return ret if ret else None\n\n    def checkUpdated(self, res, hid, delay=3600):\n        ret = []\n        if time.time()-res['When'] < delay : ret.append({hid: 'Device up-to-date'})\n        return ret if ret else None\n\n\n# Utilities routines\n\ndef rawAPI(authData, url, parameters=None):\n    fullUrl = _BASE_URL + \"api/\" + url\n    if parameters is None: parameters = {}\n    parameters[\"access_token\"] = authData.accessToken\n    resp = postRequest(\"rawAPI\", fullUrl, parameters)\n    return resp[\"body\"] if \"body\" in resp else resp\n\ndef filter_home_data(rawData, home):\n    if home:\n        # Find a home who's home id or name is the one requested\n        for h in rawData:\n            if home in (h['home_name'], h['home_id']):\n                return h\n        return None\n    # By default, the first home is returned\n    return rawData[0]\n\ndef cameraCommand(cameraUrl, commande, parameters=None, timeout=3):\n    url = cameraUrl + ( commande % parameters if parameters else commande)\n    return postRequest(\"Camera\", url, timeout=timeout)\n\ndef processErrorResp(resp):\n    try:\n        error_detail = json.loads(resp.fp.read().decode(\"utf-8\"))[\"error\"]\n        logger.error(\"Netatmo response error 403 : %s\" % repr(error_detail))\n    except Exception as e:\n        logger.error(\"Error getting body of 403 HTTP error from Netatmo : %s\" % e)\n\ndef postRequest(topic, url, params=None, timeout=10):\n    if PYTHON3:\n        req = urllib.request.Request(url)\n        if params:\n            req.add_header(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\")\n            if \"access_token\" in params:\n                req.add_header(\"Authorization\",\"Bearer %s\" % params.pop(\"access_token\"))\n            params = urllib.parse.urlencode(params).encode('utf-8')\n        try:\n            resp = urllib.request.urlopen(req, params, timeout=timeout) if params else urllib.request.urlopen(req, timeout=timeout)\n        except urllib.error.HTTPError as err:\n            if err.code == 403:\n                processErrorResp(err)\n            else:\n                logger.error(\"code=%s, reason=%s, body=%s\" % (err.code, err.reason, err.fp.read()))\n            return None\n    else:\n        if params:\n            token = params.pop(\"access_token\") if \"access_token\" in params else None\n            params = urlencode(params)\n            headers = {\"Content-Type\"  : \"application/x-www-form-urlencoded;charset=utf-8\"}\n            if token: headers[\"Authorization\"] = \"Bearer %s\" % token\n        req = urllib2.Request(url=url, data=params, headers=headers) if params else urllib2.Request(url=url, headers=headers)\n        try:\n            resp = urllib2.urlopen(req, timeout=timeout)\n        except urllib2.HTTPError as err:\n            logger.error(\"code=%s, reason=%s\" % (err.code, err.reason))\n            return None\n    data = b\"\"\n    for buff in iter(lambda: resp.read(65535), b''): data += buff\n    # Return values in bytes if not json data to handle properly camera images\n    returnedContentType = resp.getheader(\"Content-Type\") if PYTHON3 else resp.info()[\"Content-Type\"]\n    return json.loads(data.decode(\"utf-8\")) if \"application/json\" in returnedContentType else data\n\ndef toTimeString(value):\n    return time.strftime(\"%Y-%m-%d_%H:%M:%S\", time.localtime(int(value)))\n\ndef toEpoch(value):\n    return int(time.mktime(time.strptime(value,\"%Y-%m-%d_%H:%M:%S\")))\n\ndef todayStamps():\n    today = time.strftime(\"%Y-%m-%d\")\n    today = int(time.mktime(time.strptime(today,\"%Y-%m-%d\")))\n    return today, today+3600*24\n\n# Global shortcut\n\ndef getStationMinMaxTH(station=None, module=None, home=None):\n    authorization = ClientAuth()\n    devList = WeatherStationData(authorization, station=station, home=home)\n    if module == \"*\":\n        pass\n    elif module:\n        module = devList.moduleById(module) or devList.moduleByName(module)\n        if not module: raise NoDevice(\"No such module %s\" % module)\n        module = module[\"module_name\"]\n    else:\n        module = list(devList.modules.values())[0][\"module_name\"]\n    lastD = devList.lastData()\n    if module == \"*\":\n        result = {}\n        for m,v in lastD.items():\n            if time.time()-v['When'] > 3600 : continue\n            r = devList.MinMaxTH(module=m)\n            if r:\n                result[m] = (r[0], v['Temperature'], r[1])\n    else:\n        if time.time()-lastD[module]['When'] > 3600 : result = [\"-\", \"-\"]\n        else :\n            result = [lastD[module]['Temperature'], lastD[module]['Humidity']]\n            result.extend(devList.MinMaxTH(module))\n    return result\n\n\n# auto-test when executed directly\n\nif __name__ == \"__main__\":\n\n    logging.basicConfig(format='%(name)s - %(levelname)s: %(message)s', level=logging.INFO)\n\n    authorization = ClientAuth()                                                          # Test authentication method\n\n    try:\n        try:\n            weatherStation = WeatherStationData(authorization)                                # Test DEVICELIST\n        except NoDevice:\n            logger.warning(\"No weather station available for testing\")\n        else:\n            weatherStation.MinMaxTH()                                                         # Test GETMEASUR\n\n        try:\n            homes = HomeData(authorization)\n        except NoDevice :\n            logger.warning(\"No home available for testing\")\n\n        try:\n            thermostat = ThermostatData(authorization)\n            Default_relay = thermostat.Relay_Plug()\n            Default_thermostat = thermostat.Thermostat_Data()\n            thermostat.getThermostat()\n            print (thermostat.moduleNamesList())\n            #print (thermostat.getModuleByName(name))\n        except NoDevice:\n            logger.warning(\"No thermostat avaible for testing\")\n\n        try:\n            print (' ')\n            logger.info(\"Homes Data\")\n            #homesdata = HomesData(authorization, homeid)\n            homesdata = HomesData(authorization)\n            homeid = homesdata.homeid\n        except NoDevice:\n            logger.warning(\"No HomesData avaible for testing\")\n\n        try:\n            print (' ')\n            logger.info(\"Home Status\")\n            HomeStatus(authorization, homeid)\n        except NoDevice:\n            logger.warning(\"No Home available for testing\")\n\n        try:\n            print (' ')\n            logger.info(\"HomeCoach\")\n            Homecoach = HomeCoach(authorization)\n        except NoDevice:\n            logger.warning(\"No HomeCoach avaible for testing\")\n\n    except OutOfScope:\n        logger.warning(\"Your current scope do not allow such access\")\n\n    # If we reach this line, all is OK\n    logger.info(\"OK\")\n\n    exit(0)\n"
  },
  {
    "path": "samples/get_direct_camera_snapshot",
    "content": "#!/usr/bin/python3\n\n# Locate the camera name \"MyCam\" IP on the local LAN\n# to collect a snapshot of what the camera sees\n# If available use a local connection to save internet bandwith\n\n\nfrom sys import exit\nimport lnetatmo\n\n# The name I gave the camera in the Netatmo Security App\nMY_CAMERA = \"MyCam\"\n\n# Authenticate (see authentication in documentation)\n# Note you will need the appropriate scope (read_welcome access_welcome or read_presence access_presence)\n# depending of the camera you are trying to reach\n# The default library scope ask for all aceess to all cameras\nauthorization = lnetatmo.ClientAuth()\n\n# Gather Home information (available cameras and other infos)\nhomeData = lnetatmo.HomeData(authorization)\n\n# Request a snapshot from the camera\nsnapshot = homeData.getLiveSnapshot( camera=MY_CAMERA )\n\n# If all was Ok, I should have an image, if None there was an error\nif not snapshot :\n    # Decide what to do with an error situation (alert, log, ...)\n    exit(1)\n\n# You can then archive the snapshot, send it by mail, message App, ...\n# Example : Save the snapshot in a file\nwith open(\"MyCamSnap.jpg\", \"wb\") as f: f.write(snapshot)\n\nexit(0)\n"
  },
  {
    "path": "samples/graphLast3Days",
    "content": "#!/usr/bin/python\n# coding=utf-8\n\n# 2013-01 : philippelt@users.sourceforge.net \n\n# This is an example of graphing Temperature and Humidity from a module on the last 3 days\n# The Matplotlib library is used and should be installed before running this sample program\n\nimport datetime, time\n\nimport lnetatmo\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib import dates\nfrom matplotlib.ticker import FormatStrFormatter\n\n# Access to the sensors\nauth = lnetatmo.ClientAuth()\ndev  = lnetatmo.DeviceList(auth)\n\n# Time of information collection : 3*24hours windows to now\nnow = time.time()\nstart = now - 3 * 24 * 3600\n\n# Get Temperature and Humidity with GETMEASURE web service (1 sample every 30min)\nresp = dev.getMeasure( device_id='xxxx',                             # Replace with your values\n                       module_id='xxxx',                             #    \"      \"    \"    \"\n                       scale=\"30min\",\n                       mtype=\"Temperature,Humidity\",\n                       date_begin=start,\n                       date_end=now)\n\n# Extract the timestamp, temperature and humidity from the more complex response structure\nresult = [(int(k),v[0],v[1]) for k,v in resp['body'].items()]\n# Sort samples by timestamps (Warning, they are NOT sorted by default)\nresult.sort()\n# Split in 3 lists for use with Matplotlib (timestamp on x, temperature and humidity on two y axis)\nxval, ytemp, yhum = zip(*result)\n\n# Convert the x axis values from Netatmo timestamp to matplotlib timestamp...\nxval = [dates.date2num(datetime.datetime.fromtimestamp(x)) for x in xval]\n\n# Build the two curves graph (check Matplotlib documentation for details)\nfig = plt.figure()\nplt.xticks(rotation='vertical')\n\ngraph1 = fig.add_subplot(111)\n\ngraph1.plot(xval, ytemp, color='r', linewidth=3)\ngraph1.set_ylabel(u'Température', color='r')\ngraph1.set_ylim(0, 25)\ngraph1.yaxis.grid(color='gray', linestyle='dashed')\nfor t in graph1.get_yticklabels() : t.set_color('r')\ngraph1.yaxis.set_major_formatter(FormatStrFormatter(u'%2.0f °C'))\n\ngraph2 = graph1.twinx()\n\ngraph2.plot(xval, yhum, color='b', linewidth=3)\ngraph2.set_ylabel(u'Humidité',color='b')\ngraph2.set_ylim(50,100)\nfor t in graph2.get_yticklabels(): t.set_color('b')\ngraph2.yaxis.set_major_formatter(FormatStrFormatter(u'%2i %%'))\n\ngraph1.xaxis.set_major_locator(dates.HourLocator(interval=6))\ngraph1.xaxis.set_minor_locator(dates.HourLocator())\ngraph1.xaxis.set_major_formatter(dates.DateFormatter(\"%d-%Hh\"))\ngraph1.xaxis.grid(color='gray')\ngraph1.set_xlabel(u'Jour et heure de la journée')\n\n# X display the resulting graph (you could generate a PDF/PNG/... in place of display).\n# The display provides a minimal interface that notably allows you to save your graph\nplt.show()\n"
  },
  {
    "path": "samples/printAllLastData.py",
    "content": "#!/usr/bin/python3\n# encoding=utf-8\n\n# 2014-01 : philippelt@users.sourceforge.net \n\n# Just connect to a Netatmo account, and print all last informations available for\n# station(s) and modules of the user account\n# (except if module data is more than one hour old that usually means module lost\n#  wether out of radio range or battery exhausted thus information is no longer\n#  significant)\n\nimport time\nimport lnetatmo\n\nauthorization = lnetatmo.ClientAuth()\nweather = lnetatmo.WeatherStationData(authorization)\n\nuser = weather.user\n\nprint(\"Station owner : \", user.mail)\nprint(\"Data units    : \", user.unit)\n\n# For each station in the account\nfor station in weather.stations:\n\n    print(\"\\nSTATION : %s\\n\" % weather.stations[station][\"station_name\"])\n\n    # For each available module in the returned data of the specified station\n    # that should not be older than one hour (3600 s) from now\n    for module, moduleData in weather.lastData(station=station, exclude=3600).items() :\n       \n        # Name of the module (or station embedded module)\n        # You setup this name in the web netatmo account station management\n        print(module)\n        \n        # List key/values pair of sensor information (eg Humidity, Temperature, etc...)\n        for sensor, value in moduleData.items() :\n            # To ease reading, print measurement event in readable text (hh:mm:ss)\n            if sensor == \"When\" : value = time.strftime(\"%H:%M:%S\",time.localtime(value))\n            print(\"%30s : %s\" % (sensor, value))\n\n\n# OUTPUT SAMPLE :\n#\n# $ printAllLastData\n#\n#Station owner :  ph.larduinat@wanadoo.fr\n#Data units    :  metric\n#\n#\n#STATION : TEST-STATION-1\n#\n#Office\n#    AbsolutePressure : 988.7\n#                 CO2 : 726\n#       date_max_temp : 1400760301\n#       date_min_temp : 1400736146\n#            Humidity : 60\n#            max_temp : 19.6\n#            min_temp : 17.9\n#               Noise : 46\n#            Particle : 12768\n#            Pressure : 988.7\n#         Temperature : 19.6\n#                When : 14:10:01\n#Outdoor\n#          battery_vp : 5200\n#                 CO2 : 555\n#       date_max_temp : 1400759951\n#       date_min_temp : 1400732524\n#            Humidity : 75\n#            max_temp : 17.9\n#            min_temp : 10.3\n#           rf_status : 57\n#         Temperature : 17.9\n#                When : 14:09:25\n#Greenhouse\n#      date_min_temp : 1400732204\n#            Humidity : 89\n#            max_temp : 19.9\n#            min_temp : 9.1\n#           rf_status : 83\n#         Temperature : 19.9\n#                When : 14:09:12\n"
  },
  {
    "path": "samples/printThermostat.py",
    "content": "#!/usr/bin/python3\n# encoding=utf-8\n\n# 2018-02 : ph.larduinat@wanadoo.fr\n\n# Thermostat basic sample\n\nimport sys\nimport lnetatmo\n\nauthorization = lnetatmo.ClientAuth()\nthermostat = lnetatmo.ThermostatData(authorization)\n\n\ndefaultThermostat = thermostat.getThermostat()\nif not defaultThermostat : sys.exit(1)\ndefaultModule = thermostat.defaultModule\n\nprint('Thermostat name      :', defaultThermostat['name'])\nprint('Default module       :', defaultModule['name'])\nprint('Module measured temp :', defaultModule['measured']['temperature'])\nprint('Module set point     :', defaultModule['measured']['setpoint_temp'])\nprint('Module battery       : %s%%' % defaultModule['battery_percent'])\nfor p in defaultModule['therm_program_list']:\n    print(\"\\tProgram: \", p['name'])\n    for z in p['zones']:\n        name = z['name'] if 'name' in z else '<noname>'\n        print(\"\\t%15s : %s\" % (name, z['temp']))\n"
  },
  {
    "path": "samples/rawAPIsample.py",
    "content": "#!/usr/bin/python3\n\n# 2023-07 : ph.larduinat@wanadoo.fr\n# Library 3.2.0\n\n# Direct call of Netatmo API with authentication token\n# Return a dictionary of body of Netatmo response\n\nimport lnetatmo\n\nauthorization = lnetatmo.ClientAuth()\nrawData = lnetatmo.rawAPI(authorization, \"gethomesdata\")\n\nprint(\"Home name : home_id\")\nfor h in rawData[\"homes\"]:\n  print(f\"{h['name']} : {h['id']}\")\n\nprint(\"Radio communication strength by home\")\nfor h in rawData[\"homes\"]:\n  print(f\"\\nFor {h['name']}:\")\n  modules = lnetatmo.rawAPI(authorization, \"homestatus\", {\"home_id\" : h['id']})['home']\n  if not 'modules' in modules:\n    print(\"No modules available\")\n  else:\n    print([(m['id'],m['rf_strength']) for m in modules['modules'] if 'rf_strength' in m])"
  },
  {
    "path": "samples/simpleLastData.py",
    "content": "#!/usr/bin/python3\n# encoding=utf-8\n\n# 2013-01 : philippelt@users.sourceforge.net \n\n# Just connect to a Netatmo account, and print internal and external temperature of the default (or single) station\n# In this case, sensors of the station and the external module have been named 'internal' and 'external' in the\n# Account station settings.\n\nimport lnetatmo\n\nauthorization = lnetatmo.ClientAuth()\ndevList = lnetatmo.WeatherStationData(authorization)\n\nprint (\"Current temperature (inside/outside): %s / %s °C\" %\n        ( devList.lastData()['internal']['Temperature'],\n          devList.lastData()['external']['Temperature'])\n      )\n\n"
  },
  {
    "path": "samples/smsAlarm.py",
    "content": "#!/usr/bin/python3\n# encoding=utf-8\n\n# 2013-01 : philippelt@users.sourceforge.net \n\n# Simple example run in a cron job (every 30' for example) to send an alarm SMS if some condition is reached\n# and an other SMS when condition returned to normal. In both case, a single SMS is emitted to multiple\n# peoples (here phone1 and phone2 are two mobile phone numbers)\n# Note : lsms is my personnal library to send SMS using a GSM modem, you have to use your method/library\n\nimport sys, os\nimport lnetatmo,lsms\n\nMARKER_FILE = \"/<somewhere>/TempAlarm\"   # This flag file will be used to avoid sending multiple SMS on the same event\n                                         # Remember that the user who run the cron job must have the rights to create the file\n\n# Access the station\nauthorization = lnetatmo.ClientAuth()\ndevList = lnetatmo.WeatherStationData(authorization)\n\nmessage = []\n\n# Condition 1 : the external temperature is below our limit\ncurT = devList.lastData()['external']['Temperature']\nif curT < 5 : message.append(\"Temperature going below 5°C\")\n\n# Condition 2 : The external temperature data is older that 1 hour\nsomeLost = devList.checkNotUpdated()\nif someLost and 'external' in someLost : message.append(\"Sensor is no longer active\")\n\n# Condition 3 : The outdoor module battery is dying\nvolts = devList.lastData()['external']['battery_vp'] # I suspect that this is the total Voltage in mV\nif volts < 5000 : message.append(\"External module battery needs replacement\") # I will adjust the threshold over time\n\n# If one condition is present, at least, send an alarm by SMS\nif message :\n    if not os.path.exists(MARKER_FILE) :\n        message = \"WEATHER ALERT\\n\" + \"\\n\".join(message)\n        for p in ('<phone1>', '<phone2>') :\n            lsms.sendSMS(p, message, flash=True)\n        open(MARKER_FILE,\"w\").close() # Just to create the empty marker file and avoid to resend the same alert\nelse :\n    if os.path.exists(MARKER_FILE) :\n        os.remove(MARKER_FILE)\n        for p in ('<phone1>', '<phone2>') :\n            lsms.sendSMS(p, \"END of WEATHER alert, current temperature is %s°C\" % curT)\n\nsys.exit(0)\n"
  },
  {
    "path": "samples/weather2file.md",
    "content": "# weather2file\nThe 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.\n\nWhen 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.\n\nThe 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.\n\nThe 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 ~).\n\n\n# How to run\n1. Clone or download the repository.\n2. Enter credential information according one of the alternatives in [lnetatmo.py](https://github.com/philippelt/netatmo-api-python/blob/master/lnetatmo.py)\n3. Enter the directory and run:\n    ```PYTHONPATH=. ./samples/weather2file --format csv``` (change --format if you prefer a different format, and use any of the optional flags)\n\n```sh\n$ PYTHONPATH=. ./samples/weather2file -h\nusage: 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]\n                    [-hrl HOUR_RATE_LIMIT] [-t TEN_SECOND_RATE_LIMIT]\n\nSave historical information for all weather modules from Netatmo to file\n\noptional arguments:\n  -h, --help            show this help message and exit\n  -f {json,csv,pickle,hdf,feather,parquet,excel}, --format {json,csv,pickle,hdf,feather,parquet,excel}\n                        Format for which the data is to be saved\n  -e END_DATETIME, --end-datetime END_DATETIME\n                        The end datetime of data to be saved, in the format YYYY-MM-DD_hh:mm (default: now)\n  -v {debug,info,warning,error,quiet}, --verbose {debug,info,warning,error,quiet}\n                        Verbose level (default: info)\n  -n FILE_NAME, --file-name FILE_NAME\n                        Name of the output file (default: weatherdata)\n  -o OUTPUT_PATH, --output-path OUTPUT_PATH\n                        Output location (default: current folder)\n  -p PREVIOUS_REQUESTS, --previous-requests PREVIOUS_REQUESTS\n                        Assumes this many previous requests has been done, so that the rate limit is not exceeded (default: 0)\n  -hrl HOUR_RATE_LIMIT, --hour-rate-limit HOUR_RATE_LIMIT\n                        Specify the rate limit per hour (default: 400, max: 500)\n  -t TEN_SECOND_RATE_LIMIT, --ten-second-rate-limit TEN_SECOND_RATE_LIMIT\n                        Specify the rate limit per ten seconds (default: 30, max: 50)    \n```\n\n"
  },
  {
    "path": "samples/weather2file.py",
    "content": "#!/usr/bin/env python3\n\n# Copyright (c) 2020 Joel Berglund <joebe975@protonmail.com>\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License as\n# published by the Free Software Foundation; either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307\n# USA\n\nimport lnetatmo\nimport pandas as pd\nimport numpy as np\nimport argparse\nimport logging\nimport time\nimport socket\nfrom datetime import date, datetime, timedelta\nfrom pytz import timezone\nfrom os.path import expanduser, join\nfrom pathlib import Path\n    \ndef valid_datetime_type(arg_datetime_str):\n    try:\n        return datetime.strptime(arg_datetime_str, \"%Y-%m-%d_%H:%M\")\n    except ValueError:\n        msg = f\"Given Date {arg_datetime_str} not valid! Expected format, YYYY-MM-DD_hh:mm!\"\n        raise argparse.ArgumentTypeError(msg)\n\ndef valid_hour_limit(hour_limit):\n    hour_limit = int(hour_limit)\n    if hour_limit <= 0:\n        msg = \"Hour limit must be larger than 0\"\n        raise argparse.ArgumentTypeError(msg)\n    elif hour_limit > 500:\n        msg = \"Hour limit cannot be more than 500\"\n        raise argparse.ArgumentTypeError(msg)\n    \n    return hour_limit \n\n\ndef valid_ten_seconds_limit(ten_sec_limit):\n    ten_sec_limit = int(ten_sec_limit)\n    if ten_sec_limit <= 0:\n        msg = \"Ten seconds limit must be larger than 0\"\n        raise argparse.ArgumentTypeError(msg)\n    elif ten_sec_limit > 50:\n        msg = \"Ten seconds limit cannot be more than 50\"\n        raise argparse.ArgumentTypeError(msg)\n\n    return ten_sec_limit\n\n\nverbose_dict = {\n        'debug':logging.DEBUG,\n        'info':logging.INFO,\n        'warning':logging.WARNING,\n        'error':logging.ERROR\n        }\n\n\ndef userexpanded_path_str(path_str):\n    return expanduser(path_str)\n\n\nclass DataFrameHandler:\n    def __init__(self, file_name, output_path, file_format, kwargs={}):\n        logging.debug(f'Initiating {self.__class__.__name__}')\n        self.file_name = file_name\n        self.kwargs = kwargs\n        try:\n            Path(output_path).resolve(strict=True)\n        except FileNotFoundError as error:\n            logging.error(f'Output path {output_path} does not exist')\n            raise error\n        \n        self.output_path = output_path\n        self.file_extension = self.file_extension_dict[file_format]\n        self._set_df()\n\n    # Specify the column formats here\n    dtype_dict = {\n        'Pressure':np.float32,\n        'CO2':np.float32,\n        'Temperature':np.float32,\n        'Humidity':pd.Int8Dtype(),\n        'Noise':pd.Int16Dtype(),\n        'utc_time':np.uint32}\n\n\n\n\n    file_extension_dict = {\n        \"json\": \"json\",\n        \"pickle\": \"pkl\",\n        \"csv\": \"csv\",\n        \"hdf\": \"h5\",\n        \"feather\": \"feather\",\n        \"parquet\": \"parquet\",\n        \"excel\": \"xlsx\",\n    }\n    \n\n\n    def _set_df(self):\n        # If the file exists, load it. Otherwise, set empty DataFrame\n        file_path = self._get_complete_file_name()\n        p = Path(file_path)\n        try:\n            abs_path = p.resolve(strict=True)\n        except FileNotFoundError:\n            logging.info(f'Previous file {file_path} not found. Setting empty DataFrame')\n            self.df = pd.DataFrame([])\n\n        else: \n            logging.info(f'Previous file {file_path} found. Loading DataFrame.')\n            self.df = self._read_file(abs_path).astype(self.dtype_dict)\n\n\n    def _get_complete_file_name(self):         \n        return join(self.output_path, f\"{self.file_name}.{self.file_extension}\")\n\n    def _read_file(self, file_path):\n        pass\n\n    def _write_file(self, file_path):\n        pass\n\n    def save_to_file(self):\n\n        if self.df.empty:\n            logging.debug(\"Empty DataFrame. Nothing to save...\")\n            return\n        \n        full_file_path = self._get_complete_file_name() \n        logging.debug(f\"Saving to file {full_file_path} ({self.df.shape[0]} samples)\")\n        self._write_file(full_file_path)\n        logging.debug(f\"{full_file_path} saved\")\n\n    def append(self, df):\n        self.df = pd.concat([self.df, df], ignore_index=True)\n\n    def get_newest_timestamp(self,module_mac):\n        if ('module_mac' in self.df.columns):\n            module_utc_time = self.df.loc[self.df['module_mac']==module_mac,'utc_time']\n\n            if module_utc_time.size:\n                return module_utc_time.max()\n        \n        return None\n\n\n    def _remove_timezone(self):\n        if 'timestamp' in self.df.columns:\n            self.df['timestamp'] = self.df['timestamp'].apply(lambda x: x.replace(tzinfo=None))\n            logging.debug (f'Timezone was removed for {self.__class__.__name__}')\n\nclass PickleHandler(DataFrameHandler):\n    def __init__(self, file_name, output_path):\n        super().__init__(file_name, output_path, file_format=\"pickle\")\n\n    def _read_file(self, file_path):\n        return pd.read_pickle(file_path, **self.kwargs)\n\n    def _write_file(self, file_path):\n        self.df.to_pickle(file_path, **self.kwargs)\n\n\n\n\nclass JSONHandler(DataFrameHandler):\n    def __init__(self, file_name, output_path):\n        self.dtype_dict['Humidity'] = np.float64\n        self.dtype_dict['Noise'] = np.float64\n        super().__init__(file_name, output_path, file_format=\"json\", kwargs = {\"orient\": \"table\"})\n\n    def _read_file(self, file_path):\n        return  pd.read_json(file_path, convert_dates=False, **self.kwargs)\n\n    def _write_file(self, file_path):\n        logging.debug('JSON orient table does not support timezones. Removing timezone information...')\n        self._remove_timezone()\n        self.df.to_json(file_path, index=False, **self.kwargs)\n\n\n\nclass CSVHandler(DataFrameHandler):\n    def __init__(self, file_name, output_path):\n        super().__init__(file_name, output_path, file_format=\"csv\")\n\n    def _read_file(self, file_path):\n        return pd.read_csv(file_path, parse_dates=[\"timestamp\"], **self.kwargs)\n\n    def _write_file(self, file_path):\n        self.df.to_csv(file_path, index=False, **self.kwargs)\n\n\nclass HDFHandler(DataFrameHandler):\n    def __init__(self, file_name, output_path):\n        self.dtype_dict['Humidity'] = np.float64\n        self.dtype_dict['Noise'] = np.float64\n        super().__init__(file_name, output_path, file_format=\"hdf\", kwargs={\"key\": \"df\"})\n        \n    def _read_file(self, file_path):\n        return pd.read_hdf(file_path, **self.kwargs)\n\n    def _write_file(self, file_path):\n        self.df.to_hdf(file_path, mode=\"w\", **self.kwargs)\n\n\n\nclass ParquetHandler(DataFrameHandler):\n    def __init__(self, file_name, output_path):\n        self.dtype_dict['Noise'] = np.float64\n        super().__init__(file_name, output_path, file_format=\"parquet\")\n\n    def _read_file(self, file_path):\n        return pd.read_parquet(file_path, **self.kwargs)\n\n    def _write_file(self, file_path):\n        self.df.to_parquet(file_path, **self.kwargs)\n\n\nclass SQLHandler(DataFrameHandler):\n    def __init__(self, file_name, output_path):\n        raise NotImplementedError(\"sql details not setup\")\n        #from sqlalchemy import create_engine\n\n        #super().__init__(file_name, output_path, file_format=\"sql\", kwargs={\"con\": self.engine})\n        #self.engine = create_engine(\"sqlite://\", echo=False)\n\n    def _read_file(self, file_path):\n        return pd.read_sql(file_path, **self.kwargs)\n\n    def _write_file(self, file_path):\n        raise NotImplementedError(\"sql details not setup\")\n        self.df.to_sql(file_path, index=False, **self.kwargs)\n\n\nclass FeatherHandler(DataFrameHandler):\n    def __init__(self, file_name, output_path):\n        self.dtype_dict['Noise'] = np.float64\n        super().__init__(file_name, output_path, file_format=\"feather\")\n\n    def _read_file(self, file_path):\n        return pd.read_feather(file_path, **self.kwargs)\n\n    def _write_file(self, file_path):\n        self.df.to_feather(file_path, **self.kwargs)\n\n\n\nclass ExcelHandler(DataFrameHandler):\n    def __init__(self, file_name, output_path):\n        super().__init__(file_name, output_path, file_format=\"excel\")\n\n    def _read_file(self, file_path):\n        return pd.read_excel(file_path, **self.kwargs)\n\n    def _write_file(self, file_path):\n        logging.debug('Excel does not support timezones. Removing timezone information...')\n        self._remove_timezone()\n        self.df.to_excel(file_path, index=False, **self.kwargs)\n\n\ndf_handler_dict = {\n    \"json\": JSONHandler,\n    \"pickle\": PickleHandler,\n    \"csv\": CSVHandler,\n    \"hdf\": HDFHandler,\n    \"feather\": FeatherHandler,\n    \"sql\": SQLHandler,\n    \"parquet\": ParquetHandler,\n    \"excel\": ExcelHandler,\n}\n\n\n\n\nclass RateLimitHandler:\n    def __init__(self,\n                 user_request_limit_per_ten_seconds=50,\n                 user_request_limit_per_hour=500,\n                 nr_previous_requests=0):\n        \n        \n        self._USER_REQUEST_LIMIT_PER_TEN_SECONDS = user_request_limit_per_ten_seconds\n        logging.debug(f'Ten second rate limit was set to {user_request_limit_per_ten_seconds}')\n\n        self._USER_REQUST_LIMIT_PER_HOUR = user_request_limit_per_hour \n        logging.debug(f'Hour rate limit was set to {user_request_limit_per_hour}')\n\n        self._TEN_SECOND_TIMEDELTA = timedelta(seconds=10)\n        self._HOUR_TIMEDELTA = timedelta(hours=1)\n        self._SECOND_TIMEDELTA = timedelta(seconds=1)\n        \n        # Keep track of when we have done requests\n        if nr_previous_requests:\n            logging.debug(f'{nr_previous_requests} previous requests has been assumed')\n            self.requests_series = pd.Series(\n                    data=1,\n                    index=[datetime.now()],\n                    name='request_logger',\n                    dtype=np.uint16).repeat(nr_previous_requests)\n        else:\n            logging.debug('No previous requests has been assumed. Creating empty request logger')\n            self.requests_series = pd.Series(name='request_logger',dtype=np.uint16)\n            \n        self._set_authorization()\n        self._set_weather_data() \n        \n    def _get_masked_series(self, time_d):\n        return self.requests_series[self.requests_series.index >= (datetime.now() - time_d)]\n   \n    def _log_request(self):\n        self.requests_series[datetime.now()] = 1\n\n    def _set_authorization(self): \n        self._check_rate_limit_and_wait()\n        self.authorization = lnetatmo.ClientAuth()\n        self._log_request()\n\n\n    def _set_weather_data(self):\n        self._check_rate_limit_and_wait()\n        self.weather_data = lnetatmo.WeatherStationData(self.authorization)\n        self._log_request()\n\n    def _sleep(self, until_time):\n        sleep = True\n        tot_seconds = (until_time - datetime.now())/self._SECOND_TIMEDELTA\n        \n        while(sleep):\n            time_left = (until_time - datetime.now())/self._SECOND_TIMEDELTA\n            \n            if(time_left>0):\n                if logging.getLogger().isEnabledFor(logging.INFO):    \n                    print(f'\\t{time_left:.1f}/{tot_seconds:.1f} seconds left',end='\\r')\n                time.sleep(1)\n            else:\n                sleep = False\n   \n    def _check_rate_limit_and_wait(self):\n            \n        # Check the 10 second limit\n        ten_sec_series = self._get_masked_series(self._TEN_SECOND_TIMEDELTA)\n\n        if(ten_sec_series.size >= self._USER_REQUEST_LIMIT_PER_TEN_SECONDS):\n            # Wait until there is at least room for one more request\n            until_time = (ten_sec_series.index[-self._USER_REQUEST_LIMIT_PER_TEN_SECONDS] + self._TEN_SECOND_TIMEDELTA)\n            logging.info(f'10 second limit. Waiting for {(until_time - datetime.now())/self._SECOND_TIMEDELTA:.1f} seconds...')\n            self._sleep(until_time)\n        \n        # Check the 500 second limit\n        hour_series = self._get_masked_series(self._HOUR_TIMEDELTA)\n\n        if(hour_series.size >= self._USER_REQUST_LIMIT_PER_HOUR):\n            # Wait until there is at least room for one more request\n            until_time = (hour_series.index[-self._USER_REQUST_LIMIT_PER_HOUR] + self._HOUR_TIMEDELTA)\n            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...')\n            self._sleep(until_time)\n    \n    def _get_measurement(self, input_dict):\n        \n        # Check that we don't exceed the user rate limit\n        self._check_rate_limit_and_wait()\n       \n        # Log this request\n        self._log_request()\n       \n        try:\n            return self.weather_data.getMeasure(**input_dict)\n        except socket.timeout as socket_timeout:\n            logging.error(socket_timeout)\n            return None\n   \n    def get_stations(self):\n       return self.weather_data.stations.items()\n    \n\n\n    def _get_field_dict(self, station_id,module_id,data_type,start_date,end_date):\n        \"\"\"Returns a dict to be used when requesting data through the Netatmo API\"\"\"\n        \n        return {'device_id':station_id,\n         'scale':'max',\n         'mtype':','.join(data_type),\n         'module_id':module_id,\n         'date_begin':start_date,\n         'date_end':end_date}\n\n    def _get_date_from_timestamp(self, ts, tz=None):\n        return datetime.fromtimestamp(ts,tz).date()\n\n    def _get_timestamp_from_date(self, d, tz=None):\n        \"\"\"Returns the timetamp corresponding to the end of the day d\"\"\"\n        # Create datetime from date\n        combined_datetime = datetime.combine(d, datetime.max.time(), tzinfo=tz)\n        return np.floor(datetime.timestamp(combined_datetime))\n        \n    def _get_common_elements(self, keys, column_names):\n        return list(set(keys).intersection(column_names))\n\n\n    def _to_dataframe(self, module_data_body, module_data, station_name, station_mac, dtype={}, time_z=None):\n        \"\"\"Convert the dict to a pandas DataFrame\"\"\"\n\n\n        df = pd.DataFrame.from_dict(module_data_body,orient='index',columns=module_data['data_type'])\n\n        df['type'] = module_data['type']\n        df['module_name'] = module_data['module_name']\n        df['module_mac'] = module_data['_id']\n        df['station_name'] = station_name\n        df['station_mac'] = station_mac\n\n        df.index.set_names('utc_time',inplace=True)\n        df.reset_index(inplace=True)\n        df['timestamp'] = df['utc_time'].apply(lambda x: datetime.fromtimestamp(np.uint32(x), tz=time_z))\n\n        common_names = self._get_common_elements(dtype.keys(), df.columns)\n        dtypes = {k: dtype[k] for k in common_names}\n\n        return df.astype(dtypes)\n\n    def get_module_df(self, newest_utctime, station_name, station_mac, module_data_overview, end_date_timestamp, dtype={}, time_z=None):\n        logging.info(f'Processing {module_data_overview[\"module_name\"]}...')\n        \n        \n        module_name = module_data_overview[\"module_name\"]\n        \n        # We start by collecting new data\n        keep_collecting_module_data = True\n\n        # Start with the oldest timestamp\n        module_start_date_timestamp = module_data_overview['last_setup']\n\n        # Fill array with data\n        data = []\n\n        if(newest_utctime):\n            # Found newer data! Change start time according to the newest value\n\n            if(newest_utctime > module_start_date_timestamp):\n                module_start_date_timestamp = newest_utctime + 1\n                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)}')\n            else:\n                logging.debug(f'No newer data found for module {module_name}, starting from last setup.')\n\n        if(end_date_timestamp < module_start_date_timestamp):\n            logging.info('Start date is after end date. Nothing to do...')\n            keep_collecting_module_data = False\n        else:\n            logging.info(f'Collecting data for {module_name}...')\n        \n        while(keep_collecting_module_data):\n            \n            # Get new data from Netatmo\n            d = self._get_field_dict(station_mac,\n                               module_data_overview['_id'],\n                               module_data_overview['data_type'],\n                               module_start_date_timestamp,\n                               end_date_timestamp)\n            \n            retreived_module_data = self._get_measurement(d) \n\n            if retreived_module_data is None:\n                logging.warning(f'None received. Aborting data collection from module {module_name}')\n                keep_collecting_module_data = False\n            else:\n                try:\n                    # Was there any data?\n                    if(retreived_module_data['body']):\n                        new_df = self._to_dataframe(retreived_module_data['body'],\n                                            module_data_overview,\n                                            station_name,\n                                            station_mac,\n                                            dtype,\n                                            time_z)\n                        data.append(new_df)\n                        new_df['utc_time'].min()\n                        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]}')\n                        # Now change the start_time\n                        module_start_date_timestamp = new_df['utc_time'].max() + 1\n\n                    else:\n                        keep_collecting_module_data = False\n                        logging.debug(f'Data not found for {module_name}. Proceeding...')\n\n                except Exception as e:\n                    logging.error(e)\n                    keep_collecting_module_data = False\n                    logging.error(f'Something fishy is going on... Aborting collection for module {module_name}')\n        \n\n        if data:\n            df_module = pd.concat(data,ignore_index=True)\n        else:\n            df_module = pd.DataFrame([])\n\n\n        logging.info(f'Collected data from {module_name} contains {df_module.shape[0]} samples.')\n        return df_module\n\ndef main():\n\n    parser = argparse.ArgumentParser(\n        description=\"Save historical information for all weather modules from Netatmo to file\"\n    )\n    \n    parser.add_argument(\n        \"-f\",\n        \"--format\",\n        choices=[\"json\", \"csv\", \"pickle\", \"hdf\", \"feather\", \"parquet\", \"excel\"],\n        required=True,\n        help=\"Format for which the data is to be saved\",\n    )\n\n    parser.add_argument(\n        \"-e\",\n        \"--end-datetime\",\n        type=valid_datetime_type,\n        default=datetime.now(),\n        required=False,\n        help=\"The end datetime of data to be saved, in the format YYYY-MM-DD_hh:mm (default: now)\",\n    )\n\n    parser.add_argument(\n        \"-v\",\n        \"--verbose\",\n        choices=[\"debug\", \"info\", \"warning\", \"error\", \"quiet\"],\n        default=\"info\",\n        required=False,\n        help=\"Verbose level (default: info)\")\n\n    parser.add_argument(\n        \"-n\",\n        \"--file-name\",\n        default=\"weatherdata\",\n        required=False,\n        help=\"Name of the output file (default: weatherdata)\")\n\n\n    parser.add_argument(\n        \"-o\",\n        \"--output-path\",\n        type=userexpanded_path_str,\n        default=\".\",\n        required=False,\n        help=\"Output location (default: current folder)\")\n\n\n    parser.add_argument(\n        \"-p\",\n        \"--previous-requests\",\n        type=np.uint16,\n        default=np.uint8(0),\n        required=False,\n        help=\"Assumes this many previous requests has been done, so that the rate limit is not exceeded (default: 0)\")\n\n\n    parser.add_argument(\n        \"-hrl\",\n        \"--hour-rate-limit\",\n        type=valid_hour_limit,\n        default=400,\n        required=False,\n        help=\"Specify the rate limit per hour (default: 400, max: 500)\")\n\n\n\n    parser.add_argument(\n        \"-t\",\n        \"--ten-second-rate-limit\",\n        type=valid_ten_seconds_limit,\n        default=30,\n        required=False,\n        help=\"Specify the rate limit per ten seconds (default: 30, max: 50)\")\n\n\n    args = parser.parse_args()\n\n\n    if(args.verbose == 'quiet'):\n        logging.disable(logging.DEBUG)\n    else:\n        logging.basicConfig(format=\" %(levelname)s: %(message)s\", level=verbose_dict[args.verbose])\n\n    \n    # Handle dataframes (loading, appending, saving).\n    df_handler = df_handler_dict[args.format](file_name=args.file_name, output_path=args.output_path)\n\n    \n    # Rate handler to make sure that we don't exceed Netatmos user rate limits\n    rate_limit_handler = RateLimitHandler(\n            user_request_limit_per_ten_seconds=args.ten_second_rate_limit,\n            user_request_limit_per_hour=args.hour_rate_limit,\n            nr_previous_requests=args.previous_requests)\n\n\n    for station_name, station_data_overview in rate_limit_handler.get_stations():\n    \n        station_mac = station_data_overview['_id']\n    \n        station_timezone = timezone(station_data_overview['place']['timezone'])\n        logging.info(f'Timezone {station_timezone} extracted from data.')\n        \n        end_datetime_timestamp = np.floor(datetime.timestamp(station_timezone.localize(args.end_datetime)))\n        newest_utc = df_handler.get_newest_timestamp(station_data_overview['_id'])\n        df_handler.append(\n            rate_limit_handler.get_module_df(\n                newest_utc,\n                station_name,\n                station_mac,\n                station_data_overview,\n                end_datetime_timestamp,\n                df_handler.dtype_dict,\n                station_timezone))\n\n        for module_data_overview in station_data_overview['modules']:\n        \n            df_handler.append(\n                rate_limit_handler.get_module_df(\n                    df_handler.get_newest_timestamp(module_data_overview['_id']),\n                    station_name,\n                    station_mac,\n                    module_data_overview,\n                    end_datetime_timestamp,\n                    df_handler.dtype_dict,\n                    station_timezone)) \n        \n\n\n\n    # Save the data after the collection\n    df_handler.save_to_file()\n\nif __name__ == \"__main__\":\n    main()\n \n"
  },
  {
    "path": "setup.cfg",
    "content": "[metadata]\ndescription-file = README.md\n\n"
  },
  {
    "path": "setup.py",
    "content": "# python setup.py --dry-run --verbose install\n\nfrom distutils.core import setup\n\nsetup(\n    name='lnetatmo',\n    version='4.2.1',\n    classifiers=[\n        'Development Status :: 5 - Production/Stable',\n        'Intended Audience :: Developers',\n        'Programming Language :: Python :: 2.7',\n        'Programming Language :: Python :: 3'\n        ],\n    author='Philippe Larduinat',\n    author_email='ph.larduinat@wanadoo.fr',\n    py_modules=['lnetatmo'],\n    scripts=[],\n    data_files=[],\n    url='https://github.com/philippelt/netatmo-api-python',\n    download_url='https://github.com/philippelt/netatmo-api-python/archive/v4.2.1.tar.gz',\n    license='GPL V3',\n    description='Simple API to access Netatmo weather station data from any python script.'\n)\n"
  },
  {
    "path": "usage.md",
    "content": "Python Netatmo API programmers guide\n------------------------------------\n\n\n\n>2013-01-21, philippelt@users.sourceforge.net\n\n>2014-01-13, Revision to include new modules additionnal informations\n\n>2016-06-25, Update documentation for Netatmo Welcome\n\n>2017-01-09, Minor updates to packaging info\n\n>2020-12-07, Breaking changes due to removal of direct access to devices, \"home\" being now required (Netatmo redesign)\n\n>2023-07-12, Breaking changes due to deprecation of grant_type \"password\" for ALL apps\n\n>2023-07-24, Adding rawAPI call to direct access the netatmo API when no additional support is provided by the library\n\n>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)\n\n>2024-01-03, New authentication method priorities, credential file as a parameter\n\nNo additional library other than standard Python library is required.\n\nBoth Python V2.7x and V3.x.x are supported without change.\n\nMore information about the Netatmo REST API can be obtained from http://dev.netatmo.com/doc/\n\nThis package support only preauthenticated scoped tokens created along apps.\n\n\n\n### 1 Setup your environment from Netatmo Web interface ###\n\n\n\n\nBefore being able to use the module you will need :\n\n  * A Netatmo user account having access to, at least, one station\n  * An application registered from the user account (see http://dev.netatmo.com/dev/createapp) to obtain application credentials.\n  * Create a couple access_token/refresh_token at the same time with your required scope (depending of your intents on library use)\n\n\nIn 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.\n\nPossible NETATMO_SCOPES ;\nread_station read_smarther write_smarther read_thermostat write_thermostat read_camera write_camera read_doorbell \nread_presence write_precense read_homecoach read_carbonmonoxidedetector read_smokedetector read_magellen write_magellan \nread_bubendorff write_bubendorff read_mx write_mx read_mhs1 write_mhs1\n\n\n\n### 2 Setup your authentication information ###\n\n\n\nCopy the lnetatmo.py file in your work directory (or use pip install lnetatmo).\n\nAuthentication data can be supplied with 3 different methods (each method override any settings of previous methods) : \n\n 1. Some or all values can be defined by explicit call to initializer of ClientAuth class  \n \n        ̀```bash\n        # Example: REFRESH_TOKEN supposed to be defined by an other method\n        authData = lnetatmo.ClientAuth( clientId=\"netatmo-client-id\",\n                                        clientSecret=\"secret\" )\n        ```\n\n 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  \n \n        ̀̀```bash\n        $ cat .netatmo.credentials   # Here all values are defined but it is not mandatory\n        {\n            \"CLIENT_ID\" : \"`xxx\",\n            \"CLIENT_SECRET\" : \"xxx\",\n            \"REFRESH_TOKEN\" : \"xxx\"\n        }\n        $\n        ̀̀```\n\n 3. Some or all values can be overriden by environment variables. This is the easiest method if your are packaging your application with Docker.\n \n        ̀̀```bash\n        $ export REFRESH_TOKEN=\"yyy\"\n        $ python3 MyCodeUsingLnetatmo.py\n        ̀̀```\n        \n> 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.\n\nIf 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.\n\nThis 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.\n\n```bash\n$ python3 lnetatmo.py  # or python2 as well\nlnetatmo.py : OK\n$ echo $?\n0\n```\n\nWhatever is your choice for the library authentication setup, your application code if you were using previous library version, will not be affected.\n\n\n### 3 Package guide ###\n\n  \n\nMost of the time, the sequence of operations will be :\n\n  1. Authenticate your program against Netatmo web server\n  2. Get the device list accessible to the user\n  3. Request data on one of these devices or directly access last data sent by the station\n\n\nExample :\n\n```python\n#!/usr/bin/python3\n# encoding=utf-8\n\nimport lnetatmo\n\n# 1 : Authenticate\nauthorization = lnetatmo.ClientAuth()\n\n# 2 : Get devices list\nweatherData = lnetatmo.WeatherStationData(authorization)\n\n# 3 : Access most fresh data directly\nprint (\"Current temperature (inside/outside): %s / %s °C\" %\n            ( weatherData.lastData()['indoor']['Temperature'],\n              weatherData.lastData()['outdoor']['Temperature'])\n)\n```\n\nIn 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).\n\nThe Netatmo design is based on stations (usually the in-house module) and modules (radio sensors reporting to a station, usually an outdoor sensor).\n\nSensor 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.\n\nThe 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\nmodules**.\n\nHaving two roles, the station has a 'station_name' property as well as a 'module_name' for its internal sensor.\n\n>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).\n\n\nSensors (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\nmultiple 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).\n\nThe 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).\n\n\n\n### 4 Package classes and functions ###\n\n\n\n#### 4-1 Global variables ####\n\n  \n```python\n_CLIENT_ID, _CLIENT_SECRET = Application ID and secret provided by Netatmo\napplication registration in your user account\n\n_REFRESH_TOKEN : Refresh token created along the app client credentials\n\n_BASE_URL and _*_REQ : Various URL to access Netatmo web services. They are\ndocumented in http://dev.netatmo.com/doc/ They should not be changed unless\nNetatmo API changes.\n```  \n\n\n\n#### 4-2 ClientAuth class ####\n\n\n\nConstructor\n\n```python\n    authorization = lnetatmo.ClientAuth( clientId = _CLIENT_ID,\n                                         clientSecret = _CLIENT_SECRET,\n                                         refreshToken = _REFRESH_TOKEN,\n                                         credentialFile = \"~/.netatmo.credentials\"\n                                        )\n```\n\n\nRequires : 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 = …)\n\n\nReturn : 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.\n\n\nProperties, all properties are read-only unless specified :\n\n  * **accessToken** : Retrieve a valid access token (renewed if necessary)\n  * **refreshToken** : The token used to renew the access token (normally should not be used explicitely)\n  * **expiration** : The expiration time (epoch) of the current token\n \n  \n\n#### 4-3 User class ####\n\n\n\nConstructor\n\n```python\n    user = lnetatmo.User( authorization )\n```\n\n\nRequires : an authorization object (ClientAuth instance)\n\n\nReturn : a User object. This object provides multiple informations on the user account such as the mail address of the user, the preferred language, …\n\n\nProperties, all properties are read-only unless specified :\n\n\n  * **rawData** : Full dictionary of the returned JSON GETUSER Netatmo API service\n  * **ownerMail** : eMail address associated to the user account\n  * **devList** : List of Station's id accessible to the user account\n\n\nIn 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.\n\n\n\n#### 4-4 WeatherStationData class ####\n\n\n\nConstructor\n\n```python\n    weatherData = lnetatmo.WeatherStationData( authorization, home=None, station=None )\n```\n\n\n * Input : an authorization object (ClientAuth instance), an optional home name, an optional station name or id\n\nReturn : 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.\n\nRaise a lnetatmo.NoDevice exception if no weather station is available for the given account.\n\nIf no home is specified, the first returned home will be set as default home. Same apply to station.\nIf 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.\n\n>**Breaking change:**  \nIf 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.\n\nProperties, all properties are read-only unless specified:\n\n\n  * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service\n  * **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).\n  * **stations** : Dictionary of stations (indexed by ID) accessible to this user account\n  * **modules** : Dictionary of modules (indexed by ID) accessible to the user account (whatever station there are plugged in)\n\n\nMethods :\n\n\n  * **getStation** (station=None) : Find a station by it's station name or station ID\n    * Input : Station name or ID to lookup (str)\n    * Output : station dictionary or None\n\n  * **stationByName** (station=None) : Find a station by it's station name\n    * Input : Station name to lookup (str)\n    * Output : station dictionary or None\n\n  * **stationById** (sid) : Find a station by it's Netatmo ID (mac address)\n    * Input : Station ID\n    * Output : station dictionary or None\n\n  * **moduleByName** (module, station=None) : Find a module by it's module name\n    * Input : module name and optional station name\n    * Output : module dictionary or None\n\n     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).\n\n  * **moduleById** (mid, sid=None) : Find a module by it's ID and belonging station's ID\n    * Input : module ID and optional Station ID\n    * Output : module dictionary or None\n\n  * **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()\n\n  * **lastData** (station=None, exclude=0) : Get the last data uploaded by the station, exclude sensors with measurement older than given value (default return all)\n    * Input : station name OR id. If not provided default_station is used. Exclude is the delay in seconds from now to filter sensor readings.\n    * Output : Sensors data dictionary (Key is sensor name)\n\n     AT the time of this document, Available measures types are :\n      * 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\n      * battery_vp : likely to be total battery voltage for external sensors (running on batteries) in mV (undocumented)\n      * rf_status : likely to be the % of radio signal between the station and a module (undocumented)\n\n     See Netatmo API documentation for units of regular measurements\n\n     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 :\n\n```python\n# Last data access example\n\ntheData = weatherData.lastData()\nprint('Available modules : ', theData.keys() )\nprint('In-house CO2 level : ', theData['indoor']['Co2'] )\nprint('Outside temperature : ', theData['outdoor']['Temperature'] )\nprint('External module battery : ', \"OK\" if int(theData['outdoor']['battery_vp']) > 5000 \\\n                                     else \"NEEDS TO BE REPLACED\" )\n```\n  * **checkNotUpdated** (station=None, delay=3600) :\n    * Input : optional station name (else default_station is used)\n    * 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).\n\n     For example (following the previous one)\n\n```python\n# Ensure data sanity\n\nfor m in weatherData.checkNotUpdated(\"<optional station name>\"):\n    print(\"Warning, sensor %s information is obsolete\" % m)\n    if moduleByName(m) == None : # Sensor is not an external module\n        print(\"The station is lost\")\n```\n  * **checkUpdated** (station=None, delay=3600) :\n    * Input : optional station name (else default_station is used)\n    * Output : list of modules name for which last data update is newer than specified delay (default 1 hour).\n\n     Complement of the previous service\n\n  * **getMeasure** (device_id, scale, mtype, module_id=None, date_begin=None, date_end=None, limit=None, optimize=False) :\n    * Input : All parameters specified in the Netatmo API service GETMEASURE (type being a python reserved word as been replaced by mtype).\n    * Output : A python dictionary reflecting the full service response. No transformation is applied.\n  * **MinMaxTH** (station=None, module=None, frame=\"last24\") : Return min and max temperature and humidity for the given station/module in the given timeframe\n    * Input :\n      * An optional station Name or ID, default_station is used if not supplied,\n      * An optional module name or ID, default : station sensor data is used\n      * A time frame that can be :\n        * \"last24\" : For a shifting window of the last 24 hours\n        * \"day\" : For all available data in the current day\n    * Output :\n      * A 4 values tuple (Temp mini, Temp maxi, Humid mini, Humid maxi)\n\n     >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\nat all if you slip over two days as required in a shifting 24 hours window.\n\n\n#### 4-5 HomeData class ####\n\n\n\nConstructor\n\n```python\n    homeData = lnetatmo.HomeData( authorization )\n```\n\n\nRequires : an authorization object (ClientAuth instance)\n\n\nReturn : a homeData object. This object contains most administration properties of home security products and notably Welcome & Presence cameras.\n\n\nNote : 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.\n\nProperties, all properties are read-only unless specified:\n\n\n  * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service\n  * **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).\n  * **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).\n  * **homes** : Dictionary of homes (indexed by ID) accessible to this user account\n  * **cameras** : Dictionnary of cameras (indexed by home name and cameraID) accessible to this user\n  * **persons** : Dictionary of persons (indexed by ID) accessible to the user account\n  * **events** : Dictionary of events (indexed by cameraID and timestamp) seen by cameras\n\n\nMethods :\n\n  * **homeById** (hid) : Find a home by its Netatmo ID\n    * Input : Home ID\n    * Output : home dictionary or None\n\n  * **homeByName** (home=None) : Find a home by it's home name\n    * Input : home name to lookup (str)\n    * Output : home dictionary or None\n\n  * **cameraById** (hid) : Find a camera by its Netatmo ID\n    * Input : camera ID\n    * Output : camera dictionary or None\n\n  * **cameraByName** (camera=None, home=None) : Find a camera by it's camera name\n    * Input : camera name and home name to lookup (str)\n    * Output : camera dictionary or None\n\n  * **cameraUrls** (camera=None, home=None, cid=None) : return Urls to access camera live feed\n    * Input : camera name and optional home name or cameraID to lookup (str)\n    * Output : tuple with the vpn_url (for remote access) and local url to access the camera (commands)\n\n  * **url** (camera=None, home=None, cid=None) : return the best url to access camera live feed\n    * Input : camera name and optional home name or cameraID to lookup (str)\n    * Output : the local url if available to reduce internet bandwith usage else the vpn url\n\n  * **personsAtHome** (home=None) : return the list of known persons who are at home\n    * Input : home name to lookup (str)\n    * Output : list of persons seen\n\n  * **getCameraPicture** (image_id, key): Download a specific image (of an event or user face) from the camera\n    * Input : image_id and key of an events or person face\n    * Output: Tuple with image data (to be stored in a file) and image type (jpg, png...)\n\n  * **getProfileImage** (name) : Retreive the face of a given person\n    * Input : person name (str)\n    * Output: **getCameraPicture** data\n\n  * **updateEvent** (event=None, home=None): Update the list of events\n    * Input: Id of the latest event and home name to update event list\n\n  * **personSeenByCamera** (name, home=None, camera=None): Return true is a specific person has been seen by the camera in the last event\n\n  * **someoneKnownSeen** (home=None, camera=None) : Return true is a known person has been in the last event\n\n  * **someoneUnknownSeen** (home=None, camera=None) : Return true is an unknown person has been seen in the last event\n\n  * **motionDetected** (home=None, camera=None) : Return true is a movement has been detected in the last event\n\n  * **presenceLight** (camera=None, home=None, cid=None, setting=None) : return or set the Presence camera lighting mode\n    * Input : camera name and optional home name or cameraID to lookup (str), setting must be None|auto|on|off. *currently not supported*\n    * Output : setting requested if supplied else current camera setting\n\n  * **presenceStatus** (mode, camera=None, home=None, cid=None) : set the camera on or off (current status in camera properties)\n    * Input : mode (on|off) (str), camera name and optional home name or cameraID to lookup (str)\n    * Output : requested mode if changed else None\n\n  * **getLiveSnapshot** (camera=None, home=None, cid=None) : Get a jpeg of current live view of the camera\n    * Input : camera name and optional home name or cameraID to lookup (str)\n    * Output : jpeg binary content\n\n```\n    homedata = lnetatmo.HomeData(authorization)    \n    for k, v in homedata.homes.items():\n        homeid = k\n        S = v.get('smokedetectors')\n        C = v.get('cameras')\n        P = v.get('persons')\n        E = v.get('events')\n    if S or C or P or E:\n        print ('devices in HomeData')\n        for smokedetector in homedata.homes[homeid].get('smokedetectors'):\n            print (smokedetector['name'])\n        for camera in homedata.homes[homeid].get('cameras'):\n            print (camera['name'])\n        for persons in homedata.homes[homeid].get('persons'):\n            print (persons['name'])\n        for events in homedata.homes[homeid].get('events'):\n            print (events['name'])\n        return homeid\n    else:\n        homeid = k\n        return homeid\n\n```\n  \n\n#### 4-6 HomeStatus class ####\n\n\nConstructor\n\n```\n    homeStatus = lnetatmo.HomeStatus( authorization, home_id )\n\n```\n\nRequires : \n- an authorization object (ClientAuth instance)\n- home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using \"class homedata\"\n\nReturn : a homeStatus object. This object contains most administration properties of Home+ Control devices such as Smarther thermostat, Socket, Cable Output, Centralized fan, Micromodules, ...\n\nMethods :\n\n  * **getRoomsId** : return all room ID\n    * Output : list of IDs of every single room (only the one with Smarther thermostat)\n\n  * **getListRoomParam** : return every parameters of a room\n    * Input : room ID\n    * Output : list of parameters of a room\n\n  * **getRoomParam** : return a specific parameter for a specific room\n    * Input : room ID and parameter\n    * Output : value\n\n  * **getModulesId** : return all module IDs\n    * Output : list of IDs of every single module (socket, cable outlet, ...)\n\n  * **getListModuleParam** : return every parameters of a module\n    * Input : module ID\n    * Output : list of parameters of a module\n\n  * **getModuleParam** : return a specific parameter for a specific module\n    * Input : module ID and parameter\n    * Output : value\n\n```\n    homestatus = lnetatmo.HomeStatus(authorization, homeid)\n    print ('Rooms in Homestatus')\n    for r in homestatus.rooms:\n        print (r)\n    print ('Persons in Homestatus')\n    if 'persons' in homestatus.rawData.keys():\n        for pp in homestatus.rawData['persons']:\n             print (pp)\n    print ('Modules in Homestatus')\n    for m in homestatus.modules:\n        for kt, vt in m.items():\n            if kt == 'type':\n                print (m['type'])\n                print (m['id'])\n                print (lnetatmo.TYPES[vt])\n                print (m.keys())\n\n\n```\n\n\n#### 4-7 ThermostatData class ####\n\n\nConstructor\n\n```\n    device = lnetatmo.ThermostatData ( authorization, home_id )\n    \n```\n\nRequires : \n- an authorization object (ClientAuth instance)\n- home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using \"class homedata\"\n\nReturn : a device object. This object contains the Relay_Plug with Thermostat and temperature modules.\n\nMethods :\n\n  * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service\n    * Output : list of IDs of every relay_plug\n\n  * **Relay_Plug** : \n    * Output : Dictionairy of First Relay object  \n\n  * **Thermostat_Data** : \n    * Output : Dictionairy of Thermostat object in First Relay[Modules].\n   \nExample :  \n\n```\n    device = lnetatmo.ThermostatData(authorization, homeid)\n    for i in device.rawData:\n        print ('rawData')\n        print (i['_id'])\n        print (i['station_name'])\n        print (dir(i))\n        print ('modules in rawData')\n        print (i['modules'][0]['_id'])\n        print (i['modules'][0]['module_name'])\n        print (' ')\n    print ('Relay Data')\n    Relay = device.Relay_Plug()\n    print (Relay.keys())\n    print ('Thermostat Data')\n    TH = device.Thermostat_Data()\n    print (TH.keys())\n\n```\n\n#### 4-8 HomesData class ####\n\n\nConstructor\n\n```python\n    homesData = lnetatmo.HomesData ( authorization, home_id )\n```\n\nRequires : \n- an authorization object (ClientAuth instance)\n- home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using \"class homedata\"\n\nReturn : a homesdata object. This object contains the Netatmo actual topology and static information of\n         all devices present into a user account. It is also possible to specify a home_id to focus on one home.\n\nMethods :\n\n  * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service\n    * Output : list of IDs of every devices\n\nExample :  \n\n```\n    homesData = lnetatmo.HomesData ( authorization, home_id )\n    print (homesdata.Homes_Data['name'])\n    print (homesdata.Homes_Data['altitude'])\n    print (homesdata.Homes_Data['coordinates'])\n    print (homesdata.Homes_Data['country'])\n    print (homesdata.Homes_Data['timezone'])\n    print ('rooms in HomesData')\n    for r in homesdata.Homes_Data.get('rooms'):\n        print (r)\n    print ('Devices in HomesData')\n    for m in homesdata.Homes_Data.get('modules'):\n        print (m)\n    print ('Persons in HomesData')\n    if 'persons' in homesdata.Homes_Data.keys():\n        for P in homesdata.Homes_Data.get('persons'):\n            print (P)\n    print ('Schedules in HomesData')\n    print (homesdata.Homes_Data['schedules'][0].keys())\n\n```\n\n#### 4-9 Homecoach class ####\n\n\nConstructor\n\n```python\n    homecoach = lnetatmo.HomeCoach(authorization, home_id )\n```\n\nRequires : \n- an authorization object (ClientAuth instance)\n- home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using \"class homedata\"\n\nReturn : a homecoach object. This object contains all Homecoach Data.\n\nMethods :\n\n  * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service\n    * Output : list of all Homecoach in user account\n\n  * **checkNotUpdated** :\n    * Output : list of modules name for which last data update is older than specified delay (default 1 hour).\n\n\n  * **checkUpdated** :\n    * Output : list of modules name for which last data update is newer than specified delay (default 1 hour).\n\nExample :\n\n\n```\n    homecoach = lnetatmo.HomeCoach(authorization, homeid)\n    #\n    Not_updated = []\n    updated = []\n    d = {}\n    for device in homecoach.rawData:\n        _id = device['_id']\n        d.update({'When': device['dashboard_data']['time_utc']})\n        a = homecoach.checkNotUpdated(d, _id)\n        b = homecoach.checkUpdated(d, _id)\n        print (device['station_name'])\n        print (device['date_setup'])\n        print (device['last_setup'])\n        print (device['type'])\n        print (device['last_status_store'])\n        print (device['firmware'])\n        print (device['last_upgrade'])\n        print (device['wifi_status'])\n        print (device['reachable'])\n        print (device['co2_calibrating'])\n        print (device['data_type'])\n        print (device['place'])\n        print (device['dashboard_data'])\n        Not_updated.append(a)\n        updated.append(b)\n    D = homecoach.HomecoachDevice['dashboard_data']\n    print (D.keys())\n    # dict_keys(['time_utc', 'Temperature', 'CO2', 'Humidity', 'Noise', 'Pressure', 'AbsolutePressure', 'health_idx', 'min_temp', 'max_temp', 'date_max_temp', 'date_min_temp'])\n    print (Not_updated)\n    print (updated)\n\n```\n\n\n#### 4-10 Utilities functions ####\n\n\n  * **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\")\n  * **toTimeString** (timestamp) : Convert a Netatmo time stamp to a readable date/time format.\n  * **toEpoch**( dateString) : Convert a date string (form YYYY-MM-DD_HH:MM:SS) to timestamp\n  * **todayStamps**() : Return a couple of epoch time (start, end) for the current day\n\n\n#### 4-11 All-in-One function ####\n\n\nIf 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 :\n\n\n**getStationMinMaxTH**(station=None, module=None, home=None) :\n  * 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).\n    if no home is specified, first returned home will be used\n  * Output : A tuple of 6 values (Temperature, Humidity, minT, MaxT, minH, maxH)\n\n```python\n>>> import lnetatmo\n>>> print(lnetatmo.getStationMinMaxTH())\n[20, 33, 18.1, 20, 30, 34]\n>>>\n>>> print(lnetatmo.getStationMinMaxTH(module='outdoor'))\n[2, 53, 1.2, 5.4, 51, 74]\n"
  }
]