├── .github
└── workflows
│ └── lint_python.yml
├── .gitignore
├── .netatmo.credentials
├── LICENSE.txt
├── README.md
├── lnetatmo.py
├── samples
├── get_direct_camera_snapshot
├── graphLast3Days
├── printAllLastData.py
├── printThermostat.py
├── rawAPIsample.py
├── simpleLastData.py
├── smsAlarm.py
├── weather2file.md
└── weather2file.py
├── setup.cfg
├── setup.py
└── usage.md
/.github/workflows/lint_python.yml:
--------------------------------------------------------------------------------
1 | name: lint_python
2 | on: [pull_request, push]
3 | jobs:
4 | lint_python:
5 | runs-on: ubuntu-latest
6 | steps:
7 | - uses: actions/checkout@v2
8 | - uses: actions/setup-python@v2
9 | - run: pip install black codespell flake8 isort pytest pyupgrade
10 | - run: black --check . || true
11 | - run: codespell --quiet-level=2 || true # --ignore-words-list="" --skip=""
12 | - run: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
13 | - run: isort --profile black . || true
14 | - run: pip install -r requirements.txt || true
15 | - run: pytest . || true
16 | - run: shopt -s globstar && pyupgrade --py36-plus **/*.py || true
17 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | build/
3 |
4 | dist/
5 |
6 | lnetatmo.egg-info/
7 |
8 | *.pyc
9 |
10 | __pycache__/
11 |
12 | MANIFEST*
13 |
14 | *.csv
15 | *.h5
16 | *.feather
17 | *.json
18 | *.parquet
19 | *.pkl
20 | *.xlsx
21 |
22 |
--------------------------------------------------------------------------------
/.netatmo.credentials:
--------------------------------------------------------------------------------
1 | {
2 | "CLIENT_ID" : "",
3 | "CLIENT_SECRET" : "",
4 | "REFRESH_TOKEN" : ""
5 | }
6 |
7 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | netatmo-api-python
2 | ==================
3 |
4 | Simple API to access Netatmo weather station data from any python script
5 | For more detailed information see http://dev.netatmo.com
6 |
7 | I have no relation with the netatmo company, I wrote this because I needed it myself,
8 | and published it to save time to anyone who would have same needs.
9 |
10 | There is no longer credential load at library import, credentials are loaded at `ClientAuth` class initialization and a new parameter `credentialFile` allow to specify private name and location for the credential file. It is recommended to use this parameter to specify the location of the credential file using absolute path to be able to be independant of the account used to run the program.
11 | >[!CAUTION]
12 | > 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.
13 |
14 | >[!NOTE]
15 | > 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.
16 | > 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.
17 | > It is only an information for the Netatmo records, there is absolutely no use of this information by the library.
18 |
19 | >[!CAUTION]
20 | > 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.
21 |
22 | ### Install ###
23 |
24 | To install lnetatmo simply run:
25 |
26 | python setup.py install
27 |
28 | or
29 |
30 | pip install lnetatmo
31 |
32 | Depending on your permissions you might be required to use sudo.
33 |
34 | It is a single file module, on platforms where you have limited access, you just have to clone the repo and take the lnetatmo.py in the same directory than your main program.
35 |
36 | Once installed you can simple add lnetatmo to your python scripts by including:
37 |
38 | import lnetatmo
39 |
40 | For documentation, see usage
41 |
--------------------------------------------------------------------------------
/lnetatmo.py:
--------------------------------------------------------------------------------
1 | # Published Jan 2013
2 | # Author : Philippe Larduinat, ph.larduinat@wanadoo.fr
3 | # Multiple contributors : see https://github.com/philippelt/netatmo-api-python
4 | # License : GPL V3
5 | """
6 | This API provides access to the Netatmo weather station or/and other installed devices
7 | This package can be used with Python2 or Python3 applications and do not
8 | require anything else than standard libraries
9 |
10 | PythonAPI Netatmo REST data access
11 | coding=utf-8
12 | """
13 |
14 | import warnings
15 | if __name__ == "__main__": warnings.filterwarnings("ignore") # For installation test only
16 |
17 | from sys import version_info
18 | from os import getenv
19 | from os.path import expanduser
20 | import json, time
21 | import logging
22 |
23 | # Just in case method could change
24 | PYTHON3 = version_info.major > 2
25 |
26 | # HTTP libraries depends upon Python 2 or 3
27 | if PYTHON3 :
28 | import urllib.parse, urllib.request
29 | else:
30 | from urllib import urlencode
31 | import urllib2
32 |
33 |
34 | ######################## AUTHENTICATION INFORMATION ######################
35 |
36 | # To be able to have a program accessing your netatmo data, you have to register your program as
37 | # a Netatmo app in your Netatmo account. All you have to do is to give it a name (whatever) and you will be
38 | # returned a client_id and secret that your app has to supply to access netatmo servers.
39 |
40 | # To ease Docker packaging of your application, you can setup your authentication parameters through env variables
41 |
42 | # Authentication:
43 | # 1 - Values defined in environment variables : CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN
44 | # 2 - Parameters passed to ClientAuth initialization
45 | # 3 - The .netatmo.credentials file in JSON format in your home directory (now mandatory for regular use)
46 |
47 | # Note that the refresh token being short lived, using envvar will be restricted to speific testing use case
48 |
49 | #########################################################################
50 |
51 |
52 | # Common definitions
53 |
54 | _BASE_URL = "https://api.netatmo.com/"
55 | _AUTH_REQ = _BASE_URL + "oauth2/token"
56 | _GETMEASURE_REQ = _BASE_URL + "api/getmeasure"
57 | _GETSTATIONDATA_REQ = _BASE_URL + "api/getstationsdata"
58 | _GETTHERMOSTATDATA_REQ = _BASE_URL + "api/getthermostatsdata"
59 | _GETHOMEDATA_REQ = _BASE_URL + "api/gethomedata"
60 | _GETCAMERAPICTURE_REQ = _BASE_URL + "api/getcamerapicture"
61 | _GETEVENTSUNTIL_REQ = _BASE_URL + "api/geteventsuntil"
62 | _HOME_STATUS = _BASE_URL + "api/homestatus" # Used for Home+ Control Devices
63 | _GETHOMES_DATA = _BASE_URL + "api/homesdata" # New API
64 | _GETHOMECOACH = _BASE_URL + "api/gethomecoachsdata" #
65 |
66 | #TODO# Undocumented (but would be very usefull) API : Access currently forbidden (403)
67 |
68 | _POST_UPDATE_HOME_REQ = _BASE_URL + "/api/updatehome"
69 |
70 | # For presence setting (POST BODY):
71 | # _PRES_BODY_REC_SET = "home_id=%s&presence_settings[presence_record_%s]=%s" # (HomeId, DetectionKind, DetectionSetup.index)
72 | _PRES_DETECTION_KIND = ("humans", "animals", "vehicles", "movements")
73 | _PRES_DETECTION_SETUP = ("ignore", "record", "record & notify")
74 |
75 | # _PRES_BODY_ALERT_TIME = "home_id=%s&presence_settings[presence_notify_%s]=%s" # (HomeID, "from"|"to", "hh:mm")
76 |
77 | # Regular (documented) commands (both cameras)
78 |
79 | _PRES_CDE_GET_SNAP = "/live/snapshot_720.jpg"
80 |
81 | #TODO# Undocumented (taken from https://github.com/KiboOst/php-NetatmoCameraAPI/blob/master/class/NetatmoCameraAPI.php)
82 | # Work with local_url only (undocumented scope control probably)
83 |
84 | # For Presence camera
85 |
86 | _PRES_CDE_GET_LIGHT = "/command/floodlight_get_config"
87 | # Not working yet, probably due to scope restriction
88 | #_PRES_CDE_SET_LIGHT = "/command/floodlight_set_config?config=mode:%s" # "auto"|"on"|"off"
89 |
90 |
91 | # For all cameras
92 |
93 | _CAM_CHANGE_STATUS = "/command/changestatus?status=%s" # "on"|"off"
94 | # Not working yet
95 | #_CAM_FTP_ACTIVE = "/command/ftp_set_config?config=on_off:%s" # "on"|"off"
96 |
97 | #Known TYPE used by Netatmo services + API, there can be more types possible
98 | TYPES = {
99 | 'BFII' : ["Bticino IP Indoor unit", 'Home + Security'],
100 | 'BFIC' : ["Bticino IP Guard station", 'Home + Security'],
101 | 'BFIO' : ["Bticino IP Entrance panel", 'Home + Security'],
102 | 'BFIS' : ["Bticino Server DES", 'Home + Security'],
103 | 'BN3L' : ["Bticino 3rd party light", 'Home+Control'],
104 | 'BNAB' : ["Bticino module automatic blind", 'Home+Control'],
105 | 'BNAS' : ["Bticino module automatic shutter", 'Home+Control'],
106 | 'BNS' : ["Smarther with Netatmo Thermostat", 'Home+Control'],
107 | 'BNCU' : ["Bticino Bticino Alarm Central Unit", 'Home + Security'],
108 | 'BNCS' : ["Bticino module Controlled Socket", 'Home+Control'],
109 | 'BNCX' : ["Bticino Class 300 EOS", 'Home + Security'],
110 | 'BNDL' : ["Bticino Doorlock", 'Home + Security'],
111 | 'BNEU' : ["Bticino external unit", 'Home + Security'],
112 | 'BNFC' : ["Bticino Thermostat", 'Home+Control'],
113 | 'BNIL' : ["Bticino intelligent light", 'Home+Control'],
114 | 'BNLD' : ["Bticino module lighting dimmer", 'Home+Control'],
115 | 'BNMH' : ["Bticino My Home Server 1", 'Home + Security'], # also API Home+Control GATEWAY
116 | 'BNMS' : ["Bticino module motorized shade", 'Home+Control'],
117 | 'BNSE' : ["Bticino Alarm Sensor", 'Home + Security'],
118 | 'BNSL' : ["Bticino Staircase Light", 'Home + Security'],
119 | 'BNTH' : ["Bticino Thermostat", 'Home+Control'],
120 | 'BNTR' : ["Bticino module towel rail", 'Home+Control'],
121 | 'BNXM' : ["Bticino X meter", 'Home+Control'],
122 |
123 | 'NACamera' : ["indoor camera", 'Home + Security'],
124 | 'NACamDoorTag' : ["door tag", 'Home + Security'],
125 | 'NAMain' : ["weather station", 'Weather'],
126 | 'NAModule1' : ["outdoor unit", 'Weather'],
127 | 'NAModule2' : ["wind unit", 'Weather'],
128 | 'NAModule3' : ["rain unit", 'Weather'],
129 | 'NAModule4' : ["indoor unit", 'Weather'],
130 | 'NAPlug' : ["thermostat relais station", 'Energy'], # A smart thermostat exist of a thermostat module and a Relay device
131 | # The relay device is also the bridge for thermostat and Valves
132 | 'NATherm1' : ["thermostat", 'Energy'],
133 | 'NCO' : ["co2 sensor", 'Home + Security'], # The same API as smoke sensor
134 | 'NDB' : ["doorbell", 'Home + Security'],
135 | 'NOC' : ["outdoor camera", 'Home + Security'],
136 | 'NRV' : ["thermostat valves", 'Energy'], # also API Home+Control
137 | 'NSD' : ["smoke sensor", 'Home + Security'],
138 | 'NHC' : ["home coach", 'Aircare'],
139 | 'NIS' : ["indoor sirene", 'Home + Security'],
140 | 'NDL' : ["Doorlock", 'Home + Security'],
141 |
142 | 'NLAO' : ["Magellan Green power remote control on-off", 'Home+Control'],
143 | 'NLAS' : ["Magellan Green Power Remote control scenarios", 'Home+Control'],
144 | 'NLAV' : ["Wireless Batteryless Shutter Switch", 'Home+Control'],
145 | 'NLC' : ["Cable Outlet", 'Home+Control'],
146 | 'NLD' : ["Wireless 2 button switch light", 'Home+Control'],
147 | 'NLDP' : ["Magellan Pocket Remote", 'Home+Control'],
148 | 'NLE' : ["Ecometer", 'Home+Control'],
149 | 'NLF' : ["Dimmer Light Switch", 'Home+Control'],
150 | 'NLFE' : ["Dimmer Light Switch Evolution", 'Home+Control'],
151 | 'NLFN' : ["Dimmer Light with Neutral", 'Home+Control'],
152 | 'NLG' : ["Gateway", 'Home+Control'],
153 | 'NLGS' : ["Standard DIN Gateway", 'Home+Control'],
154 | 'NLIS' : ["Double Switch with Neutral", 'Home+Control'],
155 | 'NLIV' : ["1/2 Gangs Shutter Switch", 'Home+Control'],
156 | 'NLL' : ["Light Switch with Neutral", 'Home+Control'],
157 | 'NLLF' : ["Centralized Ventilation Control", 'Home+Control'],
158 | 'NLLV' : ["Roller Shutter Switch with level detection", 'Home+Control'],
159 | 'NLM' : ["Light Micromodule", 'Home+Control'],
160 | 'NLP' : ["Power Outlet", 'Home+Control'],
161 | 'NLPS' : ["Smart Load Shedder", 'Home+Control'],
162 | 'NLPC' : ["DIN Energy meter", 'Home+Control'],
163 | 'NLPD' : ["Dry contact", 'Home+Control'],
164 | 'NLPM' : ["Mobile Socket", 'Home+Control'],
165 | 'NLPO' : ["Contactor", 'Home+Control'],
166 | 'NLPT' : ["Teleruptor", 'Home+Control'],
167 | 'NLT' : ["Magellan Remote Control", 'Home+Control'],
168 | 'NLTS' : ["Magellan Remote Motion Sensor", 'Home+Control'],
169 | 'NLV' : ["Roller Shutter Switch", 'Home+Control'],
170 |
171 | 'OTH' : ["Opentherm Thermostat Relay", 'Home+Control'],
172 | 'OTM' : ["Smart modulating Thermostat", 'Home+Control'],
173 |
174 | 'Z3L' : ["Zigbee 3rd party light", 'Home+Control'],
175 | 'Z3V' : ["Generic window covering", 'Home+Control']
176 | }
177 |
178 | # UNITS used by Netatmo services
179 | UNITS = {
180 | "unit" : {
181 | 0: "metric",
182 | 1: "imperial"
183 | },
184 | "windunit" : {
185 | 0: "kph",
186 | 1: "mph",
187 | 2: "ms",
188 | 3: "beaufort",
189 | 4: "knot"
190 | },
191 | "pressureunit" : {
192 | 0: "mbar",
193 | 1: "inHg",
194 | 2: "mmHg"
195 | },
196 | "Health index" : { # Homecoach
197 | 0: "Healthy",
198 | 1: "Fine",
199 | 2: "Fair",
200 | 3: "Poor",
201 | 4: "Unhealthy"
202 | },
203 | "Wifi status" : { # Wifi Signal quality
204 | 86: "Bad",
205 | 71: "Average",
206 | 56: "Good"
207 | }
208 | }
209 |
210 | # Logger context
211 | logger = logging.getLogger("lnetatmo")
212 |
213 |
214 | class NoDevice( Exception ):
215 | """No device available in the user account"""
216 |
217 |
218 | class NoHome( Exception ):
219 | """No home defined in the user account"""
220 |
221 |
222 | class AuthFailure( Exception ):
223 | """Credentials where rejected by Netatmo (or netatmo server unavailability)"""
224 |
225 | class OutOfScope( Exception ):
226 | """Your current auth scope do not allow access to this resource"""
227 |
228 | class ClientAuth:
229 | """
230 | Request authentication and keep access token available through token method. Renew it automatically if necessary
231 |
232 | Args:
233 | clientId (str): Application clientId delivered by Netatmo on dev.netatmo.com
234 | clientSecret (str): Application Secret key delivered by Netatmo on dev.netatmo.com
235 | refreshToken (str) : Scoped refresh token
236 | """
237 |
238 | def __init__(self, clientId=None,
239 | clientSecret=None,
240 | refreshToken=None,
241 | credentialFile=None):
242 |
243 | # replace values with content of env variables if defined
244 | clientId = getenv("CLIENT_ID", clientId)
245 | clientSecret = getenv("CLIENT_SECRET", clientSecret)
246 | refreshToken = getenv("REFRESH_TOKEN", refreshToken)
247 |
248 | # Look for credentials in file if not already provided
249 | # Note: this file will be rewritten by the library to record refresh_token change
250 | # If you run your application in container, remember to persist this file
251 | if not (clientId and clientSecret and refreshToken):
252 | self._credentialFile = credentialFile or expanduser("~/.netatmo.credentials")
253 | with open(self._credentialFile, "r", encoding="utf-8") as f:
254 | cred = {k.upper():v for k,v in json.loads(f.read()).items()}
255 | else:
256 | # Calling program will need to handle the returned refresh_token for futur call
257 | # by getting refreshToken property of the ClientAuth instance and persist it somewhere
258 | self._credentialFile = None
259 |
260 | self._clientId = clientId or cred["CLIENT_ID"]
261 | self._clientSecret = clientSecret or cred["CLIENT_SECRET"]
262 | self._accessToken = None # Will be refreshed before any use
263 | self.refreshToken = refreshToken or cred["REFRESH_TOKEN"]
264 | self.expiration = 0 # Force refresh token
265 |
266 | @property
267 | def accessToken(self):
268 | if self.expiration < time.time() : self.renew_token()
269 | return self._accessToken
270 |
271 | def renew_token(self):
272 | postParams = {
273 | "grant_type" : "refresh_token",
274 | "refresh_token" : self.refreshToken,
275 | "client_id" : self._clientId,
276 | "client_secret" : self._clientSecret
277 | }
278 | resp = postRequest("authentication", _AUTH_REQ, postParams)
279 | if self.refreshToken != resp['refresh_token']:
280 | self.refreshToken = resp['refresh_token']
281 | cred = {"CLIENT_ID":self._clientId,
282 | "CLIENT_SECRET":self._clientSecret,
283 | "REFRESH_TOKEN":self.refreshToken }
284 | if self._credentialFile:
285 | with open(self._credentialFile, "w", encoding="utf-8") as f:
286 | f.write(json.dumps(cred, indent=True))
287 | self._accessToken = resp['access_token']
288 | self.expiration = int(resp['expire_in'] + time.time())
289 |
290 |
291 | class User:
292 | """
293 | This class returns basic information about the user
294 |
295 | Args:
296 | authData (ClientAuth): Authentication information with a working access Token
297 | """
298 | warnings.warn("The 'User' class is no longer maintained by Netatmo",
299 | DeprecationWarning )
300 | def __init__(self, authData):
301 | postParams = {
302 | "access_token" : authData.accessToken
303 | }
304 | resp = postRequest("Weather station", _GETSTATIONDATA_REQ, postParams)
305 | self.rawData = resp['body']
306 | self.devList = self.rawData['devices']
307 | self.ownerMail = self.rawData['user']['mail']
308 |
309 |
310 | class UserInfo:
311 | """
312 | This class is dynamicaly populated with data from various Netatmo requests to provide
313 | complimentary data (eg Units for Weatherdata)
314 | """
315 |
316 |
317 | class HomeStatus:
318 | """
319 | List all Home+Control devices (Smarther thermostat, Socket, Cable Output, Centralized fan, Micromodules, ......)
320 |
321 | Args:
322 | authData (clientAuth): Authentication information with a working access Token
323 | home : Home name or id of the home who's thermostat belongs to
324 | """
325 | def __init__(self, authData, home_id):
326 |
327 | self.getAuthToken = authData.accessToken
328 | postParams = {
329 | "access_token" : self.getAuthToken,
330 | "home_id": home_id
331 | }
332 | resp = postRequest("home_status", _HOME_STATUS, postParams)
333 | self.resp = resp
334 | self.rawData = resp['body']['home']
335 | if not self.rawData : raise NoHome("No home %s found" % home_id)
336 | self.rooms = self.rawData['rooms']
337 | self.modules = self.rawData['modules']
338 |
339 | def getRoomsId(self):
340 | return [room['id'] for room in self.rooms]
341 |
342 | def getListRoomParam(self, room_id):
343 | for room in self.rooms:
344 | if room['id'] == room_id:
345 | return list(room)
346 | return None
347 |
348 | def getRoomParam(self, room_id, param):
349 | for room in self.rooms:
350 | if(room['id'] == room_id and param in room):
351 | return room[param]
352 | return None
353 |
354 | def getModulesId(self):
355 | return [module['id'] for module in self.modules]
356 |
357 | def getListModuleParam(self, module_id):
358 | for module in self.modules:
359 | if module['id'] == module_id:
360 | return list(module)
361 | return None
362 |
363 | def getModuleParam(self, module_id, param):
364 | for module in self.modules:
365 | if module['id'] == module_id and param in module:
366 | return module[param]
367 | return None
368 |
369 |
370 | class ThermostatData:
371 | """
372 | List the Relay station and Thermostat modules
373 | Valves are controlled by HomesData and HomeStatus in new API
374 | Args:
375 | authData (clientAuth): Authentication information with a working access Token
376 | home : Home name or id of the home who's thermostat belongs to
377 | """
378 | def __init__(self, authData, home=None):
379 |
380 | # I don't own a thermostat thus I am not able to test the Thermostat support
381 | warnings.warn("The Thermostat code is not tested due to the lack of test environment.\n" \
382 | "As Netatmo is continuously breaking API compatibility, risk that current bindings are wrong is high.\n" \
383 | "Please report found issues (https://github.com/philippelt/netatmo-api-python/issues)",
384 | RuntimeWarning )
385 |
386 | self.getAuthToken = authData.accessToken
387 | postParams = {
388 | "access_token" : self.getAuthToken
389 | }
390 | resp = postRequest("Thermostat", _GETTHERMOSTATDATA_REQ, postParams)
391 | self.rawData = resp['body']['devices']
392 | if not self.rawData : raise NoDevice("No thermostat available")
393 | #
394 | # keeping OLD code for Reference
395 | # self.thermostatData = filter_home_data(self.rawData, home)
396 | # if not self.thermostatData : raise NoHome("No home %s found" % home)
397 | # self.thermostatData['name'] = self.thermostatData['home_name'] # New key = 'station_name'
398 | # for m in self.thermostatData['modules']:
399 | # m['name'] = m['module_name']
400 | # self.defaultThermostat = self.thermostatData['home_name'] # New key = 'station_name'
401 | # self.defaultThermostatId = self.thermostatData['_id']
402 | # self.defaultModule = self.thermostatData['modules'][0]
403 | # Standard the first Relaystation and Thermostat is returned
404 | # self.rawData is list all stations
405 |
406 | # if no ID is given the Relaystation at index 0 is returned
407 | def Relay_Plug(self, Rid=""):
408 | for Relay in self.rawData:
409 | if Rid in Relay['_id']:
410 | print ('Relay ', Rid, 'in rawData')
411 | #print (Relay.keys())
412 | #print (Relay['_id'])
413 | return Relay
414 | #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'])
415 |
416 | # if no ID is given the Thermostatmodule at index 0 is returned
417 | def Thermostat_Data(self, tid=""):
418 | for Relay in self.rawData:
419 | for thermostat in Relay['modules']:
420 | if tid in thermostat['_id']:
421 | print ('Thermostat ',tid, 'in Relay', Relay['_id'], Relay['station_name'])
422 | #print (thermostat['_id'])
423 | #print (thermostat.keys())
424 | return thermostat
425 | #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'])
426 |
427 |
428 | def getThermostat(self, name=None, id=""):
429 | for Relay in self.rawData:
430 | for module in Relay['modules']:
431 | if id == Relay['_id']:
432 | print ('Relay ', id, 'found')
433 | return Relay
434 | elif name == Relay['station_name']:
435 | print ('Relay ', name, 'found')
436 | return Relay
437 | elif id == module['_id']:
438 | print ('Thermostat ', id, 'found in Relay', Relay['_id'], Relay['station_name'])
439 | return module
440 | elif name == module['module_name']:
441 | print ('Thermostat ', name, 'found in Relay', Relay['_id'], Relay['station_name'])
442 | return module
443 | else:
444 | #print ('Device NOT Found')
445 | pass
446 |
447 | def moduleNamesList(self, name=None, tid=None):
448 | l = []
449 | for Relay in self.rawData:
450 | if id == Relay['_id'] or name == Relay['station_name']:
451 | RL = []
452 | for module in Relay['modules']:
453 | RL.append(module['module_name'])
454 | return RL
455 | else:
456 | #print ("Cloud Data")
457 | for module in Relay['modules']:
458 | l.append(module['module_name'])
459 | #This return a list off all connected Thermostat in the cloud.
460 | return l
461 |
462 | def getModuleByName(self, name, tid=""):
463 | for Relay in self.rawData:
464 | for module in Relay['modules']:
465 | #print (module['module_name'], module['_id'])
466 | if module['module_name'] == name:
467 | return module
468 | elif module['_id'] == tid:
469 | return module
470 | else:
471 | pass
472 |
473 |
474 | class WeatherStationData:
475 | """
476 | List the Weather Station devices (stations and modules)
477 |
478 | Args:
479 | authData (ClientAuth): Authentication information with a working access Token
480 | """
481 | def __init__(self, authData, home=None, station=None):
482 | self.getAuthToken = authData.accessToken
483 | postParams = {
484 | "access_token" : self.getAuthToken
485 | }
486 | resp = postRequest("Weather station", _GETSTATIONDATA_REQ, postParams)
487 | self.rawData = resp['body']['devices']
488 | # Weather data
489 | if not self.rawData : raise NoDevice("No weather station in any homes")
490 | # Stations are no longer in the Netatmo API, keeping them for compatibility
491 | self.stations = { d['station_name'] : d for d in self.rawData }
492 | self.stationIds = { d['_id'] : d for d in self.rawData }
493 | self.homes = { d['home_name'] : d["station_name"] for d in self.rawData }
494 | # Keeping the old behavior for default station name
495 | if home and home not in self.homes : raise NoHome("No home with name %s" % home)
496 | self.default_home = home or list(self.homes.keys())[0]
497 | if station:
498 | if station not in self.stations:
499 | # May be a station_id convert it to corresponding station name
500 | s = self.stationById(station)
501 | if s :
502 | station = s["station_name"]
503 | else:
504 | raise NoDevice("No station with name or id %s" % station)
505 | self.default_station = station
506 | else:
507 | self.default_station = [v["station_name"] for k,v in self.stations.items() if v["home_name"] == self.default_home][0]
508 | self.modules = {}
509 | self.default_station_data = self.stationByName(self.default_station)
510 | if 'modules' in self.default_station_data:
511 | for m in self.default_station_data['modules']:
512 | self.modules[ m['_id'] ] = m
513 | # User data
514 | userData = resp['body']['user']
515 | self.user = UserInfo()
516 | setattr(self.user, "mail", userData['mail'])
517 | for k,v in userData['administrative'].items():
518 | if k in UNITS:
519 | setattr(self.user, k, UNITS[k][v])
520 | else:
521 | setattr(self.user, k, v)
522 |
523 | def modulesNamesList(self, station=None):
524 | s = self.getStation(station)
525 | if not s: raise NoDevice("No station with name or id %s" % station)
526 | self.default_station = station
527 | self.default_station_data = s
528 | self.modules = {}
529 | if 'modules' in self.default_station_data:
530 | for m in self.default_station_data['modules']:
531 | self.modules[ m['_id'] ] = m
532 | res = [m['module_name'] for m in self.modules.values()]
533 | res.append(s['module_name'])
534 | return res
535 |
536 | # Both functions (byName and byStation) are here for historical reason,
537 | # considering that chances are low that a station name could be confused with a station ID,
538 | # there should be in fact a single function for getting station data
539 |
540 | def getStation(self, station=None):
541 | if not station : station = self.default_station
542 | if station in self.stations : return self.stations[station]
543 | if station in self.stationIds : return self.stationIds[station]
544 | return None
545 |
546 | def getModule(self, module):
547 | if module in self.modules: return self.modules[module]
548 | for m in self.modules.values():
549 | if m['module_name'] == module : return m
550 | return None
551 |
552 | # Functions for compatibility with previous versions
553 | def stationByName(self, station=None):
554 | return self.getStation(station)
555 | def stationById(self, sid):
556 | return self.getStation(sid)
557 | def moduleByName(self, module):
558 | return self.getModule(module)
559 | def moduleById(self, mid):
560 | return self.getModule(mid)
561 |
562 | def lastData(self, station=None, exclude=0):
563 | s = self.stationByName(station) or self.stationById(station)
564 | # Breaking change from Netatmo : dashboard_data no longer available if station lost
565 | if not s or 'dashboard_data' not in s : return None
566 | lastD = {}
567 | # Define oldest acceptable sensor measure event
568 | limit = (time.time() - exclude) if exclude else 0
569 | ds = s['dashboard_data']
570 | if ds.get('time_utc',limit+10) > limit :
571 | lastD[s['module_name']] = ds.copy()
572 | lastD[s['module_name']]['When'] = lastD[s['module_name']].pop("time_utc") if 'time_utc' in lastD[s['module_name']] else time.time()
573 | lastD[s['module_name']]['wifi_status'] = s['wifi_status']
574 | if 'modules' in s:
575 | for module in s["modules"]:
576 | # Skip lost modules that no longer have dashboard data available
577 | if 'dashboard_data' not in module : continue
578 | ds = module['dashboard_data']
579 | if ds.get('time_utc',limit+10) > limit :
580 | # If no module_name has been setup, use _id by default
581 | if "module_name" not in module : module['module_name'] = module["_id"]
582 | lastD[module['module_name']] = ds.copy()
583 | lastD[module['module_name']]['When'] = lastD[module['module_name']].pop("time_utc") if 'time_utc' in lastD[module['module_name']] else time.time()
584 | # For potential use, add battery and radio coverage information to module data if present
585 | for i in ('battery_vp', 'battery_percent', 'rf_status') :
586 | if i in module : lastD[module['module_name']][i] = module[i]
587 | return lastD
588 |
589 | def checkNotUpdated(self, delay=3600):
590 | res = self.lastData()
591 | ret = []
592 | for mn,v in res.items():
593 | if time.time()-v['When'] > delay : ret.append(mn)
594 | return ret if ret else None
595 |
596 | def checkUpdated(self, delay=3600):
597 | res = self.lastData()
598 | ret = []
599 | for mn,v in res.items():
600 | if time.time()-v['When'] < delay : ret.append(mn)
601 | return ret if ret else None
602 |
603 | def getMeasure(self, device_id, scale, mtype, module_id=None, date_begin=None, date_end=None, limit=None, optimize=False, real_time=False):
604 | postParams = { "access_token" : self.getAuthToken }
605 | postParams['device_id'] = device_id
606 | if module_id : postParams['module_id'] = module_id
607 | postParams['scale'] = scale
608 | postParams['type'] = mtype
609 | if date_begin : postParams['date_begin'] = date_begin
610 | if date_end : postParams['date_end'] = date_end
611 | if limit : postParams['limit'] = limit
612 | postParams['optimize'] = "true" if optimize else "false"
613 | postParams['real_time'] = "true" if real_time else "false"
614 | return postRequest("Weather station", _GETMEASURE_REQ, postParams)
615 |
616 | def MinMaxTH(self, module=None, frame="last24"):
617 | s = self.default_station_data
618 | if frame == "last24":
619 | end = time.time()
620 | start = end - 24*3600 # 24 hours ago
621 | elif frame == "day":
622 | start, end = todayStamps()
623 | if module and module != s['module_name']:
624 | m = self.moduleById(module) or self.moduleByName(module)
625 | if not m : raise NoDevice("Can't find module %s" % module)
626 | # retrieve module's data
627 | resp = self.getMeasure(
628 | device_id = s['_id'],
629 | module_id = m['_id'],
630 | scale = "max",
631 | mtype = "Temperature,Humidity",
632 | date_begin = start,
633 | date_end = end)
634 | else : # retrieve station's data
635 | resp = self.getMeasure(
636 | device_id = s['_id'],
637 | scale = "max",
638 | mtype = "Temperature,Humidity",
639 | date_begin = start,
640 | date_end = end)
641 | if resp and resp['body']:
642 | T = [v[0] for v in resp['body'].values()]
643 | H = [v[1] for v in resp['body'].values()]
644 | return min(T), max(T), min(H), max(H)
645 | return None
646 |
647 |
648 | class DeviceList(WeatherStationData):
649 | """
650 | This class is now deprecated. Use WeatherStationData directly instead
651 | """
652 | warnings.warn("The 'DeviceList' class was renamed 'WeatherStationData'",
653 | DeprecationWarning )
654 |
655 |
656 | class HomeData:
657 | """
658 | List the Netatmo home informations (Homes, cameras, events, persons)
659 |
660 | Args:
661 | authData (ClientAuth): Authentication information with a working access Token
662 | home : Home name of the home where's devices are installed
663 | """
664 | def __init__(self, authData, home=None):
665 | warnings.warn("The 'HomeData' class is deprecated'",
666 | DeprecationWarning )
667 | self.getAuthToken = authData.accessToken
668 | postParams = {
669 | "access_token" : self.getAuthToken
670 | }
671 | resp = postRequest("Home data", _GETHOMEDATA_REQ, postParams)
672 | self.rawData = resp['body']
673 | # Collect homes
674 | self.homes = self.rawData['homes'][0]
675 | for d in self.rawData['homes'] :
676 | if home == d['name']:
677 | self.homes = d
678 | else:
679 | pass
680 | #
681 | #print (self.homes.keys())
682 | #dict_keys(['id', 'name', 'persons', 'place', 'cameras', 'smokedetectors', 'events'])
683 | self.homeid = self.homes['id']
684 | C = self.homes['cameras']
685 | P = self.homes['persons']
686 | S = self.homes['smokedetectors']
687 | E = None
688 | # events not always in self.homes
689 | if 'events' in self.homes.keys():
690 | E = self.homes['events']
691 | #
692 | if not S:
693 | logger.warning('No smoke detector found')
694 | if not C:
695 | logger.warning('No Cameras found')
696 | if not P:
697 | logger.warning('No Persons found')
698 | if not E:
699 | logger.warning('No events found')
700 | # if not (C or P or S or E):
701 | # raise NoDevice("No device found in home %s" % k)
702 | if S or C or P or E:
703 | self.default_home = home or self.homes['name']
704 | # Split homes data by category
705 | self.persons = {}
706 | self.events = {}
707 | self.cameras = {}
708 | self.lastEvent = {}
709 | for i in range(len(self.rawData['homes'])):
710 | curHome = self.rawData['homes'][i]
711 | nameHome = curHome['name']
712 | if nameHome not in self.cameras:
713 | self.cameras[nameHome] = {}
714 | if 'persons' in curHome:
715 | for p in curHome['persons']:
716 | self.persons[ p['id'] ] = p
717 | if 'events' in curHome:
718 | for e in curHome['events']:
719 | if e['camera_id'] not in self.events:
720 | self.events[ e['camera_id'] ] = {}
721 | self.events[ e['camera_id'] ][ e['time'] ] = e
722 | if 'cameras' in curHome:
723 | for c in curHome['cameras']:
724 | self.cameras[nameHome][ c['id'] ] = c
725 | c["home_id"] = curHome['id']
726 | for camera,e in self.events.items():
727 | self.lastEvent[camera] = e[sorted(e)[-1]]
728 | #self.default_home has no key homeId use homeName instead!
729 | if not self.cameras[self.default_home] : raise NoDevice("No camera available in default home")
730 | self.default_camera = list(self.cameras[self.default_home].values())[0]
731 | else:
732 | pass
733 | # raise NoDevice("No Devices available")
734 |
735 | def homeById(self, hid):
736 | return None if hid not in self.homes else self.homes[hid]
737 |
738 | def homeByName(self, home=None):
739 | if not home: home = self.default_home
740 | for key,value in self.homes.items():
741 | if value['name'] == home:
742 | return self.homes[key]
743 |
744 | def cameraById(self, cid):
745 | for cam in self.cameras.values():
746 | if cid in cam:
747 | return cam[cid]
748 | return None
749 |
750 | def cameraByName(self, camera=None, home=None):
751 | if not camera and not home:
752 | return self.default_camera
753 | elif home and camera:
754 | if home not in self.cameras:
755 | return None
756 | for cam_id in self.cameras[home]:
757 | if self.cameras[home][cam_id]['name'] == camera:
758 | return self.cameras[home][cam_id]
759 | elif not home and camera:
760 | for h, cam_ids in self.cameras.items():
761 | for cam_id in cam_ids:
762 | if self.cameras[h][cam_id]['name'] == camera:
763 | return self.cameras[h][cam_id]
764 | else:
765 | return list(self.cameras[self.default_home].values())[0]
766 | return None
767 |
768 | def cameraUrls(self, camera=None, home=None, cid=None):
769 | """
770 | Return the vpn_url and the local_url (if available) of a given camera
771 | in order to access to its live feed
772 | Can't use the is_local property which is mostly false in case of operator
773 | dynamic IP change after presence start sequence
774 | """
775 | local_url = None
776 | vpn_url = None
777 | if cid:
778 | camera_data=self.cameraById(cid)
779 | else:
780 | camera_data=self.cameraByName(camera=camera, home=home)
781 | if camera_data:
782 | vpn_url = camera_data['vpn_url']
783 | resp = postRequest("Camera", vpn_url + '/command/ping')
784 | temp_local_url=resp['local_url']
785 | try:
786 | resp = postRequest("Camera", temp_local_url + '/command/ping',timeout=1)
787 | if resp and temp_local_url == resp['local_url']:
788 | local_url = temp_local_url
789 | except: # On this particular request, vithout errors from previous requests, error is timeout
790 | local_url = None
791 | return vpn_url, local_url
792 |
793 | def url(self, camera=None, home=None, cid=None):
794 | vpn_url, local_url = self.cameraUrls(camera, home, cid)
795 | # Return local if available else vpn
796 | return local_url or vpn_url
797 |
798 | def personsAtHome(self, home=None):
799 | """
800 | Return the list of known persons who are currently at home
801 | """
802 | if not home: home = self.default_home
803 | home_data = self.homeByName(home)
804 | atHome = []
805 | for p in home_data['persons']:
806 | #Only check known persons
807 | if 'pseudo' in p:
808 | if not p["out_of_sight"]:
809 | atHome.append(p['pseudo'])
810 | return atHome
811 |
812 | def getCameraPicture(self, image_id, key):
813 | """
814 | Download a specific image (of an event or user face) from the camera
815 | """
816 | postParams = {
817 | "access_token" : self.getAuthToken,
818 | "image_id" : image_id,
819 | "key" : key
820 | }
821 | resp = postRequest("Camera", _GETCAMERAPICTURE_REQ, postParams)
822 | return resp, "jpeg"
823 |
824 | def getProfileImage(self, name):
825 | """
826 | Retrieve the face of a given person
827 | """
828 | for p in self.persons.values():
829 | if 'pseudo' in p:
830 | if name == p['pseudo']:
831 | image_id = p['face']['id']
832 | key = p['face']['key']
833 | return self.getCameraPicture(image_id, key)
834 | return None, None
835 |
836 | def updateEvent(self, event=None, home=None):
837 | """
838 | Update the list of event with the latest ones
839 | """
840 | if not home: home=self.default_home
841 | if not event:
842 | #If not event is provided we need to retrieve the oldest of the last event seen by each camera
843 | listEvent = {}
844 | for e in self.lastEvent.values():
845 | listEvent[e['time']] = e
846 | event = listEvent[sorted(listEvent)[0]]
847 |
848 | home_data = self.homeByName(home)
849 | postParams = {
850 | "access_token" : self.getAuthToken,
851 | "home_id" : home_data['id'],
852 | "event_id" : event['id']
853 | }
854 | resp = postRequest("Camera", _GETEVENTSUNTIL_REQ, postParams)
855 | eventList = resp['body']['events_list']
856 | for e in eventList:
857 | self.events[ e['camera_id'] ][ e['time'] ] = e
858 | for camera,v in self.events.items():
859 | self.lastEvent[camera]=v[sorted(v)[-1]]
860 |
861 | def personSeenByCamera(self, name, home=None, camera=None):
862 | """
863 | Return True if a specific person has been seen by a camera
864 | """
865 | try:
866 | cam_id = self.cameraByName(camera=camera, home=home)['id']
867 | except TypeError:
868 | logger.warning("personSeenByCamera: Camera name or home is unknown")
869 | return False
870 | #Check in the last event is someone known has been seen
871 | if self.lastEvent[cam_id]['type'] == 'person':
872 | person_id = self.lastEvent[cam_id]['person_id']
873 | if 'pseudo' in self.persons[person_id]:
874 | if self.persons[person_id]['pseudo'] == name:
875 | return True
876 | return False
877 |
878 | def _knownPersons(self):
879 | known_persons = {}
880 | for p_id,p in self.persons.items():
881 | if 'pseudo' in p:
882 | known_persons[ p_id ] = p
883 | return known_persons
884 |
885 | def someoneKnownSeen(self, home=None, camera=None):
886 | """
887 | Return True if someone known has been seen
888 | """
889 | try:
890 | cam_id = self.cameraByName(camera=camera, home=home)['id']
891 | except TypeError:
892 | logger.warning("personSeenByCamera: Camera name or home is unknown")
893 | return False
894 | #Check in the last event is someone known has been seen
895 | if self.lastEvent[cam_id]['type'] == 'person':
896 | if self.lastEvent[cam_id]['person_id'] in self._knownPersons():
897 | return True
898 | return False
899 |
900 | def someoneUnknownSeen(self, home=None, camera=None):
901 | """
902 | Return True if someone unknown has been seen
903 | """
904 | try:
905 | cam_id = self.cameraByName(camera=camera, home=home)['id']
906 | except TypeError:
907 | logger.warning("personSeenByCamera: Camera name or home is unknown")
908 | return False
909 | #Check in the last event is someone known has been seen
910 | if self.lastEvent[cam_id]['type'] == 'person':
911 | if self.lastEvent[cam_id]['person_id'] not in self._knownPersons():
912 | return True
913 | return False
914 |
915 | def motionDetected(self, home=None, camera=None):
916 | """
917 | Return True if movement has been detected
918 | """
919 | try:
920 | cam_id = self.cameraByName(camera=camera, home=home)['id']
921 | except TypeError:
922 | logger.warning("personSeenByCamera: Camera name or home is unknown")
923 | return False
924 | if self.lastEvent[cam_id]['type'] == 'movement':
925 | return True
926 | return False
927 |
928 | def presenceUrl(self, camera=None, home=None, cid=None):
929 | camera = self.cameraByName(home=home, camera=camera) or self.cameraById(cid=cid)
930 | if camera["type"] != "NOC": return None # Not a presence camera
931 | vpnUrl, localUrl = self.cameraUrls(cid=camera["id"])
932 | return localUrl or vpnUrl
933 |
934 | def presenceLight(self, camera=None, home=None, cid=None, setting=None):
935 | url = self.presenceUrl(home=home, camera=camera) or self.cameraById(cid=cid)
936 | if not url or setting not in ("on", "off", "auto"): return None
937 | if setting : return "Currently unsupported"
938 | return cameraCommand(url, _PRES_CDE_GET_LIGHT)["mode"]
939 | # Not yet supported
940 | #if not setting: return cameraCommand(url, _PRES_CDE_GET_LIGHT)["mode"]
941 | #else: return cameraCommand(url, _PRES_CDE_SET_LIGHT, setting)
942 |
943 | def presenceStatus(self, mode, camera=None, home=None, cid=None):
944 | url = self.presenceUrl(home=home, camera=camera) or self.cameraById(cid=cid)
945 | if not url or mode not in ("on", "off") : return None
946 | r = cameraCommand(url, _CAM_CHANGE_STATUS, mode)
947 | return mode if r["status"] == "ok" else None
948 |
949 | def presenceSetAction(self, camera=None, home=None, cid=None,
950 | eventType=_PRES_DETECTION_KIND[0], action=2):
951 | raise NotImplementedError
952 | # if eventType not in _PRES_DETECTION_KIND or \
953 | # action not in _PRES_DETECTION_SETUP : return None
954 | # camera = self.cameraByName(home=home, camera=camera) or self.cameraById(cid=cid)
955 | # postParams = { "access_token" : self.getAuthToken,
956 | # "home_id" : camera["home_id"],
957 | # "presence_settings[presence_record_%s]" % eventType : _PRES_DETECTION_SETUP.index(action)
958 | # }
959 | # resp = postRequest("Camera", _POST_UPDATE_HOME_REQ, postParams)
960 | # self.rawData = resp['body']
961 |
962 | def getLiveSnapshot(self, camera=None, home=None, cid=None):
963 | camera = self.cameraByName(home=home, camera=camera) or self.cameraById(cid=cid)
964 | vpnUrl, localUrl = self.cameraUrls(cid=camera["id"])
965 | url = localUrl or vpnUrl
966 | return cameraCommand(url, _PRES_CDE_GET_SNAP)
967 |
968 |
969 | class WelcomeData(HomeData):
970 | """
971 | This class is now deprecated. Use HomeData instead
972 | Home can handle many devices, not only Welcome cameras
973 | """
974 | warnings.warn("The 'WelcomeData' class was renamed 'HomeData' to handle new Netatmo Home capabilities",
975 | DeprecationWarning )
976 |
977 |
978 | class HomesData:
979 | """
980 | List the Netatmo actual topology and static information of all devices present
981 | into a user account. It is also possible to specify a home_id to focus on one home.
982 |
983 | Args:
984 | authData (clientAuth): Authentication information with a working access Token
985 | home : Home name or id of the home who's module belongs to
986 | """
987 | def __init__(self, authData, home=None):
988 | #
989 | self.getAuthToken = authData.accessToken
990 | postParams = {
991 | "access_token" : self.getAuthToken,
992 | "home_id": home
993 | }
994 | #
995 | resp = postRequest("Module", _GETHOMES_DATA, postParams)
996 | # self.rawData = resp['body']['devices']
997 | self.rawData = resp['body']['homes']
998 | if not self.rawData : raise NoHome("No home %s found" % home)
999 | #
1000 | if home:
1001 | # Find a home who's home id or name is the one requested
1002 | for h in self.rawData:
1003 | #print (h.keys())
1004 | if home in (h["name"], h["id"]):
1005 | self.Homes_Data = h
1006 | else:
1007 | self.Homes_Data = self.rawData[0]
1008 | self.homeid = self.Homes_Data['id']
1009 | if not self.Homes_Data : raise NoDevice("No Devices available")
1010 |
1011 |
1012 | class HomeCoach:
1013 | """
1014 | List the HomeCoach modules
1015 |
1016 | Args:
1017 | authData (clientAuth): Authentication information with a working access Token
1018 | home : Home name or id of the home who's HomeCoach belongs to
1019 | """
1020 |
1021 | def __init__(self, authData):
1022 | # I don't own a HomeCoach thus I am not able to test the HomeCoach support
1023 | # Homecoach does not need or use HomeID parameter
1024 | # warnings.warn("The HomeCoach code is not tested due to the lack of test environment.\n", RuntimeWarning )
1025 | # "As Netatmo is continuously breaking API compatibility, risk that current bindings are wrong is high.\n" \
1026 | # "Please report found issues (https://github.com/philippelt/netatmo-api-python/issues)"
1027 |
1028 | self.getAuthToken = authData.accessToken
1029 | postParams = {
1030 | "access_token" : self.getAuthToken
1031 | }
1032 | resp = postRequest("HomeCoach", _GETHOMECOACH, postParams)
1033 | self.rawData = resp['body']['devices']
1034 | # homecoach data
1035 | if not self.rawData : raise NoDevice("No HomeCoach available")
1036 |
1037 | def HomecoachDevice(self, hid=""):
1038 | for device in self.rawData:
1039 | if hid == device['_id']:
1040 | return device
1041 | return None
1042 |
1043 | def Dashboard(self, hid=""):
1044 | #D = self.HomecoachDevice['dashboard_data']
1045 | for device in self.rawData:
1046 | if hid == device['_id']:
1047 | D = device['dashboard_data']
1048 | return D
1049 |
1050 | def lastData(self, hid=None, exclude=0):
1051 | for device in self.rawData:
1052 | if hid == device['_id']:
1053 | # LastData in HomeCoach
1054 | #s = self.HomecoachDevice['dashboard_data']['time_utc']
1055 | # Define oldest acceptable sensor measure event
1056 | limit = (time.time() - exclude) if exclude else 0
1057 | ds = device['dashboard_data']['time_utc']
1058 | return { '_id': hid, 'When': ds if device.get('time_utc',limit+10) > limit else 0}
1059 | else:
1060 | pass
1061 |
1062 | def checkNotUpdated(self, res, hid, delay=3600):
1063 | ret = []
1064 | if time.time()-res['When'] > delay : ret.append({hid: 'Device Not Updated'})
1065 | return ret if ret else None
1066 |
1067 | def checkUpdated(self, res, hid, delay=3600):
1068 | ret = []
1069 | if time.time()-res['When'] < delay : ret.append({hid: 'Device up-to-date'})
1070 | return ret if ret else None
1071 |
1072 |
1073 | # Utilities routines
1074 |
1075 | def rawAPI(authData, url, parameters=None):
1076 | fullUrl = _BASE_URL + "api/" + url
1077 | if parameters is None: parameters = {}
1078 | parameters["access_token"] = authData.accessToken
1079 | resp = postRequest("rawAPI", fullUrl, parameters)
1080 | return resp["body"] if "body" in resp else resp
1081 |
1082 | def filter_home_data(rawData, home):
1083 | if home:
1084 | # Find a home who's home id or name is the one requested
1085 | for h in rawData:
1086 | if home in (h['home_name'], h['home_id']):
1087 | return h
1088 | return None
1089 | # By default, the first home is returned
1090 | return rawData[0]
1091 |
1092 | def cameraCommand(cameraUrl, commande, parameters=None, timeout=3):
1093 | url = cameraUrl + ( commande % parameters if parameters else commande)
1094 | return postRequest("Camera", url, timeout=timeout)
1095 |
1096 | def processErrorResp(resp):
1097 | try:
1098 | error_detail = json.loads(resp.fp.read().decode("utf-8"))["error"]
1099 | logger.error("Netatmo response error 403 : %s" % repr(error_detail))
1100 | except Exception as e:
1101 | logger.error("Error getting body of 403 HTTP error from Netatmo : %s" % e)
1102 |
1103 | def postRequest(topic, url, params=None, timeout=10):
1104 | if PYTHON3:
1105 | req = urllib.request.Request(url)
1106 | if params:
1107 | req.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
1108 | if "access_token" in params:
1109 | req.add_header("Authorization","Bearer %s" % params.pop("access_token"))
1110 | params = urllib.parse.urlencode(params).encode('utf-8')
1111 | try:
1112 | resp = urllib.request.urlopen(req, params, timeout=timeout) if params else urllib.request.urlopen(req, timeout=timeout)
1113 | except urllib.error.HTTPError as err:
1114 | if err.code == 403:
1115 | processErrorResp(err)
1116 | else:
1117 | logger.error("code=%s, reason=%s, body=%s" % (err.code, err.reason, err.fp.read()))
1118 | return None
1119 | else:
1120 | if params:
1121 | token = params.pop("access_token") if "access_token" in params else None
1122 | params = urlencode(params)
1123 | headers = {"Content-Type" : "application/x-www-form-urlencoded;charset=utf-8"}
1124 | if token: headers["Authorization"] = "Bearer %s" % token
1125 | req = urllib2.Request(url=url, data=params, headers=headers) if params else urllib2.Request(url=url, headers=headers)
1126 | try:
1127 | resp = urllib2.urlopen(req, timeout=timeout)
1128 | except urllib2.HTTPError as err:
1129 | logger.error("code=%s, reason=%s" % (err.code, err.reason))
1130 | return None
1131 | data = b""
1132 | for buff in iter(lambda: resp.read(65535), b''): data += buff
1133 | # Return values in bytes if not json data to handle properly camera images
1134 | returnedContentType = resp.getheader("Content-Type") if PYTHON3 else resp.info()["Content-Type"]
1135 | return json.loads(data.decode("utf-8")) if "application/json" in returnedContentType else data
1136 |
1137 | def toTimeString(value):
1138 | return time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime(int(value)))
1139 |
1140 | def toEpoch(value):
1141 | return int(time.mktime(time.strptime(value,"%Y-%m-%d_%H:%M:%S")))
1142 |
1143 | def todayStamps():
1144 | today = time.strftime("%Y-%m-%d")
1145 | today = int(time.mktime(time.strptime(today,"%Y-%m-%d")))
1146 | return today, today+3600*24
1147 |
1148 | # Global shortcut
1149 |
1150 | def getStationMinMaxTH(station=None, module=None, home=None):
1151 | authorization = ClientAuth()
1152 | devList = WeatherStationData(authorization, station=station, home=home)
1153 | if module == "*":
1154 | pass
1155 | elif module:
1156 | module = devList.moduleById(module) or devList.moduleByName(module)
1157 | if not module: raise NoDevice("No such module %s" % module)
1158 | module = module["module_name"]
1159 | else:
1160 | module = list(devList.modules.values())[0]["module_name"]
1161 | lastD = devList.lastData()
1162 | if module == "*":
1163 | result = {}
1164 | for m,v in lastD.items():
1165 | if time.time()-v['When'] > 3600 : continue
1166 | r = devList.MinMaxTH(module=m)
1167 | if r:
1168 | result[m] = (r[0], v['Temperature'], r[1])
1169 | else:
1170 | if time.time()-lastD[module]['When'] > 3600 : result = ["-", "-"]
1171 | else :
1172 | result = [lastD[module]['Temperature'], lastD[module]['Humidity']]
1173 | result.extend(devList.MinMaxTH(module))
1174 | return result
1175 |
1176 |
1177 | # auto-test when executed directly
1178 |
1179 | if __name__ == "__main__":
1180 |
1181 | logging.basicConfig(format='%(name)s - %(levelname)s: %(message)s', level=logging.INFO)
1182 |
1183 | authorization = ClientAuth() # Test authentication method
1184 |
1185 | try:
1186 | try:
1187 | weatherStation = WeatherStationData(authorization) # Test DEVICELIST
1188 | except NoDevice:
1189 | logger.warning("No weather station available for testing")
1190 | else:
1191 | weatherStation.MinMaxTH() # Test GETMEASUR
1192 |
1193 | try:
1194 | homes = HomeData(authorization)
1195 | except NoDevice :
1196 | logger.warning("No home available for testing")
1197 |
1198 | try:
1199 | thermostat = ThermostatData(authorization)
1200 | Default_relay = thermostat.Relay_Plug()
1201 | Default_thermostat = thermostat.Thermostat_Data()
1202 | thermostat.getThermostat()
1203 | print (thermostat.moduleNamesList())
1204 | #print (thermostat.getModuleByName(name))
1205 | except NoDevice:
1206 | logger.warning("No thermostat avaible for testing")
1207 |
1208 | try:
1209 | print (' ')
1210 | logger.info("Homes Data")
1211 | #homesdata = HomesData(authorization, homeid)
1212 | homesdata = HomesData(authorization)
1213 | homeid = homesdata.homeid
1214 | except NoDevice:
1215 | logger.warning("No HomesData avaible for testing")
1216 |
1217 | try:
1218 | print (' ')
1219 | logger.info("Home Status")
1220 | HomeStatus(authorization, homeid)
1221 | except NoDevice:
1222 | logger.warning("No Home available for testing")
1223 |
1224 | try:
1225 | print (' ')
1226 | logger.info("HomeCoach")
1227 | Homecoach = HomeCoach(authorization)
1228 | except NoDevice:
1229 | logger.warning("No HomeCoach avaible for testing")
1230 |
1231 | except OutOfScope:
1232 | logger.warning("Your current scope do not allow such access")
1233 |
1234 | # If we reach this line, all is OK
1235 | logger.info("OK")
1236 |
1237 | exit(0)
1238 |
--------------------------------------------------------------------------------
/samples/get_direct_camera_snapshot:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | # Locate the camera name "MyCam" IP on the local LAN
4 | # to collect a snapshot of what the camera sees
5 | # If available use a local connection to save internet bandwith
6 |
7 |
8 | from sys import exit
9 | import lnetatmo
10 |
11 | # The name I gave the camera in the Netatmo Security App
12 | MY_CAMERA = "MyCam"
13 |
14 | # Authenticate (see authentication in documentation)
15 | # Note you will need the appropriate scope (read_welcome access_welcome or read_presence access_presence)
16 | # depending of the camera you are trying to reach
17 | # The default library scope ask for all aceess to all cameras
18 | authorization = lnetatmo.ClientAuth()
19 |
20 | # Gather Home information (available cameras and other infos)
21 | homeData = lnetatmo.HomeData(authorization)
22 |
23 | # Request a snapshot from the camera
24 | snapshot = homeData.getLiveSnapshot( camera=MY_CAMERA )
25 |
26 | # If all was Ok, I should have an image, if None there was an error
27 | if not snapshot :
28 | # Decide what to do with an error situation (alert, log, ...)
29 | exit(1)
30 |
31 | # You can then archive the snapshot, send it by mail, message App, ...
32 | # Example : Save the snapshot in a file
33 | with open("MyCamSnap.jpg", "wb") as f: f.write(snapshot)
34 |
35 | exit(0)
36 |
--------------------------------------------------------------------------------
/samples/graphLast3Days:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # coding=utf-8
3 |
4 | # 2013-01 : philippelt@users.sourceforge.net
5 |
6 | # This is an example of graphing Temperature and Humidity from a module on the last 3 days
7 | # The Matplotlib library is used and should be installed before running this sample program
8 |
9 | import datetime, time
10 |
11 | import lnetatmo
12 |
13 | from matplotlib import pyplot as plt
14 | from matplotlib import dates
15 | from matplotlib.ticker import FormatStrFormatter
16 |
17 | # Access to the sensors
18 | auth = lnetatmo.ClientAuth()
19 | dev = lnetatmo.DeviceList(auth)
20 |
21 | # Time of information collection : 3*24hours windows to now
22 | now = time.time()
23 | start = now - 3 * 24 * 3600
24 |
25 | # Get Temperature and Humidity with GETMEASURE web service (1 sample every 30min)
26 | resp = dev.getMeasure( device_id='xxxx', # Replace with your values
27 | module_id='xxxx', # " " " "
28 | scale="30min",
29 | mtype="Temperature,Humidity",
30 | date_begin=start,
31 | date_end=now)
32 |
33 | # Extract the timestamp, temperature and humidity from the more complex response structure
34 | result = [(int(k),v[0],v[1]) for k,v in resp['body'].items()]
35 | # Sort samples by timestamps (Warning, they are NOT sorted by default)
36 | result.sort()
37 | # Split in 3 lists for use with Matplotlib (timestamp on x, temperature and humidity on two y axis)
38 | xval, ytemp, yhum = zip(*result)
39 |
40 | # Convert the x axis values from Netatmo timestamp to matplotlib timestamp...
41 | xval = [dates.date2num(datetime.datetime.fromtimestamp(x)) for x in xval]
42 |
43 | # Build the two curves graph (check Matplotlib documentation for details)
44 | fig = plt.figure()
45 | plt.xticks(rotation='vertical')
46 |
47 | graph1 = fig.add_subplot(111)
48 |
49 | graph1.plot(xval, ytemp, color='r', linewidth=3)
50 | graph1.set_ylabel(u'Température', color='r')
51 | graph1.set_ylim(0, 25)
52 | graph1.yaxis.grid(color='gray', linestyle='dashed')
53 | for t in graph1.get_yticklabels() : t.set_color('r')
54 | graph1.yaxis.set_major_formatter(FormatStrFormatter(u'%2.0f °C'))
55 |
56 | graph2 = graph1.twinx()
57 |
58 | graph2.plot(xval, yhum, color='b', linewidth=3)
59 | graph2.set_ylabel(u'Humidité',color='b')
60 | graph2.set_ylim(50,100)
61 | for t in graph2.get_yticklabels(): t.set_color('b')
62 | graph2.yaxis.set_major_formatter(FormatStrFormatter(u'%2i %%'))
63 |
64 | graph1.xaxis.set_major_locator(dates.HourLocator(interval=6))
65 | graph1.xaxis.set_minor_locator(dates.HourLocator())
66 | graph1.xaxis.set_major_formatter(dates.DateFormatter("%d-%Hh"))
67 | graph1.xaxis.grid(color='gray')
68 | graph1.set_xlabel(u'Jour et heure de la journée')
69 |
70 | # X display the resulting graph (you could generate a PDF/PNG/... in place of display).
71 | # The display provides a minimal interface that notably allows you to save your graph
72 | plt.show()
73 |
--------------------------------------------------------------------------------
/samples/printAllLastData.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # encoding=utf-8
3 |
4 | # 2014-01 : philippelt@users.sourceforge.net
5 |
6 | # Just connect to a Netatmo account, and print all last informations available for
7 | # station(s) and modules of the user account
8 | # (except if module data is more than one hour old that usually means module lost
9 | # wether out of radio range or battery exhausted thus information is no longer
10 | # significant)
11 |
12 | import time
13 | import lnetatmo
14 |
15 | authorization = lnetatmo.ClientAuth()
16 | weather = lnetatmo.WeatherStationData(authorization)
17 |
18 | user = weather.user
19 |
20 | print("Station owner : ", user.mail)
21 | print("Data units : ", user.unit)
22 |
23 | # For each station in the account
24 | for station in weather.stations:
25 |
26 | print("\nSTATION : %s\n" % weather.stations[station]["station_name"])
27 |
28 | # For each available module in the returned data of the specified station
29 | # that should not be older than one hour (3600 s) from now
30 | for module, moduleData in weather.lastData(station=station, exclude=3600).items() :
31 |
32 | # Name of the module (or station embedded module)
33 | # You setup this name in the web netatmo account station management
34 | print(module)
35 |
36 | # List key/values pair of sensor information (eg Humidity, Temperature, etc...)
37 | for sensor, value in moduleData.items() :
38 | # To ease reading, print measurement event in readable text (hh:mm:ss)
39 | if sensor == "When" : value = time.strftime("%H:%M:%S",time.localtime(value))
40 | print("%30s : %s" % (sensor, value))
41 |
42 |
43 | # OUTPUT SAMPLE :
44 | #
45 | # $ printAllLastData
46 | #
47 | #Station owner : ph.larduinat@wanadoo.fr
48 | #Data units : metric
49 | #
50 | #
51 | #STATION : TEST-STATION-1
52 | #
53 | #Office
54 | # AbsolutePressure : 988.7
55 | # CO2 : 726
56 | # date_max_temp : 1400760301
57 | # date_min_temp : 1400736146
58 | # Humidity : 60
59 | # max_temp : 19.6
60 | # min_temp : 17.9
61 | # Noise : 46
62 | # Particle : 12768
63 | # Pressure : 988.7
64 | # Temperature : 19.6
65 | # When : 14:10:01
66 | #Outdoor
67 | # battery_vp : 5200
68 | # CO2 : 555
69 | # date_max_temp : 1400759951
70 | # date_min_temp : 1400732524
71 | # Humidity : 75
72 | # max_temp : 17.9
73 | # min_temp : 10.3
74 | # rf_status : 57
75 | # Temperature : 17.9
76 | # When : 14:09:25
77 | #Greenhouse
78 | # date_min_temp : 1400732204
79 | # Humidity : 89
80 | # max_temp : 19.9
81 | # min_temp : 9.1
82 | # rf_status : 83
83 | # Temperature : 19.9
84 | # When : 14:09:12
85 |
--------------------------------------------------------------------------------
/samples/printThermostat.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # encoding=utf-8
3 |
4 | # 2018-02 : ph.larduinat@wanadoo.fr
5 |
6 | # Thermostat basic sample
7 |
8 | import sys
9 | import lnetatmo
10 |
11 | authorization = lnetatmo.ClientAuth()
12 | thermostat = lnetatmo.ThermostatData(authorization)
13 |
14 |
15 | defaultThermostat = thermostat.getThermostat()
16 | if not defaultThermostat : sys.exit(1)
17 | defaultModule = thermostat.defaultModule
18 |
19 | print('Thermostat name :', defaultThermostat['name'])
20 | print('Default module :', defaultModule['name'])
21 | print('Module measured temp :', defaultModule['measured']['temperature'])
22 | print('Module set point :', defaultModule['measured']['setpoint_temp'])
23 | print('Module battery : %s%%' % defaultModule['battery_percent'])
24 | for p in defaultModule['therm_program_list']:
25 | print("\tProgram: ", p['name'])
26 | for z in p['zones']:
27 | name = z['name'] if 'name' in z else ''
28 | print("\t%15s : %s" % (name, z['temp']))
29 |
--------------------------------------------------------------------------------
/samples/rawAPIsample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | # 2023-07 : ph.larduinat@wanadoo.fr
4 | # Library 3.2.0
5 |
6 | # Direct call of Netatmo API with authentication token
7 | # Return a dictionary of body of Netatmo response
8 |
9 | import lnetatmo
10 |
11 | authorization = lnetatmo.ClientAuth()
12 | rawData = lnetatmo.rawAPI(authorization, "gethomesdata")
13 |
14 | print("Home name : home_id")
15 | for h in rawData["homes"]:
16 | print(f"{h['name']} : {h['id']}")
17 |
18 | print("Radio communication strength by home")
19 | for h in rawData["homes"]:
20 | print(f"\nFor {h['name']}:")
21 | modules = lnetatmo.rawAPI(authorization, "homestatus", {"home_id" : h['id']})['home']
22 | if not 'modules' in modules:
23 | print("No modules available")
24 | else:
25 | print([(m['id'],m['rf_strength']) for m in modules['modules'] if 'rf_strength' in m])
--------------------------------------------------------------------------------
/samples/simpleLastData.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # encoding=utf-8
3 |
4 | # 2013-01 : philippelt@users.sourceforge.net
5 |
6 | # Just connect to a Netatmo account, and print internal and external temperature of the default (or single) station
7 | # In this case, sensors of the station and the external module have been named 'internal' and 'external' in the
8 | # Account station settings.
9 |
10 | import lnetatmo
11 |
12 | authorization = lnetatmo.ClientAuth()
13 | devList = lnetatmo.WeatherStationData(authorization)
14 |
15 | print ("Current temperature (inside/outside): %s / %s °C" %
16 | ( devList.lastData()['internal']['Temperature'],
17 | devList.lastData()['external']['Temperature'])
18 | )
19 |
20 |
--------------------------------------------------------------------------------
/samples/smsAlarm.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # encoding=utf-8
3 |
4 | # 2013-01 : philippelt@users.sourceforge.net
5 |
6 | # Simple example run in a cron job (every 30' for example) to send an alarm SMS if some condition is reached
7 | # and an other SMS when condition returned to normal. In both case, a single SMS is emitted to multiple
8 | # peoples (here phone1 and phone2 are two mobile phone numbers)
9 | # Note : lsms is my personnal library to send SMS using a GSM modem, you have to use your method/library
10 |
11 | import sys, os
12 | import lnetatmo,lsms
13 |
14 | MARKER_FILE = "//TempAlarm" # This flag file will be used to avoid sending multiple SMS on the same event
15 | # Remember that the user who run the cron job must have the rights to create the file
16 |
17 | # Access the station
18 | authorization = lnetatmo.ClientAuth()
19 | devList = lnetatmo.WeatherStationData(authorization)
20 |
21 | message = []
22 |
23 | # Condition 1 : the external temperature is below our limit
24 | curT = devList.lastData()['external']['Temperature']
25 | if curT < 5 : message.append("Temperature going below 5°C")
26 |
27 | # Condition 2 : The external temperature data is older that 1 hour
28 | someLost = devList.checkNotUpdated()
29 | if someLost and 'external' in someLost : message.append("Sensor is no longer active")
30 |
31 | # Condition 3 : The outdoor module battery is dying
32 | volts = devList.lastData()['external']['battery_vp'] # I suspect that this is the total Voltage in mV
33 | if volts < 5000 : message.append("External module battery needs replacement") # I will adjust the threshold over time
34 |
35 | # If one condition is present, at least, send an alarm by SMS
36 | if message :
37 | if not os.path.exists(MARKER_FILE) :
38 | message = "WEATHER ALERT\n" + "\n".join(message)
39 | for p in ('', '') :
40 | lsms.sendSMS(p, message, flash=True)
41 | open(MARKER_FILE,"w").close() # Just to create the empty marker file and avoid to resend the same alert
42 | else :
43 | if os.path.exists(MARKER_FILE) :
44 | os.remove(MARKER_FILE)
45 | for p in ('', '') :
46 | lsms.sendSMS(p, "END of WEATHER alert, current temperature is %s°C" % curT)
47 |
48 | sys.exit(0)
49 |
--------------------------------------------------------------------------------
/samples/weather2file.md:
--------------------------------------------------------------------------------
1 | # weather2file
2 | The script [weather2file](https://github.com/philippelt/netatmo-api-python/blob/master/samples/weather2file) can be used to save data from [Netatmo](https://www.netatmo.com) to file. The data is extracted through the Netatmo api and is aggregated into a pandas DataFrame which is then saved into one of the possible output formats (-f flag). Each sample/row in the dataframe consists of common columns such as utc_time (int), timestamp (datetime including timezone if supported by output format), type, module_name, module_mac, station_name, station_mac. There are also a number of columns corresponding to the module data such as Temperature, CO2, Humidity, Noise and Pressure. All samples/rows will contain all data columns, however the non-relevant columns (such as pressure for an indoor module) will be set to NaN.
3 |
4 | When run, it will check if a data file already exists. If it exists, it will be loaded and only new data will be extracted from Netatmo. It will thus not download duplicates. In case of certain types of errors, it will exit data collection for the current module and save whatever it managed to collect, and then continue with the next module until data has been collected from all modules. This means that even if the data collection fails, you will not have to download that data again, but will continue from whatever data it already has.
5 |
6 | The script also handles user specific rate limits such as 50 requests per 10s and 500 requests per hour, by logging the time of the requests and make sure that those are never exceeded by waiting, if necessary. You can specify lower rate limits than the maximum as to not eat up all resources such that other services might not work. This is done with the -hlr flag for the hour limit and the -t flag for the 10 seconds limit. The script does however not keep track of requests between different runs. In such cases, one kan use the -p flag to specify the number of assumed previous requests.
7 |
8 | The default name of the output is "weatherdata" followed by the file format ending, but you can change the name with the -n flag. The default output directory is the curent directory. You can change this value with the -o flag (also supports ~).
9 |
10 |
11 | # How to run
12 | 1. Clone or download the repository.
13 | 2. Enter credential information according one of the alternatives in [lnetatmo.py](https://github.com/philippelt/netatmo-api-python/blob/master/lnetatmo.py)
14 | 3. Enter the directory and run:
15 | ```PYTHONPATH=. ./samples/weather2file --format csv``` (change --format if you prefer a different format, and use any of the optional flags)
16 |
17 | ```sh
18 | $ PYTHONPATH=. ./samples/weather2file -h
19 | usage: weather2file [-h] -f {json,csv,pickle,hdf,feather,parquet,excel} [-e END_DATETIME] [-v {debug,info,warning,error,quiet}] [-n FILE_NAME] [-o OUTPUT_PATH] [-p PREVIOUS_REQUESTS]
20 | [-hrl HOUR_RATE_LIMIT] [-t TEN_SECOND_RATE_LIMIT]
21 |
22 | Save historical information for all weather modules from Netatmo to file
23 |
24 | optional arguments:
25 | -h, --help show this help message and exit
26 | -f {json,csv,pickle,hdf,feather,parquet,excel}, --format {json,csv,pickle,hdf,feather,parquet,excel}
27 | Format for which the data is to be saved
28 | -e END_DATETIME, --end-datetime END_DATETIME
29 | The end datetime of data to be saved, in the format YYYY-MM-DD_hh:mm (default: now)
30 | -v {debug,info,warning,error,quiet}, --verbose {debug,info,warning,error,quiet}
31 | Verbose level (default: info)
32 | -n FILE_NAME, --file-name FILE_NAME
33 | Name of the output file (default: weatherdata)
34 | -o OUTPUT_PATH, --output-path OUTPUT_PATH
35 | Output location (default: current folder)
36 | -p PREVIOUS_REQUESTS, --previous-requests PREVIOUS_REQUESTS
37 | Assumes this many previous requests has been done, so that the rate limit is not exceeded (default: 0)
38 | -hrl HOUR_RATE_LIMIT, --hour-rate-limit HOUR_RATE_LIMIT
39 | Specify the rate limit per hour (default: 400, max: 500)
40 | -t TEN_SECOND_RATE_LIMIT, --ten-second-rate-limit TEN_SECOND_RATE_LIMIT
41 | Specify the rate limit per ten seconds (default: 30, max: 50)
42 | ```
43 |
44 |
--------------------------------------------------------------------------------
/samples/weather2file.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # Copyright (c) 2020 Joel Berglund
4 | #
5 | # This program is free software; you can redistribute it and/or
6 | # modify it under the terms of the GNU General Public License as
7 | # published by the Free Software Foundation; either version 3 of the
8 | # License, or (at your option) any later version.
9 | #
10 | # This program is distributed in the hope that it will be useful, but
11 | # WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 | # General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU General Public License
16 | # along with this program; if not, write to the Free Software
17 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18 | # USA
19 |
20 | import lnetatmo
21 | import pandas as pd
22 | import numpy as np
23 | import argparse
24 | import logging
25 | import time
26 | import socket
27 | from datetime import date, datetime, timedelta
28 | from pytz import timezone
29 | from os.path import expanduser, join
30 | from pathlib import Path
31 |
32 | def valid_datetime_type(arg_datetime_str):
33 | try:
34 | return datetime.strptime(arg_datetime_str, "%Y-%m-%d_%H:%M")
35 | except ValueError:
36 | msg = f"Given Date {arg_datetime_str} not valid! Expected format, YYYY-MM-DD_hh:mm!"
37 | raise argparse.ArgumentTypeError(msg)
38 |
39 | def valid_hour_limit(hour_limit):
40 | hour_limit = int(hour_limit)
41 | if hour_limit <= 0:
42 | msg = "Hour limit must be larger than 0"
43 | raise argparse.ArgumentTypeError(msg)
44 | elif hour_limit > 500:
45 | msg = "Hour limit cannot be more than 500"
46 | raise argparse.ArgumentTypeError(msg)
47 |
48 | return hour_limit
49 |
50 |
51 | def valid_ten_seconds_limit(ten_sec_limit):
52 | ten_sec_limit = int(ten_sec_limit)
53 | if ten_sec_limit <= 0:
54 | msg = "Ten seconds limit must be larger than 0"
55 | raise argparse.ArgumentTypeError(msg)
56 | elif ten_sec_limit > 50:
57 | msg = "Ten seconds limit cannot be more than 50"
58 | raise argparse.ArgumentTypeError(msg)
59 |
60 | return ten_sec_limit
61 |
62 |
63 | verbose_dict = {
64 | 'debug':logging.DEBUG,
65 | 'info':logging.INFO,
66 | 'warning':logging.WARNING,
67 | 'error':logging.ERROR
68 | }
69 |
70 |
71 | def userexpanded_path_str(path_str):
72 | return expanduser(path_str)
73 |
74 |
75 | class DataFrameHandler:
76 | def __init__(self, file_name, output_path, file_format, kwargs={}):
77 | logging.debug(f'Initiating {self.__class__.__name__}')
78 | self.file_name = file_name
79 | self.kwargs = kwargs
80 | try:
81 | Path(output_path).resolve(strict=True)
82 | except FileNotFoundError as error:
83 | logging.error(f'Output path {output_path} does not exist')
84 | raise error
85 |
86 | self.output_path = output_path
87 | self.file_extension = self.file_extension_dict[file_format]
88 | self._set_df()
89 |
90 | # Specify the column formats here
91 | dtype_dict = {
92 | 'Pressure':np.float32,
93 | 'CO2':np.float32,
94 | 'Temperature':np.float32,
95 | 'Humidity':pd.Int8Dtype(),
96 | 'Noise':pd.Int16Dtype(),
97 | 'utc_time':np.uint32}
98 |
99 |
100 |
101 |
102 | file_extension_dict = {
103 | "json": "json",
104 | "pickle": "pkl",
105 | "csv": "csv",
106 | "hdf": "h5",
107 | "feather": "feather",
108 | "parquet": "parquet",
109 | "excel": "xlsx",
110 | }
111 |
112 |
113 |
114 | def _set_df(self):
115 | # If the file exists, load it. Otherwise, set empty DataFrame
116 | file_path = self._get_complete_file_name()
117 | p = Path(file_path)
118 | try:
119 | abs_path = p.resolve(strict=True)
120 | except FileNotFoundError:
121 | logging.info(f'Previous file {file_path} not found. Setting empty DataFrame')
122 | self.df = pd.DataFrame([])
123 |
124 | else:
125 | logging.info(f'Previous file {file_path} found. Loading DataFrame.')
126 | self.df = self._read_file(abs_path).astype(self.dtype_dict)
127 |
128 |
129 | def _get_complete_file_name(self):
130 | return join(self.output_path, f"{self.file_name}.{self.file_extension}")
131 |
132 | def _read_file(self, file_path):
133 | pass
134 |
135 | def _write_file(self, file_path):
136 | pass
137 |
138 | def save_to_file(self):
139 |
140 | if self.df.empty:
141 | logging.debug("Empty DataFrame. Nothing to save...")
142 | return
143 |
144 | full_file_path = self._get_complete_file_name()
145 | logging.debug(f"Saving to file {full_file_path} ({self.df.shape[0]} samples)")
146 | self._write_file(full_file_path)
147 | logging.debug(f"{full_file_path} saved")
148 |
149 | def append(self, df):
150 | self.df = pd.concat([self.df, df], ignore_index=True)
151 |
152 | def get_newest_timestamp(self,module_mac):
153 | if ('module_mac' in self.df.columns):
154 | module_utc_time = self.df.loc[self.df['module_mac']==module_mac,'utc_time']
155 |
156 | if module_utc_time.size:
157 | return module_utc_time.max()
158 |
159 | return None
160 |
161 |
162 | def _remove_timezone(self):
163 | if 'timestamp' in self.df.columns:
164 | self.df['timestamp'] = self.df['timestamp'].apply(lambda x: x.replace(tzinfo=None))
165 | logging.debug (f'Timezone was removed for {self.__class__.__name__}')
166 |
167 | class PickleHandler(DataFrameHandler):
168 | def __init__(self, file_name, output_path):
169 | super().__init__(file_name, output_path, file_format="pickle")
170 |
171 | def _read_file(self, file_path):
172 | return pd.read_pickle(file_path, **self.kwargs)
173 |
174 | def _write_file(self, file_path):
175 | self.df.to_pickle(file_path, **self.kwargs)
176 |
177 |
178 |
179 |
180 | class JSONHandler(DataFrameHandler):
181 | def __init__(self, file_name, output_path):
182 | self.dtype_dict['Humidity'] = np.float64
183 | self.dtype_dict['Noise'] = np.float64
184 | super().__init__(file_name, output_path, file_format="json", kwargs = {"orient": "table"})
185 |
186 | def _read_file(self, file_path):
187 | return pd.read_json(file_path, convert_dates=False, **self.kwargs)
188 |
189 | def _write_file(self, file_path):
190 | logging.debug('JSON orient table does not support timezones. Removing timezone information...')
191 | self._remove_timezone()
192 | self.df.to_json(file_path, index=False, **self.kwargs)
193 |
194 |
195 |
196 | class CSVHandler(DataFrameHandler):
197 | def __init__(self, file_name, output_path):
198 | super().__init__(file_name, output_path, file_format="csv")
199 |
200 | def _read_file(self, file_path):
201 | return pd.read_csv(file_path, parse_dates=["timestamp"], **self.kwargs)
202 |
203 | def _write_file(self, file_path):
204 | self.df.to_csv(file_path, index=False, **self.kwargs)
205 |
206 |
207 | class HDFHandler(DataFrameHandler):
208 | def __init__(self, file_name, output_path):
209 | self.dtype_dict['Humidity'] = np.float64
210 | self.dtype_dict['Noise'] = np.float64
211 | super().__init__(file_name, output_path, file_format="hdf", kwargs={"key": "df"})
212 |
213 | def _read_file(self, file_path):
214 | return pd.read_hdf(file_path, **self.kwargs)
215 |
216 | def _write_file(self, file_path):
217 | self.df.to_hdf(file_path, mode="w", **self.kwargs)
218 |
219 |
220 |
221 | class ParquetHandler(DataFrameHandler):
222 | def __init__(self, file_name, output_path):
223 | self.dtype_dict['Noise'] = np.float64
224 | super().__init__(file_name, output_path, file_format="parquet")
225 |
226 | def _read_file(self, file_path):
227 | return pd.read_parquet(file_path, **self.kwargs)
228 |
229 | def _write_file(self, file_path):
230 | self.df.to_parquet(file_path, **self.kwargs)
231 |
232 |
233 | class SQLHandler(DataFrameHandler):
234 | def __init__(self, file_name, output_path):
235 | raise NotImplementedError("sql details not setup")
236 | #from sqlalchemy import create_engine
237 |
238 | #super().__init__(file_name, output_path, file_format="sql", kwargs={"con": self.engine})
239 | #self.engine = create_engine("sqlite://", echo=False)
240 |
241 | def _read_file(self, file_path):
242 | return pd.read_sql(file_path, **self.kwargs)
243 |
244 | def _write_file(self, file_path):
245 | raise NotImplementedError("sql details not setup")
246 | self.df.to_sql(file_path, index=False, **self.kwargs)
247 |
248 |
249 | class FeatherHandler(DataFrameHandler):
250 | def __init__(self, file_name, output_path):
251 | self.dtype_dict['Noise'] = np.float64
252 | super().__init__(file_name, output_path, file_format="feather")
253 |
254 | def _read_file(self, file_path):
255 | return pd.read_feather(file_path, **self.kwargs)
256 |
257 | def _write_file(self, file_path):
258 | self.df.to_feather(file_path, **self.kwargs)
259 |
260 |
261 |
262 | class ExcelHandler(DataFrameHandler):
263 | def __init__(self, file_name, output_path):
264 | super().__init__(file_name, output_path, file_format="excel")
265 |
266 | def _read_file(self, file_path):
267 | return pd.read_excel(file_path, **self.kwargs)
268 |
269 | def _write_file(self, file_path):
270 | logging.debug('Excel does not support timezones. Removing timezone information...')
271 | self._remove_timezone()
272 | self.df.to_excel(file_path, index=False, **self.kwargs)
273 |
274 |
275 | df_handler_dict = {
276 | "json": JSONHandler,
277 | "pickle": PickleHandler,
278 | "csv": CSVHandler,
279 | "hdf": HDFHandler,
280 | "feather": FeatherHandler,
281 | "sql": SQLHandler,
282 | "parquet": ParquetHandler,
283 | "excel": ExcelHandler,
284 | }
285 |
286 |
287 |
288 |
289 | class RateLimitHandler:
290 | def __init__(self,
291 | user_request_limit_per_ten_seconds=50,
292 | user_request_limit_per_hour=500,
293 | nr_previous_requests=0):
294 |
295 |
296 | self._USER_REQUEST_LIMIT_PER_TEN_SECONDS = user_request_limit_per_ten_seconds
297 | logging.debug(f'Ten second rate limit was set to {user_request_limit_per_ten_seconds}')
298 |
299 | self._USER_REQUST_LIMIT_PER_HOUR = user_request_limit_per_hour
300 | logging.debug(f'Hour rate limit was set to {user_request_limit_per_hour}')
301 |
302 | self._TEN_SECOND_TIMEDELTA = timedelta(seconds=10)
303 | self._HOUR_TIMEDELTA = timedelta(hours=1)
304 | self._SECOND_TIMEDELTA = timedelta(seconds=1)
305 |
306 | # Keep track of when we have done requests
307 | if nr_previous_requests:
308 | logging.debug(f'{nr_previous_requests} previous requests has been assumed')
309 | self.requests_series = pd.Series(
310 | data=1,
311 | index=[datetime.now()],
312 | name='request_logger',
313 | dtype=np.uint16).repeat(nr_previous_requests)
314 | else:
315 | logging.debug('No previous requests has been assumed. Creating empty request logger')
316 | self.requests_series = pd.Series(name='request_logger',dtype=np.uint16)
317 |
318 | self._set_authorization()
319 | self._set_weather_data()
320 |
321 | def _get_masked_series(self, time_d):
322 | return self.requests_series[self.requests_series.index >= (datetime.now() - time_d)]
323 |
324 | def _log_request(self):
325 | self.requests_series[datetime.now()] = 1
326 |
327 | def _set_authorization(self):
328 | self._check_rate_limit_and_wait()
329 | self.authorization = lnetatmo.ClientAuth()
330 | self._log_request()
331 |
332 |
333 | def _set_weather_data(self):
334 | self._check_rate_limit_and_wait()
335 | self.weather_data = lnetatmo.WeatherStationData(self.authorization)
336 | self._log_request()
337 |
338 | def _sleep(self, until_time):
339 | sleep = True
340 | tot_seconds = (until_time - datetime.now())/self._SECOND_TIMEDELTA
341 |
342 | while(sleep):
343 | time_left = (until_time - datetime.now())/self._SECOND_TIMEDELTA
344 |
345 | if(time_left>0):
346 | if logging.getLogger().isEnabledFor(logging.INFO):
347 | print(f'\t{time_left:.1f}/{tot_seconds:.1f} seconds left',end='\r')
348 | time.sleep(1)
349 | else:
350 | sleep = False
351 |
352 | def _check_rate_limit_and_wait(self):
353 |
354 | # Check the 10 second limit
355 | ten_sec_series = self._get_masked_series(self._TEN_SECOND_TIMEDELTA)
356 |
357 | if(ten_sec_series.size >= self._USER_REQUEST_LIMIT_PER_TEN_SECONDS):
358 | # Wait until there is at least room for one more request
359 | until_time = (ten_sec_series.index[-self._USER_REQUEST_LIMIT_PER_TEN_SECONDS] + self._TEN_SECOND_TIMEDELTA)
360 | logging.info(f'10 second limit. Waiting for {(until_time - datetime.now())/self._SECOND_TIMEDELTA:.1f} seconds...')
361 | self._sleep(until_time)
362 |
363 | # Check the 500 second limit
364 | hour_series = self._get_masked_series(self._HOUR_TIMEDELTA)
365 |
366 | if(hour_series.size >= self._USER_REQUST_LIMIT_PER_HOUR):
367 | # Wait until there is at least room for one more request
368 | until_time = (hour_series.index[-self._USER_REQUST_LIMIT_PER_HOUR] + self._HOUR_TIMEDELTA)
369 | 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...')
370 | self._sleep(until_time)
371 |
372 | def _get_measurement(self, input_dict):
373 |
374 | # Check that we don't exceed the user rate limit
375 | self._check_rate_limit_and_wait()
376 |
377 | # Log this request
378 | self._log_request()
379 |
380 | try:
381 | return self.weather_data.getMeasure(**input_dict)
382 | except socket.timeout as socket_timeout:
383 | logging.error(socket_timeout)
384 | return None
385 |
386 | def get_stations(self):
387 | return self.weather_data.stations.items()
388 |
389 |
390 |
391 | def _get_field_dict(self, station_id,module_id,data_type,start_date,end_date):
392 | """Returns a dict to be used when requesting data through the Netatmo API"""
393 |
394 | return {'device_id':station_id,
395 | 'scale':'max',
396 | 'mtype':','.join(data_type),
397 | 'module_id':module_id,
398 | 'date_begin':start_date,
399 | 'date_end':end_date}
400 |
401 | def _get_date_from_timestamp(self, ts, tz=None):
402 | return datetime.fromtimestamp(ts,tz).date()
403 |
404 | def _get_timestamp_from_date(self, d, tz=None):
405 | """Returns the timetamp corresponding to the end of the day d"""
406 | # Create datetime from date
407 | combined_datetime = datetime.combine(d, datetime.max.time(), tzinfo=tz)
408 | return np.floor(datetime.timestamp(combined_datetime))
409 |
410 | def _get_common_elements(self, keys, column_names):
411 | return list(set(keys).intersection(column_names))
412 |
413 |
414 | def _to_dataframe(self, module_data_body, module_data, station_name, station_mac, dtype={}, time_z=None):
415 | """Convert the dict to a pandas DataFrame"""
416 |
417 |
418 | df = pd.DataFrame.from_dict(module_data_body,orient='index',columns=module_data['data_type'])
419 |
420 | df['type'] = module_data['type']
421 | df['module_name'] = module_data['module_name']
422 | df['module_mac'] = module_data['_id']
423 | df['station_name'] = station_name
424 | df['station_mac'] = station_mac
425 |
426 | df.index.set_names('utc_time',inplace=True)
427 | df.reset_index(inplace=True)
428 | df['timestamp'] = df['utc_time'].apply(lambda x: datetime.fromtimestamp(np.uint32(x), tz=time_z))
429 |
430 | common_names = self._get_common_elements(dtype.keys(), df.columns)
431 | dtypes = {k: dtype[k] for k in common_names}
432 |
433 | return df.astype(dtypes)
434 |
435 | def get_module_df(self, newest_utctime, station_name, station_mac, module_data_overview, end_date_timestamp, dtype={}, time_z=None):
436 | logging.info(f'Processing {module_data_overview["module_name"]}...')
437 |
438 |
439 | module_name = module_data_overview["module_name"]
440 |
441 | # We start by collecting new data
442 | keep_collecting_module_data = True
443 |
444 | # Start with the oldest timestamp
445 | module_start_date_timestamp = module_data_overview['last_setup']
446 |
447 | # Fill array with data
448 | data = []
449 |
450 | if(newest_utctime):
451 | # Found newer data! Change start time according to the newest value
452 |
453 | if(newest_utctime > module_start_date_timestamp):
454 | module_start_date_timestamp = newest_utctime + 1
455 | 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)}')
456 | else:
457 | logging.debug(f'No newer data found for module {module_name}, starting from last setup.')
458 |
459 | if(end_date_timestamp < module_start_date_timestamp):
460 | logging.info('Start date is after end date. Nothing to do...')
461 | keep_collecting_module_data = False
462 | else:
463 | logging.info(f'Collecting data for {module_name}...')
464 |
465 | while(keep_collecting_module_data):
466 |
467 | # Get new data from Netatmo
468 | d = self._get_field_dict(station_mac,
469 | module_data_overview['_id'],
470 | module_data_overview['data_type'],
471 | module_start_date_timestamp,
472 | end_date_timestamp)
473 |
474 | retreived_module_data = self._get_measurement(d)
475 |
476 | if retreived_module_data is None:
477 | logging.warning(f'None received. Aborting data collection from module {module_name}')
478 | keep_collecting_module_data = False
479 | else:
480 | try:
481 | # Was there any data?
482 | if(retreived_module_data['body']):
483 | new_df = self._to_dataframe(retreived_module_data['body'],
484 | module_data_overview,
485 | station_name,
486 | station_mac,
487 | dtype,
488 | time_z)
489 | data.append(new_df)
490 | new_df['utc_time'].min()
491 | 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]}')
492 | # Now change the start_time
493 | module_start_date_timestamp = new_df['utc_time'].max() + 1
494 |
495 | else:
496 | keep_collecting_module_data = False
497 | logging.debug(f'Data not found for {module_name}. Proceeding...')
498 |
499 | except Exception as e:
500 | logging.error(e)
501 | keep_collecting_module_data = False
502 | logging.error(f'Something fishy is going on... Aborting collection for module {module_name}')
503 |
504 |
505 | if data:
506 | df_module = pd.concat(data,ignore_index=True)
507 | else:
508 | df_module = pd.DataFrame([])
509 |
510 |
511 | logging.info(f'Collected data from {module_name} contains {df_module.shape[0]} samples.')
512 | return df_module
513 |
514 | def main():
515 |
516 | parser = argparse.ArgumentParser(
517 | description="Save historical information for all weather modules from Netatmo to file"
518 | )
519 |
520 | parser.add_argument(
521 | "-f",
522 | "--format",
523 | choices=["json", "csv", "pickle", "hdf", "feather", "parquet", "excel"],
524 | required=True,
525 | help="Format for which the data is to be saved",
526 | )
527 |
528 | parser.add_argument(
529 | "-e",
530 | "--end-datetime",
531 | type=valid_datetime_type,
532 | default=datetime.now(),
533 | required=False,
534 | help="The end datetime of data to be saved, in the format YYYY-MM-DD_hh:mm (default: now)",
535 | )
536 |
537 | parser.add_argument(
538 | "-v",
539 | "--verbose",
540 | choices=["debug", "info", "warning", "error", "quiet"],
541 | default="info",
542 | required=False,
543 | help="Verbose level (default: info)")
544 |
545 | parser.add_argument(
546 | "-n",
547 | "--file-name",
548 | default="weatherdata",
549 | required=False,
550 | help="Name of the output file (default: weatherdata)")
551 |
552 |
553 | parser.add_argument(
554 | "-o",
555 | "--output-path",
556 | type=userexpanded_path_str,
557 | default=".",
558 | required=False,
559 | help="Output location (default: current folder)")
560 |
561 |
562 | parser.add_argument(
563 | "-p",
564 | "--previous-requests",
565 | type=np.uint16,
566 | default=np.uint8(0),
567 | required=False,
568 | help="Assumes this many previous requests has been done, so that the rate limit is not exceeded (default: 0)")
569 |
570 |
571 | parser.add_argument(
572 | "-hrl",
573 | "--hour-rate-limit",
574 | type=valid_hour_limit,
575 | default=400,
576 | required=False,
577 | help="Specify the rate limit per hour (default: 400, max: 500)")
578 |
579 |
580 |
581 | parser.add_argument(
582 | "-t",
583 | "--ten-second-rate-limit",
584 | type=valid_ten_seconds_limit,
585 | default=30,
586 | required=False,
587 | help="Specify the rate limit per ten seconds (default: 30, max: 50)")
588 |
589 |
590 | args = parser.parse_args()
591 |
592 |
593 | if(args.verbose == 'quiet'):
594 | logging.disable(logging.DEBUG)
595 | else:
596 | logging.basicConfig(format=" %(levelname)s: %(message)s", level=verbose_dict[args.verbose])
597 |
598 |
599 | # Handle dataframes (loading, appending, saving).
600 | df_handler = df_handler_dict[args.format](file_name=args.file_name, output_path=args.output_path)
601 |
602 |
603 | # Rate handler to make sure that we don't exceed Netatmos user rate limits
604 | rate_limit_handler = RateLimitHandler(
605 | user_request_limit_per_ten_seconds=args.ten_second_rate_limit,
606 | user_request_limit_per_hour=args.hour_rate_limit,
607 | nr_previous_requests=args.previous_requests)
608 |
609 |
610 | for station_name, station_data_overview in rate_limit_handler.get_stations():
611 |
612 | station_mac = station_data_overview['_id']
613 |
614 | station_timezone = timezone(station_data_overview['place']['timezone'])
615 | logging.info(f'Timezone {station_timezone} extracted from data.')
616 |
617 | end_datetime_timestamp = np.floor(datetime.timestamp(station_timezone.localize(args.end_datetime)))
618 | newest_utc = df_handler.get_newest_timestamp(station_data_overview['_id'])
619 | df_handler.append(
620 | rate_limit_handler.get_module_df(
621 | newest_utc,
622 | station_name,
623 | station_mac,
624 | station_data_overview,
625 | end_datetime_timestamp,
626 | df_handler.dtype_dict,
627 | station_timezone))
628 |
629 | for module_data_overview in station_data_overview['modules']:
630 |
631 | df_handler.append(
632 | rate_limit_handler.get_module_df(
633 | df_handler.get_newest_timestamp(module_data_overview['_id']),
634 | station_name,
635 | station_mac,
636 | module_data_overview,
637 | end_datetime_timestamp,
638 | df_handler.dtype_dict,
639 | station_timezone))
640 |
641 |
642 |
643 |
644 | # Save the data after the collection
645 | df_handler.save_to_file()
646 |
647 | if __name__ == "__main__":
648 | main()
649 |
650 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | description-file = README.md
3 |
4 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # python setup.py --dry-run --verbose install
2 |
3 | from distutils.core import setup
4 |
5 | setup(
6 | name='lnetatmo',
7 | version='4.2.1',
8 | classifiers=[
9 | 'Development Status :: 5 - Production/Stable',
10 | 'Intended Audience :: Developers',
11 | 'Programming Language :: Python :: 2.7',
12 | 'Programming Language :: Python :: 3'
13 | ],
14 | author='Philippe Larduinat',
15 | author_email='ph.larduinat@wanadoo.fr',
16 | py_modules=['lnetatmo'],
17 | scripts=[],
18 | data_files=[],
19 | url='https://github.com/philippelt/netatmo-api-python',
20 | download_url='https://github.com/philippelt/netatmo-api-python/archive/v4.2.1.tar.gz',
21 | license='GPL V3',
22 | description='Simple API to access Netatmo weather station data from any python script.'
23 | )
24 |
--------------------------------------------------------------------------------
/usage.md:
--------------------------------------------------------------------------------
1 | Python Netatmo API programmers guide
2 | ------------------------------------
3 |
4 |
5 |
6 | >2013-01-21, philippelt@users.sourceforge.net
7 |
8 | >2014-01-13, Revision to include new modules additionnal informations
9 |
10 | >2016-06-25, Update documentation for Netatmo Welcome
11 |
12 | >2017-01-09, Minor updates to packaging info
13 |
14 | >2020-12-07, Breaking changes due to removal of direct access to devices, "home" being now required (Netatmo redesign)
15 |
16 | >2023-07-12, Breaking changes due to deprecation of grant_type "password" for ALL apps
17 |
18 | >2023-07-24, Adding rawAPI call to direct access the netatmo API when no additional support is provided by the library
19 |
20 | >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)
21 |
22 | >2024-01-03, New authentication method priorities, credential file as a parameter
23 |
24 | No additional library other than standard Python library is required.
25 |
26 | Both Python V2.7x and V3.x.x are supported without change.
27 |
28 | More information about the Netatmo REST API can be obtained from http://dev.netatmo.com/doc/
29 |
30 | This package support only preauthenticated scoped tokens created along apps.
31 |
32 |
33 |
34 | ### 1 Setup your environment from Netatmo Web interface ###
35 |
36 |
37 |
38 |
39 | Before being able to use the module you will need :
40 |
41 | * A Netatmo user account having access to, at least, one station
42 | * An application registered from the user account (see http://dev.netatmo.com/dev/createapp) to obtain application credentials.
43 | * Create a couple access_token/refresh_token at the same time with your required scope (depending of your intents on library use)
44 |
45 |
46 | In the netatmo philosophy, both the application itself and the user have to be registered thus have authentication credentials to be able to access any station. Registration is free for both.
47 |
48 | Possible NETATMO_SCOPES ;
49 | read_station read_smarther write_smarther read_thermostat write_thermostat read_camera write_camera read_doorbell
50 | read_presence write_precense read_homecoach read_carbonmonoxidedetector read_smokedetector read_magellen write_magellan
51 | read_bubendorff write_bubendorff read_mx write_mx read_mhs1 write_mhs1
52 |
53 |
54 |
55 | ### 2 Setup your authentication information ###
56 |
57 |
58 |
59 | Copy the lnetatmo.py file in your work directory (or use pip install lnetatmo).
60 |
61 | Authentication data can be supplied with 3 different methods (each method override any settings of previous methods) :
62 |
63 | 1. Some or all values can be defined by explicit call to initializer of ClientAuth class
64 |
65 | ̀```bash
66 | # Example: REFRESH_TOKEN supposed to be defined by an other method
67 | authData = lnetatmo.ClientAuth( clientId="netatmo-client-id",
68 | clientSecret="secret" )
69 | ```
70 |
71 | 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
72 |
73 | ̀̀```bash
74 | $ cat .netatmo.credentials # Here all values are defined but it is not mandatory
75 | {
76 | "CLIENT_ID" : "`xxx",
77 | "CLIENT_SECRET" : "xxx",
78 | "REFRESH_TOKEN" : "xxx"
79 | }
80 | $
81 | ̀̀```
82 |
83 | 3. Some or all values can be overriden by environment variables. This is the easiest method if your are packaging your application with Docker.
84 |
85 | ̀̀```bash
86 | $ export REFRESH_TOKEN="yyy"
87 | $ python3 MyCodeUsingLnetatmo.py
88 | ̀̀```
89 |
90 | > 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.
91 |
92 | If you provide all the values in a credential file, you can test that everything is working properly by simply running the package as a standalone program.
93 |
94 | This will run a full access test to the account and stations and return 0 as return code if everything works well. If run interactively, it will also display an OK message.
95 |
96 | ```bash
97 | $ python3 lnetatmo.py # or python2 as well
98 | lnetatmo.py : OK
99 | $ echo $?
100 | 0
101 | ```
102 |
103 | Whatever is your choice for the library authentication setup, your application code if you were using previous library version, will not be affected.
104 |
105 |
106 | ### 3 Package guide ###
107 |
108 |
109 |
110 | Most of the time, the sequence of operations will be :
111 |
112 | 1. Authenticate your program against Netatmo web server
113 | 2. Get the device list accessible to the user
114 | 3. Request data on one of these devices or directly access last data sent by the station
115 |
116 |
117 | Example :
118 |
119 | ```python
120 | #!/usr/bin/python3
121 | # encoding=utf-8
122 |
123 | import lnetatmo
124 |
125 | # 1 : Authenticate
126 | authorization = lnetatmo.ClientAuth()
127 |
128 | # 2 : Get devices list
129 | weatherData = lnetatmo.WeatherStationData(authorization)
130 |
131 | # 3 : Access most fresh data directly
132 | print ("Current temperature (inside/outside): %s / %s °C" %
133 | ( weatherData.lastData()['indoor']['Temperature'],
134 | weatherData.lastData()['outdoor']['Temperature'])
135 | )
136 | ```
137 |
138 | In this example, no init parameters are supplied to ClientAuth, the library is supposed to have been customized with the required values (see §2). The user must have nammed the sensors indoor and outdoor through the Web interface (or any other name as long as the program is requesting the same name).
139 |
140 | The Netatmo design is based on stations (usually the in-house module) and modules (radio sensors reporting to a station, usually an outdoor sensor).
141 |
142 | Sensor design is not exactly the same for station and external modules and they are not addressed the same way wether in the station or an external module. This is a design issue of the API that restrict the ability to write generic code that could work for station sensor the same way than other modules sensors. The station role (the reporting device) and module role (getting environmental data) should not have been mixed. The fact that a sensor is physically built in the station should not interfere with this two distincts objects.
143 |
144 | The consequence is that, for the API, we will use terms of station data (for the sensors inside the station) and module data (for external(s) module). Lookup methods like moduleByName look for external modules and **NOT station
145 | modules**.
146 |
147 | Having two roles, the station has a 'station_name' property as well as a 'module_name' for its internal sensor.
148 |
149 | >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).
150 |
151 |
152 | Sensors (stations and modules) are managed in the API using ID's (network hardware adresses). The Netatmo web account management gives you the capability to associate names to station sensor and module (and to the station itself). This is by far more comfortable and the interface provides service to locate a station or a module by name or by Id depending of your taste. Module lookup by name includes the optional station name in case
153 | multiple stations would have similar module names (if you monitor multiple stations/locations, it would not be a surprise that each of them would have an 'outdoor' module). This is a benefit in the sense it give you the ability to write generic code (for exemple, collect all 'outdoor' temperatures for all your stations).
154 |
155 | The results are Python data structures, mostly dictionaries as they mirror easily the JSON returned data. All supplied classes provides simple properties to use as well as access to full data returned by the netatmo web services (rawData property for most classes).
156 |
157 |
158 |
159 | ### 4 Package classes and functions ###
160 |
161 |
162 |
163 | #### 4-1 Global variables ####
164 |
165 |
166 | ```python
167 | _CLIENT_ID, _CLIENT_SECRET = Application ID and secret provided by Netatmo
168 | application registration in your user account
169 |
170 | _REFRESH_TOKEN : Refresh token created along the app client credentials
171 |
172 | _BASE_URL and _*_REQ : Various URL to access Netatmo web services. They are
173 | documented in http://dev.netatmo.com/doc/ They should not be changed unless
174 | Netatmo API changes.
175 | ```
176 |
177 |
178 |
179 | #### 4-2 ClientAuth class ####
180 |
181 |
182 |
183 | Constructor
184 |
185 | ```python
186 | authorization = lnetatmo.ClientAuth( clientId = _CLIENT_ID,
187 | clientSecret = _CLIENT_SECRET,
188 | refreshToken = _REFRESH_TOKEN,
189 | credentialFile = "~/.netatmo.credentials"
190 | )
191 | ```
192 |
193 |
194 | Requires : Application and User credentials to access Netatmo API. if all this parameters are put in global variables they are not required (in library source code or in the main program through lnetatmo._CLIENT_ID = …)
195 |
196 |
197 | Return : an authorization object that will supply the access token required by other web services. This class will handle the renewal of the access token if expiration is reached.
198 |
199 |
200 | Properties, all properties are read-only unless specified :
201 |
202 | * **accessToken** : Retrieve a valid access token (renewed if necessary)
203 | * **refreshToken** : The token used to renew the access token (normally should not be used explicitely)
204 | * **expiration** : The expiration time (epoch) of the current token
205 |
206 |
207 |
208 | #### 4-3 User class ####
209 |
210 |
211 |
212 | Constructor
213 |
214 | ```python
215 | user = lnetatmo.User( authorization )
216 | ```
217 |
218 |
219 | Requires : an authorization object (ClientAuth instance)
220 |
221 |
222 | Return : a User object. This object provides multiple informations on the user account such as the mail address of the user, the preferred language, …
223 |
224 |
225 | Properties, all properties are read-only unless specified :
226 |
227 |
228 | * **rawData** : Full dictionary of the returned JSON GETUSER Netatmo API service
229 | * **ownerMail** : eMail address associated to the user account
230 | * **devList** : List of Station's id accessible to the user account
231 |
232 |
233 | In most cases, you will not need to use this class that is oriented toward an application that would use the other authentication method to an unknown user and then get information about him.
234 |
235 |
236 |
237 | #### 4-4 WeatherStationData class ####
238 |
239 |
240 |
241 | Constructor
242 |
243 | ```python
244 | weatherData = lnetatmo.WeatherStationData( authorization, home=None, station=None )
245 | ```
246 |
247 |
248 | * Input : an authorization object (ClientAuth instance), an optional home name, an optional station name or id
249 |
250 | Return : a WeatherStationData object. This object contains most administration properties of stations and modules accessible to the user and the last data pushed by the station to the Netatmo servers.
251 |
252 | Raise a lnetatmo.NoDevice exception if no weather station is available for the given account.
253 |
254 | If no home is specified, the first returned home will be set as default home. Same apply to station.
255 | If you have only one home and one station, you can safely ignore these new parameters. Note that return order is undefined. If you have multiple homes and a weather station in only one, the default home may be the one without station and the call will fail.
256 |
257 | >**Breaking change:**
258 | If you used the station name in the past in any method call, you should be aware that Netatmo decided to rename your station with their own value thus your existing code will have to be updated.
259 |
260 | Properties, all properties are read-only unless specified:
261 |
262 |
263 | * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service
264 | * **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).
265 | * **stations** : Dictionary of stations (indexed by ID) accessible to this user account
266 | * **modules** : Dictionary of modules (indexed by ID) accessible to the user account (whatever station there are plugged in)
267 |
268 |
269 | Methods :
270 |
271 |
272 | * **getStation** (station=None) : Find a station by it's station name or station ID
273 | * Input : Station name or ID to lookup (str)
274 | * Output : station dictionary or None
275 |
276 | * **stationByName** (station=None) : Find a station by it's station name
277 | * Input : Station name to lookup (str)
278 | * Output : station dictionary or None
279 |
280 | * **stationById** (sid) : Find a station by it's Netatmo ID (mac address)
281 | * Input : Station ID
282 | * Output : station dictionary or None
283 |
284 | * **moduleByName** (module, station=None) : Find a module by it's module name
285 | * Input : module name and optional station name
286 | * Output : module dictionary or None
287 |
288 | 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).
289 |
290 | * **moduleById** (mid, sid=None) : Find a module by it's ID and belonging station's ID
291 | * Input : module ID and optional Station ID
292 | * Output : module dictionary or None
293 |
294 | * **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()
295 |
296 | * **lastData** (station=None, exclude=0) : Get the last data uploaded by the station, exclude sensors with measurement older than given value (default return all)
297 | * Input : station name OR id. If not provided default_station is used. Exclude is the delay in seconds from now to filter sensor readings.
298 | * Output : Sensors data dictionary (Key is sensor name)
299 |
300 | AT the time of this document, Available measures types are :
301 | * 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
302 | * battery_vp : likely to be total battery voltage for external sensors (running on batteries) in mV (undocumented)
303 | * rf_status : likely to be the % of radio signal between the station and a module (undocumented)
304 |
305 | See Netatmo API documentation for units of regular measurements
306 |
307 | 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 :
308 |
309 | ```python
310 | # Last data access example
311 |
312 | theData = weatherData.lastData()
313 | print('Available modules : ', theData.keys() )
314 | print('In-house CO2 level : ', theData['indoor']['Co2'] )
315 | print('Outside temperature : ', theData['outdoor']['Temperature'] )
316 | print('External module battery : ', "OK" if int(theData['outdoor']['battery_vp']) > 5000 \
317 | else "NEEDS TO BE REPLACED" )
318 | ```
319 | * **checkNotUpdated** (station=None, delay=3600) :
320 | * Input : optional station name (else default_station is used)
321 | * 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).
322 |
323 | For example (following the previous one)
324 |
325 | ```python
326 | # Ensure data sanity
327 |
328 | for m in weatherData.checkNotUpdated(""):
329 | print("Warning, sensor %s information is obsolete" % m)
330 | if moduleByName(m) == None : # Sensor is not an external module
331 | print("The station is lost")
332 | ```
333 | * **checkUpdated** (station=None, delay=3600) :
334 | * Input : optional station name (else default_station is used)
335 | * Output : list of modules name for which last data update is newer than specified delay (default 1 hour).
336 |
337 | Complement of the previous service
338 |
339 | * **getMeasure** (device_id, scale, mtype, module_id=None, date_begin=None, date_end=None, limit=None, optimize=False) :
340 | * Input : All parameters specified in the Netatmo API service GETMEASURE (type being a python reserved word as been replaced by mtype).
341 | * Output : A python dictionary reflecting the full service response. No transformation is applied.
342 | * **MinMaxTH** (station=None, module=None, frame="last24") : Return min and max temperature and humidity for the given station/module in the given timeframe
343 | * Input :
344 | * An optional station Name or ID, default_station is used if not supplied,
345 | * An optional module name or ID, default : station sensor data is used
346 | * A time frame that can be :
347 | * "last24" : For a shifting window of the last 24 hours
348 | * "day" : For all available data in the current day
349 | * Output :
350 | * A 4 values tuple (Temp mini, Temp maxi, Humid mini, Humid maxi)
351 |
352 | >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
353 | at all if you slip over two days as required in a shifting 24 hours window.
354 |
355 |
356 | #### 4-5 HomeData class ####
357 |
358 |
359 |
360 | Constructor
361 |
362 | ```python
363 | homeData = lnetatmo.HomeData( authorization )
364 | ```
365 |
366 |
367 | Requires : an authorization object (ClientAuth instance)
368 |
369 |
370 | Return : a homeData object. This object contains most administration properties of home security products and notably Welcome & Presence cameras.
371 |
372 |
373 | Note : the is_local property of camera is most of the time unusable if your IP changes, use cameraUrls to try to get a local IP as a replacement.
374 |
375 | Properties, all properties are read-only unless specified:
376 |
377 |
378 | * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service
379 | * **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).
380 | * **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).
381 | * **homes** : Dictionary of homes (indexed by ID) accessible to this user account
382 | * **cameras** : Dictionnary of cameras (indexed by home name and cameraID) accessible to this user
383 | * **persons** : Dictionary of persons (indexed by ID) accessible to the user account
384 | * **events** : Dictionary of events (indexed by cameraID and timestamp) seen by cameras
385 |
386 |
387 | Methods :
388 |
389 | * **homeById** (hid) : Find a home by its Netatmo ID
390 | * Input : Home ID
391 | * Output : home dictionary or None
392 |
393 | * **homeByName** (home=None) : Find a home by it's home name
394 | * Input : home name to lookup (str)
395 | * Output : home dictionary or None
396 |
397 | * **cameraById** (hid) : Find a camera by its Netatmo ID
398 | * Input : camera ID
399 | * Output : camera dictionary or None
400 |
401 | * **cameraByName** (camera=None, home=None) : Find a camera by it's camera name
402 | * Input : camera name and home name to lookup (str)
403 | * Output : camera dictionary or None
404 |
405 | * **cameraUrls** (camera=None, home=None, cid=None) : return Urls to access camera live feed
406 | * Input : camera name and optional home name or cameraID to lookup (str)
407 | * Output : tuple with the vpn_url (for remote access) and local url to access the camera (commands)
408 |
409 | * **url** (camera=None, home=None, cid=None) : return the best url to access camera live feed
410 | * Input : camera name and optional home name or cameraID to lookup (str)
411 | * Output : the local url if available to reduce internet bandwith usage else the vpn url
412 |
413 | * **personsAtHome** (home=None) : return the list of known persons who are at home
414 | * Input : home name to lookup (str)
415 | * Output : list of persons seen
416 |
417 | * **getCameraPicture** (image_id, key): Download a specific image (of an event or user face) from the camera
418 | * Input : image_id and key of an events or person face
419 | * Output: Tuple with image data (to be stored in a file) and image type (jpg, png...)
420 |
421 | * **getProfileImage** (name) : Retreive the face of a given person
422 | * Input : person name (str)
423 | * Output: **getCameraPicture** data
424 |
425 | * **updateEvent** (event=None, home=None): Update the list of events
426 | * Input: Id of the latest event and home name to update event list
427 |
428 | * **personSeenByCamera** (name, home=None, camera=None): Return true is a specific person has been seen by the camera in the last event
429 |
430 | * **someoneKnownSeen** (home=None, camera=None) : Return true is a known person has been in the last event
431 |
432 | * **someoneUnknownSeen** (home=None, camera=None) : Return true is an unknown person has been seen in the last event
433 |
434 | * **motionDetected** (home=None, camera=None) : Return true is a movement has been detected in the last event
435 |
436 | * **presenceLight** (camera=None, home=None, cid=None, setting=None) : return or set the Presence camera lighting mode
437 | * Input : camera name and optional home name or cameraID to lookup (str), setting must be None|auto|on|off. *currently not supported*
438 | * Output : setting requested if supplied else current camera setting
439 |
440 | * **presenceStatus** (mode, camera=None, home=None, cid=None) : set the camera on or off (current status in camera properties)
441 | * Input : mode (on|off) (str), camera name and optional home name or cameraID to lookup (str)
442 | * Output : requested mode if changed else None
443 |
444 | * **getLiveSnapshot** (camera=None, home=None, cid=None) : Get a jpeg of current live view of the camera
445 | * Input : camera name and optional home name or cameraID to lookup (str)
446 | * Output : jpeg binary content
447 |
448 | ```
449 | homedata = lnetatmo.HomeData(authorization)
450 | for k, v in homedata.homes.items():
451 | homeid = k
452 | S = v.get('smokedetectors')
453 | C = v.get('cameras')
454 | P = v.get('persons')
455 | E = v.get('events')
456 | if S or C or P or E:
457 | print ('devices in HomeData')
458 | for smokedetector in homedata.homes[homeid].get('smokedetectors'):
459 | print (smokedetector['name'])
460 | for camera in homedata.homes[homeid].get('cameras'):
461 | print (camera['name'])
462 | for persons in homedata.homes[homeid].get('persons'):
463 | print (persons['name'])
464 | for events in homedata.homes[homeid].get('events'):
465 | print (events['name'])
466 | return homeid
467 | else:
468 | homeid = k
469 | return homeid
470 |
471 | ```
472 |
473 |
474 | #### 4-6 HomeStatus class ####
475 |
476 |
477 | Constructor
478 |
479 | ```
480 | homeStatus = lnetatmo.HomeStatus( authorization, home_id )
481 |
482 | ```
483 |
484 | Requires :
485 | - an authorization object (ClientAuth instance)
486 | - home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using "class homedata"
487 |
488 | Return : a homeStatus object. This object contains most administration properties of Home+ Control devices such as Smarther thermostat, Socket, Cable Output, Centralized fan, Micromodules, ...
489 |
490 | Methods :
491 |
492 | * **getRoomsId** : return all room ID
493 | * Output : list of IDs of every single room (only the one with Smarther thermostat)
494 |
495 | * **getListRoomParam** : return every parameters of a room
496 | * Input : room ID
497 | * Output : list of parameters of a room
498 |
499 | * **getRoomParam** : return a specific parameter for a specific room
500 | * Input : room ID and parameter
501 | * Output : value
502 |
503 | * **getModulesId** : return all module IDs
504 | * Output : list of IDs of every single module (socket, cable outlet, ...)
505 |
506 | * **getListModuleParam** : return every parameters of a module
507 | * Input : module ID
508 | * Output : list of parameters of a module
509 |
510 | * **getModuleParam** : return a specific parameter for a specific module
511 | * Input : module ID and parameter
512 | * Output : value
513 |
514 | ```
515 | homestatus = lnetatmo.HomeStatus(authorization, homeid)
516 | print ('Rooms in Homestatus')
517 | for r in homestatus.rooms:
518 | print (r)
519 | print ('Persons in Homestatus')
520 | if 'persons' in homestatus.rawData.keys():
521 | for pp in homestatus.rawData['persons']:
522 | print (pp)
523 | print ('Modules in Homestatus')
524 | for m in homestatus.modules:
525 | for kt, vt in m.items():
526 | if kt == 'type':
527 | print (m['type'])
528 | print (m['id'])
529 | print (lnetatmo.TYPES[vt])
530 | print (m.keys())
531 |
532 |
533 | ```
534 |
535 |
536 | #### 4-7 ThermostatData class ####
537 |
538 |
539 | Constructor
540 |
541 | ```
542 | device = lnetatmo.ThermostatData ( authorization, home_id )
543 |
544 | ```
545 |
546 | Requires :
547 | - an authorization object (ClientAuth instance)
548 | - home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using "class homedata"
549 |
550 | Return : a device object. This object contains the Relay_Plug with Thermostat and temperature modules.
551 |
552 | Methods :
553 |
554 | * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service
555 | * Output : list of IDs of every relay_plug
556 |
557 | * **Relay_Plug** :
558 | * Output : Dictionairy of First Relay object
559 |
560 | * **Thermostat_Data** :
561 | * Output : Dictionairy of Thermostat object in First Relay[Modules].
562 |
563 | Example :
564 |
565 | ```
566 | device = lnetatmo.ThermostatData(authorization, homeid)
567 | for i in device.rawData:
568 | print ('rawData')
569 | print (i['_id'])
570 | print (i['station_name'])
571 | print (dir(i))
572 | print ('modules in rawData')
573 | print (i['modules'][0]['_id'])
574 | print (i['modules'][0]['module_name'])
575 | print (' ')
576 | print ('Relay Data')
577 | Relay = device.Relay_Plug()
578 | print (Relay.keys())
579 | print ('Thermostat Data')
580 | TH = device.Thermostat_Data()
581 | print (TH.keys())
582 |
583 | ```
584 |
585 | #### 4-8 HomesData class ####
586 |
587 |
588 | Constructor
589 |
590 | ```python
591 | homesData = lnetatmo.HomesData ( authorization, home_id )
592 | ```
593 |
594 | Requires :
595 | - an authorization object (ClientAuth instance)
596 | - home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using "class homedata"
597 |
598 | Return : a homesdata object. This object contains the Netatmo actual topology and static information of
599 | all devices present into a user account. It is also possible to specify a home_id to focus on one home.
600 |
601 | Methods :
602 |
603 | * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service
604 | * Output : list of IDs of every devices
605 |
606 | Example :
607 |
608 | ```
609 | homesData = lnetatmo.HomesData ( authorization, home_id )
610 | print (homesdata.Homes_Data['name'])
611 | print (homesdata.Homes_Data['altitude'])
612 | print (homesdata.Homes_Data['coordinates'])
613 | print (homesdata.Homes_Data['country'])
614 | print (homesdata.Homes_Data['timezone'])
615 | print ('rooms in HomesData')
616 | for r in homesdata.Homes_Data.get('rooms'):
617 | print (r)
618 | print ('Devices in HomesData')
619 | for m in homesdata.Homes_Data.get('modules'):
620 | print (m)
621 | print ('Persons in HomesData')
622 | if 'persons' in homesdata.Homes_Data.keys():
623 | for P in homesdata.Homes_Data.get('persons'):
624 | print (P)
625 | print ('Schedules in HomesData')
626 | print (homesdata.Homes_Data['schedules'][0].keys())
627 |
628 | ```
629 |
630 | #### 4-9 Homecoach class ####
631 |
632 |
633 | Constructor
634 |
635 | ```python
636 | homecoach = lnetatmo.HomeCoach(authorization, home_id )
637 | ```
638 |
639 | Requires :
640 | - an authorization object (ClientAuth instance)
641 | - home_id which can be found in https://dev.netatmo.com/apidocumentation/control by using "class homedata"
642 |
643 | Return : a homecoach object. This object contains all Homecoach Data.
644 |
645 | Methods :
646 |
647 | * **rawData** : Full dictionary of the returned JSON DEVICELIST Netatmo API service
648 | * Output : list of all Homecoach in user account
649 |
650 | * **checkNotUpdated** :
651 | * Output : list of modules name for which last data update is older than specified delay (default 1 hour).
652 |
653 |
654 | * **checkUpdated** :
655 | * Output : list of modules name for which last data update is newer than specified delay (default 1 hour).
656 |
657 | Example :
658 |
659 |
660 | ```
661 | homecoach = lnetatmo.HomeCoach(authorization, homeid)
662 | #
663 | Not_updated = []
664 | updated = []
665 | d = {}
666 | for device in homecoach.rawData:
667 | _id = device['_id']
668 | d.update({'When': device['dashboard_data']['time_utc']})
669 | a = homecoach.checkNotUpdated(d, _id)
670 | b = homecoach.checkUpdated(d, _id)
671 | print (device['station_name'])
672 | print (device['date_setup'])
673 | print (device['last_setup'])
674 | print (device['type'])
675 | print (device['last_status_store'])
676 | print (device['firmware'])
677 | print (device['last_upgrade'])
678 | print (device['wifi_status'])
679 | print (device['reachable'])
680 | print (device['co2_calibrating'])
681 | print (device['data_type'])
682 | print (device['place'])
683 | print (device['dashboard_data'])
684 | Not_updated.append(a)
685 | updated.append(b)
686 | D = homecoach.HomecoachDevice['dashboard_data']
687 | print (D.keys())
688 | # dict_keys(['time_utc', 'Temperature', 'CO2', 'Humidity', 'Noise', 'Pressure', 'AbsolutePressure', 'health_idx', 'min_temp', 'max_temp', 'date_max_temp', 'date_min_temp'])
689 | print (Not_updated)
690 | print (updated)
691 |
692 | ```
693 |
694 |
695 | #### 4-10 Utilities functions ####
696 |
697 |
698 | * **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")
699 | * **toTimeString** (timestamp) : Convert a Netatmo time stamp to a readable date/time format.
700 | * **toEpoch**( dateString) : Convert a date string (form YYYY-MM-DD_HH:MM:SS) to timestamp
701 | * **todayStamps**() : Return a couple of epoch time (start, end) for the current day
702 |
703 |
704 | #### 4-11 All-in-One function ####
705 |
706 |
707 | If you just need the current temperature and humidity reported by a sensor with associated min and max values on the last 24 hours, you can get it all with only one call that handle all required steps including authentication :
708 |
709 |
710 | **getStationMinMaxTH**(station=None, module=None, home=None) :
711 | * 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).
712 | if no home is specified, first returned home will be used
713 | * Output : A tuple of 6 values (Temperature, Humidity, minT, MaxT, minH, maxH)
714 |
715 | ```python
716 | >>> import lnetatmo
717 | >>> print(lnetatmo.getStationMinMaxTH())
718 | [20, 33, 18.1, 20, 30, 34]
719 | >>>
720 | >>> print(lnetatmo.getStationMinMaxTH(module='outdoor'))
721 | [2, 53, 1.2, 5.4, 51, 74]
722 |
--------------------------------------------------------------------------------