Compare commits

...

584 Commits

Author SHA1 Message Date
Paulus Schoutsen
6603b3eccd Merge pull request #19228 from home-assistant/rc
0.84.1
2018-12-12 17:54:37 +01:00
Paulus Schoutsen
e2bf3ac095 Bumped version to 0.84.1 2018-12-12 17:18:47 +01:00
Paulus Schoutsen
ced96775fe Fix owntracks topic in encrypted ios (#19220)
* Fix owntracks topic

* Warn if per-topic secret and using HTTP
2018-12-12 17:18:38 +01:00
Jason Hunter
f65e57bf7b Add automation and script events to logbook event types (#19219) 2018-12-12 17:18:37 +01:00
Paulus Schoutsen
88cda043ac Merge pull request #19215 from home-assistant/rc
0.84
2018-12-12 14:17:53 +01:00
Paulus Schoutsen
404fbe388c Bumped version to 0.84.0 2018-12-12 11:45:42 +01:00
Paulus Schoutsen
a0bc96c20d Revert PR #18602 (#19188) 2018-12-12 11:45:20 +01:00
Paulus Schoutsen
e98476e026 Bumped version to 0.84.0b4 2018-12-11 10:33:58 +01:00
Paulus Schoutsen
aa45ff83bd Fix cloud defaults (#19172) 2018-12-11 10:33:21 +01:00
Paulus Schoutsen
029d006beb Updated frontend to 20181211.0 2018-12-11 10:30:35 +01:00
Paulus Schoutsen
e94eb686a6 Bumped version to 0.84.0b3 2018-12-10 13:00:41 +01:00
Paulus Schoutsen
2da5a02285 Add raw service data to event (#19163) 2018-12-10 13:00:35 +01:00
Paulus Schoutsen
e3b1008511 Fix lovelace save (#19162) 2018-12-10 13:00:34 +01:00
Paulus Schoutsen
cb874fefbb Drop OwnTracks bad packets (#19161) 2018-12-10 13:00:34 +01:00
phnx
0454a5fa3f home-assistant/home-assistant#18645: revert heat-cool -> auto change 2018-12-10 13:00:09 +01:00
phnx
d8f6331318 home-assistant/home-assistant#18645: Remove un-used constants. 2018-12-10 13:00:09 +01:00
phnx
d7459c73e0 home-assistant/home-assistant#18645: Fix climate mode mapping. 2018-12-10 13:00:09 +01:00
Eric Nagley
fa9fe4067a Google assistant fix target temp for *F values. (#19083)
* home-assistant/home-assistant#18524 : Add rounding to *F temps

* home-assistant/home-assistant#18524 : Linting

* simplify round behavior

* fix trailing whitespace

(thanks github editor)
2018-12-10 12:59:16 +01:00
Paulus Schoutsen
55aaa894c3 Updated frontend to 20181210.1 2018-12-10 12:50:42 +01:00
Paulus Schoutsen
18bc772cbb Bumped version to 0.84.0b2 2018-12-10 09:55:19 +01:00
arigilder
a5072f0fe4 Remove marking device tracker stale if state is stale (#19133) 2018-12-10 09:54:37 +01:00
Paulus Schoutsen
76c26da4cb Lovelace using storage (#19101)
* Add MVP

* Remove unused code

* Fix

* Add force back

* Fix tests

* Storage keyed

* Error out when storage doesnt find config

* Use old load_yaml

* Set config for panel correct

* Use instance cache var

* Make config option
2018-12-10 09:54:36 +01:00
Nick Horvath
3528d865b7 Bump skybellpy version to fix api issue (#19100) 2018-12-10 09:54:36 +01:00
Daniel Høyer Iversen
e6c224fa40 Upgrade Tibber lib (#19098) 2018-12-10 09:54:35 +01:00
Pierre Ståhl
048f219a7f Upgrade pyatv to 0.3.12 (#19085) 2018-12-10 09:54:35 +01:00
Paulus Schoutsen
945b84a7df Updated frontend to 20181210.0 2018-12-10 09:54:20 +01:00
Paulus Schoutsen
393ada0312 Bumped version to 0.84.0b1 2018-12-07 07:14:19 +01:00
Anders Melchiorsen
da160066c3 Upgrade aiolifx to 0.6.7 (#19077) 2018-12-07 07:13:35 +01:00
Bram Kragten
ff9427d463 Force refresh Lovelace (#19073)
* Force refresh Lovelace

* Check config on load

* Update __init__.py

* Update __init__.py
2018-12-07 07:13:35 +01:00
Mike Miller
3eb646eb0d Fix missing colorTemperatureInKelvin from Alexa responses (#19069)
* Fix missing colorTemperatureInKelvin from Alexa responses

* Update smart_home.py

* Add test
2018-12-07 07:13:34 +01:00
Paulus Schoutsen
578fe371c6 Revert #17745 (#19064) 2018-12-07 07:13:34 +01:00
Paulus Schoutsen
1b03a35fa1 Updated frontend to 20181207.0 2018-12-07 07:13:23 +01:00
Paulus Schoutsen
4fd4e84b72 Bumped version to 0.84.0b0 2018-12-06 09:34:21 +01:00
Daniel Høyer Iversen
d4c8024522 Add support for more Tibber Pulse data (#19033) 2018-12-06 09:30:11 +01:00
Martin Gross
72379c166e Update locationsharinglib to 3.0.9 (#19045) 2018-12-06 09:29:30 +01:00
Paulus Schoutsen
f198706767 Remove Instapush notify platform (#19051) 2018-12-06 09:28:31 +01:00
pbalogh77
f0d534cebc Implemented unique ID support for Fibaro hub integration (#19055)
* Unique ID support

New unique ID support, based on hub's serial number and device's permanent ID

* Fixes, showing attributes

Minor fixes
Showing room, hub, fibaro_id for easier mapping and finding of devices

* Update fibaro.py
2018-12-06 09:28:06 +01:00
Daniel Perna
47320adcc6 Update pyhomematic to 0.1.53 (#19056) 2018-12-06 09:25:39 +01:00
Bram Kragten
b9ed4b7a76 Fix saving YAML as JSON with empty array (#19057)
* Fix saving YAML as JSON with empty array

* Lint
2018-12-06 09:24:49 +01:00
Erik Eriksson
b71d65015a VOC: Update external dependency to fix engine start issue (#19062) 2018-12-06 09:22:49 +01:00
Paulus Schoutsen
962358bf87 Fix cloud const (#19052)
* Fix cloud const

* Fix tests
2018-12-06 09:20:53 +01:00
Paulus Schoutsen
26a38f1fae Updated frontend to 20181205.0 2018-12-06 00:30:45 +01:00
Paulus Schoutsen
83311df933 Add translations 2018-12-06 00:30:33 +01:00
emontnemery
06285d1bf3 Merge pull request #19019 from emontnemery/fix_mqtt_availability
Fix entity unavailable after reconfiguring MQTT availability
2018-12-05 22:14:37 +01:00
photinus
0aee355b14 Bump pyvizio version (#19048)
* Update vizio.py

Bump pyvizio version to reoslve get volume call and component setup failures

* Update of requirement_all
2018-12-05 16:00:49 -05:00
Fabian Affolter
b2b4712bb7 Remove Instapush notify platform 2018-12-05 21:17:02 +01:00
Sebastian Muszynski
af96694430 Remove unsupported strong mode of the Xiaomi Air Humidifier CA1 (#18926)
* Remove unsupported strong mode of the Xiaomi Air Humidifier CA1

* Clean up filter of unsupported modes
2018-12-05 20:56:43 +01:00
Erik
df346feb65 Review comments 2018-12-05 19:48:44 +01:00
Aaron Bach
08702548f3 Add support for multiple RainMachine controllers (#18989)
* Add support for multiple RainMachine controllers

* Member comments

* Member comments

* Member comments

* Cleanup

* More config flow cleanup

* Member comments
2018-12-05 10:31:32 -07:00
Teemu R
bc69309b46 Add last clean times to xiaomi vacuum (#19043) 2018-12-05 18:20:26 +01:00
Teemu R
da0542e961 Bump python-miio to 0.4.4 (#19042) 2018-12-05 18:19:30 +01:00
Jeff Irion
16e25f2039 Catch 'BrokenPipeError' exceptions for ADB commands (#19011) 2018-12-05 17:04:08 +01:00
Sébastien RAMAGE
3627de3e8a Change error to warning (#19035) 2018-12-05 15:58:46 +01:00
Glenn Waters
b31c52419d Bump version of elkm1_lib (#19030) 2018-12-05 09:31:07 -05:00
Paulus Schoutsen
578a2cf357 Small refactoring of MQTT switch (#19010) 2018-12-05 14:47:02 +01:00
emontnemery
69fd3aa856 Small refactoring of MQTT light (#19009) 2018-12-05 14:46:37 +01:00
Paulus Schoutsen
12f222b5e3 Don't wait for answer for webhook register (#19025) 2018-12-05 14:45:30 +01:00
Paulus Schoutsen
eb317bd302 Merge pull request #19036 from sdague/mychevy_1.0.1
update mychevy to 1.0.1
2018-12-05 14:44:43 +01:00
Paulus Schoutsen
ab9d1a83af Bump waterfurnace to 1.0 (#19040)
This bumps to the new version of the waterfurnace API. In the new
version the unit id is no longer manually set by the user, instead it
is retrieved from the service after login. This is less error prone as
it turns out discovering the correct unit id is hard from an end user
perspective.

Breaking change on the config, as the unit parameter is removed from
config. However I believe the number of users is very low (possibly
only 2), so adaptation should be easy.
2018-12-05 14:44:25 +01:00
Paulus Schoutsen
0e9e253b7b Fix CI by pinning IDNA (#19038)
* Fix CI

* Actual fix by @sdague
2018-12-05 14:43:29 +01:00
Bram Kragten
850caef5c1 Add states to panels (#19026)
* Add states to panels

* Line too long

* remove extra urls for states

* Update __init__.py
2018-12-05 14:27:35 +01:00
Sean Dague
8c0b50b5df Bump waterfurnace to 1.0
This bumps to the new version of the waterfurnace API. In the new
version the unit id is no longer manually set by the user, instead it
is retrieved from the service after login. This is less error prone as
it turns out discovering the correct unit id is hard from an end user
perspective.

Breaking change on the config, as the unit parameter is removed from
config. However I believe the number of users is very low (possibly
only 2), so adaptation should be easy.
2018-12-05 07:03:27 -05:00
Sean Dague
a785a1ab5d update mychevy to 1.0.1
After six months the chevy website finally has been reimplemented to
something that seems to work and is stable. The backend library has
been updated thanks to upstream help, and now is working again.
2018-12-05 05:42:27 -05:00
Paulus Schoutsen
3928d034a3 Allow checking entity permissions based on devices (#19007)
* Allow checking entity permissions based on devices

* Fix tests
2018-12-05 11:41:00 +01:00
jxwolstenholme
2680bf8a61 Update requirement btsmarthub_devicelist==0.1.3 (#18961)
* Added requirement 'btsmarthub_devicelist==0.1.2'

* Update requirements_all.txt

* Update bt_smarthub.py

* Update requirements_all.txt

* Update bt_smarthub.py
2018-12-04 23:26:20 +01:00
majuss
a8b5cc833d Lupupy version push to 0.0.17 - will now transmitted state_alarm_triggered (#19008)
* added state_alarm_triggered transmission; pushed lupupy version

* added state_alarm_triggered transmission; pushed lupupy version

* added state_alarm_triggered transmission; pushed lupupy version

* added state_alarm_triggered transmission; pushed lupupy version
2018-12-04 22:04:39 +01:00
Erik
f54710c454 Fix bug when reconfiguring MQTT availability 2018-12-04 21:25:18 +01:00
Erik
47d48c5990 Small refactoring of MQTT switch 2018-12-04 16:39:49 +01:00
Matt Hamilton
38b09b1613 Remove stale user salts code (#19004)
user['salt'] was originally used as a part of the pbkdf2 implementation.
I failed to remove this as a part of the cleanup in #18736.
2018-12-04 14:39:43 +01:00
Paulus Schoutsen
26dd490e8e Fix toon operation mode (#18966)
* Fix toon

* Update toon.py
2018-12-04 13:24:18 +01:00
Emil Stjerneman
1c99960357 Fix VOC configuration resource list (#18992) 2018-12-04 11:39:42 +01:00
Alexei Chetroi
3e1ab1b23a Sort import order of zha component. (#18993) 2018-12-04 11:38:57 +01:00
pbalogh77
2a0c2d5247 Fibaro Light fixes (#18972)
* minor fixes to color scaling

* capped input to fibaro on setcolor
2018-12-04 11:38:21 +01:00
Paulus Schoutsen
b65bffd849 Mock out device tracker configuration loading funcs in Geofency + OwnTracks (#18968)
* Mock out device tracker configuration loading funcs

* Update test_init.py

* Update test_init.py
2018-12-04 10:45:41 +01:00
cdce8p
ab7c52a9c4 Add unnecessary-pass for pylint-update (#18985) 2018-12-04 10:45:16 +01:00
Fredrik Erlandsson
d6a4e106a9 Tellduslive refactoring (#18780)
* move component to a package

* move TelldusLiveEntry to separate file

* refactor

* move entities from a shared container
* using the dispatch helper instead for communication between component and platforms

* updated covereagerc and codeowners

* suggestions from MartinHjelmare

* don't make update async

* "Strip is good!"
2018-12-04 10:08:40 +01:00
Pierre Gronlier
a6511fc0b9 remove the need to have query feature support (#18942)
* remove the need to have query feature support

Some InfluxDB servers don't have /query support feature but are still valid servers for storing data.
Usually those servers are proxies to others timeseries databases.
The change proposes to still validate the configuration but with less requirements on the server side.

* `.query` call is replaced by `.write_points`

* no more query call in the influxdb component. remove test

* reset mock after the setup and before the test

* remove unused import

* reset mock stats after component setup
2018-12-04 09:59:03 +01:00
Bram Kragten
75b855ef93 Lovelace fix: badges are removed from view after update (#18983)
* badges are removed from view after update

* Only add badges and cards when not provided in new config
2018-12-04 09:56:30 +01:00
Dom
d8a7e9ded8 Updated Yale Smart Alarm platform to new Yale API (#18990)
* Updated Yale Smart Alarm platform to use Yale's new API which replaces the deprecated version. Bumped yalesmartalarmclient to v0.1.5.

* Update requirements
2018-12-04 09:56:14 +01:00
Craig J. Midwinter
f3d7cc66e5 downgrade version of client (#18995)
* downgrade version of client

* update requirements
2018-12-04 09:52:30 +01:00
Jason Hunter
b900005d1e New Events and Context Fixes (#18765)
* Add new events for automation trigger and script run, fix context for image processing, add tests to ensure same context

* remove custom logbook entry for automation and add new automation event to logbook

* code review updates
2018-12-04 09:45:17 +01:00
Daniel Høyer Iversen
8e9c73eb18 Upgrade switchbot lib (#18980) 2018-12-04 06:48:27 +01:00
Daniel Høyer Iversen
b024c3a833 Add @danielhiversen as codeowner (#18979) 2018-12-04 06:48:16 +01:00
Daniel Høyer Iversen
31078b2b3e Merge pull request #18928 from home-assistant/tibber_err_handle
Tibber, Improve logging and error handling
2018-12-04 06:47:50 +01:00
Joakim Sørensen
ad0e3cea8a Update CODEOWNERS (#18976) 2018-12-03 21:49:15 -05:00
Bram Kragten
b5e7e45f6c no ordered dict (#18982) 2018-12-03 21:54:34 +01:00
Kevin Fronczak
4486de743d Support for mulitple Blink sync modules (#18663) 2018-12-03 20:45:12 +00:00
Daniel Høyer Iversen
df3c683023 Improve err handling 2018-12-03 20:53:18 +01:00
Erik Eriksson
d7a10136df VOC: Update library version. Moved method one step out. Instruments can be a set as well (#18967) 2018-12-03 19:52:50 +01:00
Otto Winter
c8d92ce907 Fix MQTT re-subscription logic (#18953)
* Fix MQTT re-subscription logic

* Cleanup

* Lint

* Fix
2018-12-03 19:16:58 +01:00
Fredrik Erlandsson
111a3254fb Point fix for multiple devices (#18959)
* fix for multiple devices closes, #18956

* Point API finally supports "all" events
2018-12-03 16:50:05 +01:00
Paulus Schoutsen
d028236bf2 Refactor script helper actions into their own methods (#18962)
* Refactor script helper actions into their own methods

* Lint

* Lint
2018-12-03 15:46:25 +01:00
Bram Kragten
d0751ffd91 Add id when not exist and fix dup id check (#18960)
* Add id when not exist and fix dup id check

* config possibly not be a yaml dict
2018-12-03 15:44:04 +01:00
Paulus Schoutsen
2fff0324f8 Merge remote-tracking branch 'origin/master' into dev 2018-12-03 15:26:55 +01:00
pbalogh77
149eddaf46 Initial scene support for Fibaro hubs (#18779)
* Initial scene support

Added initial support for fibaro scenes

* removed comments

* cleanup based on code review

* Removed unused functions

* grrr, my mistake.

My local pylint and flake8 are playing tricks with me

* Update homeassistant/components/scene/fibaro.py

* fixes based on code review

ABC ordered the list of platforms
changed setup platform to async
removed overloaded name property as the FibaroDevice parent class already provides this
Changed to new style string formatting

* Update homeassistant/components/scene/fibaro.py

Co-Authored-By: pbalogh77 <peter.balogh2@gmail.com>
2018-12-03 14:57:55 +01:00
Paulus Schoutsen
acd2f55d4f Merge pull request #18958 from home-assistant/rc
0.83.3
2018-12-03 13:56:35 +01:00
Paulus Schoutsen
4ef1bf2157 Bumped version to 0.83.3 2018-12-03 11:42:49 +01:00
kennedyshead
106cb63922 bump aioasuswrt version (#18955) 2018-12-03 11:42:39 +01:00
kennedyshead
f6a79059e5 fix aioasuswrt sometimes return empty lists (#18742)
* aioasuswrt sometimes return empty lists

* Bumping aioasuswrt to 1.1.12
2018-12-03 11:42:38 +01:00
Paulus Schoutsen
35690d5b29 Add users added via credentials to admin group too (#18922)
* Add users added via credentials to admin group too

* Update test_init.py
2018-12-03 11:41:04 +01:00
William Scanlon
3575c34f77 Use capability of sensor if present to fix multisensor Wink devices (#18907) 2018-12-03 11:41:03 +01:00
ludeeus
ee1c29b392 corrects , -> . typo 2018-12-03 11:40:50 +01:00
ludeeus
82d89edb4f Use dict.get('key') instead of dict['key'] 2018-12-03 11:40:50 +01:00
ludeeus
475be636d6 Fix requirements_all 2018-12-03 11:40:50 +01:00
ludeeus
f8218b5e01 Fix IndexError for home stats 2018-12-03 11:40:50 +01:00
ludeeus
79a9c1af9e bump ghlocalapi to use clear_scan_result 2018-12-03 11:40:03 +01:00
ludeeus
6de0ed3f0a Fix stability issues with multiple units 2018-12-03 11:40:03 +01:00
Andrew Hayworth
1d717b768d bugfix: ensure the google_assistant component respects allow_unlock (#18874)
The `Config` object specific to the `google_assistant` component
had a default value for `allow_unlock`. We were not overriding this
default when constructing the Config object during `google_assistant`
component setup, whereas we do when setting up the `cloud` component.

To fix, we thread the `allow_unlock` parameter down through http setup,
and ensure that it's set correctly. Moreover, we also change the
ordering of the `Config` parameters, and remove the default. Future
refactoring should not miss it, as it is now a required parameter.
2018-12-03 11:38:43 +01:00
William Scanlon
85c0de550c Use capability of sensor if present to fix multisensor Wink devices (#18907) 2018-12-03 11:34:22 +01:00
Paulus Schoutsen
d2b62840f2 Add users added via credentials to admin group too (#18922)
* Add users added via credentials to admin group too

* Update test_init.py
2018-12-03 11:34:01 +01:00
kennedyshead
17c6ef5d54 bump aioasuswrt version (#18955) 2018-12-03 11:13:06 +01:00
cdce8p
3904d83c32 Extend partial reload to include packages (#18884)
* Merge packages after partial reload

* Remove merge from core reload & test

* Integrate merge in 'async_hass_config_yaml'

* Merge executors
2018-12-03 10:56:26 +01:00
Oliver
f3946cb54f Push to version 0.7.7 of denonavr (#18917) 2018-12-03 10:07:43 +01:00
James Hilliard
832fa61477 Initial hlk-sw16 relay switch support (#17855)
* Initial hlk-sw16 relay switch support

* remove entity_id and validate relay id's

* Bump hlk-sw16 library version and cleanup component

* refactor hlk-sw16 switch platform loading

* Use voluptuous to coerce relay id to string

* remove force_update for SW16Switch

* Move to callback based hlk-sw16 relay state changes

* fix hlk-sw16 default port and cleanup some unused variables

* Refactor to allow registration of multiple HLK-SW16 device

* Store protocol in instance variable instead of class variable

* remove is_connected

* flake8 style fix

* Move reconnect logic into HLK-SW16 client library

* Cleanup and improve logging

* Load hlk-sw16 platform entities at same time per device

* scope SIGNAL_AVAILABILITY to device_id

* Fixes for connection resume

* move device_client out of switches loop

* Add timeout for commands and keep alive

* remove unused variables
2018-12-03 09:31:53 +01:00
Andrew Hayworth
5ae65142b8 Allow verisure locks to be configured with a default code (#18873)
* Allow verisure locks to be configured with a default code

* linting fix

* PR feedback

* PR feedback - try harder to prevent future typos

A python mock is a magical thing, and will respond to basicaly
any method you call on it. It's somewhat better to assert against
an explicit variable named 'mock', rather than to assert on the
method name you wanted to mock... could prevent a typo from messing up
tests.

* PR feedback: convert tests to integration-style tests

Set up a fake verisure hub, stub out a _lot_ of calls, then test
after platform discovery and service calls.

It should be noted that we're overriding the `update()` calls in
these tests. This was done to prevent even further mocking of
the verisure hub's responses.

Hopefully, this'll be a foundation for people to write more tests.

* more pr feedback
2018-12-03 07:25:54 +01:00
GeoffAtHome
eb584a26e2 Add lightwave components for switches and lights (#18026)
* Added lightwave components for switches and lights.

* Address warnings raised by Hound

* Correcting lint messages and major typo. This time tested before commit.

* Trying to fix author

* Minor lint changes

* Attempt to correct other lint error.

* Another lint attempt.

* More lint issues.

* Last two lint errors! Hurrah.

* Changes after review from fabaff.

* Moved device dependent code to PyPi.

* Replaced DEPENDENCIES with REQUIREMENTS

* Updated following code review from Martin Hjelmare.

* Added lightwave to requirements_all.txt

* Omit lightwave from tests.

* Updated requirements_all.txt

* Refactored how lightwave lights and switches load.

* Removed imports that were no longer required.

* Add guard for no discovery_info.

* Make it a guard clause and save indentation. Rename LRFxxx to LWRFxxx.

* Sorted imports to match style guidelines.

* Correct return value.

* Update requirements_all.txt

* Catch case where we have no lights or switches configured.

* Improve configuration validation.
2018-12-02 20:58:31 +01:00
emontnemery
87fb492b14 Remove commented out code (#18925) 2018-12-02 19:12:03 +01:00
Paulus Schoutsen
d1a621601d No more opt-out auth (#18854)
* No more opt-out auth

* Fix var
2018-12-02 16:32:53 +01:00
emontnemery
ae9e3d83d7 Reconfigure MQTT switch component if discovery info is changed (#18179) 2018-12-02 16:16:46 +01:00
emontnemery
afa99915e3 Reconfigure MQTT light component if discovery info is changed (#18176) 2018-12-02 16:16:36 +01:00
Martin Fuchs
bb13829e13 Set sensor to unavailable if battery is dead. (#18802) 2018-12-02 16:01:18 +01:00
Daniel Høyer Iversen
fb12294bb7 remove unused import 2018-12-02 15:54:52 +01:00
Vladimir Eremin
debae6ad2e Fix hdmi_cec entity race (#18753)
* Update shouldn't be called before adding the entity.
* Transitional states from
  8adc786bac/include/cectypes.h (L458-L459)

Addressing https://github.com/home-assistant/home-assistant/issues/12846
2018-12-02 15:51:04 +01:00
Otto Winter
eec4564c71 Show ANSI color codes in logs in Hass.io (#18834)
* Hass.io: Show ANSI color codes in logs

* Lint

* Fix test

* Lint
2018-12-02 15:46:14 +01:00
Daniel Høyer Iversen
08dbd792cd Improve logging and error handling 2018-12-02 15:35:59 +01:00
Andrew Hayworth
b7e2522083 bugfix: ensure the google_assistant component respects allow_unlock (#18874)
The `Config` object specific to the `google_assistant` component
had a default value for `allow_unlock`. We were not overriding this
default when constructing the Config object during `google_assistant`
component setup, whereas we do when setting up the `cloud` component.

To fix, we thread the `allow_unlock` parameter down through http setup,
and ensure that it's set correctly. Moreover, we also change the
ordering of the `Config` parameters, and remove the default. Future
refactoring should not miss it, as it is now a required parameter.
2018-12-02 11:14:46 +01:00
Paulus Schoutsen
a62fc7ca04 Use string formatting (#18886)
* Use string formatting

* Fix lint issue

* Fix change
2018-12-02 10:53:09 +01:00
pbalogh77
0a68cae507 Fibaro ubs (#18889)
* Fibaro HC connection, initial commit

Very first steps working, connects, fetches devices, represents sensors, binary_sensors and lights towards HA.

* Cover, switch, bugfixes

Initial support for covers
Initial support for switches
Bugfixes

* Some cleanup and improved lights

pylint based cleanup
light switches handled properly
light features reported correctly

* Added status updates and actions

Lights, Blinds, Switches are mostly working now

* Code cleanup, fiblary3 req

Fiblary3 is now in pypi, set it as req
Cleanup based on pylint

* Included in .coveragerc and added how to use guide

Included the fibaro component in coveragerc
Added usage instructions to file header

* PyLint inspired fixes

Fixed pylint warnings

* PyLint inspired fixes

PyLint inspired fixes

* updated to fiblary3 0.1.5

* Minor fixes to finally pass pull req

Fixed fiblary3 to work with python 3.5
Updated fiblary3 to 0.1.6
(added energy and batteryLevel dummies)

* module import and flake8 fixes

Finally (hopefully) figured out what lint is complaining about

* Fixed color support for lights, simplified callback

Fixed color support for lights
Simplified callback for updates
Uses updated fiblary3 for color light handling

* Lean and mean refactor

While waiting for a brave reviewer, I've been making the code smaller and easier to understand.

* Minor fixes to please HoundCI

* Removed unused component

Scenes are not implemented yet

* Nicer comments.

* DEVICE_CLASS, ignore plugins, improved mapping

Added support for device class and icons in sensors and binary_sensors
Improved mapping of sensors and added heuristic matching
Added support for hidden devices
Fixed conversion to float in sensors

* Fixed dimming

Fibaro apparently does not need, nor like the extra turnOn commands for dimmers

* flake8

* Cleanup, Light fixes, switch power

Cleanup of the component to separate init from connect, handle connection error better
Improved light handling, especially for RGBW strips and working around Fibaro quirks
Added energy and power reporting to switches

* Missing comment added

Missing comment added to please flake8

* Removed everything but bin.sensors

Stripdown, hoping for a review

* better aligned comments

OMG

* Fixes based on code review

Fixes based on code review

* Implemented stopping

Implemented stopping of StateHandler thread
Cleanup for clarity

* Minor fix

Removed unnecessary list copying

* Nicer wording on shutdown

* Minor changes based on code review

* minor fixes based on code review

* removed extra line break

* Added Fibaro omcponents

Added cover, light, sensor and switch components

* Improved support for Fibaro UBS

Improved support for Fibaro Universal Binary Sensor, when configured to flood sensor or motion sensor.
2018-12-02 10:52:37 +01:00
Adam Mills
a10cbadb57 Restore states when removing/adding entities (#18890) 2018-12-02 10:51:15 +01:00
emontnemery
bbb40fde84 Optionally do not log template rendering errors (#18724) 2018-12-02 10:31:46 +01:00
emontnemery
ce218b172a Small refactoring of MQTT climate (#18814) 2018-12-02 10:30:07 +01:00
emontnemery
2e4e673bbe Small refactoring of MQTT alarm (#18813) 2018-12-02 10:29:31 +01:00
emontnemery
db4a0e3244 Small refactoring of MQTT cover (#18850) 2018-12-02 10:27:50 +01:00
Daniel Høyer Iversen
de82df3c6b Merge pull request #18892 from home-assistant/upgrade-sphinx
Upgrade Sphinx to 1.8.2
2018-12-02 09:57:52 +01:00
Daniel Høyer Iversen
3bc83920b4 Merge branch 'dev' into upgrade-sphinx 2018-12-02 08:46:34 +01:00
Daniel Høyer Iversen
253dc66129 Merge pull request #18895 from home-assistant/upgrade-slacker
Upgrade slacker to 0.11.0
2018-12-02 08:45:02 +01:00
Daniel Høyer Iversen
b063547138 Merge pull request #18851 from emontnemery/mqtt_fan_refactor
Small refactoring of MQTT fan
2018-12-02 08:43:56 +01:00
Daniel Høyer Iversen
d8c6cb1112 Merge pull request #18852 from emontnemery/mqtt_sensor_refactor
Small refactoring of MQTT sensor
2018-12-02 08:40:57 +01:00
Daniel Høyer Iversen
5b0c12b12b Merge pull request #18864 from meatheadmike/dev
Bump pywemo to 0.4.33 (expanded port range fixes dimmers on latest firmware)
2018-12-02 08:38:37 +01:00
Daniel Høyer Iversen
ba372c085c Merge pull request #18880 from ludeeus/tautulli-fix
Fixes error with getting attributes from Tautulli
2018-12-02 08:35:30 +01:00
Daniel Høyer Iversen
2c36f4411e Merge pull request #18879 from ludeeus/multiple-googlehome
Fix stability issues with multiple googlehome units
2018-12-02 08:33:33 +01:00
Daniel Høyer Iversen
8eb9445bea Merge pull request #18904 from home-assistant/upgrade-Pillow
Upgrade pillow to 5.3.0
2018-12-02 08:28:27 +01:00
Daniel Høyer Iversen
456cec2931 Merge pull request #18903 from home-assistant/upgrade-ruamel.yaml
Upgrade ruamel.yaml to 0.15.80
2018-12-02 08:28:04 +01:00
Daniel Høyer Iversen
af7fe8c4fd Merge pull request #18902 from home-assistant/upgrade-restrictedpython
Upgrade restrictedpython to 4.0b7
2018-12-02 08:27:40 +01:00
Daniel Høyer Iversen
41ad04276b Upgrade sphinx-autodoc-typehints to 1.5.1 (#18893) 2018-12-02 08:26:46 +01:00
Fabian Affolter
e591234b59 Upgrade keyring to 17.0.0 (#18901) 2018-12-02 08:26:23 +01:00
Fabian Affolter
9f3c9cdb11 Upgrade pillow to 5.3.0 2018-12-02 00:30:02 +01:00
Fabian Affolter
48b8fc9e01 Upgrade ruamel.yaml to 0.15.80 2018-12-02 00:17:41 +01:00
Fabian Affolter
4807ad7875 Upgrade restrictedpython to 4.0b7 2018-12-02 00:11:47 +01:00
Fabian Affolter
7b6893c9d3 Fix change 2018-12-01 22:08:15 +01:00
Fabian Affolter
4b85ffae4f Upgrade slacker to 0.11.0 2018-12-01 22:01:22 +01:00
Fabian Affolter
2ca4893948 Upgrade sphinx-autodoc-typehints to 1.5.1 2018-12-01 21:48:56 +01:00
Fabian Affolter
9156a827ce Upgrade Sphinx to 1.8.2 2018-12-01 21:45:16 +01:00
ludeeus
1dac84e9dd corrects , -> . typo 2018-12-01 21:34:31 +01:00
ludeeus
da715c2a03 Use dict.get('key') instead of dict['key'] 2018-12-01 21:32:31 +01:00
Fabian Affolter
fc1a4543d3 Fix lint issue 2018-12-01 20:57:39 +01:00
Fabian Affolter
54904fb6c0 Use string formatting 2018-12-01 19:27:21 +01:00
Michael Nosthoff
bd09e96681 Reintroduce unique_id for Netatmo sensor (#18774)
* netatmo: make module type identification more consistent

For the interpretation of voltage values the different types of netatmo
modules need to be distinguished. This is currently done by selecting
the second character of the modules '_id'. The _id-field actually
contains a mac address. This is an undocumented way of identifying the
module_type.

The netatmo API also delivers a field called 'type' which provides a
more consistent way to differentiate the fields. This commit introduces
a differentiation which uses this provided type. This should improve
readability.

Also the field module_id is renamed to module_type which should better
resemble what it actually represents.

* netatmo: reintroduce unique_id using actual module mac address

Each netatmo module features a unique MAC-Address. The base station uses
an actual assigned MAC Address it also uses on the Wifi it connects to.
All other modules have unique MAC Addresses which are only assigned and
used by Netatmo on the internal Wireless-Network. All theses Addresses
are exposed via the API. So we could use the combination
MAC-Address-Sensor_type as unique_id.

In a previous commit this had already been tried but there was a
misunderstanding in what the 'module_id' represented. It was actually
only a module_type representation so it clashed when two modules of the
same type where used.

* Netatmo: fixed line length
2018-12-01 18:00:49 +01:00
ludeeus
8e84401b68 bump ghlocalapi to use clear_scan_result 2018-12-01 16:28:22 +01:00
ludeeus
934eccfeee Fix stability issues with multiple units 2018-12-01 14:55:50 +01:00
ludeeus
89bd6fa494 Fix requirements_all 2018-12-01 14:51:32 +01:00
ludeeus
d8b9bee7fb Fix IndexError for home stats 2018-12-01 14:51:32 +01:00
Joakim Sørensen
558504c686 Fix ordinal filter in template (#18878) 2018-12-01 14:49:34 +01:00
Eliseo Martelli
c69fe43e75 fixed state case for rtorrent (#18778) 2018-12-01 12:00:35 +01:00
Carlos Gustavo Sarmiento
29f15393b1 Updated UVC camera component to support SSL connections (#18829) 2018-12-01 11:58:59 +01:00
Mahasri Kalavala
c23792d1fb Added new filters for templates (#18125)
* added additional filters

Added base64_encode, base64_decode and ordinal filters.

* added test cases

added test cases for base64_encode, base64_decode and ordinal filters.

* forgot to add filters :)
2018-12-01 10:38:10 +01:00
damarco
1ae58ce48b Add support for zha device registry (#18755) 2018-12-01 10:31:49 +01:00
ehendrix23
ecca51b16b Add tests for directv platform (#18590)
* Create test for platform

Created test for platform.
Added media_stop to common.py test

* Multiple improvements

Fixed lint issue in common.py
Fixed lint issues in test_directv.py
Improved patching import using modile_patcher.start() and stop()
Added asserts for service calls.

* Updates based on Martin's review

Updates based on Martin's review.

* Updated test based on PR#18474

Updated test to use service play_media instead of select_source based on change from PR18474

* Lint issues

Lint issues

* Further updates based on feedback

Updates based on feedback provided.

* Using async_load_platform for discovery test

Using async_load_platform for discovery tests.
Added asserts to ensure entities are created with correct names.

* Used HASS event_loop to setup component

Use HASS event_loop to setup the component async.

* Updated to use state machine for # entities

Updated to use state machine to count # entities instead of entities.

* Use hass.loop instead of getting current loop

Small update to use hass.loop instead, thanks Martin!

* Forgot to remove asyncio

Removed asyncio import.

* Added fixtures

Added fixtures.

* Remove not needed updates and assertions

* Return mocked dtv instance from side_effect

* Fix return correct fixture instance

* Clean up assertions

* Fix remaining patches

* Mock time when setting up component in fixture

* Patch time correctly

* Attribute _last_update should return utcnow
2018-12-01 10:28:27 +01:00
Aaron Bach
3a854f4c05 Fix issues with 17track.net sensor names (#18860) 2018-11-30 21:54:40 -07:00
Aaron Bach
c24ddfb1be Bump py17track to 2.1.1 (#18861) 2018-11-30 21:12:55 -07:00
meatheadmike
0754a63969 Bumped pywemo to 0.4.33 2018-11-30 14:03:32 -07:00
meatheadmike
8a75bee82f bump pywemo to 0.4.33
Bump pywemo to 0.4.33 - includes expended port range fix for dimmers
2018-11-30 14:00:26 -07:00
Paulus Schoutsen
df21dd21f2 RFC: Call services directly (#18720)
* Call services directly

* Simplify

* Type

* Lint

* Update name

* Fix tests

* Catch exceptions in HTTP view

* Lint

* Handle ServiceNotFound in API endpoints that call services

* Type

* Don't crash recorder on non-JSON serializable objects
2018-11-30 21:28:35 +01:00
Paulus Schoutsen
bac48aa9d2 Merge pull request #18857 from home-assistant/rc
0.83.2
2018-11-30 20:09:29 +01:00
Paulus Schoutsen
53cbb28926 Fix flaky geofency test (#18855) 2018-11-30 20:06:10 +01:00
Erik Eriksson
d7809c5398 Update of volvooncall component (#18702) 2018-11-30 19:07:42 +01:00
Paulus Schoutsen
9b3373a15b Bumped version to 0.83.2 2018-11-30 17:53:14 +01:00
pbalogh77
474909b515 Hotfix for Fibaro wall plug (#18845)
Fibaro wall plug with a lamp plugged in was misrecognized as a color light, generating crashes in the update function.
2018-11-30 17:53:04 +01:00
Paulus Schoutsen
80f2c2b124 Always set hass_user (#18844) 2018-11-30 17:53:04 +01:00
Darren Foo
ada148eeae bump gtts-token to 1.1.3 (#18824) 2018-11-30 17:53:03 +01:00
emontnemery
449cde5396 Revert change to MQTT discovery_hash introduced in #18169 (#18763) 2018-11-30 17:53:03 +01:00
Paulus Schoutsen
d014517ce2 Always set hass_user (#18844) 2018-11-30 17:32:47 +01:00
pbalogh77
8f50180598 Hotfix for Fibaro wall plug (#18845)
Fibaro wall plug with a lamp plugged in was misrecognized as a color light, generating crashes in the update function.
2018-11-30 17:23:25 +01:00
Erik
1686f73749 Small refactoring of MQTT sensor 2018-11-30 16:53:56 +01:00
Erik
deb9a1133c Small refactoring of MQTT fan 2018-11-30 16:53:14 +01:00
Matt Schmitt
e0f0487ce2 Add services description (#18839) 2018-11-30 16:31:35 +01:00
Daniel Høyer Iversen
44e35ec9a1 update netatmo library (#18823) 2018-11-30 08:45:40 -05:00
emontnemery
a9990c130d Revert change to MQTT discovery_hash introduced in #18169 (#18763) 2018-11-30 13:57:17 +01:00
Darren Foo
fcdb25eb3c bump gtts-token to 1.1.3 (#18824) 2018-11-30 11:18:24 +01:00
Heine Furubotten
4bee3f760f Add Entur departure information sensor (#17286)
* Added Entur departure information sensor.

* Fixed houndci-bot comments.

* Removed tailing whitespace.

* Fixed some comments from tox lint.

* Improved docstring, i think.

* Fix for C1801

* Unit test for entur platform setup

* Rewritten entur component to have pypi dependecy.

* Propper client id for api usage.

* Minor cleanup of usage of constants.

* Made location output configurable.

* Cleaned up usage of constants.

* Moved logic to be contained within setup or update methods.

* Moved icon consts to root in module.

* Using config directly in test

* Minor changes
2018-11-30 09:06:59 +01:00
Andrew Hayworth
5f53627c0a Bump python_awair to 0.0.3 (#18819) 2018-11-30 08:47:05 +01:00
Adam Mills
22f27b8621 Store state last seen time separately (#18806)
* Store state last seen time separately

This ensures that infrequently updated entities aren't accidentally
dropped from the restore states store

* Fix mock restore cache
2018-11-30 08:26:19 +01:00
ehendrix23
a9dc4ba297 Increase pyatv to 0.3.11 (#18801) 2018-11-29 23:44:29 +01:00
Paulus Schoutsen
3701c0f219 Merge pull request #18811 from home-assistant/rc
0.83.1
2018-11-29 23:18:13 +01:00
ehendrix23
a035725c67 Service already discovered log entry (#18800)
Add debug log entry if service is already discovered.
2018-11-29 23:15:48 +01:00
Paulus Schoutsen
440614dd9d Use proper signals (#18613)
* Emulated Hue not use deprecated handler

* Remove no longer needed workaround

* Add middleware directly

* Dont always load the ban config file

* Update homeassistant/components/http/ban.py

Co-Authored-By: balloob <paulus@home-assistant.io>

* Update __init__.py
2018-11-29 23:05:23 +01:00
Paulus Schoutsen
163c881ced Bumped version to 0.83.1 2018-11-29 22:58:06 +01:00
pbalogh77
0467d0563a Hotfix for crash with virtual devices (#18808)
* Quickfix for crash with virtual devices

Added try/except to critical loops of processing
Reinforced read_devices, map_device_to_type and update processing

* oops
2018-11-29 22:57:45 +01:00
pbalogh77
2b52f27eb9 Hotfix for crash with virtual devices (#18808)
* Quickfix for crash with virtual devices

Added try/except to critical loops of processing
Reinforced read_devices, map_device_to_type and update processing

* oops
2018-11-29 22:57:05 +01:00
Aaron Bach
31d7221c90 Remove additional self from update function in RainMachine (#18810) 2018-11-29 22:51:16 +01:00
Daniel Høyer Iversen
d9124b182a Remove self from update function in rainmachine (#18807) 2018-11-29 22:51:15 +01:00
Aaron Bach
f2b818658f Bumped py17track to 2.1.0 (#18804) 2018-11-29 22:51:15 +01:00
Eric Nagley
5a6ac9ee72 BUGFIX: handle extra fan speeds. (#18799)
* BUGFIX: add support for extra fan speeds.

* Drop extra fan speeds.

Remove catch all, drop missing fan speeds.

* fix self.speed_synonyms call. Remove un-needed keys() call
2018-11-29 22:51:14 +01:00
Paulus Schoutsen
7fa5f07218 Fix race condition in group.set (#18796) 2018-11-29 22:51:13 +01:00
Paulus Schoutsen
fa9a200e3c Render the secret (#18793) 2018-11-29 22:51:13 +01:00
Paulus Schoutsen
0ca67bf6f7 Make auth backwards compat again (#18792)
* Made auth not backwards compat

* Fix tests
2018-11-29 22:51:12 +01:00
cdce8p
f1c5e756ff Fix logbook domain filter - alexa, homekit (#18790) 2018-11-29 22:51:12 +01:00
Paulus Schoutsen
ff33d34b81 Legacy api fix (#18733)
* Set user for API password requests

* Fix tests

* Fix typing
2018-11-29 22:51:11 +01:00
Ian Richardson
601389302a Convert shopping-list update to WebSockets (#18713)
* Convert shopping-list update to WebSockets

* Update shopping_list.py

* Update test_shopping_list.py
2018-11-29 22:51:10 +01:00
Ian Richardson
2ba521caf8 Add websocket call for adding item to shopping-list (#18623) 2018-11-29 22:51:10 +01:00
Aaron Bach
6f7ff9a18a Remove additional self from update function in RainMachine (#18810) 2018-11-29 14:47:41 -07:00
Daniel Høyer Iversen
4bc9e6dfe0 Remove self from update function in rainmachine (#18807) 2018-11-29 22:28:27 +01:00
Paulus Schoutsen
28215d7edd Make auth backwards compat again (#18792)
* Made auth not backwards compat

* Fix tests
2018-11-29 22:26:19 +01:00
Paulus Schoutsen
38ecf71307 Fix race condition in group.set (#18796) 2018-11-29 22:26:06 +01:00
Eric Nagley
4e272624eb BUGFIX: handle extra fan speeds. (#18799)
* BUGFIX: add support for extra fan speeds.

* Drop extra fan speeds.

Remove catch all, drop missing fan speeds.

* fix self.speed_synonyms call. Remove un-needed keys() call
2018-11-29 22:24:53 +01:00
Aaron Bach
ab4d0a7fc3 Bumped py17track to 2.1.0 (#18804) 2018-11-29 22:24:32 +01:00
Paulus Schoutsen
ca74f5efde Render the secret (#18793) 2018-11-29 22:17:01 +01:00
Eric Nagley
e50a6ef8af Add support for Mode trait in Google Assistant. (#18772)
* Add support for Mode trait in Google Assistant.

* Simplify supported logic.

* Fix SUPPORTED_MODE_SETTINGS to correct rip failures.

* more stray commas

* update tests.
2018-11-29 21:14:17 +01:00
Eliseo Martelli
5c026b1fa2 Added qbittorrent sensor platform (#18618)
* added qbittorrent sensor platform

* Added requirements

* linting

* disabled broad-except

* added noqa

* removed pass statement (left that from development session)

* Added to coveragerc & moved to async

* fixed linting

* fixed indentation

* removed white space

* added await

* Removed generic exception

* removed pylint disable

* added auth checks

* linting

* fixed linting

* fixed error

* should be fixed now

* linting

* ordered imports

* added requested changes

* Update homeassistant/components/sensor/qbittorrent.py

Co-Authored-By: eliseomartelli <martely98@gmail.com>

* Update qbittorrent.py

* Minor changes
2018-11-29 20:40:26 +01:00
cdce8p
474567e762 Fix logbook domain filter - alexa, homekit (#18790) 2018-11-29 20:16:39 +01:00
Fabian Affolter
16911a5cb4 Update lang list (fixes #18768) (#18773)
* Update lang list (fixes #18768)

* Fix lint issues
2018-11-29 19:14:14 +01:00
Daniel Høyer Iversen
46389fb6ca Update switchmate lib (#18785) 2018-11-29 19:13:08 +01:00
Paulus Schoutsen
9aeb489282 Raise NotImplementedError (#18777) 2018-11-29 16:40:49 +01:00
Daniel Høyer Iversen
8c9a39845c Round average price for Tibber (#18784) 2018-11-29 16:39:39 +01:00
Fabian Affolter
c976ac3b39 Fix lint issues 2018-11-29 12:28:50 +01:00
mdallaire
07a7ee0ac7 Add more waterfurnace sensors (#18451)
Add the following sensors that provide interesting data when using a variable speed geothermal system:

* Compressor Power
* Fan Power
* Aux Power
* Loop Pump Power
* Compressor Speed
* Fan Speed
2018-11-29 06:04:12 -05:00
Paulus Schoutsen
c6c55c4419 Merge pull request #18776 from home-assistant/rc
0.83
2018-11-29 11:45:20 +01:00
Paulus Schoutsen
1364114dc1 Bumped version to 0.83.0 2018-11-29 10:57:40 +01:00
Ian Richardson
a306475065 Convert shopping-list clear to WebSockets (#18769) 2018-11-29 10:06:18 +01:00
Fabian Affolter
faeaa43393 Update lang list (fixes #18768) 2018-11-29 09:26:48 +01:00
ehendrix23
aadf72d445 Fix statistics for binary sensor (#18764)
* Fix statistics for binary sensor

-) Binary sensors have 'on' and 'off' for state resulting in issue as numbers were expected. Fixed so that it works with non-numeric states as well.
-) Added check to skip unknown states.
-) Updates test so that binary sensor test will use non-numeric values for states.

* Using guard clause and changed debug to error

Changed to use a guard clause for state unknown.
Writing error on value error instead of debug.

* Add docstring
2018-11-29 09:01:56 +01:00
Paulus Schoutsen
05915775e3 Bumped version to 0.83.0b3 2018-11-28 22:47:37 +01:00
Paulus Schoutsen
311c796da7 Default to on if logged in (#18766) 2018-11-28 22:47:09 +01:00
Paulus Schoutsen
f860cac4ea OwnTracks Config Entry (#18759)
* OwnTracks Config Entry

* Fix test

* Fix headers

* Lint

* Username for android only

* Update translations

* Tweak translation

* Create config entry if not there

* Update reqs

* Types

* Lint
2018-11-28 22:47:08 +01:00
Adam Mills
58e0ff0b1b Async tests for owntracks device tracker (#18681) 2018-11-28 22:47:08 +01:00
Paulus Schoutsen
48e28843e6 OwnTracks Config Entry (#18759)
* OwnTracks Config Entry

* Fix test

* Fix headers

* Lint

* Username for android only

* Update translations

* Tweak translation

* Create config entry if not there

* Update reqs

* Types

* Lint
2018-11-28 22:20:13 +01:00
Paulus Schoutsen
e06fa0d2d0 Default to on if logged in (#18766) 2018-11-28 22:17:37 +01:00
ehendrix23
0bdf96d94c Add block after setting up component (#18756)
Added a block_till_done after setting up component and before starting HASS.
2018-11-28 16:14:37 +01:00
Fabian Affolter
623cec206b Upgrade Adafruit-DHT to 1.4.0 (fixes #15847) (#18614) 2018-11-28 13:38:26 +01:00
Paulus Schoutsen
a2386f871d Forbid float NaN in JSON (#18757) 2018-11-28 13:25:23 +01:00
Adam Mills
5c3a4e3d10 Restore states through a JSON store instead of recorder (#17270)
* Restore states through a JSON store

* Accept entity_id directly in restore state helper

* Keep states stored between runs for a limited time

* Remove warning
2018-11-28 13:16:43 +01:00
Diogo Gomes
a039c3209b Replace token in camera.push with webhook (#18380)
* replace token with webhook

* missing PR 18206 aditions

* remove unused property

* increase robustness

* lint

* address review comments

* id -> name
2018-11-28 10:36:29 +01:00
majuss
fc8b1f4968 Update lupupy version to 0.0.13 (#18754)
* lupupy version push
2018-11-27 21:21:27 -05:00
damarco
052d305243 Add config entry for ZHA (#18352)
* Add support for zha config entries

* Add support for zha config entries

* Fix node_config retrieval

* Dynamically load discovered entities

* Restore device config support

* Refactor loading of entities

* Remove device registry support

* Send discovery_info directly

* Clean up discovery_info in hass.data

* Update tests

* Clean up rebase

* Simplify config flow

* Address comments

* Fix config path and zigpy check timeout

* Remove device entities when unloading config entry
2018-11-27 21:21:25 +01:00
ehendrix23
43676fcaf4 Moved stop method and registering STOP_EVENT outside of init (#18582)
* Moved stop method and registering outside of init

Moved the cleanup to a seperate method and perform registering for the event in setup.

* Removed use of global variable

Removed use of global variable.

* Removed API_SESSIONS

Removed unused declaration API_SESSIONS.
2018-11-27 20:41:25 +01:00
Paulus Schoutsen
f3047b9c03 Fix logbook filtering entities (#18721)
* Fix logbook filtering entities

* Fix flaky test
2018-11-27 20:16:32 +01:00
Paulus Schoutsen
775c909a8c Bumped version to 0.83.0b2 2018-11-27 20:15:57 +01:00
Paulus Schoutsen
3a8303137a Add permission checks to Rest API (#18639)
* Add permission checks to Rest API

* Clean up unnecessary method

* Remove all the tuple stuff from entity check

* Simplify perms

* Correct param name for owner permission

* Hass.io make/update user to be admin

* Types
2018-11-27 20:15:48 +01:00
Aaron Bach
093fa6f5e9 Bumped simplisafe-python to 3.1.14 (#18752) 2018-11-27 11:40:49 -07:00
Anton Johansson
dd8544fdf8 Fix typo in log (#18751) 2018-11-27 13:09:25 -05:00
Bryan York
02309cc318 Enable Google Assistant OnOffTrait for climate devices that support them (#18544)
* Enable Google Assistant OnOffTrait for climate devices that support them

This commit enables the OnOffTrait for climate devices that have the SUPPORT_ON_OFF feature. I have tested this locally with a Sensibo device which supports ON_OFF and a nest device that does not.

* Update trait.py

* Add tests for onoff_climate

* Add OnOff trait to climate.heatpump

* Add on status to heatpump in google_assistant tests
2018-11-27 17:11:55 +01:00
Austin
2f07e92cc2 Fix decora_wifi residences (#17228)
* Fix decora multiple residences

* Fix typo

* Update decora_wifi.py
2018-11-27 16:53:28 +01:00
Luis Martinez de Bartolome Izquierdo
7b3b7d2eec Wunderlist component (#18339)
* Wunderlist component

* Check credentials

* Dont print credentials

* Update __init__.py
2018-11-27 15:44:09 +01:00
Fredrik Erlandsson
5d5c78b374 Add unique_id for Daikin entities (#18747) 2018-11-27 15:36:55 +01:00
Fredrik Erlandsson
eb2e2a116e Add unique_id for tellduslive (#18744) 2018-11-27 15:35:51 +01:00
Fredrik Erlandsson
392898e694 Updated codeowners (#18746) 2018-11-27 14:59:25 +01:00
Jason Hu
4d5338a1b0 Fix google assistant request sync service call (#17415)
* Update __init__.py

* Add optional agent_user_id field to request_sync service

* Update services.yaml
2018-11-27 14:57:42 +01:00
kennedyshead
87507c4b6f fix aioasuswrt sometimes return empty lists (#18742)
* aioasuswrt sometimes return empty lists

* Bumping aioasuswrt to 1.1.12
2018-11-27 08:20:25 -05:00
Luis Martinez de Bartolome Izquierdo
9d1b94c24a Supports the new Netatmo Home Coach (#18308)
* Supports the new Netatmo Home Coach

* unused import

* Missing docstring

* Fixed pylint

* pydocs

* doc style
2018-11-27 14:01:34 +01:00
emontnemery
16e3ff2fec Mqtt light refactor (#18227)
* Rename mqtt light files

* Refactor mqtt light

* Remove outdated testcase

* Add backwards compatibility for MQTT discovered MQTT lights.
Refactor according to review comments.
2018-11-27 14:00:05 +01:00
Robert Dunmire III
c1ed2f17ac Update librouteros and re-connect to api if connection is lost (#18421)
* Reconnect when connection is lost

* Fix tabs

* add librouteros.exceptions

* add logger

* fix line too long

* added import librouteros

* Update librouteros version

* Update mikrotik.py

* Update mikrotik.py

* Fix trailing whitespace

* Update mikrotik.py

* Update mikrotik.py
2018-11-27 13:26:52 +01:00
Fabian Affolter
1cbe080df9 Fix remaining issues (#18416) 2018-11-27 13:21:42 +01:00
Malte Franken
61e0e11156 Geo Location platform code clean up (#18717)
* code cleanup to make use of new externalised feed manager

* fixed lint

* revert change, keep asynctest

* using asynctest

* changed unit test from mocking to inspecting dispatcher signals

* code clean-up
2018-11-27 13:12:29 +01:00
Malte Franken
013e181497 U.S. Geological Survey Earthquake Hazards Program Feed platform (#18207)
* new platform for usgs earthquake hazards program feed

* lint and pylint issues

* fixed config access

* shortened names of platform, classes, etc.

* refactored tests

* fixed hound

* regenerated requirements

* refactored tests

* fixed hound
2018-11-27 12:55:15 +01:00
David Bonnes
9a25054a0d Add zones to evohome component (#18428)
* Added Zones, and removed available() logic

flesh out Zones

tidy up init

some more tidying up

Nearly there - full functionality

passed txo - ready to send PR

Ready to PR, except to remove logging

Add Zones and associated functionality to evohome component

Add Zones to evohome (some more tidying up)

Add Zones to evohome (Nearly there - full functionality)

Add Zones to evohome (passed tox)

Add Zones to evohome (except to remove logging)

Add Zones and associated functionality to evohome component

Revert _LOGGER.warn to .debug, as it should be

Cleanup stupid REBASE

* removed a duplicate/unwanted code block

* tidy up comment

* use async_added_to_hass instead of bus.listen

* Pass evo_data instead of hass when instntiating

* switch to async version of setup_platform/add_entities

* Remove workaround for bug in client library
 - using github version for now, as awaiting new PyPi package

* Avoid invalid-name lint - use 'zone_idx' instead of 'z'

* Fix line too long error

* remove commented-out line of code

* fix a logic error, improve REDACTION of potentially-sensitive infomation

* restore use of EVENT_HOMEASSISTANT_START to improve HA startup time

* added a docstring to _flatten_json

* Switch instantiation from component to platform

* Use v0.2.8 of client api (resolves logging bug)

* import rather than duplicate, and de-lint

* We use evohomeclient v0.2.8 now

* remove all the api logging

* Changed scan_interal to Throttle

* added a configurable scan_interval

* small code tidy-up, removed sub-function

* tidy up update() code

* minimize use of self.hass.data[]

* remove lint

* remove unwanted logging

* remove debug code

* correct a small coding error

* small tidyup of code

* remove flatten_json

* add @callback to _first_update()

* switch back to load_platform

* adhere to standards fro logging

* use new format string formatting

* minor change to comments

* convert scan_interval to timedelta from int

* restore rounding up of scan_interval

* code tidy up

* sync when in sync context

* fix typo

* remove raises not needed

* tidy up typos, etc.

* remove invalid-name lint

* tidy up exception handling

* de-lint/pretty-fy

* move 'status' to a JSON node, so theirs room for 'config', 'schedule' in the future
2018-11-27 12:17:22 +01:00
emontnemery
a03cb12c61 Reconfigure MQTT sensor component if discovery info is changed (#18178)
* Reconfigure MQTT sensor component if discovery info is changed

* Do not pass hass to MqttSensor constructor

* Remove duplicated line
2018-11-27 11:23:47 +01:00
emontnemery
4a4ed128db Reconfigure MQTT fan component if discovery info is changed (#18177) 2018-11-27 11:22:55 +01:00
emontnemery
6170065a2c Reconfigure MQTT cover component if discovery info is changed (#18175)
* Reconfigure MQTT cover component if discovery info is changed

* Do not pass hass to MqttCover constructor
2018-11-27 11:22:26 +01:00
Matt Hamilton
4f2e7fc912 remove pbkdf2 upgrade path (#18736) 2018-11-27 10:42:56 +01:00
Paulus Schoutsen
c2f8dfcb9f Legacy api fix (#18733)
* Set user for API password requests

* Fix tests

* Fix typing
2018-11-27 10:41:44 +01:00
Paulus Schoutsen
9d7b1fc3a7 Enforce permissions for Websocket API (#18719)
* Handle unauth exceptions in websocket

* Enforce permissions in websocket API
2018-11-27 10:12:31 +01:00
Ville Skyttä
7248c9cb0e Remove some unused imports (#18732) 2018-11-27 09:35:35 +01:00
Ville Skyttä
b4e2f2a6ef Upgrade pytest and -timeout (#18722)
* Upgrade pytest to 4.0.1

* Upgrade pytest-timeout to 1.3.3
2018-11-26 22:43:14 +01:00
Paulus Schoutsen
9894eff732 Fix logbook filtering entities (#18721)
* Fix logbook filtering entities

* Fix flaky test
2018-11-26 19:53:24 +01:00
Paulus Schoutsen
1f123ebcc1 Updated frontend to 20181126.0 2018-11-26 14:40:43 +01:00
Paulus Schoutsen
3c92aa9ecb Update translations 2018-11-26 14:30:21 +01:00
Paulus Schoutsen
f9f71c4a6d Bumped version to 0.83.0b1 2018-11-26 14:20:56 +01:00
Joakim Sørensen
c3b76b40f6 Set correct default offset (#18678) 2018-11-26 14:20:49 +01:00
Bram Kragten
56c7c8ccc5 Fix vol Dict -> dict (#18637) 2018-11-26 14:20:49 +01:00
Fredrik Erlandsson
bb75a39cf1 Updated webhook_register, version bump pypoint (#18635)
* Updated webhook_register, version bump pypoint

* A binary_sensor should be a BinarySensorDevice
2018-11-26 14:20:48 +01:00
Eliseo Martelli
2f581b1a1e fixed wording that may confuse user (#18628) 2018-11-26 14:20:48 +01:00
pbalogh77
cf22060c5e Use asyncio Lock for fibaro light (#18622)
* Use asyncio Lock for fibaro light

* line length and empty line at end

* async turn_off

Turned the turn_off into async as well

* bless you, blank lines...

My local flake8 lies to me. Not cool.
2018-11-26 14:20:47 +01:00
Paulus Schoutsen
6bcedb3ac5 Updated frontend to 20181121.1 2018-11-26 14:16:30 +01:00
Paulus Schoutsen
7848381f43 Allow managing cloud webhook (#18672)
* Add cloud webhook support

* Simplify payload

* Add cloud http api tests

* Fix tests

* Lint

* Handle cloud webhooks

* Fix things

* Fix name

* Rename it to cloudhook

* Final rename

* Final final rename?

* Fix docstring

* More tests

* Lint

* Add types

* Fix things
2018-11-26 14:10:18 +01:00
pbalogh77
4a661e351f Use asyncio Lock for fibaro light (#18622)
* Use asyncio Lock for fibaro light

* line length and empty line at end

* async turn_off

Turned the turn_off into async as well

* bless you, blank lines...

My local flake8 lies to me. Not cool.
2018-11-26 13:17:56 +01:00
Ian Richardson
b5b5bc2de8 Convert shopping-list update to WebSockets (#18713)
* Convert shopping-list update to WebSockets

* Update shopping_list.py

* Update test_shopping_list.py
2018-11-26 09:59:53 +01:00
emontnemery
d290ce3c9e Small refactoring of MQTT binary_sensor (#18674) 2018-11-25 20:53:03 +01:00
Franck Nijhof
2cbe083460 ⬆️ Upgrades InfluxDB dependency to 5.2.0 (#18668) 2018-11-25 20:52:09 +01:00
Paulus Schoutsen
8b8629a5f4 Add permission checks to Rest API (#18639)
* Add permission checks to Rest API

* Clean up unnecessary method

* Remove all the tuple stuff from entity check

* Simplify perms

* Correct param name for owner permission

* Hass.io make/update user to be admin

* Types
2018-11-25 18:04:48 +01:00
Fabian Affolter
f387cdec59 Upgrade pysnmp to 4.4.6 (#18695) 2018-11-25 17:59:14 +01:00
Adam Mills
78b90be116 Async cover template tests (#18690) 2018-11-25 11:39:35 -05:00
Adam Mills
91c526d9fe Async device sun light trigger tests (#18689) 2018-11-25 11:39:18 -05:00
Jens
f3ce463862 Adds SomfyContactIOSystemSensor to TaHoma (#18560)
* Sorts all TAHOME_TYPES and adds SomfyContactIOSystemSensor as it wasn't added with 558b659f7c

* Fixes syntax errors related to sorting of entries.
2018-11-25 13:47:16 +01:00
Joakim Sørensen
23f5d785c4 Set correct default offset (#18678) 2018-11-25 12:30:38 +01:00
Soós Péter
cd773455f0 Fix false log message on CAPsMAN only devices (#18687)
* Fix false log message on CAPsMAN only devices 

False debug log message appeared on CAPsMAN only devices without physichal wireless interfaces. This fix eliminates them.

* Fixed indentation to pass flake8 test
2018-11-25 12:21:26 +01:00
Fabian Affolter
5a5cbe4e72 Upgrade youtube_dl to 2018.11.23 (#18694) 2018-11-25 11:41:49 +01:00
Daniel Høyer Iversen
ad2e8b3174 update mill lib, handle bad data from mill server (#18693) 2018-11-25 09:39:06 +01:00
Andrew Hayworth
eb6b6ed87d Add Awair sensor platform (#18570)
* Awair Sensor Platform

This commit adds a sensor platform for Awair devices, by accessing
their beta API. Awair heavily rate-limits this API, so we throttle
updates based on the number of devices found. We also allow for the
user to bypass API device listing entirely, because the device list
endpoint is limited to only 6 calls per day. A crashing or restarting
server would quickly hit that limit.

This sensor platform uses the python_awair library (also written
as part of this PR), which is available for async usage.

* Disable pylint warning for broad try/catch

It's true that this is generally not a great idea, but we really don't
want to crash here. If we can't set up the platform, logging it and
continuing is the right answer.

* Add space to satisfy the linter

* Awair platform PR feedback

- Bump python_awair to 0.0.2, which has support for more granular exceptions
- Ensure we have python_awair available in test
- Raise PlatformNotReady if we can't set up Awair
- Make the 'Awair score' its own sensor, rather than exposing it other ways
- Set the platform up as polling, and set a sensible default
- Pass in throttling parameters to the underlying data class, rather
than use hacky global variable access to dynamically set the interval
- Switch to dict access for required variables
- Use pytest coroutines, set up components via async_setup_component,
  and test/modify/assert in generally better ways
- Commit test data as fixtures

* Awair PR feedback, volume 2

- Don't force updates in test, instead modify time itself and let
  homeassistant update things "normally".
- Remove unneeded polling attribute
- Rename timestamp attribute to 'last_api_update', to better reflect
  that it is the timestamp of the last time the Awair API servers
  received data from this device.
- Use that attribute to flag the component as unavailable when data
  is stale. My own Awair device periodically goes offline and it really
  hardly indicates that at all.
- Dynamically set fixture timestamps to the test run utcnow() value,
  so that we don't have to worry about ancient timestamps in tests
  blowing up down the line.
- Don't assert on entities directly, for the most part. Find desired
  attributes in ... the attributes dict.

* Patch an instance of utcnow I overlooked

* Switch to using a context manager for timestream modification

Honestly, it's just a lot easier to keep track of patches. Moreover,
the ones I seem to have missed are now caught, and tests seem to
consistently pass.

Also, switch test_throttle_async_update to manipulating time more
explicitly.

* Missing blank line, thank you hound

* Fix pydocstyle error

I very much need to set up a script to do this quickly w/o tox, because
running flake8 is not enough!

* PR feedback

* PR feedback
2018-11-25 09:01:19 +01:00
Adam Mills
00c9ca64c8 Async tests for mqtt switch (#18685) 2018-11-24 17:08:28 -05:00
Adam Mills
6f0a3b4b22 Async tests for counter (#18684) 2018-11-24 16:12:29 -05:00
Adam Mills
66f1643de5 Async timer tests (#18683) 2018-11-24 16:12:19 -05:00
Adam Mills
50a30d4dc9 Async tests for remaining device trackers (#18682) 2018-11-24 15:10:57 -05:00
Adam Mills
6ebdc7dabc Async tests for owntracks device tracker (#18681) 2018-11-24 14:34:36 -05:00
Adam Mills
d24ea7da90 Async tests for device tracker mqtt (#18680) 2018-11-24 13:24:06 -05:00
emontnemery
5e18d52302 Reconfigure MQTT alarm component if discovery info is changed (#18173) 2018-11-24 10:48:01 +01:00
emontnemery
e41af133fc Reconfigure MQTT climate component if discovery info is changed (#18174) 2018-11-24 10:40:07 +01:00
Bram Kragten
986ca23934 Dict -> dict (#18665) 2018-11-24 10:02:06 +01:00
Kacper Krupa
8771f9f7dd converted majority of effects from ifs to dict map, which makes it easier to extend in the future. Also, added LSD effect! (#18656) 2018-11-23 23:53:33 +01:00
Bram Kragten
37327f6cbd Add save command to lovelace (#18655)
* Add save command to lovelace

* Default for save should by json

* typing
2018-11-23 22:56:58 +01:00
emontnemery
4c04abfccc Merge pull request #18654 from emontnemery/fix_mqtt_availability_qos
Support updated MQTT QoS when reconfiguring MQTT availability
2018-11-23 17:13:29 +01:00
Erik
b198bb441a Support updated MQTT QoS when reconfiguring MQTT availability 2018-11-23 15:32:24 +01:00
Eliseo Martelli
1c17b885db Added deviceclass timestamp constant (#18652)
* Added deviceclass timestamp

* added device class timestamp to sensor

* fixed comment
2018-11-23 14:51:26 +01:00
Paulus Schoutsen
c0cf29aba9 Remove since last boot from systemmonitor sensor (#18644)
* Remove since last boot

* Make systemmonitor last_boot be a timestamp
2018-11-23 11:55:45 +01:00
Ian Richardson
92978b2f26 Add websocket call for adding item to shopping-list (#18623) 2018-11-23 08:56:18 +01:00
Adam Mills
c99204149c Convert device tracker init tests to async (#18640) 2018-11-23 08:55:25 +01:00
cdheiser
98f159a039 [Breaking Change] Cleanup Lutron light component (#18650)
Remove the return value from setup_platform
Convert LutronLight.__init__ to use super() when referencing the parent class.
Change device_state_attributes() to use lowercase snakecase (Rename 'Lutron Integration ID' to 'lutron_integration_id')
2018-11-23 08:54:28 +01:00
Eliseo Martelli
bb37151987 fixed wording that may confuse user (#18628) 2018-11-23 01:46:22 +01:00
Diogo Gomes
af0f3fcbdb IPMA Weather Service - version bump (#18626)
* version bump

* gen

* gen
2018-11-22 19:09:45 -05:00
Joakim Sørensen
c7bfdbf3cf Merge pull request #18632 from dshokouhi/neato_additional_error_messages
Add additional neato error messages to status attribute
2018-11-22 22:20:58 +01:00
David F. Mulcahey
67aa76d295 Refactor ZHA (#18629)
* refactor ZHA

* lint

* review request

* Exclude more zha modules from coverage
2018-11-22 19:00:46 +01:00
Fredrik Erlandsson
cccc41c23e Updated webhook_register, version bump pypoint (#18635)
* Updated webhook_register, version bump pypoint

* A binary_sensor should be a BinarySensorDevice
2018-11-22 16:43:10 +01:00
Pascal Vizeli
13144af65e Fix raising objects on proxy camera component 2018-11-22 15:06:31 +01:00
Giuseppe
b246fc977e Add support for cropping pictures in proxy camera (#18431)
* Added support for cropping pictures in proxy camera

This includes extending the configuration to introduce a mode
(either 'resize', default, or 'crop') and further coordinates
for the crop operation.

* Also fixed async job type, following code review
2018-11-22 13:14:28 +01:00
Bram Kragten
e5d2900151 Fix vol Dict -> dict (#18637) 2018-11-22 12:48:50 +01:00
mopolus
01ee03a9a1 Add support for multiple IHC controllers (#18058)
* Added support for secondary IHC controller

Most IHC systems only have one controller but the system can be setup with a linked secondary controller.
I have updated the code to have it support both primary and secondary controller. Existing configuration is not impacted and secondary controller can be setup the same way, with similar settings nested under 'secondary' in the configuration

* Update __init__.py

* Update __init__.py

* Update __init__.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update __init__.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update __init__.py

* Update ihc.py

* Update ihc.py

* Update __init__.py

* Update ihc.py

* Update __init__.py

* Update const.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update __init__.py

* Update __init__.py

* Update __init__.py

* Update const.py

* Update __init__.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update __init__.py

* Update __init__.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update __init__.py

* Update ihc.py

* Update ihc.py

* Update __init__.py

* Update ihc.py

* Update ihc.py

* Update __init__.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update ihc.py

* Update __init__.py

* Update __init__.py

* Update ihc.py

* Update __init__.py

* Update __init__.py

* Update __init__.py

* Update __init__.py

* Update __init__.py

* Update __init__.py

indentation was incorrect for "load_platform" in "get_manual_configuration". Load_platform was not called with the correct component name
2018-11-22 09:45:40 +01:00
Daniel Shokouhi
7daf2caef2 Correct error message 2018-11-21 23:31:08 -08:00
Daniel Shokouhi
9f36cebe59 Add additional neato error messages to status attribute 2018-11-21 22:47:30 -08:00
Nick Whyte
22ab83acae Cleanup BOM dependencies + add basic test + IDEA autoformat (#18462)
* Cleanup BOM dependencies + add basic test
2018-11-21 20:41:53 -05:00
nragon
1ad3c3b1e2 Minor change to still image on mjpeg (#18602)
* Update mjpeg.py

* Lint
2018-11-21 23:12:16 +01:00
Josh Anderson
3d178708fc Add /sbin to launchd PATH (#18601)
* Add /sbin to launchd PATH

* Put /sbin at the end to allow overrides

Co-Authored-By: andersonshatch <andersonshatch@gmail.com>
2018-11-21 20:56:38 +01:00
Paulus Schoutsen
1341ecd2eb Use proper signals (#18613)
* Emulated Hue not use deprecated handler

* Remove no longer needed workaround

* Add middleware directly

* Dont always load the ban config file

* Update homeassistant/components/http/ban.py

Co-Authored-By: balloob <paulus@home-assistant.io>

* Update __init__.py
2018-11-21 20:55:21 +01:00
Paulus Schoutsen
5b3e9399a9 Bump to 0.84.0.dev0 2018-11-21 20:53:44 +01:00
Paulus Schoutsen
fd7fff2ce8 Version bump to 0.83.0b0 2018-11-21 20:50:11 +01:00
Paulus Schoutsen
4e58eb8bae Updated frontend to 20181121.0 2018-11-21 20:35:46 +01:00
Paulus Schoutsen
49121f2347 Update translations 2018-11-21 20:18:56 +01:00
Fabian Affolter
708ababd78 Upgrade requests to 2.20.1 (#18615) 2018-11-21 19:58:56 +01:00
Pawel
92c0f9e4aa Fix mqtt cover inverted (#18456)
* Fixed state and position retrieval in inverted mode 100-0

* Always calculating find_percentage_in_range

* Added usage of max/min functions.
2018-11-21 15:48:44 +01:00
Martin Gross
81cac33801 Update locationsharinglib requirement to 3.0.8 (#18612) 2018-11-21 15:13:20 +01:00
Jonathan McDowell
1e3930a447 Add support for Panasonic Blu-Ray players (#18541)
* Add support for Panasonic Blu-Ray players

* Update panasonic_bluray.py

* Update panasonic_bluray.py
2018-11-21 14:22:24 +01:00
Joakim Sørensen
3cde8dc3a9 Add support for HTTPS and basic HTTP authentication for Glances (#18608)
* Add support for SSL and basic HTTP auth

* Remove blank line at the end of the file
2018-11-21 12:38:42 +01:00
Paulus Schoutsen
36c31a6293 Add permissions check in service helper (#18596)
* Add permissions check in service helper

* Lint

* Fix tests

* Lint

* Typing

* Fix unused impoert
2018-11-21 12:26:08 +01:00
Kevin Fronczak
8aa2cefd75 Upgrade blinkpy to 0.10.3 (Fixes #18341) (#18603) 2018-11-21 08:57:59 +01:00
pbalogh77
3b53003795 Fibaro components (#18487)
* Added Fibaro omcponents

Added cover, light, sensor and switch components

* Improvements based on code review

Improvements based on code review

* Fixes based on code review

Fixes based on code review

* Changes to light behavior based on code review

Changes to light behavior based on code review

* Internal changes

Changed how brightness is represented internally.
It should have no impact on functionality.
2018-11-21 06:15:54 +01:00
ehendrix23
377730a37c Change channel with play_media instead of select_source (#18474)
* Use service play_media instead of select_source

Use service play_media instead of select_source to change the channel as play_media is the right service for that.

* Log error on invalid media type

Log an error instead of raising a NotImplementedError if an invalid media type is provided.

* Changed so that success is not in else statement

Updated so that if media_type is channel that it is not in the else of an if.

* Update directv.py

Removed SELECT_SOURCE as supported feature.

* Rebased

Re-based with dev
2018-11-20 16:05:25 -07:00
Paulus Schoutsen
d9c7f777c5 Add cloud pref for Google unlock (#18600) 2018-11-20 23:23:07 +01:00
Charles Garwood
b7742999cf Update Z-Wave Tests asyncio/yield from -> async/await (#18599)
* Update lock tests

* Update binary sensor

* Update zwave component tests
2018-11-20 14:58:03 -05:00
Daniel Høyer Iversen
8742750926 Improve available for Mill heater (#18597)
* improve available for Mill heater

* typo
2018-11-20 20:00:13 +01:00
Charles Garwood
e87ecbd500 Z-Wave Lock Config Entry Support (#18209)
* Config Entry setup for zwave lock

* fix merge conflict

* lint

* Update other tests

* Fix tests

* Remove debug line and unused import
2018-11-20 14:59:34 +01:00
Fredrik Erlandsson
3838be4cb8 Add support for Daikin BRP069B41 (#18564)
* Add support for BRP069B41, fixes #18563

* Use fan_mode and swing_mode from pydaikin 0.8
2018-11-20 14:14:11 +01:00
Pascal Vizeli
0ddd502d00 Hass.io config check (#18576) 2018-11-20 13:30:09 +01:00
dapowers87
d88040eeed Revert changes that broke UI (#18495)
* Revert changes that broke UI

* Change from UNKNOWN to None

* Remove STATE_UNKNOWN import
2018-11-20 13:29:05 +01:00
Ian Richardson
44b33d45b1 Add websocket calls to shopping-list (#18392)
* Add websocket calls to shopping-list

Plan to deprecate API calls once shopping-list panel is removed from UI and replaced fully by Lovelace card

* Address ci-bot issues

* Fix violations

* Address travis complaints

* Address review comments

* Update test_shopping_list.py
2018-11-20 12:44:17 +01:00
Paulus Schoutsen
9b53b7e9e4 Bump Python-Nest to 4.0.5 (#18580)
* Fix Nest eco

* Update Python-nest to 4.0.5

* Update requirements_all.txt

* Update requirements_test_all.txt
2018-11-20 12:18:46 +01:00
Franck Nijhof
80cd8b180c Adds light switch platform (#18562)
* Adds light switch platform

* Addresses HoundCI warnings

* Addresses Flake8 reported issues

* Removes async_update call as per review
2018-11-20 11:51:34 +01:00
William Scanlon
b3e37af9b1 Added unique id to all Wink devices. (#18589) 2018-11-19 22:52:43 -05:00
Eliseo Martelli
57f7e7eedc Bumped ghlocalapi to 0.1.0 (#18584)
* mumped ghlocalapi to 0.1.0

* update requirement_all.txt
2018-11-19 15:01:26 -05:00
Sebastian Muszynski
14ad7428ea Prefix all xiaomi_aqara events (#17354) 2018-11-19 20:55:08 +01:00
Paulus Schoutsen
f86083cf52 Fix MQTT async_added_to_hass (#18575)
* Fix some invocations

* Update manual_mqtt.py
2018-11-19 20:48:26 +01:00
Soós Péter
3891f2eebe Add mikrotik SSL support (#17898)
* Update mikrotik.py

* Update mikrotik.py

* Added basic  api_ssl support

Added preliminary support to use api_ssl instead of api. It don't check the validity of the certificate need it.
At Home Assistant side add ssl = true to your sensor configuration, and don't forget to change the port too (to 8729 by default):

device_tracker:
  - platform: mikrotik
    host: 192.168.88.1
    port: 8729
    ssl: true
    username: homeassistant
    password: TopSecret

At MikroTik side you have to add or generate a certificate, and configure api_ssl to use it. Here is an example:

/certificate add common-name="Self signed demo certificate for API" days-valid=3650 name="Self signed demo certificate for API" key-usage=digital-signature,key-encipherment,tls-server,key-cert-sign,crl-sign
/certificate sign "Self signed demo certificate for API"
/ip service set api-ssl certificate="Self signed demo certificate for API"
/ip service enable api-ssl
/ip service disable api
/user group add name=homeassistant policy=read,api,!local,!telnet,!ssh,!ftp,!reboot,!write,!policy,!test,!winbox,!password,!web,!sniff,!sensitive,!romon,!dude,!tikapp
/user add group=homeassistant name=homeassistant
/user set password="TopSecret" homeassistant

* Fixed import missind ssl lib

* SSL support code cleanup, use ssl-api port by default if ssl enabled

* Restored accidentalli deleted method parameter

* Fixed Python 3.5.3 compilation errors

Fixed Python 3.5.3 compilation errors reported by Travis CI

* Removed duplicated MTK_DEFAULT_API_PORT
2018-11-19 16:54:09 +01:00
emontnemery
de9bac9ee3 Reconfigure MQTT binary_sensor component if discovery info is changed (#18169)
* Recreate component if discovery info is changed

* Update component instead of remove+add

* Set name and unique_id in __init__

* Update unit test

* Cleanup

* More cleanup

* Refactor according to review comments

* Change discovery_hash

* Review comments, add tests

* Fix handling of value_template
2018-11-19 16:49:04 +01:00
Oleksii Serdiuk
01953ab46b Darksky: Expose missing conditions for day 0 forecast (#18312)
Dark Sky Sensor didn't expose conditions for day 0 (today forecast) that
had the same name as current conditions. With this change all conditions
form day 0 (today) forecast are exposed the same way as conditions for
the rest of the days (1..7): as `dark_sky_<condition>_<day>`. As a
consequence, conditions for day 0 that were already exposed now have
`_0` suffix. This actually improves the code by removing most of
special handling, based on condition name.

To get day 0 conditions the user now has to add `- 0` to `forecast`
configuration parameter.

Conditions, for which suffix `_0` appeared: `precip_accumulation`,
`temperature_high`, `temperature_low`, `apparent_temperature_high`,
`apparent_temperature_low`, `precip_intensity_max`, `moon_phase`.

This is a breaking change!

Closes #18205
2018-11-19 14:48:52 +01:00
Daniel Perna
fc4dd4e51f Update pyhomematic to 0.1.52 and add features for lights (#18499)
* Update pyhomematic and add features for lights

* Lint

* Lint

* Update homematic.py

* Update homematic.py
2018-11-19 14:26:08 +01:00
bw3
90f3f2b1e7 Fix for epson state not updating (#18357)
* Fixed update method name

* Update epson.py
2018-11-19 13:47:52 +01:00
Fredrik Erlandsson
c1ca7beea1 Support for Point component (#17466)
* Minut Point support

* tox tests for Point

* config flow fixes

* fixes requested by @MartinHjelmare

* swedish translation :)

* fix tests
2018-11-19 12:52:21 +01:00
Anders Melchiorsen
84fd66c8a1 Template binary sensor to not track all state changes (#18573) 2018-11-19 12:10:48 +01:00
arigilder
97c493448b Correct cached stale device tracker handling (#18572)
* Fix async addition of stale devices

* Add comment to mark_stale

* Remove extraneous whitespace
2018-11-19 12:06:57 +01:00
ehendrix23
9fa34f0d77 Add support for sessions (#18518)
Added support for sessions to keep connection open with August portal, improving performance.
py-august version increased to 0.7.0
2018-11-19 11:53:27 +01:00
ehendrix23
cdcc818bf9 Remove turn_on and turn_off feature for clients (#18234)
* Enhancements for DirecTV media player

Following enhancements have been made:

1. Added debug logging
2. Added ability to change channel using select_source service of the remote platform.
3. State will now show paused if a recorded program is paused, for live TV playing will always be returned.
4. Added the following attributes:
    a. media_position: current position of the media (in seconds)
    b. media_position_updated_at: timestamp when media_position was updated.
   c. source: current source (channel).
   d. media_isbeingrecorded: if current media is being recorded or not.
   e. media_rating: TV/Movie rating of the media
   f. media_recorded: if current media is recorded or live TV
   g. media_starttime: Timestamp media was aired

Reordered properties to follow same order as how they are in __init__.py of remote platform.

* Fixed error and cleaned up few items

Fixed an issue when determining if a program is recorded or not.
Cleaned up some coding.

* Added available property

Added available property

* Disable feature TURN_ON and TURN_OFF for DVR clients

Disable the feature turn_on and turn_off for DVR clients.

* self._is_client and raise NotImplementedError

Updated setting self._is_client
Raise NotImplementedError if turn_on or turn_off is called for clients.
2018-11-19 11:47:00 +01:00
Phil Bruckner
83b4e56978 Log delay and wait_template steps in scripts (#18448)
* Log delay and wait_template steps in scripts

Help improve script debugging by logging delay and wait_template steps in scripts.

* Update tests

* Fix lint issue
2018-11-19 11:14:00 +01:00
Aleksandr Smirnov
089a2f4e71 Logbook speedup (#18376)
* filter logbook results by entity_id prior to instantiating them

* include by default, pass pep8

* pass pylint

* use entityfilter, update tests
2018-11-19 10:36:00 +01:00
emontnemery
f241becf7f Avoid race in entity_platform.async_add_entities() (#18445)
This avoids a race between multiple concurrent calls to
entity_platform.async_add_entities() which may cause
entities to be created with non-unique entity_id
2018-11-19 10:13:50 +01:00
emontnemery
7e702d3caa Fix small issue related to topic prefix (#18512)
Fix expansion of topic prefix when discovery message contains non string-type items.
2018-11-19 09:59:07 +01:00
Jeff Irion
ab8c127a4a Enable native support + ADB authentication for Fire TV (#17767)
* Enable native support + ADB authentication for Fire TV

* Remove unnecessary underscore assignments

* Bump firetv to 1.0.5.3

* Change requirements to 'firetv>=1.0.6'

* Change requirement from 'firetv>=1.0.6' to 'firetv==1.0.6'

* Address pylint errors

* Ran 'python script/gen_requirements_all.py'

* Address some minor reviewer comments

* Run 'python script/gen_requirements_all.py'

* Just use the 'requirements_all.txt' and 'requirements_test_all.txt' from the 'dev' branch...

* Edit the 'requirements_all.txt' file manually

* Pass flake8 tests

* Pass pylint tests, add extended description for 'select_source'

* More precise exception catching

* More Pythonic returns

* Import exceptions inside '__init__'

* Remove 'time.sleep' command

* Sort the imports

* Use 'config[key]' instead of 'config.get(key)'

* Remove accessing of hidden attributes; bump firetv version to 1.0.7

* Bump firetv to 1.0.7 in 'requirements_all.txt'

* Don't access 'self.firetv._adb', use 'self.available' instead

* Remove '_host' and '_adbkey' attributes

* Create the 'FireTV' object in 'setup_platform' and check the connection before instantiating the entity

* Fixed config validation for 'adbkey'

* add_devices -> add_entities

* Remove 'pylint: disable=no-name-in-module'

* Don't assume the device is available after attempting to connect

* Update the state after reconnecting

* Modifications to 'adb_decorator'

* Modifications to 'setup_platform'

* Don't update the state if the ADB reconnect attempt was unsuccessful

* 'return None' -> 'return'

* Use 'threading.Lock()' instead of a boolean for 'adb_lock'

* Use a non-blocking 'threading.Lock'
2018-11-19 07:05:58 +01:00
sdelliot
afe21b4408 Re-adding the season attribute (#18523) 2018-11-18 18:35:36 -07:00
Anders Melchiorsen
b066877453 Allow unloading of LIFX config entry (#18535) 2018-11-18 19:51:17 +01:00
Per Sandström
796933de68 Upgrade vsure to 1.5.2 (#18557)
Upgrade vsure to 1.5.2
2018-11-18 19:41:24 +01:00
Aaron Bach
8f59be2059 Make MyQ platform async (#18489)
* Make MyQ platform async

* Bumped requirements

* Member comments

* Member updates
2018-11-18 18:37:03 +01:00
Ville Skyttä
dfb8f60fe2 Upgrade pytest and pytest-cov (#18542)
* Upgrade pytest to 4.0.0

* Upgrade pytest-cov to 2.6.0
2018-11-18 09:33:01 +01:00
Daniel Høyer Iversen
3f747f1a8c Mill lib (#18529)
* Mill attr and update the lib

* lib

* heater_generation
2018-11-17 18:39:38 +01:00
Fabian Affolter
4751ad69a7 Upgrade ruamel.yaml to 0.15.78 (#18508) 2018-11-17 13:20:17 +01:00
Anders Melchiorsen
c6ca27e9b4 Improve handling of unavailable Sonos speakers (#18534) 2018-11-17 13:18:51 +01:00
Aaron Bach
e73b9b9b8f Clean up left-behind dispatcher handlers when removing RainMachine (#18488)
* Clean up left-behind dispatcher handlers when removing RainMachine

* Member comments
2018-11-17 10:42:50 +01:00
Daniel Høyer Iversen
6b2f50b29e Improve real time consumption for Tibber sensor (#18517) 2018-11-16 14:19:54 -05:00
Eliseo Martelli
fcd756d58a fixed sky_hub schema to reflect documentation (#18509) 2018-11-16 14:14:46 -05:00
Paulus Schoutsen
24db2b66ab Ban systemair-savecair (#18483) 2018-11-16 14:28:39 +01:00
Fabian Affolter
320efdb744 Upgrade sqlalchemy to 1.2.14 (#18504) 2018-11-16 14:15:53 +01:00
Fabian Affolter
9e0497875e Upgrade sphinx-autodoc-typehints to 1.5.0 (#18505) 2018-11-16 14:15:04 +01:00
Fabian Affolter
30806fa362 Upgrade numpy to 1.15.4 (#18506) 2018-11-16 14:14:40 +01:00
Fabian Affolter
9f51deb1de Upgrade youtube_dl to 2018.11.07 (#18507) 2018-11-16 14:14:20 +01:00
cdce8p
0ca94f239d Update HAP-python 2.4.1 (#18417)
* Bugfixes
2018-11-16 11:42:48 +01:00
cdce8p
ed7aea006a Add safe_mode HomeKit (#18356)
* Use: 'safe_mode: True' in case of pairing issues
2018-11-16 11:08:39 +01:00
Martin Gross
b7b8296c73 Alexa v3 name change for additionalApplianceDetails (#18485) 2018-11-15 11:15:50 -07:00
Leothlon
afb3a52b5b Fixed bug for receivers without support for new command (#18478)
* Fixed bug for receivers without support for new command

* removed extra parenthesis
2018-11-15 10:49:10 -07:00
Aaron Bach
4446b15cb0 Add Rainmachine to the device registry (#18452)
* Device registry in

* Member comments

* Hound
2018-11-15 10:43:20 -07:00
Oleksii Serdiuk
d1b5bc19da AirVisual: Show icon for air pollution level, based on its value (#18482)
Show excited, happy, neutral, sad, dead emoticon, or biohazard icon,
based on air pollution level.

Also, fix a small typo and change air quality index icon to
`mdi:chart-line`. Seems a bit more logical.
2018-11-15 10:23:46 -07:00
Paulus Schoutsen
75bb78d440 Update translations 2018-11-15 14:30:37 +01:00
Paulus Schoutsen
2d870a29c4 Merge branch 'master' into dev 2018-11-15 14:30:21 +01:00
Paulus Schoutsen
7cb7c76a83 Merge pull request #18481 from home-assistant/rc
0.82.1
2018-11-15 14:25:56 +01:00
Paulus Schoutsen
b40b934029 Bumped version to 0.82.1 2018-11-15 14:01:21 +01:00
Pascal Vizeli
5ffcb99b4f Update pyozw to 0.1.1 (#18436)
* Update pyozw to 0.1.1

* Update requirements_all.txt
2018-11-15 14:01:15 +01:00
Abílio Costa
69d358fa08 edp_redy: increase UPDATE_INTERVAL (#18429)
The server was getting a bit mad sometimes and would lock users out.
2018-11-15 14:01:14 +01:00
Fredrik Erlandsson
f36b94b376 updated pydaikin version (#18413) 2018-11-15 14:01:14 +01:00
Pawel
b5d4e18880 Changed checking of cover state closed from 0 to closed_position variable. (#18407)
Change error message to avoid expression "get_position_topic".
2018-11-15 14:01:13 +01:00
Paulus Schoutsen
43271ca0f7 Bump aioasuswrt to 1.1.6 2018-11-15 14:01:02 +01:00
Diogo Gomes
7659c33439 cancel off_delay action (#18389) 2018-11-15 13:56:14 +01:00
Clayton Nummer
b8ddbc3fdb Fix default value for optional Sense configuration parameter (#18379) 2018-11-15 13:56:13 +01:00
Bram Kragten
2aa2233d9b Fix including from sub dir (#18378)
The include path is now always relative to the root of the config dir.
2018-11-15 13:56:13 +01:00
Martin Hjelmare
6bcba1fbea Fix hangouts notify (#18372)
* Remove notify schema from hangouts platform

* Notify platforms shouldn't overwrite the notify component service
  schema. That has no effect.

* Fix hangouts service data key value
2018-11-15 13:56:12 +01:00
Jason Hunter
466d3a5ef8 catch key error when saving image (#18365) 2018-11-15 13:56:12 +01:00
Aaron Bach
8aa1283adc Add Rainmachine config entry (#18419)
* Initial stuff

* More work in place

* Starting with tests

* Device registry in place

* Hound

* Linting

* Member comments (including extracting device registry)

* Member comments (plus I forgot cleanup!)

* Hound

* More Hound

* Removed old import

* Adding config entry test to coverage

* Updated strings
2018-11-14 13:23:49 -07:00
pbalogh77
312872961f Initial support for Fibaro HomeCenter hubs (#17891)
* Fibaro HC connection, initial commit

Very first steps working, connects, fetches devices, represents sensors, binary_sensors and lights towards HA.

* Cover, switch, bugfixes

Initial support for covers
Initial support for switches
Bugfixes

* Some cleanup and improved lights

pylint based cleanup
light switches handled properly
light features reported correctly

* Added status updates and actions

Lights, Blinds, Switches are mostly working now

* Code cleanup, fiblary3 req

Fiblary3 is now in pypi, set it as req
Cleanup based on pylint

* Included in .coveragerc and added how to use guide

Included the fibaro component in coveragerc
Added usage instructions to file header

* PyLint inspired fixes

Fixed pylint warnings

* PyLint inspired fixes

PyLint inspired fixes

* updated to fiblary3 0.1.5

* Minor fixes to finally pass pull req

Fixed fiblary3 to work with python 3.5
Updated fiblary3 to 0.1.6
(added energy and batteryLevel dummies)

* module import and flake8 fixes

Finally (hopefully) figured out what lint is complaining about

* Fixed color support for lights, simplified callback

Fixed color support for lights
Simplified callback for updates
Uses updated fiblary3 for color light handling

* Lean and mean refactor

While waiting for a brave reviewer, I've been making the code smaller and easier to understand.

* Minor fixes to please HoundCI

* Removed unused component

Scenes are not implemented yet

* Nicer comments.

* DEVICE_CLASS, ignore plugins, improved mapping

Added support for device class and icons in sensors and binary_sensors
Improved mapping of sensors and added heuristic matching
Added support for hidden devices
Fixed conversion to float in sensors

* Fixed dimming

Fibaro apparently does not need, nor like the extra turnOn commands for dimmers

* flake8

* Cleanup, Light fixes, switch power

Cleanup of the component to separate init from connect, handle connection error better
Improved light handling, especially for RGBW strips and working around Fibaro quirks
Added energy and power reporting to switches

* Missing comment added

Missing comment added to please flake8

* Removed everything but bin.sensors

Stripdown, hoping for a review

* better aligned comments

OMG

* Fixes based on code review

Fixes based on code review

* Implemented stopping

Implemented stopping of StateHandler thread
Cleanup for clarity

* Minor fix

Removed unnecessary list copying

* Nicer wording on shutdown

* Minor changes based on code review

* minor fixes based on code review

* removed extra line break
2018-11-14 20:58:32 +01:00
Daniel Høyer Iversen
00235cf6f0 Improve support for 1. generation mill heater (#18423)
* Improve support for 1. gen mill heater

* style

* None operation_list for gen 1 heater

* Remove SUPPORT_OPERATION_MODE for gen 1
2018-11-14 19:35:12 +01:00
Rick van Hattem
80e616cacf Make mikrotik method setting optional as intended (#18454)
Pull request #17852 accidently made the `method` setting required.
2018-11-14 18:05:29 +01:00
Maikel Punie
c7ac216602 Readded climate.velbus (#18434)
* Readded climate.velbus

* houndci-bot changes

* Added more comments

* Fix flake8 error

* return TEMP_* constants

* more comments
2018-11-14 09:40:43 -05:00
Fredrik Erlandsson
0d43cb6d0e fixes for last version bump on pydaikin (#18438) 2018-11-14 09:38:16 -05:00
ehendrix23
d2e102ee2f Init statistics sensor upon HASS start (#18236)
* Update query to include maxAge

Updated the query from recorded to include MaxAge if set; reducing the amount of records retrieved that would otherwise be purged anyway for the sensor.

* Initialization upon HASS start

Register the state listener and read previous information from recorder once HASS is started.

* Updated test_statistics.py for HASS start

Updated test_statistics.py to start HASS and wait it is completed before running test.

* Added newline in docstring

Added newline in docstring.

* Added start of HASS to test_initialize_from_database_with_maxage

Added start of HASS to new test test_initialize_from_database_with_maxage.

* Updates based on review

Following updates based on review:
-) Removed self._hass and passing hass
-) Changed async_add_job to async_create_task
-) For state update, calling async_schedule_update_ha_state
2018-11-14 15:13:32 +01:00
Sebastian Muszynski
d2907b8e53 Add Philips Zhirui Downlight support (#18455) 2018-11-14 12:33:27 +01:00
Glenn Waters
419400f90b Bump elkm1_lib version (#18450) 2018-11-14 02:20:15 +01:00
Pascal Vizeli
532a75b487 Update pyozw to 0.1.1 (#18436)
* Update pyozw to 0.1.1

* Update requirements_all.txt
2018-11-13 23:43:01 +01:00
JC Connell
291fba0ba4 Update Magicseaweed sensor (#18446)
* Increment python-magicseaweed version.

* Update requirements_all.txt
2018-11-13 23:41:58 +01:00
Joakim Sørensen
597da90622 Fixes issue for returning the correct docker version. (#18439) 2018-11-13 21:00:21 +01:00
Abílio Costa
f14251bdcc edp_redy: increase UPDATE_INTERVAL (#18429)
The server was getting a bit mad sometimes and would lock users out.
2018-11-13 14:24:30 +01:00
kennedyshead
ebdfb56803 Bumping aioasuswrt (#18427) 2018-11-13 14:04:36 +01:00
Daniel Høyer Iversen
7aa41d66e9 Avg price for tibber sensor (#18426)
* Avg price for tibber sensor

* change to sum_price
2018-11-13 11:29:04 +01:00
Fabian Affolter
7113ec6073 Fix smhi docstrings (#18414)
* Fix docstrings

* Fix lint

* Fix another typo

* Fix mobile phone edit
2018-11-13 10:01:14 +01:00
kbickar
f78dcb96b0 Sense will not list removed devices (#18410)
* Sense will not list removed devices

* quote update
2018-11-13 08:34:11 +01:00
Fredrik Erlandsson
996da72a4c Daikin fixes (#18415)
* updated pydaikin version

* some Daikin models does not support fan settings
2018-11-13 08:33:34 +01:00
Aaron Bach
8547489014 Bumps pytile to 2.0.5 (#18395) 2018-11-12 19:10:03 -07:00
Fredrik Erlandsson
c6683cba7d updated pydaikin version (#18413) 2018-11-12 22:53:50 +01:00
Fabian Affolter
ea4480f170 Use existing constant (#18408) 2018-11-12 22:32:30 +01:00
Diogo Gomes
0ab81b03a8 cancel off_delay action (#18389) 2018-11-12 21:28:00 +01:00
Pawel
d0463942be Changed checking of cover state closed from 0 to closed_position variable. (#18407)
Change error message to avoid expression "get_position_topic".
2018-11-12 19:45:59 +00:00
Glenn Waters
275b485b36 Add support for keypad keypress (#18393)
* Add support for keypad keypress

* Update requirements_all
2018-11-12 16:10:28 +01:00
Levi Govaerts
15c77fe548 Add niko-home-control support (#18019)
* Add niko-home-control support

* Remove the sensor platform

* Minor changes

* Fix docstring
2018-11-12 15:59:52 +01:00
Philipp Wensauer
e5930da972 Update pynello to 2.0.2 (#18402)
* Update to pynello 2.0.2

* Update to pynello 2.0.2

* Update to pynello 2.0.2
2018-11-12 09:54:08 -05:00
Paulus Schoutsen
8fb6030f97 Bump frontend to 20181112.0 2018-11-12 15:14:37 +01:00
Jorim Tielemans
9eac11dcbe Filter Coinbase account wallets (#18167)
Only add sensor entities for accounts with the specified currencies.
This is a none breaking change.
If it's not specified then all account wallets will be loaded.
2018-11-12 11:26:05 +01:00
kennedyshead
afd9c44ffb Bumping aioasuswrt (#18400) 2018-11-12 11:10:53 +01:00
Hmmbob
1f06d6ac1a Update waze_travel_time.py (#18399) 2018-11-12 11:09:39 +01:00
Adam Belebczuk
ca86755409 Discord - Minor bugfixes (#18385)
Suppress PyNaCl warnings of Discord notify
2018-11-11 23:16:23 +01:00
Clayton Nummer
1f476936a2 Fix default value for optional Sense configuration parameter (#18379) 2018-11-11 22:55:45 +01:00
Eric Nagley
ddeeba20b9 Google assistant enable fan speed controls (#18373)
* Initial commit of Traits changes.

* Initial commit of tests chagnes for added FanSpeed trait.

* pylint fixes.

* Default reversible to false

* Ensure reversible returns True/False.

* Fix FanSpeed trait name and fix order.

* Add remaining checks to FanSpeed trait Test.

* Remove un-needed blank lines at EOF.

* Update homeassistant/components/google_assistant/trait.py

Co-Authored-By: marchingphoenix <eanagley@gmail.com>

* use fan.SPEED_* constants as keys to speed_synonyms dict.
convert True if() to bool() for reversible assignment.

* use fan.SPEED_OFF constant of 'on' check.
2018-11-11 22:02:33 +01:00
Aaron Bach
5129a48750 Fixed misspellings in some of the Pollen sensor names (#18382) 2018-11-11 13:01:26 -07:00
Fabian Affolter
95eae47438 Bump version to 0.83.0 2018-11-11 18:22:28 +01:00
bouni
372470f52a Fix and improvment of Swiss Hydrological Data component (#17166)
* Fix and improvment of Swiss Hydrological Data component

* changed component to get data from a REST API rather than from crawling the website

* fixed several issues and lint errors

* Fix and improvment of Swiss Hydrological Data component

* Minor changes

- Simplify the sensor configuration (expose value as attributes rather than sensor)
- Make the setup fail if station is not available
- Add unique ID
- Prepare for config flow
2018-11-11 17:48:44 +01:00
Martin Hjelmare
02cc6a2f9a Fix hangouts notify (#18372)
* Remove notify schema from hangouts platform

* Notify platforms shouldn't overwrite the notify component service
  schema. That has no effect.

* Fix hangouts service data key value
2018-11-11 17:46:28 +01:00
Jason Hunter
9cb6464c58 catch key error when saving image (#18365) 2018-11-11 17:44:41 +01:00
Jack Wilsdon
5b9a9d8e04 Return color information in Alexa Smart Home response (#18368)
Fixes #18367.
2018-11-11 17:43:01 +01:00
Ville Skyttä
9411fca955 Add more type hints to helpers (#18350)
* Add type hints to helpers.entityfilter

* Add type hints to helpers.deprecation
2018-11-11 17:39:50 +01:00
Bram Kragten
b8c06ad019 Fix including from sub dir (#18378)
The include path is now always relative to the root of the config dir.
2018-11-11 17:15:58 +01:00
Steven Looman
9c92151ad1 Upgrade async_upnp_client to 0.13.2 (#18377) 2018-11-11 15:10:03 +00:00
Daniel Høyer Iversen
f0a0ce504b Better error handling in Tibber (#18363)
* Better error handling in Tibber

* return if received error
2018-11-11 14:06:21 +01:00
Matthew Garrett
d9533127f9 Merge pull request #18364 from mjg59/avion
Bump python-avion dependency
2018-11-10 18:34:27 -08:00
Matthew Garrett
fa127188df Bump python-avion dependency
The current version of python-avion doesn't work correctly with Python 3.5.
Update it to one that does.
2018-11-10 18:03:55 -08:00
Chris Kacerguis
667b41dd4a Show battery_level as a percent vs a decimal (#18328) 2018-11-10 21:30:03 +01:00
Ville Skyttä
f236e14bd6 Upgrade pytest and pytest-sugar (#18338)
* Upgrade pytest to 3.10.0

* Upgrade pytest-sugar to 0.9.2
2018-11-10 21:08:32 +01:00
Antoine Meillet
e75f9b36f9 add heartbeat support to mysensors (#18359) 2018-11-10 21:08:03 +01:00
cdce8p
132bb7902a Update HAP-python to 2.4.0 (#18355) 2018-11-10 18:33:45 +01:00
Paulus Schoutsen
df2ab62ce9 Merge pull request #18335 from home-assistant/rc
0.82
2018-11-10 09:52:37 +01:00
Adam Belebczuk
f7c99ada9d WeMo - Change name of discovery option (#18348) 2018-11-10 09:32:09 +01:00
Tyler Page
8bd281d5a3 Update credstash.py (#18349)
* Update credstash.py

* Update requirements_all.txt
2018-11-10 08:21:39 +01:00
Adam Belebczuk
210eab16da WeMo - Change name of discovery option (#18348) 2018-11-10 08:17:24 +01:00
uchagani
64ada1ea5a bump total connect client to 0.22 (#18344) 2018-11-09 20:04:28 -05:00
Daniel Høyer Iversen
14ad5c0006 Switchmate library update (#18336) 2018-11-09 23:41:44 +01:00
Joakim Sørensen
d34c47a9e1 Rename sensor.launch to sensor.launch_library (#18337) 2018-11-09 22:24:26 +01:00
Aaron Bach
f971309113 Add support for sensors from Flu Near You (#18136)
* Add support for sensors from Flu Near You

* Added sensor for total reports with symptoms

* Member comments

* Member comments
2018-11-09 08:23:07 -07:00
Paulus Schoutsen
f8ca4cfd91 Merge remote-tracking branch 'origin/master' into rc 2018-11-09 15:44:17 +01:00
Paulus Schoutsen
4324d87673 Bumped version to 0.82.0 2018-11-09 15:42:17 +01:00
Abílio Costa
7f48a280ee fix last device ignored (#18329) 2018-11-09 15:41:21 +01:00
Paulus Schoutsen
f4c35a389d Remove Velbus climate platform (#18319) 2018-11-09 15:41:20 +01:00
Daniel Høyer Iversen
8ab2f669d2 Fix xiaomi binary_sensor warning (#18280)
* Fix xiaomi binary_sensor warning

* Fix xiaomi binary_sensor warning
2018-11-09 15:41:20 +01:00
Paulus Schoutsen
de37fc90c0 Bump frontend to 20181103.3 2018-11-09 15:40:46 +01:00
Daniel Høyer Iversen
c571637176 Fix xiaomi binary_sensor warning (#18280)
* Fix xiaomi binary_sensor warning

* Fix xiaomi binary_sensor warning
2018-11-09 11:36:00 +01:00
Abílio Costa
b803075eb4 fix last device ignored (#18329) 2018-11-09 10:41:08 +01:00
ehendrix23
ae85baf396 Restrict recorder query to include max age (#18231)
* Update query to include maxAge

Updated the query from recorded to include MaxAge if set; reducing the amount of records retrieved that would otherwise be purged anyway for the sensor.

* Added newline in docstring

Added newline in docstring.

* Add test + small fix

Added test to ensure query works correctly
Query should be greater then or equal instead of greater then. Fixed.

* Fixed lint issue

Fixed lint issue.
2018-11-08 23:08:36 +00:00
Brig Lamoreaux
05eac915d1 Srpenergy (#18036)
* Add srp_energy

* Update message on TypeError. Add check for None state.

* Add check for none in history

* Add srpenergy to Test requirements.

* Add srpenergy to requirments.

* Change = to ==.

* Change import for srpenergy

* Fix Flak8 errors

* Add srp to gen requirements script

* Change config name.

* Add daily usage test

* Add test for daily usage.

* Fix Flake8 message.

* Remove blank after docstring.

* Add srpenergy to coverage

* Bump requires version to srpenergy

* Fix type in coverage. Import from Sensor. Use dict.

* Update to 1.0.5. Check credentials on setup. Standalone test.

* Fix formating.

* Remove period. Rename _ variables.

* Fix rebase merge

* Add rebase requirement

* Improve Mock Patching.
2018-11-08 19:19:30 +01:00
horga83
8f107c46fe W800rf32 (#17920)
* Initial commit of w800rf32 component and binary_sensor.

The W800 family is an X10 RF receiver used with keypads and motion sensors etc.

* Initial commit of w800rf32 switch platform.

The W800 family is an X10 RF receiver used with keypads and motion sensors etc.

* Remove unused code.

* Additions for w800rf32 component and platform code

* Fix w800rf32 minor lint issues and make sure gen_requirements.py correctlly adds w800rf32

* Added dispatch_connect/send and refactor somewhat

* Fix missed indentation lint

* Removed shared entity dict and use async_dispatch code

* Fix long line not caught by lint

* One more line too long, missed it

* Remove unused code and changes for async

* Remove  @callback that shouldn't be there.

* Remove switch platform, can't have read only switch.

* Remove unused CONF_DEBUG

* Remove used vars and make CONF_DEVICES required

* Move CONF_OFF_DELAY to platform, only used there
2018-11-08 18:49:00 +01:00
Joakim Sørensen
fd2987e551 Add new launch sensor to keep track of space launches. (#18274)
* Add new launch sensor to keep track of space launches.

* Added attribution to Launch Library.

* Adds data class and throtle, reuse aiohttp session.

* Add one extra blank line before the new class..

* Change throttle to simpler SCAN_INTERVAL.

* Remove the usage of the LaunchData class.

* Bump pylaunches, remove . from log, fix line breaker for agency_country_code, remove CONF_ from ATTRIBUTION.
2018-11-08 16:37:11 +01:00
Matthias Urlichs
9472529d43 Doc fix: a circular dependency does not raise an error. (#18298)
This is easier to handle than raising an exception: a circular
dependency causes multiple error entries in the log, which is what we
want.

This is harder to achieve with an exception. Since there is only one
user of this code, I choose to fix the documentation -- instead of
adding a lot of mostly-useless exception handling.

Closes: #13147
2018-11-08 12:59:58 +01:00
Paulus Schoutsen
f7f0a4e811 System groups (#18303)
* Add read only and admin policies

* Migrate to 2 system groups

* Add system groups

* Add system groups admin & read only

* Dont' mutate parameters

* Fix types
2018-11-08 12:57:00 +01:00
Paulus Schoutsen
54b0cde52a Remove Velbus climate platform (#18319) 2018-11-08 11:17:44 +01:00
Joakim Sørensen
a016dd2140 Bump pyhaversion to 2.0.2 (#18318) 2018-11-08 10:07:49 +01:00
Pascal Vizeli
878e369c4a Fix log error message (#18305)
* Fix log error message

* Update __init__.py
2018-11-08 10:07:48 +01:00
Nick Touran
599542394a Added optional precision configuration option to generic_thermostat. (#18317)
* Added optional precision configuration option to generic_thermostat.

* Added optional precision configuration option to generic_thermostat.

* Style update.
2018-11-08 09:39:35 +01:00
Joakim Sørensen
7fed49c4ab Bump pyhaversion to 2.0.2 (#18318) 2018-11-08 09:27:51 +01:00
Aaron Bach
954191c385 Add support for 17track.net package sensors (#18038)
* Add support for 17track.net package sensors

* Updated CODEOWNERS

* Addressing comments

* Fixed requirements

* Member comments

* Revert "Member comments"

This reverts commit 61a19d7966.

* Member comments

* Member comments
2018-11-07 22:25:08 -07:00
Pascal Vizeli
e2fca0691e Fix log error message (#18305)
* Fix log error message

* Update __init__.py
2018-11-08 00:33:51 +01:00
Paulus Schoutsen
f24979c7cf Bumped version to 0.82.0b4 2018-11-07 21:58:18 +01:00
Jeff Wilson
5bab0018f5 Make flux switch async (#18277)
* Make flux switch async

* Fix line lengths

* Fix indentation

* Set tracker before await to avoid race condition

* Fix lint errors
2018-11-07 21:52:55 +01:00
Pascal Vizeli
f541b101c9 Bugfix discovery (delete/mqtt) call for Hass.io (#18159)
* Bugfix discovery delete call for Hass.io

* Fix host

* fix tests
2018-11-07 21:45:47 +01:00
Joakim Sørensen
0bf054fb59 Update pyruter to 1.1.0 to be able to reuse aiohttp session. (#18310)
* Update pyruter to 1.1.0 to be able to reuse aiohttp session.

* Taged correct version of pyruter.
2018-11-07 13:54:33 -05:00
kennedyshead
aa4da479b5 Add upload and download sensors and component for asuswrt (#17757)
* Adds upload and download sensors for asuswrt and makes it a component.

* Rebase

* removes warnings

* Fixing review issues

* More robust connection phase

* Generate dependencies

* Not needed try catch

* Rename sensors

* Revorked tests so they can be turned on again

* Using component setup

* Test through correct setup

* Forgot we dont need to worry about older py
2018-11-07 18:32:13 +01:00
Steven Looman
d93716bd84 Add SUPPORT_SEEK for DLNA DMR devices + now (better) providing media_image_url for DLNA DMR devices (#18157)
* Upgrade to async_upnp_client==0.13.2, now (better) providing media_image_url for DLNA DMR devices

* Add SUPPORT_SEEK for DLNA DMR devices
2018-11-07 13:48:51 +01:00
Tsvi Mostovicz
f99701f41a Upgrade hdate to 0.7.5 (#18296)
In 0.7.x the API to HDate was cleaned up so as to move logic from homeassistant to
the HDate external library.

This commit removes all the superfluous code, updates the required tests and changes the
requirement from version 0.6.5 to 0.7.5
2018-11-07 13:30:41 +01:00
Jorim Tielemans
29be78e08e Improve version sensor (#18292)
* Validate value against valid list

* Show correct name

Constants in alphabetical order.
Added default name when not showing the local/current version.

* Add icon

Icon was already defined but not set

* Unnecessary "elif" after "return" (no-else-return)
2018-11-07 13:28:25 +01:00
majuss
ec732c896d Add support for Lupusec alarm control panel (#17691)
* Adds support for Lupusec alarm control panel

* fixed various mostly cosmetic issues

* fixed generic type of binary sensors

* fixed some formatting; removed scan interval completely -> defaults now to 2 secs

* removed unused data caches; added check if binary sensor class exists

* cosmetics

* generic type fix

* small fix

* small fixes

* guard clause added

* small fixes
2018-11-07 12:51:12 +01:00
Paulus Schoutsen
00c1b40940 Add translations 2018-11-07 10:45:29 +01:00
Paulus Schoutsen
4287d1dd2d Bump frontend to 20181107.0 2018-11-07 10:45:15 +01:00
Oleksii Serdiuk
5cee9942a6 Darksky: Add icon to summary sensors (#18275)
The icon changes dynamically, based on summary.
2018-11-07 10:01:05 +01:00
Adam Mills
65be458ce0 Update input component tests to async (#18290) 2018-11-07 09:56:32 +01:00
Adam Mills
ce069be16e Update manual ACP tests to async (#18289) 2018-11-07 09:56:24 +01:00
Adam Mills
0d7cb54872 Update litejet automation tests to async (#18287) 2018-11-07 09:56:10 +01:00
Adam Mills
6935b62487 Remove skipped device tracker tests (#18291) 2018-11-07 09:55:55 +01:00
mvn23
e698fc2553 Bump pyotgw to 0.3b1 (#18286)
* Bump pyotgw to 0.3b1

* Update requirements_all.txt
2018-11-07 09:55:22 +01:00
Sebastian Muszynski
df3d82e0e3 Use async_add_executor_job at the xiaomi_miio platforms (#18294) 2018-11-07 09:03:35 +01:00
Johann Kellerman
35ae85e14e SMA Guard against older pysma (#18278) 2018-11-07 08:52:51 +02:00
Pascal Vizeli
c89dade619 Migrate python-openzwave to homeassistant-pyozw (#18268)
* Migrate python-openzwave to homeassistant-pyozw

* Update requirements_all.txt

* Fix requirements
2018-11-06 22:08:04 +01:00
Rohan Kapoor
bdba3852d0 Split out geofency with a component and platform (#17933)
* Split out geofency with a component and platform

* Make geofency component/device_tracker more async

* Move geofency tests to new package

* Remove coroutine in geofency callback

* Lint

* Fix coroutine in geofency callback

* Fix incorrect patch
2018-11-06 20:12:03 +01:00
Joakim Sørensen
c41ca37a04 Add Norwegian Public Transportation sensor (Ruter). (#18237)
* Add Norwegian Public Transportation sensor (Ruter).

* Corrected typo.

* change stopid to stop_id, actually use attributes, changed logging, corrected link, removed unused variable.

* Change to RuterSensor for the class, and move logic to me more readable.

* Use correct sensor class.

* Add return if blank list, remove else
2018-11-06 19:49:38 +01:00
Adam Mills
917ebed4c9 Update PR checklist with commented out code check (#18272)
Along with hopefully helping resolve these actual problems, a nudge for people to look at their own code might help catch other quick fixes before anyone else has to review a PR.
2018-11-06 19:47:19 +01:00
Paulus Schoutsen
43ae57cc59 Lint 2018-11-06 19:27:52 +01:00
Pascal Vizeli
f4d3d5904e HmIP thermostat fix with operations (#18068)
* HmIP thermostat fix with operations

* Update homematic.py
2018-11-06 16:36:12 +01:00
Paulus Schoutsen
bde02afe4f Normalize MAC addresses (#16916)
* Normalize MAC addresses

* Handle all mac formats
2018-11-06 16:33:31 +01:00
Matt Schmitt
42fea4fb97 Add services to set/update and cancel Nest ETA (#17836)
* Add service to cancel ETA

* Update test requirements

* Change service name and update logging

* Reformat logging to verify structures
2018-11-06 16:11:10 +01:00
Daniel Shokouhi
52074ee9bb Update Neato states, actions and alerts based on Neato docs (#17353)
* Update neato sstates actions and alerts based on neato docs

* Remove unused STATES
2018-11-06 16:10:39 +01:00
Georgi Kirichkov
eb385515c8 Switch OwnTracks HTTP to use webhook component (#17034)
* Update OwnTracks_HTTP to use the webhook component

* Update owntracks_http.py

* Update owntracks_http.py
2018-11-06 16:10:17 +01:00
emontnemery
589764900a Move more MQTT platforms to config entries (#18180)
* Move Lock MQTT platform to config entries

* Move MQTT JSON Light platform to config entries

* Review comments

* Review comments

* Revert mqtt_json changes
2018-11-06 16:09:46 +01:00
Filip Bednárik
9329ec2486 Add support for switches in homekit controller (#17916) 2018-11-06 15:32:32 +01:00
Ludovico de Nittis
47af194d06 Add iAlarm "triggered" support (#18263) 2018-11-06 15:30:41 +01:00
kennedyshead
39412dc930 Adding current_humidity to attributes if its not None. (#18261)
* Adding current humidity if not None

* Removed the logic in supported feature

* More appropriate placement
2018-11-06 15:18:46 +01:00
Fabian Affolter
2e517ab6bc Enable config flow for Luftdaten (#17700)
* Move file to new location

* Update requirement

* Enable config flow

* Add luftdaten

* Add tests

* Update

* Add constants

* Changes according to the review comments

* Remove wrong entry from flows

* Fix dict handling

* Add callback and use OrderedDict

* Remve leftover

* Fix

* Remove await
2018-11-06 14:27:52 +01:00
Matthew Parlane
7933bd7f91 Allow alexa to simply turn on and off climate components. (#16989) 2018-11-06 14:17:56 +01:00
Sebastian Muszynski
58c77e1f55 Add Xiaomi Air Purifier 2s support (#18260) 2018-11-06 14:16:15 +01:00
Tyler
e3a8f3a106 Add input_boolean reporting to Prometheus (#17966) 2018-11-06 13:19:36 +01:00
akloeckner
1aba4699b9 Add attributes of ARP table (#17987)
* Add attributes of ARP table

This adds the device attributes available in the ARP table and a few more. Implementation is inspired by the nmap scanner.

* lint spaces
2018-11-06 13:15:48 +01:00
4lloyd
114bc8ec18 Support eco mode option on Ziggo Mediabox XL (#17990)
* Added eco mode option to Ziggo Mediabox XL

* Changed eco_mode_on to eco_mode

* Removed eco_mode option, the player is unavailable when offline

* Timeout on connection, on/off states are handled via update

* Improved state detection and added available property
2018-11-06 13:14:52 +01:00
kennedyshead
c6f3c239bb Melissa state_attributes (#18201)
* Melissa attributes

* overide device_state_attributes rather than state_attributes

* Selected attributes

* Adding current humidity rather than a state_attribute
2018-11-06 13:08:58 +01:00
Glen Takahashi
34d7758b4a Correct expose_by_default interaction with expose_domains (#17745)
Based on the documentation here: https://www.home-assistant.io/components/google_assistant/#expose_by_default it seems that expose_by_default means all devices should be exposed unless explicitly set to false, and that regardless if this is set domains in exposed_domains should be exposed.
2018-11-06 12:53:47 +01:00
Joakim Sørensen
2c36b9db1f Add support for Google Home device tracking (#18190)
* Add support for Google Home device tracking.

* Use dict[key] for options.

* Delete googlehome.py.save

* Change stylling of name, and attr mac_address to btle_mac_address, removed unesssesarry attributes copying.
2018-11-06 12:47:53 +01:00
Filip Bednárik
24efda20bf Add additional property to HomeKitSwitch to show whether the Homekit outlet is in use (#17448)
* Add additional property to HomeKitSwitch to show whether the Homekit outlet is in use or not

* Fix issues from review - Remove unused property, simplify and rename the device_state_attributes method
2018-11-06 12:43:47 +01:00
akloeckner
3322fee814 Fritz keepalive (#18155)
* Add keepalive support

- adds keepalive support
- adds debug messages
- corrects CONF_PHONEBOOK and CONF_PREFIXES constants

* Add keepalive config constant

* Fix default value

* More visual indentation

* move to platform

* Move to platform

* Make keepalive default and remove option

* Forgot a few lines
2018-11-06 12:43:16 +01:00
Matthias Urlichs
4581a741bd Report *which* component didn't return a bool (#18258)
* Report *which* component didn't return a bool

* break over-long line
2018-11-06 12:41:39 +01:00
Matthias Urlichs
b506aafbb4 docstring fix (#18257) 2018-11-06 12:41:15 +01:00
Jorim Tielemans
121ec5c684 Add season icons (#18221)
* Add season icons

* Use STATE constants

* Calm down hound

* Update season.py
2018-11-06 12:34:11 +01:00
Matthew Treinish
087bffeaae Add workaround to use notification state for zwave lock state (#17386)
* Add workaround to use notification state for zwave lock state

There are several zwave lock models out there which do not seem to
update the lock state on non-rf events (see #11934 #14632 #14534 for
examples) including kwikset smartkey zwave plus locks (which I own).
In these cases it seems that the notifications for non-rf events the
access_control value is updated but not the primary value for the
lock state, which is what is used to set the is_locked property. To
properly have the lock state accurate for all types of notifications
on these models we need to use the access_control field. This commit
adds a workaround for the 4 models reported to exhibit this behavior
so that home-assistant will reliably set the lock state for all
device notifications.

* Add YRD220 as per adrum to workaround list

* Inline constants
2018-11-06 11:00:48 +01:00
Andrew Hayworth
2bf2214d51 Add support for locks in google assistant component (#18233)
* Add support for locks in google assistant component

This is supported by the smarthome API, but there is no documentation
for it. This work is based on an article I found with screenshots of
documentation that was erroneously uploaded:

https://www.androidpolice.com/2018/01/17/google-assistant-home-can-now-natively-control-smart-locks-august-vivint-first-supported/

Google Assistant now supports unlocking certain locks - Nest and August
come to mind - via this API, and this commit allows Home Assistant to
do so as well.

Notably, I've added a config option `allow_unlock` that controls
whether we actually honor requests to unlock a lock via the google
assistant. It defaults to false.

Additionally, we add the functionNotSupported error, which makes a
little more sense when we're unable to execute the desired state
transition.

https://developers.google.com/actions/reference/smarthome/errors-exceptions#exception_list

* Fix linter warnings

* Ensure that certain groups are never exposed to cloud entities

For example, the group.all_locks entity - we should probably never
expose this to third party cloud integrations. It's risky.

This is not configurable, but can be extended by adding to the
cloud.const.NEVER_EXPOSED_ENTITIES array.

It's implemented in a modestly hacky fashion, because we determine
whether or not a entity should be excluded/included in several ways.

Notably, we define this array in the top level const.py, to avoid
circular import problems between the cloud/alexa components.
2018-11-06 10:39:10 +01:00
Tom Harris
ddee5f8b86 Fix IOLinc sensor (#18250) 2018-11-06 10:36:52 +01:00
Robert Svensson
c5d0440041 deCONZ - manual input fallback in config flow (#18116)
* Add config flow step for manual input
Remove support for loading discovery config from json file

* Small cleanup
Fix all translations to step user instead of step init

* Revert to using step_init

* Small cleanup
Add test_gateway that was forgotten in a previous PR

* Fix hound comment

* Fix empty pydocstring
2018-11-06 10:34:24 +01:00
Bram Kragten
24c110ad3c Lovelace: Duplicate ID check on load config + caching (#18152)
* Add caching + dupl. ID check

* duplicate imports...

* lint

* remove for/else

* found

* Missed one...
2018-11-05 20:12:31 -05:00
Glenn Waters
7077e19cf8 Elk-M1 fixes (#18154)
* Fix default value for temperature unit

* Add defaults for subdomains

* Remove unused import

* Fix PR comment
2018-11-05 20:09:07 -05:00
Mikko Tapionlinna
6f568d1cf6 Update pynetgear to 0.5.1 (#18238) 2018-11-05 19:00:46 -05:00
Sebastian Muszynski
d951ed4d68 Add Xiaomi Smartmi Fresh Air System support (#18097)
* Add Xiaomi Air Fresh VA2 support

* Add LED property again (available now)
2018-11-06 00:09:15 +01:00
Daniel Høyer Iversen
3366d2c1ad Tibber login validate (#18235)
* tibber login validate

* requirements
2018-11-05 23:29:42 +01:00
ehendrix23
46b5b6240f Improve debug log information (#18230)
Added debug log information for when records are purged and added entity_id to existing debug information to identify the entity the debug information is for.
2018-11-05 23:12:46 +01:00
Bram Kragten
abf147ed57 Check if os has chown (#18229) 2018-11-05 21:41:19 +01:00
quthla
c59b038512 Add scenes as switches HomeKit (#17799) 2018-11-05 21:36:30 +01:00
Daniel Høyer Iversen
93b16e7efb Mill room temp (#18203)
* mill, avg room temp

* typo

* Mill device_state_attributes
2018-11-05 20:52:34 +01:00
ehendrix23
561f6996c6 Duplicate entities on discovery (#18074)
* Enhancements for DirecTV media player

Following enhancements have been made:

1. Added debug logging
2. Added ability to change channel using select_source service of the remote platform.
3. State will now show paused if a recorded program is paused, for live TV playing will always be returned.
4. Added the following attributes:
    a. media_position: current position of the media (in seconds)
    b. media_position_updated_at: timestamp when media_position was updated.
   c. source: current source (channel).
   d. media_isbeingrecorded: if current media is being recorded or not.
   e. media_rating: TV/Movie rating of the media
   f. media_recorded: if current media is recorded or live TV
   g. media_starttime: Timestamp media was aired

Reordered properties to follow same order as how they are in __init__.py of remote platform.

* Fixed error and cleaned up few items

Fixed an issue when determining if a program is recorded or not.
Cleaned up some coding.

* Fix issue in checking if DTV device is already configured

If a DTV device was configured before, then discovery would add this device again seperately if the name specified in the configuration is different from the name on the DTV.

This issue is fixed now. Part of the fix also ensure to allow multiple "primary" devices on the network to be discovered.
Further also added debug logging to the setup_platform.

* Further improvements

Some additional improvements related to handling the DATA_DIRECTV in hass.data.

* Fixed flake8 issue

Fixed flake8 issue

* Added available property

Added available property

* Updated to use get_locations()

Replaced doing the request for getLocations with the get_locations() API from DirectPy instead.

* Fix for checking if device is available

Fix for checking if device is available and small update to debug log message.

* Fixed lint issue

Fixed lint issue with unused variable by adding ingore for it as this is for a enumerate

* Updated try/except and removed available

Updated tr/except having the except by the statement we're doing except on.
Removed available, will be a different PR.

* Updated known_devices to be tupples in a set

Updated known_devices to be a tupple in a set, removing loop to determine if client was already added.
2018-11-05 19:33:59 +01:00
vetegrodd
b261c4b7f8 Activate kodi media player progress bar (#17626)
* Added code for progress bar

* Added doc string

* Using in

* More cleaning

* Only update position if needed.
2018-11-05 12:39:37 -05:00
cdce8p
26ba4a56e8 Ignore duplicate state changes GarageDoor HomeKit (#18149)
* Ignore duplicate state changes GarageDoor HomeKit

* Don't ignore service_call
2018-11-05 16:42:19 +01:00
Robert Svensson
dcdae325ea deCONZ - reflect hub status on entities (#18106)
* Support for controlling entity available attribute based on gateways availability

* Fix string not being in imperative mood
2018-11-05 16:21:44 +01:00
ehendrix23
3d4ff74761 Add available property to DirecTV (#18168)
* Enhancements for DirecTV media player

Following enhancements have been made:

1. Added debug logging
2. Added ability to change channel using select_source service of the remote platform.
3. State will now show paused if a recorded program is paused, for live TV playing will always be returned.
4. Added the following attributes:
    a. media_position: current position of the media (in seconds)
    b. media_position_updated_at: timestamp when media_position was updated.
   c. source: current source (channel).
   d. media_isbeingrecorded: if current media is being recorded or not.
   e. media_rating: TV/Movie rating of the media
   f. media_recorded: if current media is recorded or live TV
   g. media_starttime: Timestamp media was aired

Reordered properties to follow same order as how they are in __init__.py of remote platform.

* Fixed error and cleaned up few items

Fixed an issue when determining if a program is recorded or not.
Cleaned up some coding.

* Fix issue in checking if DTV device is already configured

If a DTV device was configured before, then discovery would add this device again seperately if the name specified in the configuration is different from the name on the DTV.

This issue is fixed now. Part of the fix also ensure to allow multiple "primary" devices on the network to be discovered.
Further also added debug logging to the setup_platform.

* Further improvements

Some additional improvements related to handling the DATA_DIRECTV in hass.data.

* Fixed flake8 issue

Fixed flake8 issue

* Added available property

Added available property

* Updated to use get_locations()

Replaced doing the request for getLocations with the get_locations() API from DirectPy instead.

* Fix for checking if device is available

Fix for checking if device is available and small update to debug log message.

* Fixed lint issue

Fixed lint issue with unused variable by adding ingore for it as this is for a enumerate

* Updated try/except and removed available

Updated tr/except having the except by the statement we're doing except on.
Removed available, will be a different PR.

* Add available property

Add the available property to the entiry.
2018-11-05 16:19:03 +01:00
Paulus Schoutsen
81fa74e5ca Remove unrelated scripts (#18219)
* Remove influxDB scripts

* Remove ancient db migrator

* Update requirements
2018-11-05 16:14:34 +01:00
kennedyshead
f9f53fd278 Removes melissa sensors (they should be state attributes as implemented in #18201) (#18214) 2018-11-05 16:10:30 +01:00
Adam Belebczuk
36524e9d3f Bump version of pywemo to 0.4.29 (#18217) 2018-11-05 13:23:46 +01:00
Paulus Schoutsen
bf54582d76 Cloud conf (#18216)
* Add original config to entityfilter

* Add alexa/google config to cloud status call

* Lint
2018-11-05 13:21:03 +01:00
Marcel Hoppe
8de79ed57c add service to reconnect the bot (#18142) 2018-11-05 13:14:22 +01:00
quthla
8ee0e0c6c6 Turn off not cancellable scripts automatically HomeKit (#17793) 2018-11-05 11:11:26 +01:00
Joakim Sørensen
a901c594a9 Add Traccar device tracker (#18200)
* Add Traccar device tracker.

* Updated pytraccar to 0.1.1

* Adds default values for optional options.

* Use dict[key] for options.

* remove logging, duplicate by core
2018-11-05 09:28:02 +01:00
Paulus Schoutsen
2e9132873a Webhook names (#18206)
* Add new automation_info param to async_trigger

* Add domain and name to webhook registration and add WS command
2018-11-05 09:23:58 +01:00
Dav0815
6e4ce35a69 Add destination and icon (#18210)
* Add destination and icon

* Update test_transport_nsw.py

* Error handling fix in external lib

* Reverse sensor name change to prevent break
2018-11-05 08:27:20 +01:00
Andrea Tosatto
1c3ef8be55 Implemented tplink_lte components and notify service via SMS (#17111)
* Implemented tplink_lte components and notify service

* Device discovery for the notify component

* Improved the config schema. Small fixes

* Improved login retry mechanism

* Log successful connection only on retries

* Removed CancelledError handlers and small fixes
2018-11-05 02:09:29 +01:00
Ville Skyttä
922f34f72d Add more type hints to helpers (#18196)
* Test typing for helpers.__init__ and temperature

* Add type hints to helpers.sun

* Add type hints to helpers.signal

* Add type hints to helpers.entity_values

* Add type hints to helpers.dispatcher
2018-11-04 22:46:42 +01:00
cdce8p
959fa81ea6 Fix temperature interval Thermostat HomeKit (#18192)
* Will round to nearest .0 or .5
2018-11-04 22:04:51 +01:00
Martin Hjelmare
9a6c229b1d Refactor mysensors message handling (#17214)
* Refactor mysensors message handling

* Add handler module and register handlers per message type or message
  sub-type. This will allow easier extension of message handling in the
  future.
* Move some common functions to a helpers module.

* Add node handler and signal

* Fix inconsistent return

* Upgrade pymysensors to 0.18.0

* Fix bug in message modification.
2018-11-04 21:08:27 +01:00
rafale77
4a7507bcea Update python-openzwave to 0.4.11 (#18160)
* Update Python OpenZWave to 0.4.11

* Update requirements_all.txt
2018-11-04 14:21:53 -05:00
Johann Kellerman
44556a86e3 SMA: Optional import in schema & backoff fix (#18099) 2018-11-04 19:09:14 +02:00
Fabian Affolter
e161dc3b77 Upgrade toonlib to 1.1.3 (#18189) 2018-11-04 17:22:03 +01:00
Troy Kelly
dbf721cd2c Added AU (Australia) (#18183)
Added missing Australia region
2018-11-04 15:46:02 +01:00
jjlawren
0992e83f8d Remove config (breaking change) (#18153) 2018-11-04 15:20:32 +01:00
Pascal Vizeli
a498e15910 Add support for TensorFlow in official docker (#18191) 2018-11-04 15:19:48 +01:00
Pascal Vizeli
27e159f63f Handle TensorFlow like OpenCV (#18185)
* Handle TensorFlow like OpenCV

* Update requirements_all.txt
2018-11-04 15:15:14 +01:00
Paulus Schoutsen
7b53238f9b Merge pull request #18188 from home-assistant/816
0.81.6
2018-11-04 14:17:23 +01:00
Paulus Schoutsen
075169a7a9 Bumped version to 0.81.6 2018-11-04 13:20:25 +01:00
Pascal Vizeli
3abe49bace Bugfix discovery (delete/mqtt) call for Hass.io (#18159)
* Bugfix discovery delete call for Hass.io

* Fix host

* fix tests
2018-11-04 13:20:20 +01:00
Pascal Vizeli
eb0d989c88 Bugfix discovery (delete/mqtt) call for Hass.io (#18159)
* Bugfix discovery delete call for Hass.io

* Fix host

* fix tests
2018-11-04 12:19:04 +01:00
Jorim Tielemans
42cb23f768 Update Coinbase icons (#18172)
* Add extra icons

and don't rely on the name

* Use dictionary for icons

use safe get() with default value

* Use better vars
2018-11-04 09:50:00 +01:00
Florian Klien
5418e0510d XMPP HTTP upload (#17426)
* notify.xmpp: first working http upload

* extension guessing for upload

* docstrings, flake8, pylint

* hass.async_add_executor_job(...)

* catch more errors, allow unverified SSL request

allow user to specify unverified SSL request to URL
cleaner code
catch more exceptions

* pylint

* catching XMPP exceptions, timeout for requests call

removed calls for roster and presence
added timeout for upload request call
cleared up debug, info, warning messages
cleared up requests call for secure and insecure retrieval of image
catching IqError, IqTimeout, XMPPError from slixmpp
docstring updated

* added timout for http upload of local files

* timeout, mimetypes, random filenames

guessing filetypes and mimetypes with stdlib mimetypes
setting a random filename for privacy
working around slixmpp timeout issues with asyncio.wait_for

* code cleanup

* added file upload for rooms/groupchats

* version bump for slixmpp to 1.4.1

added NotConnectedError, removed double catches of IqErrors
removed asyncio import

* slixmpp 1.4.1 in requirements_all

* added url and path templating

* Minor changes

* fixed review requests

fixed possible path issue for foo/../bar/ paths
fixed possible access for non-whitelisted files
fixed None or X
fixed try-else block, moved else block into try
fixed raising error in upload_file if url is None
fixed using data.get after it's already been checked
fixed added docstring for tiny get_url function
2018-11-04 09:17:05 +01:00
Anders Melchiorsen
164c68093b Improve netgear_lte logging when unconnected (#18163)
* Improve netgear_lte logging when unconnected

* Use callback
2018-11-04 09:15:57 +01:00
Jorim Tielemans
5dd691e55d Rename huawei_lte.py to test_huawei_lte.py (#18170) 2018-11-04 01:33:05 +01:00
Corey Edwards
155df912e5 Add option to manually specify device detection method (#17852)
* Add option to manually specify device detection method

* Fix style and lint issue
2018-11-03 23:48:08 +01:00
Joakim Sørensen
610b0b6494 Add Tautulli sensor platform (#17835)
* Adds Tautulli as a sensor platform.

* Remove blank last line.

* Rewrite the platform to comply with review.

* Linting issues.

* Remove tailing newline.

* Corrected typo

* Correcte check_connection, removed wierd defaults, added line in imports, removed unused var, use the correct user list.

* Use dict[key] for required config options.

* Minor changes
2018-11-03 23:47:31 +01:00
rafale77
f76ccb636c Add support for various load level devices (#18161) 2018-11-03 22:25:05 +01:00
Paulus Schoutsen
fbcf0880f3 Bump frontend to 20181103.1 2018-11-03 19:18:20 +01:00
800 changed files with 31110 additions and 15524 deletions

View File

@@ -120,6 +120,9 @@ omit =
homeassistant/components/eufy.py
homeassistant/components/*/eufy.py
homeassistant/components/fibaro.py
homeassistant/components/*/fibaro.py
homeassistant/components/gc100.py
homeassistant/components/*/gc100.py
@@ -145,6 +148,9 @@ omit =
homeassistant/components/hive.py
homeassistant/components/*/hive.py
homeassistant/components/hlk_sw16.py
homeassistant/components/*/hlk_sw16.py
homeassistant/components/homekit_controller/__init__.py
homeassistant/components/*/homekit_controller.py
@@ -200,9 +206,15 @@ omit =
homeassistant/components/linode.py
homeassistant/components/*/linode.py
homeassistant/components/lightwave.py
homeassistant/components/*/lightwave.py
homeassistant/components/logi_circle.py
homeassistant/components/*/logi_circle.py
homeassistant/components/lupusec.py
homeassistant/components/*/lupusec.py
homeassistant/components/lutron.py
homeassistant/components/*/lutron.py
@@ -256,6 +268,10 @@ omit =
homeassistant/components/pilight.py
homeassistant/components/*/pilight.py
homeassistant/components/point/__init__.py
homeassistant/components/point/const.py
homeassistant/components/*/point.py
homeassistant/components/switch/qwikswitch.py
homeassistant/components/light/qwikswitch.py
@@ -265,7 +281,7 @@ omit =
homeassistant/components/raincloud.py
homeassistant/components/*/raincloud.py
homeassistant/components/rainmachine/*
homeassistant/components/rainmachine/__init__.py
homeassistant/components/*/rainmachine.py
homeassistant/components/raspihats.py
@@ -313,7 +329,8 @@ omit =
homeassistant/components/tahoma.py
homeassistant/components/*/tahoma.py
homeassistant/components/tellduslive.py
homeassistant/components/tellduslive/__init__.py
homeassistant/components/tellduslive/entry.py
homeassistant/components/*/tellduslive.py
homeassistant/components/tellstick.py
@@ -333,6 +350,9 @@ omit =
homeassistant/components/toon.py
homeassistant/components/*/toon.py
homeassistant/components/tplink_lte.py
homeassistant/components/*/tplink_lte.py
homeassistant/components/tradfri.py
homeassistant/components/*/tradfri.py
@@ -365,6 +385,9 @@ omit =
homeassistant/components/*/webostv.py
homeassistant/components/w800rf32.py
homeassistant/components/*/w800rf32.py
homeassistant/components/wemo.py
homeassistant/components/*/wemo.py
@@ -384,6 +407,8 @@ omit =
homeassistant/components/zha/__init__.py
homeassistant/components/zha/const.py
homeassistant/components/zha/entities/*
homeassistant/components/zha/helpers.py
homeassistant/components/*/zha.py
homeassistant/components/zigbee.py
@@ -474,6 +499,7 @@ omit =
homeassistant/components/device_tracker/freebox.py
homeassistant/components/device_tracker/fritz.py
homeassistant/components/device_tracker/google_maps.py
homeassistant/components/device_tracker/googlehome.py
homeassistant/components/device_tracker/gpslogger.py
homeassistant/components/device_tracker/hitron_coda.py
homeassistant/components/device_tracker/huawei_router.py
@@ -496,6 +522,7 @@ omit =
homeassistant/components/device_tracker/tile.py
homeassistant/components/device_tracker/tomato.py
homeassistant/components/device_tracker/tplink.py
homeassistant/components/device_tracker/traccar.py
homeassistant/components/device_tracker/trackr.py
homeassistant/components/device_tracker/ubus.py
homeassistant/components/downloader.py
@@ -530,6 +557,7 @@ omit =
homeassistant/components/light/lw12wifi.py
homeassistant/components/light/mystrom.py
homeassistant/components/light/nanoleaf_aurora.py
homeassistant/components/light/niko_home_control.py
homeassistant/components/light/opple.py
homeassistant/components/light/osramlightify.py
homeassistant/components/light/piglow.py
@@ -572,7 +600,7 @@ omit =
homeassistant/components/media_player/itunes.py
homeassistant/components/media_player/kodi.py
homeassistant/components/media_player/lg_netcast.py
homeassistant/components/media_player/lg_soundbar.py
homeassistant/components/media_player/lg_soundbar.py
homeassistant/components/media_player/liveboxplaytv.py
homeassistant/components/media_player/mediaroom.py
homeassistant/components/media_player/mpchc.py
@@ -581,6 +609,7 @@ omit =
homeassistant/components/media_player/nadtcp.py
homeassistant/components/media_player/onkyo.py
homeassistant/components/media_player/openhome.py
homeassistant/components/media_player/panasonic_bluray.py
homeassistant/components/media_player/panasonic_viera.py
homeassistant/components/media_player/pandora.py
homeassistant/components/media_player/philips_js.py
@@ -617,7 +646,6 @@ omit =
homeassistant/components/notify/group.py
homeassistant/components/notify/hipchat.py
homeassistant/components/notify/homematic.py
homeassistant/components/notify/instapush.py
homeassistant/components/notify/kodi.py
homeassistant/components/notify/lannouncer.py
homeassistant/components/notify/llamalab_automate.py
@@ -696,6 +724,7 @@ omit =
homeassistant/components/sensor/fints.py
homeassistant/components/sensor/fitbit.py
homeassistant/components/sensor/fixer.py
homeassistant/components/sensor/flunearyou.py
homeassistant/components/sensor/folder.py
homeassistant/components/sensor/foobot.py
homeassistant/components/sensor/fritzbox_callmonitor.py
@@ -720,6 +749,7 @@ omit =
homeassistant/components/sensor/kwb.py
homeassistant/components/sensor/lacrosse.py
homeassistant/components/sensor/lastfm.py
homeassistant/components/sensor/launch_library.py
homeassistant/components/sensor/linky.py
homeassistant/components/sensor/linux_battery.py
homeassistant/components/sensor/loopenergy.py
@@ -758,15 +788,18 @@ omit =
homeassistant/components/sensor/pushbullet.py
homeassistant/components/sensor/pvoutput.py
homeassistant/components/sensor/pyload.py
homeassistant/components/sensor/qbittorrent.py
homeassistant/components/sensor/qnap.py
homeassistant/components/sensor/radarr.py
homeassistant/components/sensor/rainbird.py
homeassistant/components/sensor/ripple.py
homeassistant/components/sensor/rtorrent.py
homeassistant/components/sensor/ruter.py
homeassistant/components/sensor/scrape.py
homeassistant/components/sensor/sensehat.py
homeassistant/components/sensor/serial_pm.py
homeassistant/components/sensor/serial.py
homeassistant/components/sensor/seventeentrack.py
homeassistant/components/sensor/sht31.py
homeassistant/components/sensor/shodan.py
homeassistant/components/sensor/sigfox.py
@@ -786,9 +819,11 @@ omit =
homeassistant/components/sensor/swiss_public_transport.py
homeassistant/components/sensor/syncthru.py
homeassistant/components/sensor/synologydsm.py
homeassistant/components/sensor/srp_energy.py
homeassistant/components/sensor/systemmonitor.py
homeassistant/components/sensor/sytadin.py
homeassistant/components/sensor/tank_utility.py
homeassistant/components/sensor/tautulli.py
homeassistant/components/sensor/ted5000.py
homeassistant/components/sensor/temper.py
homeassistant/components/sensor/thermoworks_smoke.py

View File

@@ -13,6 +13,7 @@
## Checklist:
- [ ] The code change is tested and works locally.
- [ ] Local tests pass with `tox`. **Your PR cannot be merged unless tests pass**
- [ ] There is no commented out code in this PR.
If user exposed functionality or configuration variables are added/changed:
- [ ] Documentation added/updated in [home-assistant.io](https://github.com/home-assistant/home-assistant.io)

View File

@@ -51,6 +51,7 @@ homeassistant/components/alarm_control_panel/egardia.py @jeroenterheerdt
homeassistant/components/alarm_control_panel/manual_mqtt.py @colinodell
homeassistant/components/binary_sensor/hikvision.py @mezz64
homeassistant/components/binary_sensor/threshold.py @fabaff
homeassistant/components/binary_sensor/uptimerobot.py @ludeeus
homeassistant/components/camera/yi.py @bachya
homeassistant/components/climate/ephember.py @ttroy50
homeassistant/components/climate/eq3btsmart.py @rytilahti
@@ -61,9 +62,11 @@ homeassistant/components/cover/group.py @cdce8p
homeassistant/components/cover/template.py @PhracturedBlue
homeassistant/components/device_tracker/asuswrt.py @kennedyshead
homeassistant/components/device_tracker/automatic.py @armills
homeassistant/components/device_tracker/googlehome.py @ludeeus
homeassistant/components/device_tracker/huawei_router.py @abmantis
homeassistant/components/device_tracker/quantum_gateway.py @cisasteelersfan
homeassistant/components/device_tracker/tile.py @bachya
homeassistant/components/device_tracker/traccar.py @ludeeus
homeassistant/components/device_tracker/bt_smarthub.py @jxwolstenholme
homeassistant/components/history_graph.py @andrey-git
homeassistant/components/influx.py @fabaff
@@ -102,14 +105,15 @@ homeassistant/components/sensor/darksky.py @fabaff
homeassistant/components/sensor/file.py @fabaff
homeassistant/components/sensor/filter.py @dgomes
homeassistant/components/sensor/fixer.py @fabaff
homeassistant/components/sensor/flunearyou.py.py @bachya
homeassistant/components/sensor/gearbest.py @HerrHofrat
homeassistant/components/sensor/gitter.py @fabaff
homeassistant/components/sensor/glances.py @fabaff
homeassistant/components/sensor/gpsd.py @fabaff
homeassistant/components/sensor/irish_rail_transport.py @ttroy50
homeassistant/components/sensor/jewish_calendar.py @tsvi
homeassistant/components/sensor/launch_library.py @ludeeus
homeassistant/components/sensor/linux_battery.py @fabaff
homeassistant/components/sensor/luftdaten.py @fabaff
homeassistant/components/sensor/miflora.py @danielhiversen @ChristianKuehnel
homeassistant/components/sensor/min_max.py @fabaff
homeassistant/components/sensor/moon.py @fabaff
@@ -119,20 +123,25 @@ homeassistant/components/sensor/pi_hole.py @fabaff
homeassistant/components/sensor/pollen.py @bachya
homeassistant/components/sensor/pvoutput.py @fabaff
homeassistant/components/sensor/qnap.py @colinodell
homeassistant/components/sensor/ruter.py @ludeeus
homeassistant/components/sensor/scrape.py @fabaff
homeassistant/components/sensor/serial.py @fabaff
homeassistant/components/sensor/seventeentrack.py @bachya
homeassistant/components/sensor/shodan.py @fabaff
homeassistant/components/sensor/sma.py @kellerza
homeassistant/components/sensor/sql.py @dgomes
homeassistant/components/sensor/statistics.py @fabaff
homeassistant/components/sensor/swiss*.py @fabaff
homeassistant/components/sensor/sytadin.py @gautric
homeassistant/components/sensor/tautulli.py @ludeeus
homeassistant/components/sensor/time_data.py @fabaff
homeassistant/components/sensor/version.py @fabaff
homeassistant/components/sensor/waqi.py @andrey-git
homeassistant/components/sensor/worldclock.py @fabaff
homeassistant/components/shiftr.py @fabaff
homeassistant/components/spaceapi.py @fabaff
homeassistant/components/switch/switchbot.py @danielhiversen
homeassistant/components/switch/switchmate.py @danielhiversen
homeassistant/components/switch/tplink.py @rytilahti
homeassistant/components/vacuum/roomba.py @pschmitt
homeassistant/components/weather/__init__.py @fabaff
@@ -156,9 +165,12 @@ homeassistant/components/*/bmw_connected_drive.py @ChristianKuehnel
homeassistant/components/*/broadlink.py @danielhiversen
# C
homeassistant/components/cloudflare.py @ludeeus
homeassistant/components/counter/* @fabaff
# D
homeassistant/components/daikin.py @fredrike @rofrantz
homeassistant/components/*/daikin.py @fredrike @rofrantz
homeassistant/components/*/deconz.py @kane610
homeassistant/components/digital_ocean.py @fabaff
homeassistant/components/*/digital_ocean.py @fabaff
@@ -189,6 +201,8 @@ homeassistant/components/*/konnected.py @heythisisnate
# L
homeassistant/components/lifx.py @amelchio
homeassistant/components/*/lifx.py @amelchio
homeassistant/components/luftdaten/* @fabaff
homeassistant/components/*/luftdaten.py @fabaff
# M
homeassistant/components/matrix.py @tinloaf
@@ -201,6 +215,10 @@ homeassistant/components/*/mystrom.py @fabaff
homeassistant/components/openuv/* @bachya
homeassistant/components/*/openuv.py @bachya
# P
homeassistant/components/point/* @fredrike
homeassistant/components/*/point.py @fredrike
# Q
homeassistant/components/qwikswitch.py @kellerza
homeassistant/components/*/qwikswitch.py @kellerza
@@ -218,8 +236,8 @@ homeassistant/components/*/simplisafe.py @bachya
# T
homeassistant/components/tahoma.py @philklei
homeassistant/components/*/tahoma.py @philklei
homeassistant/components/tellduslive.py @molobrakos @fredrike
homeassistant/components/*/tellduslive.py @molobrakos @fredrike
homeassistant/components/tellduslive/*.py @fredrike
homeassistant/components/*/tellduslive.py @fredrike
homeassistant/components/tesla.py @zabuldon
homeassistant/components/*/tesla.py @zabuldon
homeassistant/components/thethingsnetwork.py @fabaff

View File

@@ -13,6 +13,7 @@ from homeassistant.core import callback, HomeAssistant
from homeassistant.util import dt as dt_util
from . import auth_store, models
from .const import GROUP_ID_ADMIN
from .mfa_modules import auth_mfa_module_from_config, MultiFactorAuthModule
from .providers import auth_provider_from_config, AuthProvider, LoginFlow
@@ -77,11 +78,6 @@ class AuthManager:
hass, self._async_create_login_flow,
self._async_finish_login_flow)
@property
def active(self) -> bool:
"""Return if any auth providers are registered."""
return bool(self._providers)
@property
def support_legacy(self) -> bool:
"""
@@ -117,6 +113,10 @@ class AuthManager:
"""Retrieve a user."""
return await self._store.async_get_user(user_id)
async def async_get_group(self, group_id: str) -> Optional[models.Group]:
"""Retrieve all groups."""
return await self._store.async_get_group(group_id)
async def async_get_user_by_credentials(
self, credentials: models.Credentials) -> Optional[models.User]:
"""Get a user by credential, return None if not found."""
@@ -127,13 +127,15 @@ class AuthManager:
return None
async def async_create_system_user(self, name: str) -> models.User:
async def async_create_system_user(
self, name: str,
group_ids: Optional[List[str]] = None) -> models.User:
"""Create a system user."""
user = await self._store.async_create_user(
name=name,
system_generated=True,
is_active=True,
groups=[],
group_ids=group_ids or [],
)
self.hass.bus.async_fire(EVENT_USER_ADDED, {
@@ -144,11 +146,10 @@ class AuthManager:
async def async_create_user(self, name: str) -> models.User:
"""Create a user."""
group = (await self._store.async_get_groups())[0]
kwargs = {
'name': name,
'is_active': True,
'groups': [group]
'group_ids': [GROUP_ID_ADMIN]
} # type: Dict[str, Any]
if await self._user_should_be_owner():
@@ -184,6 +185,7 @@ class AuthManager:
credentials=credentials,
name=info.name,
is_active=info.is_active,
group_ids=[GROUP_ID_ADMIN],
)
self.hass.bus.async_fire(EVENT_USER_ADDED, {
@@ -213,6 +215,17 @@ class AuthManager:
'user_id': user.id
})
async def async_update_user(self, user: models.User,
name: Optional[str] = None,
group_ids: Optional[List[str]] = None) -> None:
"""Update a user."""
kwargs = {} # type: Dict[str,Any]
if name is not None:
kwargs['name'] = name
if group_ids is not None:
kwargs['group_ids'] = group_ids
await self._store.async_update_user(user, **kwargs)
async def async_activate_user(self, user: models.User) -> None:
"""Activate a user."""
await self._store.async_activate_user(user)

View File

@@ -1,4 +1,5 @@
"""Storage for auth models."""
import asyncio
from collections import OrderedDict
from datetime import timedelta
import hmac
@@ -10,11 +11,14 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.util import dt as dt_util
from . import models
from .permissions import DEFAULT_POLICY
from .const import GROUP_ID_ADMIN, GROUP_ID_READ_ONLY
from .permissions import PermissionLookup, system_policies
from .permissions.types import PolicyType # noqa: F401
STORAGE_VERSION = 1
STORAGE_KEY = 'auth'
INITIAL_GROUP_NAME = 'All Access'
GROUP_NAME_ADMIN = 'Administrators'
GROUP_NAME_READ_ONLY = 'Read Only'
class AuthStore:
@@ -31,6 +35,7 @@ class AuthStore:
self.hass = hass
self._users = None # type: Optional[Dict[str, models.User]]
self._groups = None # type: Optional[Dict[str, models.Group]]
self._perm_lookup = None # type: Optional[PermissionLookup]
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY,
private=True)
@@ -42,6 +47,14 @@ class AuthStore:
return list(self._groups.values())
async def async_get_group(self, group_id: str) -> Optional[models.Group]:
"""Retrieve all users."""
if self._groups is None:
await self._async_load()
assert self._groups is not None
return self._groups.get(group_id)
async def async_get_users(self) -> List[models.User]:
"""Retrieve all users."""
if self._users is None:
@@ -63,7 +76,7 @@ class AuthStore:
is_active: Optional[bool] = None,
system_generated: Optional[bool] = None,
credentials: Optional[models.Credentials] = None,
groups: Optional[List[models.Group]] = None) -> models.User:
group_ids: Optional[List[str]] = None) -> models.User:
"""Create a new user."""
if self._users is None:
await self._async_load()
@@ -71,11 +84,19 @@ class AuthStore:
assert self._users is not None
assert self._groups is not None
groups = []
for group_id in (group_ids or []):
group = self._groups.get(group_id)
if group is None:
raise ValueError('Invalid group specified {}'.format(group_id))
groups.append(group)
kwargs = {
'name': name,
# Until we get group management, we just put everyone in the
# same group.
'groups': groups or [],
'groups': groups,
'perm_lookup': self._perm_lookup,
} # type: Dict[str, Any]
if is_owner is not None:
@@ -115,6 +136,33 @@ class AuthStore:
self._users.pop(user.id)
self._async_schedule_save()
async def async_update_user(
self, user: models.User, name: Optional[str] = None,
is_active: Optional[bool] = None,
group_ids: Optional[List[str]] = None) -> None:
"""Update a user."""
assert self._groups is not None
if group_ids is not None:
groups = []
for grid in group_ids:
group = self._groups.get(grid)
if group is None:
raise ValueError("Invalid group specified.")
groups.append(group)
user.groups = groups
user.invalidate_permission_cache()
for attr_name, value in (
('name', name),
('is_active', is_active),
):
if value is not None:
setattr(user, attr_name, value)
self._async_schedule_save()
async def async_activate_user(self, user: models.User) -> None:
"""Activate a user."""
user.is_active = True
@@ -224,13 +272,18 @@ class AuthStore:
async def _async_load(self) -> None:
"""Load the users."""
data = await self._store.async_load()
[ent_reg, data] = await asyncio.gather(
self.hass.helpers.entity_registry.async_get_registry(),
self._store.async_load(),
)
# Make sure that we're not overriding data if 2 loads happened at the
# same time
if self._users is not None:
return
self._perm_lookup = perm_lookup = PermissionLookup(ent_reg)
if data is None:
self._set_defaults()
return
@@ -238,38 +291,99 @@ class AuthStore:
users = OrderedDict() # type: Dict[str, models.User]
groups = OrderedDict() # type: Dict[str, models.Group]
# When creating objects we mention each attribute explicetely. This
# Soft-migrating data as we load. We are going to make sure we have a
# read only group and an admin group. There are two states that we can
# migrate from:
# 1. Data from a recent version which has a single group without policy
# 2. Data from old version which has no groups
has_admin_group = False
has_read_only_group = False
group_without_policy = None
# When creating objects we mention each attribute explicitly. This
# prevents crashing if user rolls back HA version after a new property
# was added.
for group_dict in data.get('groups', []):
policy = None # type: Optional[PolicyType]
if group_dict['id'] == GROUP_ID_ADMIN:
has_admin_group = True
name = GROUP_NAME_ADMIN
policy = system_policies.ADMIN_POLICY
system_generated = True
elif group_dict['id'] == GROUP_ID_READ_ONLY:
has_read_only_group = True
name = GROUP_NAME_READ_ONLY
policy = system_policies.READ_ONLY_POLICY
system_generated = True
else:
name = group_dict['name']
policy = group_dict.get('policy')
system_generated = False
# We don't want groups without a policy that are not system groups
# This is part of migrating from state 1
if policy is None:
group_without_policy = group_dict['id']
continue
groups[group_dict['id']] = models.Group(
name=group_dict['name'],
id=group_dict['id'],
policy=group_dict.get('policy', DEFAULT_POLICY),
name=name,
policy=policy,
system_generated=system_generated,
)
migrate_group = None
# If there are no groups, add all existing users to the admin group.
# This is part of migrating from state 2
migrate_users_to_admin_group = (not groups and
group_without_policy is None)
if not groups:
migrate_group = models.Group(
name=INITIAL_GROUP_NAME,
policy=DEFAULT_POLICY
)
groups[migrate_group.id] = migrate_group
# If we find a no_policy_group, we need to migrate all users to the
# admin group. We only do this if there are no other groups, as is
# the expected state. If not expected state, not marking people admin.
# This is part of migrating from state 1
if groups and group_without_policy is not None:
group_without_policy = None
# This is part of migrating from state 1 and 2
if not has_admin_group:
admin_group = _system_admin_group()
groups[admin_group.id] = admin_group
# This is part of migrating from state 1 and 2
if not has_read_only_group:
read_only_group = _system_read_only_group()
groups[read_only_group.id] = read_only_group
for user_dict in data['users']:
# Collect the users group.
user_groups = []
for group_id in user_dict.get('group_ids', []):
# This is part of migrating from state 1
if group_id == group_without_policy:
group_id = GROUP_ID_ADMIN
user_groups.append(groups[group_id])
# This is part of migrating from state 2
if (not user_dict['system_generated'] and
migrate_users_to_admin_group):
user_groups.append(groups[GROUP_ID_ADMIN])
users[user_dict['id']] = models.User(
name=user_dict['name'],
groups=[groups[group_id] for group_id
in user_dict.get('group_ids', [])],
groups=user_groups,
id=user_dict['id'],
is_owner=user_dict['is_owner'],
is_active=user_dict['is_active'],
system_generated=user_dict['system_generated'],
perm_lookup=perm_lookup,
)
if migrate_group is not None and not user_dict['system_generated']:
users[user_dict['id']].groups = [migrate_group]
for cred_dict in data['credentials']:
users[cred_dict['user_id']].credentials.append(models.Credentials(
@@ -356,11 +470,12 @@ class AuthStore:
groups = []
for group in self._groups.values():
g_dict = {
'name': group.name,
'id': group.id,
# Name not read for sys groups. Kept here for backwards compat
'name': group.name
} # type: Dict[str, Any]
if group.policy is not DEFAULT_POLICY:
if group.id not in (GROUP_ID_READ_ONLY, GROUP_ID_ADMIN):
g_dict['policy'] = group.policy
groups.append(g_dict)
@@ -410,13 +525,29 @@ class AuthStore:
"""Set default values for auth store."""
self._users = OrderedDict() # type: Dict[str, models.User]
# Add default group
all_access_group = models.Group(
name=INITIAL_GROUP_NAME,
policy=DEFAULT_POLICY,
)
groups = OrderedDict() # type: Dict[str, models.Group]
groups[all_access_group.id] = all_access_group
admin_group = _system_admin_group()
groups[admin_group.id] = admin_group
read_only_group = _system_read_only_group()
groups[read_only_group.id] = read_only_group
self._groups = groups
def _system_admin_group() -> models.Group:
"""Create system admin group."""
return models.Group(
name=GROUP_NAME_ADMIN,
id=GROUP_ID_ADMIN,
policy=system_policies.ADMIN_POLICY,
system_generated=True,
)
def _system_read_only_group() -> models.Group:
"""Create read only group."""
return models.Group(
name=GROUP_NAME_READ_ONLY,
id=GROUP_ID_READ_ONLY,
policy=system_policies.READ_ONLY_POLICY,
system_generated=True,
)

View File

@@ -3,3 +3,6 @@ from datetime import timedelta
ACCESS_TOKEN_EXPIRATION = timedelta(minutes=30)
MFA_SESSION_EXPIRATION = timedelta(minutes=5)
GROUP_ID_ADMIN = 'system-admin'
GROUP_ID_READ_ONLY = 'system-read-only'

View File

@@ -4,13 +4,14 @@ Sending HOTP through notify service
"""
import logging
from collections import OrderedDict
from typing import Any, Dict, Optional, Tuple, List # noqa: F401
from typing import Any, Dict, Optional, List
import attr
import voluptuous as vol
from homeassistant.const import CONF_EXCLUDE, CONF_INCLUDE
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import ServiceNotFound
from homeassistant.helpers import config_validation as cv
from . import MultiFactorAuthModule, MULTI_FACTOR_AUTH_MODULES, \
@@ -314,8 +315,11 @@ class NotifySetupFlow(SetupFlow):
_generate_otp, self._secret, self._count)
assert self._notify_service
await self._auth_module.async_notify(
code, self._notify_service, self._target)
try:
await self._auth_module.async_notify(
code, self._notify_service, self._target)
except ServiceNotFound:
return self.async_abort(reason='notify_service_not_exist')
return self.async_show_form(
step_id='setup',

View File

@@ -8,6 +8,7 @@ import attr
from homeassistant.util import dt as dt_util
from . import permissions as perm_mdl
from .const import GROUP_ID_ADMIN
from .util import generate_secret
TOKEN_TYPE_NORMAL = 'normal'
@@ -22,6 +23,7 @@ class Group:
name = attr.ib(type=str) # type: Optional[str]
policy = attr.ib(type=perm_mdl.PolicyType)
id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex)
system_generated = attr.ib(type=bool, default=False)
@attr.s(slots=True)
@@ -29,6 +31,9 @@ class User:
"""A user."""
name = attr.ib(type=str) # type: Optional[str]
perm_lookup = attr.ib(
type=perm_mdl.PermissionLookup, cmp=False,
) # type: perm_mdl.PermissionLookup
id = attr.ib(type=str, factory=lambda: uuid.uuid4().hex)
is_owner = attr.ib(type=bool, default=False)
is_active = attr.ib(type=bool, default=False)
@@ -47,7 +52,7 @@ class User:
) # type: Dict[str, RefreshToken]
_permissions = attr.ib(
type=perm_mdl.PolicyPermissions,
type=Optional[perm_mdl.PolicyPermissions],
init=False,
cmp=False,
default=None,
@@ -64,10 +69,24 @@ class User:
self._permissions = perm_mdl.PolicyPermissions(
perm_mdl.merge_policies([
group.policy for group in self.groups]))
group.policy for group in self.groups]),
self.perm_lookup)
return self._permissions
@property
def is_admin(self) -> bool:
"""Return if user is part of the admin group."""
if self.is_owner:
return True
return self.is_active and any(
gr.id == GROUP_ID_ADMIN for gr in self.groups)
def invalidate_permission_cache(self) -> None:
"""Invalidate permission cache."""
self._permissions = None
@attr.s(slots=True)
class RefreshToken:

View File

@@ -1,24 +1,18 @@
"""Permissions for Home Assistant."""
import logging
from typing import ( # noqa: F401
cast, Any, Callable, Dict, List, Mapping, Set, Tuple, Union)
cast, Any, Callable, Dict, List, Mapping, Set, Tuple, Union,
TYPE_CHECKING)
import voluptuous as vol
from homeassistant.core import State
from .common import CategoryType, PolicyType
from .const import CAT_ENTITIES
from .models import PermissionLookup
from .types import PolicyType
from .entities import ENTITY_POLICY_SCHEMA, compile_entities
from .merge import merge_policies # noqa
# Default policy if group has no policy applied.
DEFAULT_POLICY = {
"entities": True
} # type: PolicyType
CAT_ENTITIES = 'entities'
POLICY_SCHEMA = vol.Schema({
vol.Optional(CAT_ENTITIES): ENTITY_POLICY_SCHEMA
})
@@ -29,49 +23,35 @@ _LOGGER = logging.getLogger(__name__)
class AbstractPermissions:
"""Default permissions class."""
def check_entity(self, entity_id: str, key: str) -> bool:
"""Test if we can access entity."""
_cached_entity_func = None
def _entity_func(self) -> Callable[[str, str], bool]:
"""Return a function that can test entity access."""
raise NotImplementedError
def filter_states(self, states: List[State]) -> List[State]:
"""Filter a list of states for what the user is allowed to see."""
raise NotImplementedError
def check_entity(self, entity_id: str, key: str) -> bool:
"""Check if we can access entity."""
entity_func = self._cached_entity_func
if entity_func is None:
entity_func = self._cached_entity_func = self._entity_func()
return entity_func(entity_id, key)
class PolicyPermissions(AbstractPermissions):
"""Handle permissions."""
def __init__(self, policy: PolicyType) -> None:
def __init__(self, policy: PolicyType,
perm_lookup: PermissionLookup) -> None:
"""Initialize the permission class."""
self._policy = policy
self._compiled = {} # type: Dict[str, Callable[..., bool]]
self._perm_lookup = perm_lookup
def check_entity(self, entity_id: str, key: str) -> bool:
"""Test if we can access entity."""
func = self._policy_func(CAT_ENTITIES, compile_entities)
return func(entity_id, (key,))
def filter_states(self, states: List[State]) -> List[State]:
"""Filter a list of states for what the user is allowed to see."""
func = self._policy_func(CAT_ENTITIES, compile_entities)
keys = ('read',)
return [entity for entity in states if func(entity.entity_id, keys)]
def _policy_func(self, category: str,
compile_func: Callable[[CategoryType], Callable]) \
-> Callable[..., bool]:
"""Get a policy function."""
func = self._compiled.get(category)
if func:
return func
func = self._compiled[category] = compile_func(
self._policy.get(category))
_LOGGER.debug("Compiled %s func: %s", category, func)
return func
def _entity_func(self) -> Callable[[str, str], bool]:
"""Return a function that can test entity access."""
return compile_entities(self._policy.get(CAT_ENTITIES),
self._perm_lookup)
def __eq__(self, other: Any) -> bool:
"""Equals check."""
@@ -85,13 +65,9 @@ class _OwnerPermissions(AbstractPermissions):
# pylint: disable=no-self-use
def check_entity(self, entity_id: str, key: str) -> bool:
"""Test if we can access entity."""
return True
def filter_states(self, states: List[State]) -> List[State]:
"""Filter a list of states for what the user is allowed to see."""
return states
def _entity_func(self) -> Callable[[str, str], bool]:
"""Return a function that can test entity access."""
return lambda entity_id, key: True
OwnerPermissions = _OwnerPermissions() # pylint: disable=invalid-name

View File

@@ -0,0 +1,7 @@
"""Permission constants."""
CAT_ENTITIES = 'entities'
SUBCAT_ALL = 'all'
POLICY_READ = 'read'
POLICY_CONTROL = 'control'
POLICY_EDIT = 'edit'

View File

@@ -1,16 +1,12 @@
"""Entity permissions."""
from functools import wraps
from typing import ( # noqa: F401
Callable, Dict, List, Tuple, Union)
from typing import Callable, List, Union # noqa: F401
import voluptuous as vol
from .common import CategoryType, ValueType, SUBCAT_ALL
POLICY_READ = 'read'
POLICY_CONTROL = 'control'
POLICY_EDIT = 'edit'
from .const import SUBCAT_ALL, POLICY_READ, POLICY_CONTROL, POLICY_EDIT
from .models import PermissionLookup
from .types import CategoryType, ValueType
SINGLE_ENTITY_SCHEMA = vol.Any(True, vol.Schema({
vol.Optional(POLICY_READ): True,
@@ -19,6 +15,7 @@ SINGLE_ENTITY_SCHEMA = vol.Any(True, vol.Schema({
}))
ENTITY_DOMAINS = 'domains'
ENTITY_DEVICE_IDS = 'device_ids'
ENTITY_ENTITY_IDS = 'entity_ids'
ENTITY_VALUES_SCHEMA = vol.Any(True, vol.Schema({
@@ -27,33 +24,34 @@ ENTITY_VALUES_SCHEMA = vol.Any(True, vol.Schema({
ENTITY_POLICY_SCHEMA = vol.Any(True, vol.Schema({
vol.Optional(SUBCAT_ALL): SINGLE_ENTITY_SCHEMA,
vol.Optional(ENTITY_DEVICE_IDS): ENTITY_VALUES_SCHEMA,
vol.Optional(ENTITY_DOMAINS): ENTITY_VALUES_SCHEMA,
vol.Optional(ENTITY_ENTITY_IDS): ENTITY_VALUES_SCHEMA,
}))
def _entity_allowed(schema: ValueType, keys: Tuple[str]) \
def _entity_allowed(schema: ValueType, key: str) \
-> Union[bool, None]:
"""Test if an entity is allowed based on the keys."""
if schema is None or isinstance(schema, bool):
return schema
assert isinstance(schema, dict)
return schema.get(keys[0])
return schema.get(key)
def compile_entities(policy: CategoryType) \
-> Callable[[str, Tuple[str]], bool]:
def compile_entities(policy: CategoryType, perm_lookup: PermissionLookup) \
-> Callable[[str, str], bool]:
"""Compile policy into a function that tests policy."""
# None, Empty Dict, False
if not policy:
def apply_policy_deny_all(entity_id: str, keys: Tuple[str]) -> bool:
def apply_policy_deny_all(entity_id: str, key: str) -> bool:
"""Decline all."""
return False
return apply_policy_deny_all
if policy is True:
def apply_policy_allow_all(entity_id: str, keys: Tuple[str]) -> bool:
def apply_policy_allow_all(entity_id: str, key: str) -> bool:
"""Approve all."""
return True
@@ -62,10 +60,11 @@ def compile_entities(policy: CategoryType) \
assert isinstance(policy, dict)
domains = policy.get(ENTITY_DOMAINS)
device_ids = policy.get(ENTITY_DEVICE_IDS)
entity_ids = policy.get(ENTITY_ENTITY_IDS)
all_entities = policy.get(SUBCAT_ALL)
funcs = [] # type: List[Callable[[str, Tuple[str]], Union[None, bool]]]
funcs = [] # type: List[Callable[[str, str], Union[None, bool]]]
# The order of these functions matter. The more precise are at the top.
# If a function returns None, they cannot handle it.
@@ -74,23 +73,46 @@ def compile_entities(policy: CategoryType) \
# Setting entity_ids to a boolean is final decision for permissions
# So return right away.
if isinstance(entity_ids, bool):
def allowed_entity_id_bool(entity_id: str, keys: Tuple[str]) -> bool:
def allowed_entity_id_bool(entity_id: str, key: str) -> bool:
"""Test if allowed entity_id."""
return entity_ids # type: ignore
return allowed_entity_id_bool
if entity_ids is not None:
def allowed_entity_id_dict(entity_id: str, keys: Tuple[str]) \
def allowed_entity_id_dict(entity_id: str, key: str) \
-> Union[None, bool]:
"""Test if allowed entity_id."""
return _entity_allowed(
entity_ids.get(entity_id), keys) # type: ignore
entity_ids.get(entity_id), key) # type: ignore
funcs.append(allowed_entity_id_dict)
if isinstance(device_ids, bool):
def allowed_device_id_bool(entity_id: str, key: str) \
-> Union[None, bool]:
"""Test if allowed device_id."""
return device_ids
funcs.append(allowed_device_id_bool)
elif device_ids is not None:
def allowed_device_id_dict(entity_id: str, key: str) \
-> Union[None, bool]:
"""Test if allowed device_id."""
entity_entry = perm_lookup.entity_registry.async_get(entity_id)
if entity_entry is None or entity_entry.device_id is None:
return None
return _entity_allowed(
device_ids.get(entity_entry.device_id), key # type: ignore
)
funcs.append(allowed_device_id_dict)
if isinstance(domains, bool):
def allowed_domain_bool(entity_id: str, keys: Tuple[str]) \
def allowed_domain_bool(entity_id: str, key: str) \
-> Union[None, bool]:
"""Test if allowed domain."""
return domains
@@ -98,31 +120,31 @@ def compile_entities(policy: CategoryType) \
funcs.append(allowed_domain_bool)
elif domains is not None:
def allowed_domain_dict(entity_id: str, keys: Tuple[str]) \
def allowed_domain_dict(entity_id: str, key: str) \
-> Union[None, bool]:
"""Test if allowed domain."""
domain = entity_id.split(".", 1)[0]
return _entity_allowed(domains.get(domain), keys) # type: ignore
return _entity_allowed(domains.get(domain), key) # type: ignore
funcs.append(allowed_domain_dict)
if isinstance(all_entities, bool):
def allowed_all_entities_bool(entity_id: str, keys: Tuple[str]) \
def allowed_all_entities_bool(entity_id: str, key: str) \
-> Union[None, bool]:
"""Test if allowed domain."""
return all_entities
funcs.append(allowed_all_entities_bool)
elif all_entities is not None:
def allowed_all_entities_dict(entity_id: str, keys: Tuple[str]) \
def allowed_all_entities_dict(entity_id: str, key: str) \
-> Union[None, bool]:
"""Test if allowed domain."""
return _entity_allowed(all_entities, keys)
return _entity_allowed(all_entities, key)
funcs.append(allowed_all_entities_dict)
# Can happen if no valid subcategories specified
if not funcs:
def apply_policy_deny_all_2(entity_id: str, keys: Tuple[str]) -> bool:
def apply_policy_deny_all_2(entity_id: str, key: str) -> bool:
"""Decline all."""
return False
@@ -132,16 +154,16 @@ def compile_entities(policy: CategoryType) \
func = funcs[0]
@wraps(func)
def apply_policy_func(entity_id: str, keys: Tuple[str]) -> bool:
def apply_policy_func(entity_id: str, key: str) -> bool:
"""Apply a single policy function."""
return func(entity_id, keys) is True
return func(entity_id, key) is True
return apply_policy_func
def apply_policy_funcs(entity_id: str, keys: Tuple[str]) -> bool:
def apply_policy_funcs(entity_id: str, key: str) -> bool:
"""Apply several policy functions."""
for func in funcs:
result = func(entity_id, keys)
result = func(entity_id, key)
if result is not None:
return result
return False

View File

@@ -2,7 +2,7 @@
from typing import ( # noqa: F401
cast, Dict, List, Set)
from .common import PolicyType, CategoryType
from .types import PolicyType, CategoryType
def merge_policies(policies: List[PolicyType]) -> PolicyType:

View File

@@ -0,0 +1,17 @@
"""Models for permissions."""
from typing import TYPE_CHECKING
import attr
if TYPE_CHECKING:
# pylint: disable=unused-import
from homeassistant.helpers import ( # noqa
entity_registry as ent_reg,
)
@attr.s(slots=True)
class PermissionLookup:
"""Class to hold data for permission lookups."""
entity_registry = attr.ib(type='ent_reg.EntityRegistry')

View File

@@ -0,0 +1,14 @@
"""System policies."""
from .const import CAT_ENTITIES, SUBCAT_ALL, POLICY_READ
ADMIN_POLICY = {
CAT_ENTITIES: True,
}
READ_ONLY_POLICY = {
CAT_ENTITIES: {
SUBCAT_ALL: {
POLICY_READ: True
}
}
}

View File

@@ -1,6 +1,5 @@
"""Common code for permissions."""
from typing import ( # noqa: F401
Mapping, Union, Any)
from typing import Mapping, Union
# MyPy doesn't support recursion yet. So writing it out as far as we need.
@@ -29,5 +28,3 @@ CategoryType = Union[
# Example: { entities: … }
PolicyType = Mapping[str, CategoryType]
SUBCAT_ALL = 'all'

View File

@@ -226,7 +226,11 @@ class LoginFlow(data_entry_flow.FlowHandler):
if user_input is None and hasattr(auth_module,
'async_initialize_login_mfa_step'):
await auth_module.async_initialize_login_mfa_step(self.user.id)
try:
await auth_module.async_initialize_login_mfa_step(self.user.id)
except HomeAssistantError:
_LOGGER.exception('Error initializing MFA step')
return self.async_abort(reason='unknown_error')
if user_input is not None:
expires = self.created_at + MFA_SESSION_EXPIRATION

View File

@@ -1,8 +1,6 @@
"""Home Assistant auth provider."""
import base64
from collections import OrderedDict
import hashlib
import hmac
from typing import Any, Dict, List, Optional, cast
import bcrypt
@@ -11,12 +9,10 @@ import voluptuous as vol
from homeassistant.const import CONF_ID
from homeassistant.core import callback, HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.async_ import run_coroutine_threadsafe
from . import AuthProvider, AUTH_PROVIDER_SCHEMA, AUTH_PROVIDERS, LoginFlow
from ..models import Credentials, UserMeta
from ..util import generate_secret
STORAGE_VERSION = 1
@@ -62,7 +58,6 @@ class Data:
if data is None:
data = {
'salt': generate_secret(),
'users': []
}
@@ -94,39 +89,11 @@ class Data:
user_hash = base64.b64decode(found['password'])
# if the hash is not a bcrypt hash...
# provide a transparant upgrade for old pbkdf2 hash format
if not (user_hash.startswith(b'$2a$')
or user_hash.startswith(b'$2b$')
or user_hash.startswith(b'$2x$')
or user_hash.startswith(b'$2y$')):
# IMPORTANT! validate the login, bail if invalid
hashed = self.legacy_hash_password(password)
if not hmac.compare_digest(hashed, user_hash):
raise InvalidAuth
# then re-hash the valid password with bcrypt
self.change_password(found['username'], password)
run_coroutine_threadsafe(
self.async_save(), self.hass.loop
).result()
user_hash = base64.b64decode(found['password'])
# bcrypt.checkpw is timing-safe
if not bcrypt.checkpw(password.encode(),
user_hash):
raise InvalidAuth
def legacy_hash_password(self, password: str,
for_storage: bool = False) -> bytes:
"""LEGACY password encoding."""
# We're no longer storing salts in data, but if one exists we
# should be able to retrieve it.
salt = self._data['salt'].encode() # type: ignore
hashed = hashlib.pbkdf2_hmac('sha512', password.encode(), salt, 100000)
if for_storage:
hashed = base64.b64encode(hashed)
return hashed
# pylint: disable=no-self-use
def hash_password(self, password: str, for_storage: bool = False) -> bytes:
"""Encode a password."""

View File

@@ -4,16 +4,19 @@ Support Legacy API password auth provider.
It will be removed when auth system production ready
"""
import hmac
from typing import Any, Dict, Optional, cast
from typing import Any, Dict, Optional, cast, TYPE_CHECKING
import voluptuous as vol
from homeassistant.components.http import HomeAssistantHTTP # noqa: F401
from homeassistant.core import callback
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from . import AuthProvider, AUTH_PROVIDER_SCHEMA, AUTH_PROVIDERS, LoginFlow
from ..models import Credentials, UserMeta
from .. import AuthManager
from ..models import Credentials, UserMeta, User
if TYPE_CHECKING:
from homeassistant.components.http import HomeAssistantHTTP # noqa: F401
USER_SCHEMA = vol.Schema({
@@ -31,6 +34,24 @@ class InvalidAuthError(HomeAssistantError):
"""Raised when submitting invalid authentication."""
async def async_get_user(hass: HomeAssistant) -> User:
"""Return the legacy API password user."""
auth = cast(AuthManager, hass.auth) # type: ignore
found = None
for prv in auth.auth_providers:
if prv.type == 'legacy_api_password':
found = prv
break
if found is None:
raise ValueError('Legacy API password provider not found')
return await auth.async_get_or_create_user(
await found.async_get_or_create_credentials({})
)
@AUTH_PROVIDERS.register('legacy_api_password')
class LegacyApiPasswordAuthProvider(AuthProvider):
"""Example auth provider based on hardcoded usernames and passwords."""

View File

@@ -115,11 +115,6 @@ async def async_from_config_dict(config: Dict[str, Any],
conf_util.merge_packages_config(
hass, config, core_config.get(conf_util.CONF_PACKAGES, {}))
# Ensure we have no None values after merge
for key, value in config.items():
if not value:
config[key] = {}
hass.config_entries = config_entries.ConfigEntries(hass, config)
await hass.config_entries.async_load()

View File

@@ -25,21 +25,19 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
return
data = hass.data[BLINK_DATA]
# Current version of blinkpy API only supports one sync module. When
# support for additional models is added, the sync module name should
# come from the API.
sync_modules = []
sync_modules.append(BlinkSyncModule(data, 'sync'))
for sync_name, sync_module in data.sync.items():
sync_modules.append(BlinkSyncModule(data, sync_name, sync_module))
add_entities(sync_modules, True)
class BlinkSyncModule(AlarmControlPanel):
"""Representation of a Blink Alarm Control Panel."""
def __init__(self, data, name):
def __init__(self, data, name, sync):
"""Initialize the alarm control panel."""
self.data = data
self.sync = data.sync
self.sync = sync
self._name = name
self._state = None
@@ -68,6 +66,7 @@ class BlinkSyncModule(AlarmControlPanel):
"""Return the state attributes."""
attr = self.sync.attributes
attr['network_info'] = self.data.networks
attr['associated_cameras'] = list(self.sync.cameras.keys())
attr[ATTR_ATTRIBUTION] = DEFAULT_ATTRIBUTION
return attr

View File

@@ -13,9 +13,10 @@ from homeassistant.const import (
CONF_PENDING_TIME, CONF_TRIGGER_TIME)
def setup_platform(hass, config, add_entities, discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the Demo alarm control panel platform."""
add_entities([
async_add_entities([
manual.ManualAlarm(hass, 'Alarm', '1234', None, False, {
STATE_ALARM_ARMED_AWAY: {
CONF_DELAY_TIME: datetime.timedelta(seconds=0),

View File

@@ -12,10 +12,10 @@ import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME, STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED)
STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, STATE_ALARM_TRIGGERED)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pyialarm==0.2']
REQUIREMENTS = ['pyialarm==0.3']
_LOGGER = logging.getLogger(__name__)
@@ -89,6 +89,8 @@ class IAlarmPanel(alarm.AlarmControlPanel):
state = STATE_ALARM_ARMED_AWAY
elif status == self._client.ARMED_STAY:
state = STATE_ALARM_ARMED_HOME
elif status == self._client.TRIGGERED:
state = STATE_ALARM_TRIGGERED
else:
state = None

View File

@@ -0,0 +1,70 @@
"""
This component provides HA alarm_control_panel support for Lupusec System.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/alarm_control_panel.lupusec/
"""
from datetime import timedelta
from homeassistant.components.alarm_control_panel import AlarmControlPanel
from homeassistant.components.lupusec import DOMAIN as LUPUSEC_DOMAIN
from homeassistant.components.lupusec import LupusecDevice
from homeassistant.const import (STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_HOME,
STATE_ALARM_DISARMED,
STATE_ALARM_TRIGGERED)
DEPENDENCIES = ['lupusec']
ICON = 'mdi:security'
SCAN_INTERVAL = timedelta(seconds=2)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up an alarm control panel for a Lupusec device."""
if discovery_info is None:
return
data = hass.data[LUPUSEC_DOMAIN]
alarm_devices = [LupusecAlarm(data, data.lupusec.get_alarm())]
add_entities(alarm_devices)
class LupusecAlarm(LupusecDevice, AlarmControlPanel):
"""An alarm_control_panel implementation for Lupusec."""
@property
def icon(self):
"""Return the icon."""
return ICON
@property
def state(self):
"""Return the state of the device."""
if self._device.is_standby:
state = STATE_ALARM_DISARMED
elif self._device.is_away:
state = STATE_ALARM_ARMED_AWAY
elif self._device.is_home:
state = STATE_ALARM_ARMED_HOME
elif self._device.is_alarm_triggered:
state = STATE_ALARM_TRIGGERED
else:
state = None
return state
def alarm_arm_away(self, code=None):
"""Send arm away command."""
self._device.set_away()
def alarm_disarm(self, code=None):
"""Send disarm command."""
self._device.set_standby()
def alarm_arm_home(self, code=None):
"""Send arm home command."""
self._device.set_home()

View File

@@ -21,7 +21,7 @@ from homeassistant.const import (
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import track_point_in_time
import homeassistant.util.dt as dt_util
from homeassistant.helpers.restore_state import async_get_last_state
from homeassistant.helpers.restore_state import RestoreEntity
_LOGGER = logging.getLogger(__name__)
@@ -116,7 +116,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
)])
class ManualAlarm(alarm.AlarmControlPanel):
class ManualAlarm(alarm.AlarmControlPanel, RestoreEntity):
"""
Representation of an alarm status.
@@ -310,7 +310,7 @@ class ManualAlarm(alarm.AlarmControlPanel):
async def async_added_to_hass(self):
"""Run when entity about to be added to hass."""
state = await async_get_last_state(self.hass, self.entity_id)
state = await self.async_get_last_state()
if state:
self._state = state.state
self._state_ts = state.last_updated

View File

@@ -335,11 +335,8 @@ class ManualMQTTAlarm(alarm.AlarmControlPanel):
return state_attr
def async_added_to_hass(self):
"""Subscribe to MQTT events.
This method must be run in the event loop and returns a coroutine.
"""
async def async_added_to_hass(self):
"""Subscribe to MQTT events."""
async_track_state_change(
self.hass, self.entity_id, self._async_state_changed_listener
)
@@ -359,7 +356,7 @@ class ManualMQTTAlarm(alarm.AlarmControlPanel):
_LOGGER.warning("Received unexpected payload: %s", payload)
return
return mqtt.async_subscribe(
await mqtt.async_subscribe(
self.hass, self._command_topic, message_received, self._qos)
async def _async_state_changed_listener(self, entity_id, old_state,

View File

@@ -19,7 +19,7 @@ from homeassistant.const import (
from homeassistant.components.mqtt import (
ATTR_DISCOVERY_HASH, CONF_AVAILABILITY_TOPIC, CONF_STATE_TOPIC,
CONF_COMMAND_TOPIC, CONF_PAYLOAD_AVAILABLE, CONF_PAYLOAD_NOT_AVAILABLE,
CONF_QOS, CONF_RETAIN, MqttAvailability, MqttDiscoveryUpdate)
CONF_QOS, CONF_RETAIN, MqttAvailability, MqttDiscoveryUpdate, subscription)
from homeassistant.components.mqtt.discovery import MQTT_DISCOVERY_NEW
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect
@@ -51,7 +51,7 @@ PLATFORM_SCHEMA = mqtt.MQTT_BASE_PLATFORM_SCHEMA.extend({
async def async_setup_platform(hass: HomeAssistantType, config: ConfigType,
async_add_entities, discovery_info=None):
"""Set up MQTT alarm control panel through configuration.yaml."""
await _async_setup_entity(hass, config, async_add_entities)
await _async_setup_entity(config, async_add_entities)
async def async_setup_entry(hass, config_entry, async_add_entities):
@@ -59,7 +59,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
async def async_discover(discovery_payload):
"""Discover and add an MQTT alarm control panel."""
config = PLATFORM_SCHEMA(discovery_payload)
await _async_setup_entity(hass, config, async_add_entities,
await _async_setup_entity(config, async_add_entities,
discovery_payload[ATTR_DISCOVERY_HASH])
async_dispatcher_connect(
@@ -67,54 +67,47 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
async_discover)
async def _async_setup_entity(hass, config, async_add_entities,
async def _async_setup_entity(config, async_add_entities,
discovery_hash=None):
"""Set up the MQTT Alarm Control Panel platform."""
async_add_entities([MqttAlarm(
config.get(CONF_NAME),
config.get(CONF_STATE_TOPIC),
config.get(CONF_COMMAND_TOPIC),
config.get(CONF_QOS),
config.get(CONF_RETAIN),
config.get(CONF_PAYLOAD_DISARM),
config.get(CONF_PAYLOAD_ARM_HOME),
config.get(CONF_PAYLOAD_ARM_AWAY),
config.get(CONF_CODE),
config.get(CONF_AVAILABILITY_TOPIC),
config.get(CONF_PAYLOAD_AVAILABLE),
config.get(CONF_PAYLOAD_NOT_AVAILABLE),
discovery_hash,)])
async_add_entities([MqttAlarm(config, discovery_hash)])
class MqttAlarm(MqttAvailability, MqttDiscoveryUpdate,
alarm.AlarmControlPanel):
"""Representation of a MQTT alarm status."""
def __init__(self, name, state_topic, command_topic, qos, retain,
payload_disarm, payload_arm_home, payload_arm_away, code,
availability_topic, payload_available, payload_not_available,
discovery_hash):
def __init__(self, config, discovery_hash):
"""Init the MQTT Alarm Control Panel."""
self._state = STATE_UNKNOWN
self._config = config
self._sub_state = None
availability_topic = config.get(CONF_AVAILABILITY_TOPIC)
payload_available = config.get(CONF_PAYLOAD_AVAILABLE)
payload_not_available = config.get(CONF_PAYLOAD_NOT_AVAILABLE)
qos = config.get(CONF_QOS)
MqttAvailability.__init__(self, availability_topic, qos,
payload_available, payload_not_available)
MqttDiscoveryUpdate.__init__(self, discovery_hash)
self._state = STATE_UNKNOWN
self._name = name
self._state_topic = state_topic
self._command_topic = command_topic
self._qos = qos
self._retain = retain
self._payload_disarm = payload_disarm
self._payload_arm_home = payload_arm_home
self._payload_arm_away = payload_arm_away
self._code = code
self._discovery_hash = discovery_hash
MqttDiscoveryUpdate.__init__(self, discovery_hash,
self.discovery_update)
async def async_added_to_hass(self):
"""Subscribe mqtt events."""
await MqttAvailability.async_added_to_hass(self)
await MqttDiscoveryUpdate.async_added_to_hass(self)
await super().async_added_to_hass()
await self._subscribe_topics()
async def discovery_update(self, discovery_payload):
"""Handle updated discovery message."""
config = PLATFORM_SCHEMA(discovery_payload)
self._config = config
await self.availability_discovery_update(config)
await self._subscribe_topics()
self.async_schedule_update_ha_state()
async def _subscribe_topics(self):
"""(Re)Subscribe to topics."""
@callback
def message_received(topic, payload, qos):
"""Run when new MQTT message has been received."""
@@ -126,8 +119,16 @@ class MqttAlarm(MqttAvailability, MqttDiscoveryUpdate,
self._state = payload
self.async_schedule_update_ha_state()
await mqtt.async_subscribe(
self.hass, self._state_topic, message_received, self._qos)
self._sub_state = await subscription.async_subscribe_topics(
self.hass, self._sub_state,
{'state_topic': {'topic': self._config.get(CONF_STATE_TOPIC),
'msg_callback': message_received,
'qos': self._config.get(CONF_QOS)}})
async def async_will_remove_from_hass(self):
"""Unsubscribe when removed."""
await subscription.async_unsubscribe_topics(self.hass, self._sub_state)
await MqttAvailability.async_will_remove_from_hass(self)
@property
def should_poll(self):
@@ -137,7 +138,7 @@ class MqttAlarm(MqttAvailability, MqttDiscoveryUpdate,
@property
def name(self):
"""Return the name of the device."""
return self._name
return self._config.get(CONF_NAME)
@property
def state(self):
@@ -147,9 +148,10 @@ class MqttAlarm(MqttAvailability, MqttDiscoveryUpdate,
@property
def code_format(self):
"""Return one or more digits/characters."""
if self._code is None:
code = self._config.get(CONF_CODE)
if code is None:
return None
if isinstance(self._code, str) and re.search('^\\d+$', self._code):
if isinstance(code, str) and re.search('^\\d+$', code):
return 'Number'
return 'Any'
@@ -161,8 +163,10 @@ class MqttAlarm(MqttAvailability, MqttDiscoveryUpdate,
if not self._validate_code(code, 'disarming'):
return
mqtt.async_publish(
self.hass, self._command_topic, self._payload_disarm, self._qos,
self._retain)
self.hass, self._config.get(CONF_COMMAND_TOPIC),
self._config.get(CONF_PAYLOAD_DISARM),
self._config.get(CONF_QOS),
self._config.get(CONF_RETAIN))
async def async_alarm_arm_home(self, code=None):
"""Send arm home command.
@@ -172,8 +176,10 @@ class MqttAlarm(MqttAvailability, MqttDiscoveryUpdate,
if not self._validate_code(code, 'arming home'):
return
mqtt.async_publish(
self.hass, self._command_topic, self._payload_arm_home, self._qos,
self._retain)
self.hass, self._config.get(CONF_COMMAND_TOPIC),
self._config.get(CONF_PAYLOAD_ARM_HOME),
self._config.get(CONF_QOS),
self._config.get(CONF_RETAIN))
async def async_alarm_arm_away(self, code=None):
"""Send arm away command.
@@ -183,12 +189,15 @@ class MqttAlarm(MqttAvailability, MqttDiscoveryUpdate,
if not self._validate_code(code, 'arming away'):
return
mqtt.async_publish(
self.hass, self._command_topic, self._payload_arm_away, self._qos,
self._retain)
self.hass, self._config.get(CONF_COMMAND_TOPIC),
self._config.get(CONF_PAYLOAD_ARM_AWAY),
self._config.get(CONF_QOS),
self._config.get(CONF_RETAIN))
def _validate_code(self, code, state):
"""Validate given code."""
check = self._code is None or code == self._code
conf_code = self._config.get(CONF_CODE)
check = conf_code is None or code == conf_code
if not check:
_LOGGER.warning('Wrong code entered for %s', state)
return check

View File

@@ -18,7 +18,7 @@ from homeassistant.const import (
STATE_ALARM_ARMED_CUSTOM_BYPASS)
REQUIREMENTS = ['total_connect_client==0.20']
REQUIREMENTS = ['total_connect_client==0.22']
_LOGGER = logging.getLogger(__name__)

View File

@@ -15,7 +15,7 @@ from homeassistant.const import (
STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['yalesmartalarmclient==0.1.4']
REQUIREMENTS = ['yalesmartalarmclient==0.1.5']
CONF_AREA_ID = 'area_id'

View File

@@ -16,9 +16,9 @@ from homeassistant.components import (
input_boolean, light, lock, media_player, scene, script, sensor, switch)
from homeassistant.const import (
ATTR_DEVICE_CLASS, ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES,
ATTR_TEMPERATURE, ATTR_UNIT_OF_MEASUREMENT, CONF_NAME, SERVICE_LOCK,
SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PAUSE, SERVICE_MEDIA_PLAY,
SERVICE_MEDIA_PREVIOUS_TRACK, SERVICE_MEDIA_STOP,
ATTR_TEMPERATURE, ATTR_UNIT_OF_MEASUREMENT, CLOUD_NEVER_EXPOSED_ENTITIES,
CONF_NAME, SERVICE_LOCK, SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PAUSE,
SERVICE_MEDIA_PLAY, SERVICE_MEDIA_PREVIOUS_TRACK, SERVICE_MEDIA_STOP,
SERVICE_SET_COVER_POSITION, SERVICE_TURN_OFF, SERVICE_TURN_ON,
SERVICE_UNLOCK, SERVICE_VOLUME_SET, STATE_LOCKED, STATE_ON, STATE_UNLOCKED,
TEMP_CELSIUS, TEMP_FAHRENHEIT)
@@ -474,6 +474,26 @@ class _AlexaColorController(_AlexaInterface):
def name(self):
return 'Alexa.ColorController'
def properties_supported(self):
return [{'name': 'color'}]
def properties_retrievable(self):
return True
def get_property(self, name):
if name != 'color':
raise _UnsupportedProperty(name)
hue, saturation = self.entity.attributes.get(
light.ATTR_HS_COLOR, (0, 0))
return {
'hue': hue,
'saturation': saturation / 100.0,
'brightness': self.entity.attributes.get(
light.ATTR_BRIGHTNESS, 0) / 255.0,
}
class _AlexaColorTemperatureController(_AlexaInterface):
"""Implements Alexa.ColorTemperatureController.
@@ -484,6 +504,20 @@ class _AlexaColorTemperatureController(_AlexaInterface):
def name(self):
return 'Alexa.ColorTemperatureController'
def properties_supported(self):
return [{'name': 'colorTemperatureInKelvin'}]
def properties_retrievable(self):
return True
def get_property(self, name):
if name != 'colorTemperatureInKelvin':
raise _UnsupportedProperty(name)
if 'color_temp' in self.entity.attributes:
return color_util.color_temperature_mired_to_kelvin(
self.entity.attributes['color_temp'])
return 0
class _AlexaPercentageController(_AlexaInterface):
"""Implements Alexa.PercentageController.
@@ -717,6 +751,9 @@ class _ClimateCapabilities(_AlexaEntity):
return [_DisplayCategory.THERMOSTAT]
def interfaces(self):
supported = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
if supported & climate.SUPPORT_ON_OFF:
yield _AlexaPowerController(self.entity)
yield _AlexaThermostatController(self.hass, self.entity)
yield _AlexaTemperatureSensor(self.hass, self.entity)
@@ -1194,6 +1231,11 @@ async def async_api_discovery(hass, config, directive, context):
discovery_endpoints = []
for entity in hass.states.async_all():
if entity.entity_id in CLOUD_NEVER_EXPOSED_ENTITIES:
_LOGGER.debug("Not exposing %s because it is never exposed",
entity.entity_id)
continue
if not config.should_expose(entity.entity_id):
_LOGGER.debug("Not exposing %s because filtered by config",
entity.entity_id)
@@ -1205,7 +1247,7 @@ async def async_api_discovery(hass, config, directive, context):
endpoint = {
'displayCategories': alexa_entity.display_categories(),
'additionalApplianceDetails': {},
'cookie': {},
'endpointId': alexa_entity.entity_id(),
'friendlyName': alexa_entity.friendly_name(),
'description': alexa_entity.description(),

View File

@@ -9,7 +9,9 @@ import json
import logging
from aiohttp import web
from aiohttp.web_exceptions import HTTPBadRequest
import async_timeout
import voluptuous as vol
from homeassistant.bootstrap import DATA_LOGGING
from homeassistant.components.http import HomeAssistantView
@@ -20,7 +22,9 @@ from homeassistant.const import (
URL_API_SERVICES, URL_API_STATES, URL_API_STATES_ENTITY, URL_API_STREAM,
URL_API_TEMPLATE, __version__)
import homeassistant.core as ha
from homeassistant.exceptions import TemplateError
from homeassistant.auth.permissions.const import POLICY_READ
from homeassistant.exceptions import (
TemplateError, Unauthorized, ServiceNotFound)
from homeassistant.helpers import template
from homeassistant.helpers.service import async_get_all_descriptions
from homeassistant.helpers.state import AsyncTrackStates
@@ -81,6 +85,8 @@ class APIEventStream(HomeAssistantView):
async def get(self, request):
"""Provide a streaming interface for the event bus."""
if not request['hass_user'].is_admin:
raise Unauthorized()
hass = request.app['hass']
stop_obj = object()
to_write = asyncio.Queue(loop=hass.loop)
@@ -185,7 +191,13 @@ class APIStatesView(HomeAssistantView):
@ha.callback
def get(self, request):
"""Get current states."""
return self.json(request.app['hass'].states.async_all())
user = request['hass_user']
entity_perm = user.permissions.check_entity
states = [
state for state in request.app['hass'].states.async_all()
if entity_perm(state.entity_id, 'read')
]
return self.json(states)
class APIEntityStateView(HomeAssistantView):
@@ -197,6 +209,10 @@ class APIEntityStateView(HomeAssistantView):
@ha.callback
def get(self, request, entity_id):
"""Retrieve state of entity."""
user = request['hass_user']
if not user.permissions.check_entity(entity_id, POLICY_READ):
raise Unauthorized(entity_id=entity_id)
state = request.app['hass'].states.get(entity_id)
if state:
return self.json(state)
@@ -204,6 +220,8 @@ class APIEntityStateView(HomeAssistantView):
async def post(self, request, entity_id):
"""Update state of entity."""
if not request['hass_user'].is_admin:
raise Unauthorized(entity_id=entity_id)
hass = request.app['hass']
try:
data = await request.json()
@@ -236,6 +254,8 @@ class APIEntityStateView(HomeAssistantView):
@ha.callback
def delete(self, request, entity_id):
"""Remove entity."""
if not request['hass_user'].is_admin:
raise Unauthorized(entity_id=entity_id)
if request.app['hass'].states.async_remove(entity_id):
return self.json_message("Entity removed.")
return self.json_message("Entity not found.", HTTP_NOT_FOUND)
@@ -261,6 +281,8 @@ class APIEventView(HomeAssistantView):
async def post(self, request, event_type):
"""Fire events."""
if not request['hass_user'].is_admin:
raise Unauthorized()
body = await request.text()
try:
event_data = json.loads(body) if body else None
@@ -320,8 +342,11 @@ class APIDomainServicesView(HomeAssistantView):
"Data should be valid JSON.", HTTP_BAD_REQUEST)
with AsyncTrackStates(hass) as changed_states:
await hass.services.async_call(
domain, service, data, True, self.context(request))
try:
await hass.services.async_call(
domain, service, data, True, self.context(request))
except (vol.Invalid, ServiceNotFound):
raise HTTPBadRequest()
return self.json(changed_states)
@@ -346,6 +371,8 @@ class APITemplateView(HomeAssistantView):
async def post(self, request):
"""Render a template."""
if not request['hass_user'].is_admin:
raise Unauthorized()
try:
data = await request.json()
tpl = template.Template(data['template'], request.app['hass'])
@@ -363,6 +390,8 @@ class APIErrorLog(HomeAssistantView):
async def get(self, request):
"""Retrieve API error log."""
if not request['hass_user'].is_admin:
raise Unauthorized()
return web.FileResponse(request.app['hass'].data[DATA_LOGGING])

View File

@@ -16,7 +16,7 @@ from homeassistant.helpers import discovery
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pyatv==0.3.10']
REQUIREMENTS = ['pyatv==0.3.12']
_LOGGER = logging.getLogger(__name__)

View File

@@ -0,0 +1,68 @@
"""
Support for ASUSWRT devices.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/asuswrt/
"""
import logging
import voluptuous as vol
from homeassistant.const import (
CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_PORT, CONF_MODE,
CONF_PROTOCOL)
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.discovery import async_load_platform
REQUIREMENTS = ['aioasuswrt==1.1.13']
_LOGGER = logging.getLogger(__name__)
DOMAIN = "asuswrt"
DATA_ASUSWRT = DOMAIN
CONF_PUB_KEY = 'pub_key'
CONF_SSH_KEY = 'ssh_key'
CONF_REQUIRE_IP = 'require_ip'
DEFAULT_SSH_PORT = 22
SECRET_GROUP = 'Password or SSH Key'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Optional(CONF_PROTOCOL, default='ssh'): vol.In(['ssh', 'telnet']),
vol.Optional(CONF_MODE, default='router'): vol.In(['router', 'ap']),
vol.Optional(CONF_PORT, default=DEFAULT_SSH_PORT): cv.port,
vol.Optional(CONF_REQUIRE_IP, default=True): cv.boolean,
vol.Exclusive(CONF_PASSWORD, SECRET_GROUP): cv.string,
vol.Exclusive(CONF_SSH_KEY, SECRET_GROUP): cv.isfile,
vol.Exclusive(CONF_PUB_KEY, SECRET_GROUP): cv.isfile
}),
}, extra=vol.ALLOW_EXTRA)
async def async_setup(hass, config):
"""Set up the asuswrt component."""
from aioasuswrt.asuswrt import AsusWrt
conf = config[DOMAIN]
api = AsusWrt(conf[CONF_HOST], conf.get(CONF_PORT),
conf.get(CONF_PROTOCOL) == 'telnet',
conf[CONF_USERNAME],
conf.get(CONF_PASSWORD, ''),
conf.get('ssh_key', conf.get('pub_key', '')),
conf.get(CONF_MODE), conf.get(CONF_REQUIRE_IP))
await api.connection.async_connect()
if not api.is_connected:
_LOGGER.error("Unable to setup asuswrt component")
return False
hass.data[DATA_ASUSWRT] = api
hass.async_create_task(async_load_platform(
hass, 'sensor', DOMAIN, {}, config))
hass.async_create_task(async_load_platform(
hass, 'device_tracker', DOMAIN, {}, config))
return True

View File

@@ -12,7 +12,7 @@ from requests import RequestException
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_PASSWORD, CONF_USERNAME, CONF_TIMEOUT)
CONF_PASSWORD, CONF_USERNAME, CONF_TIMEOUT, EVENT_HOMEASSISTANT_STOP)
from homeassistant.helpers import discovery
from homeassistant.util import Throttle
@@ -20,7 +20,7 @@ _LOGGER = logging.getLogger(__name__)
_CONFIGURING = {}
REQUIREMENTS = ['py-august==0.6.0']
REQUIREMENTS = ['py-august==0.7.0']
DEFAULT_TIMEOUT = 10
ACTIVITY_FETCH_LIMIT = 10
@@ -116,7 +116,8 @@ def setup_august(hass, config, api, authenticator):
if DOMAIN in _CONFIGURING:
hass.components.configurator.request_done(_CONFIGURING.pop(DOMAIN))
hass.data[DATA_AUGUST] = AugustData(api, authentication.access_token)
hass.data[DATA_AUGUST] = AugustData(
hass, api, authentication.access_token)
for component in AUGUST_COMPONENTS:
discovery.load_platform(hass, component, DOMAIN, {}, config)
@@ -136,9 +137,16 @@ def setup(hass, config):
"""Set up the August component."""
from august.api import Api
from august.authenticator import Authenticator
from requests import Session
conf = config[DOMAIN]
api = Api(timeout=conf.get(CONF_TIMEOUT))
api_http_session = None
try:
api_http_session = Session()
except RequestException as ex:
_LOGGER.warning("Creating HTTP session failed with: %s", str(ex))
api = Api(timeout=conf.get(CONF_TIMEOUT), http_session=api_http_session)
authenticator = Authenticator(
api,
@@ -148,14 +156,29 @@ def setup(hass, config):
install_id=conf.get(CONF_INSTALL_ID),
access_token_cache_file=hass.config.path(AUGUST_CONFIG_FILE))
def close_http_session(event):
"""Close API sessions used to connect to August."""
_LOGGER.debug("Closing August HTTP sessions")
if api_http_session:
try:
api_http_session.close()
except RequestException:
pass
_LOGGER.debug("August HTTP session closed.")
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, close_http_session)
_LOGGER.debug("Registered for HASS stop event")
return setup_august(hass, config, api, authenticator)
class AugustData:
"""August data object."""
def __init__(self, api, access_token):
def __init__(self, hass, api, access_token):
"""Init August data object."""
self._hass = hass
self._api = api
self._access_token = access_token
self._doorbells = self._api.get_doorbells(self._access_token) or []
@@ -201,8 +224,11 @@ class AugustData:
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def _update_device_activities(self, limit=ACTIVITY_FETCH_LIMIT):
"""Update data object with latest from August API."""
_LOGGER.debug("Updating device activities")
_LOGGER.debug("Start retrieving device activities")
for house_id in self.house_ids:
_LOGGER.debug("Updating device activity for house id %s",
house_id)
activities = self._api.get_house_activities(self._access_token,
house_id,
limit=limit)
@@ -211,6 +237,7 @@ class AugustData:
for device_id in device_ids:
self._activities_by_id[device_id] = [a for a in activities if
a.device_id == device_id]
_LOGGER.debug("Completed retrieving device activities")
def get_doorbell_detail(self, doorbell_id):
"""Return doorbell detail."""
@@ -223,7 +250,7 @@ class AugustData:
_LOGGER.debug("Start retrieving doorbell details")
for doorbell in self._doorbells:
_LOGGER.debug("Updating status for %s",
_LOGGER.debug("Updating doorbell status for %s",
doorbell.device_name)
try:
detail_by_id[doorbell.device_id] =\
@@ -267,7 +294,7 @@ class AugustData:
_LOGGER.debug("Start retrieving door status")
for lock in self._locks:
_LOGGER.debug("Updating status for %s",
_LOGGER.debug("Updating door status for %s",
lock.device_name)
try:
@@ -291,7 +318,7 @@ class AugustData:
_LOGGER.debug("Start retrieving locks status")
for lock in self._locks:
_LOGGER.debug("Updating status for %s",
_LOGGER.debug("Updating lock status for %s",
lock.device_name)
try:
status_by_id[lock.device_id] = self._api.get_lock_status(

View File

@@ -13,7 +13,7 @@
"title": "Configureu una contrasenya d'un sol \u00fas a trav\u00e9s del component de notificacions"
},
"setup": {
"description": "**notify.{notify_service}** ha enviat una contrasenya d'un sol \u00fas. Introdu\u00efu-la a continuaci\u00f3:",
"description": "S'ha enviat una contrasenya d'un sol \u00fas mitjan\u00e7ant **notify.{notify_service}**. Introdu\u00efu-la a continuaci\u00f3:",
"title": "Verifiqueu la configuraci\u00f3"
}
},

View File

@@ -0,0 +1,34 @@
{
"mfa_setup": {
"notify": {
"abort": {
"no_available_service": "\u017d\u00e1dn\u00e9 oznamovac\u00ed slu\u017eby nejsou k dispozici."
},
"error": {
"invalid_code": "Neplatn\u00fd k\u00f3d, zkuste to znovu."
},
"step": {
"init": {
"description": "Vyberte pros\u00edm jednu z oznamovac\u00edch slu\u017eeb:",
"title": "Nastavte jednor\u00e1zov\u00e9 heslo dodan\u00e9 komponentou notify"
},
"setup": {
"description": "Jednor\u00e1zov\u00e9 heslo bylo odesl\u00e1no prost\u0159ednictv\u00edm **notify.{notify_service}**. Zadejte jej n\u00ed\u017ee:",
"title": "Ov\u011b\u0159en\u00ed nastaven\u00ed"
}
}
},
"totp": {
"error": {
"invalid_code": "Neplatn\u00fd k\u00f3d, zkuste to znovu. Pokud se tato chyba opakuje, ujist\u011bte se, \u017ee hodiny syst\u00e9mu Home Assistant jsou spr\u00e1vn\u011b nastaveny."
},
"step": {
"init": {
"description": "Chcete-li aktivovat dvoufaktorovou autentizaci pomoc\u00ed jednor\u00e1zov\u00fdch hesel zalo\u017een\u00fdch na \u010dase, na\u010dt\u011bte k\u00f3d QR pomoc\u00ed va\u0161\u00ed autentiza\u010dn\u00ed aplikace. Pokud ji nem\u00e1te, doporu\u010dujeme bu\u010f [Google Authenticator](https://support.google.com/accounts/answer/1066447) nebo [Authy](https://authy.com/). \n\n {qr_code} \n \n Po skenov\u00e1n\u00ed k\u00f3du zadejte \u0161estcifern\u00fd k\u00f3d z aplikace a ov\u011b\u0159te nastaven\u00ed. Pokud m\u00e1te probl\u00e9my se skenov\u00e1n\u00edm k\u00f3du QR, prove\u010fte ru\u010dn\u00ed nastaven\u00ed s k\u00f3dem **`{code}`**.",
"title": "Nastavte dvoufaktorovou autentizaci pomoc\u00ed TOTP"
}
},
"title": "TOTP"
}
}
}

View File

@@ -0,0 +1,35 @@
{
"mfa_setup": {
"notify": {
"abort": {
"no_available_service": "No hay servicios de notificaci\u00f3n disponibles."
},
"error": {
"invalid_code": "C\u00f3digo inv\u00e1lido, por favor int\u00e9ntelo de nuevo."
},
"step": {
"init": {
"description": "Seleccione uno de los servicios de notificaci\u00f3n:",
"title": "Configure una contrase\u00f1a de un solo uso entregada por el componente de notificaci\u00f3n"
},
"setup": {
"description": "Se ha enviado una contrase\u00f1a de un solo uso a trav\u00e9s de ** notificar. {notify_service} **. Por favor introd\u00facela a continuaci\u00f3n:",
"title": "Verificar la configuraci\u00f3n"
}
},
"title": "Notificar la contrase\u00f1a de un solo uso"
},
"totp": {
"error": {
"invalid_code": "C\u00f3digo inv\u00e1lido, por favor int\u00e9ntalo de nuevo. Si recibes este error de forma consistente, por favor aseg\u00farate de que el reloj de tu Home Assistant es correcto."
},
"step": {
"init": {
"description": "Para activar la autenticaci\u00f3n de dos factores utilizando contrase\u00f1as de un solo uso basadas en el tiempo, escanea el c\u00f3digo QR con tu aplicaci\u00f3n de autenticaci\u00f3n. Si no tienes una, te recomendamos [Autenticador de Google] (https://support.google.com/accounts/answer/1066447) o [Authy] (https://authy.com/). \n\n {qr_code} \n \nDespu\u00e9s de escanear el c\u00f3digo, introduce el c\u00f3digo de seis d\u00edgitos de tu aplicaci\u00f3n para verificar la configuraci\u00f3n. Si tienes problemas para escanear el c\u00f3digo QR, realiza una configuraci\u00f3n manual con el c\u00f3digo ** ` {code} ` **.",
"title": "Configure la autenticaci\u00f3n de dos factores utilizando TOTP"
}
},
"title": "TOTP"
}
}
}

View File

@@ -1,6 +1,27 @@
{
"mfa_setup": {
"notify": {
"abort": {
"no_available_service": "Nessun servizio di notifica disponibile."
},
"error": {
"invalid_code": "Codice non valido, per favore riprovare."
},
"step": {
"init": {
"description": "Selezionare uno dei servizi di notifica:"
},
"setup": {
"description": "\u00c8 stata inviata una password monouso tramite **notify.{notify_service}**. Per favore, inseriscila qui sotto:",
"title": "Verifica l'installazione"
}
},
"title": "Notifica la Password monouso"
},
"totp": {
"error": {
"invalid_code": "Codice non valido, per favore riprovare. Se riscontri spesso questo errore, assicurati che l'orologio del sistema Home Assistant sia accurato."
},
"step": {
"init": {
"description": "Per attivare l'autenticazione a due fattori utilizzando password monouso basate sul tempo, eseguire la scansione del codice QR con l'app di autenticazione. Se non ne hai uno, ti consigliamo [Google Authenticator] (https://support.google.com/accounts/answer/1066447) o [Authy] (https://authy.com/). \n\n {qr_code} \n \n Dopo aver scansionato il codice, inserisci il codice a sei cifre dalla tua app per verificare la configurazione. Se riscontri problemi con la scansione del codice QR, esegui una configurazione manuale con codice ** ` {code} ` **.",

View File

@@ -2,18 +2,18 @@
"mfa_setup": {
"notify": {
"abort": {
"no_available_service": "Ni na voljo storitev obve\u0161\u010danja."
"no_available_service": "Storitve obve\u0161\u010danja niso na voljo."
},
"error": {
"invalid_code": "Neveljavna koda, poskusite znova."
},
"step": {
"init": {
"description": "Prosimo, izberite eno od storitev obve\u0161\u010danja:",
"description": "Izberite eno od storitev obve\u0161\u010danja:",
"title": "Nastavite enkratno geslo, ki ga dostavite z obvestilno komponento"
},
"setup": {
"description": "Enkratno geslo je poslal **notify.{notify_service} **. Vnesite ga spodaj:",
"description": "Enkratno geslo je poslal **notify.{notify_service} **. Prosimo, vnesite ga spodaj:",
"title": "Preverite nastavitev"
}
},

View File

@@ -16,12 +16,13 @@ from homeassistant.core import CoreState
from homeassistant.loader import bind_hass
from homeassistant.const import (
ATTR_ENTITY_ID, CONF_PLATFORM, STATE_ON, SERVICE_TURN_ON, SERVICE_TURN_OFF,
SERVICE_TOGGLE, SERVICE_RELOAD, EVENT_HOMEASSISTANT_START, CONF_ID)
SERVICE_TOGGLE, SERVICE_RELOAD, EVENT_HOMEASSISTANT_START, CONF_ID,
EVENT_AUTOMATION_TRIGGERED, ATTR_NAME)
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import extract_domain_configs, script, condition
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.restore_state import async_get_last_state
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.util.dt import utcnow
import homeassistant.helpers.config_validation as cv
@@ -182,7 +183,7 @@ async def async_setup(hass, config):
return True
class AutomationEntity(ToggleEntity):
class AutomationEntity(ToggleEntity, RestoreEntity):
"""Entity to show status of entity."""
def __init__(self, automation_id, name, async_attach_triggers, cond_func,
@@ -227,12 +228,13 @@ class AutomationEntity(ToggleEntity):
async def async_added_to_hass(self) -> None:
"""Startup with initial state or previous state."""
await super().async_added_to_hass()
if self._initial_state is not None:
enable_automation = self._initial_state
_LOGGER.debug("Automation %s initial state %s from config "
"initial_state", self.entity_id, enable_automation)
else:
state = await async_get_last_state(self.hass, self.entity_id)
state = await self.async_get_last_state()
if state:
enable_automation = state.state == STATE_ON
self._last_triggered = state.attributes.get('last_triggered')
@@ -285,12 +287,17 @@ class AutomationEntity(ToggleEntity):
"""
if skip_condition or self._cond_func(variables):
self.async_set_context(context)
self.hass.bus.async_fire(EVENT_AUTOMATION_TRIGGERED, {
ATTR_NAME: self._name,
ATTR_ENTITY_ID: self.entity_id,
}, context=context)
await self._async_action(self.entity_id, variables, context)
self._last_triggered = utcnow()
await self.async_update_ha_state()
async def async_will_remove_from_hass(self):
"""Remove listeners when removing automation from HASS."""
await super().async_will_remove_from_hass()
await self.async_turn_off()
async def async_enable(self):
@@ -368,8 +375,6 @@ def _async_get_action(hass, config, name):
async def action(entity_id, variables, context):
"""Execute an action."""
_LOGGER.info('Executing %s', name)
hass.components.logbook.async_log_entry(
name, 'has been triggered', DOMAIN, entity_id)
await script_obj.async_run(variables, context)
return action
@@ -400,6 +405,9 @@ async def _async_process_trigger(hass, config, trigger_configs, name, action):
This method is a coroutine.
"""
removes = []
info = {
'name': name
}
for conf in trigger_configs:
platform = await async_prepare_setup_platform(
@@ -408,7 +416,7 @@ async def _async_process_trigger(hass, config, trigger_configs, name, action):
if platform is None:
return None
remove = await platform.async_trigger(hass, conf, action)
remove = await platform.async_trigger(hass, conf, action, info)
if not remove:
_LOGGER.error("Error setting up trigger %s", name)

View File

@@ -24,7 +24,7 @@ TRIGGER_SCHEMA = vol.Schema({
})
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Listen for events based on configuration."""
event_type = config.get(CONF_EVENT_TYPE)
event_data_schema = vol.Schema(

View File

@@ -33,7 +33,7 @@ def source_match(state, source):
return state and state.attributes.get('source') == source
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Listen for state changes based on configuration."""
source = config.get(CONF_SOURCE).lower()
zone_entity_id = config.get(CONF_ZONE)

View File

@@ -22,7 +22,7 @@ TRIGGER_SCHEMA = vol.Schema({
})
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Listen for events based on configuration."""
event = config.get(CONF_EVENT)

View File

@@ -32,7 +32,7 @@ TRIGGER_SCHEMA = vol.Schema({
})
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Listen for events based on configuration."""
number = config.get(CONF_NUMBER)
held_more_than = config.get(CONF_HELD_MORE_THAN)

View File

@@ -24,7 +24,7 @@ TRIGGER_SCHEMA = vol.Schema({
})
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Listen for state changes based on configuration."""
topic = config.get(CONF_TOPIC)
payload = config.get(CONF_PAYLOAD)

View File

@@ -28,7 +28,7 @@ TRIGGER_SCHEMA = vol.All(vol.Schema({
_LOGGER = logging.getLogger(__name__)
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Listen for state changes based on configuration."""
entity_id = config.get(CONF_ENTITY_ID)
below = config.get(CONF_BELOW)

View File

@@ -26,7 +26,7 @@ TRIGGER_SCHEMA = vol.All(vol.Schema({
}), cv.key_dependency(CONF_FOR, CONF_TO))
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Listen for state changes based on configuration."""
entity_id = config.get(CONF_ENTITY_ID)
from_state = config.get(CONF_FROM, MATCH_ALL)

View File

@@ -24,7 +24,7 @@ TRIGGER_SCHEMA = vol.Schema({
})
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Listen for events based on configuration."""
event = config.get(CONF_EVENT)
offset = config.get(CONF_OFFSET)

View File

@@ -22,7 +22,7 @@ TRIGGER_SCHEMA = IF_ACTION_SCHEMA = vol.Schema({
})
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Listen for state changes based on configuration."""
value_template = config.get(CONF_VALUE_TEMPLATE)
value_template.hass = hass

View File

@@ -28,7 +28,7 @@ TRIGGER_SCHEMA = vol.All(vol.Schema({
}), cv.has_at_least_one_key(CONF_HOURS, CONF_MINUTES, CONF_SECONDS, CONF_AT))
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Listen for state changes based on configuration."""
if CONF_AT in config:
at_time = config.get(CONF_AT)

View File

@@ -14,6 +14,8 @@ from homeassistant.core import callback
from homeassistant.const import CONF_PLATFORM, CONF_WEBHOOK_ID
import homeassistant.helpers.config_validation as cv
from . import DOMAIN as AUTOMATION_DOMAIN
DEPENDENCIES = ('webhook',)
_LOGGER = logging.getLogger(__name__)
@@ -39,10 +41,11 @@ async def _handle_webhook(action, hass, webhook_id, request):
hass.async_run_job(action, {'trigger': result})
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Trigger based on incoming webhooks."""
webhook_id = config.get(CONF_WEBHOOK_ID)
hass.components.webhook.async_register(
AUTOMATION_DOMAIN, automation_info['name'],
webhook_id, partial(_handle_webhook, action))
@callback

View File

@@ -26,7 +26,7 @@ TRIGGER_SCHEMA = vol.Schema({
})
async def async_trigger(hass, config, action):
async def async_trigger(hass, config, action, automation_info):
"""Listen for state changes based on configuration."""
entity_id = config.get(CONF_ENTITY_ID)
zone_entity_id = config.get(CONF_ZONE)

View File

@@ -18,7 +18,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
data = hass.data[BLINK_DATA]
devs = []
for camera in data.sync.cameras:
for camera in data.cameras:
for sensor_type in discovery_info[CONF_MONITORED_CONDITIONS]:
devs.append(BlinkBinarySensor(data, camera, sensor_type))
add_entities(devs, True)
@@ -34,7 +34,7 @@ class BlinkBinarySensor(BinarySensorDevice):
name, icon = BINARY_SENSORS[sensor_type]
self._name = "{} {} {}".format(BLINK_DATA, camera, name)
self._icon = icon
self._camera = data.sync.cameras[camera]
self._camera = data.cameras[camera]
self._state = None
self._unique_id = "{}-{}".format(self._camera.serial, self._type)

View File

@@ -6,8 +6,8 @@ https://home-assistant.io/components/binary_sensor.deconz/
"""
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.deconz.const import (
ATTR_DARK, ATTR_ON, CONF_ALLOW_CLIP_SENSOR, DOMAIN as DATA_DECONZ,
DECONZ_DOMAIN)
ATTR_DARK, ATTR_ON, CONF_ALLOW_CLIP_SENSOR, DECONZ_REACHABLE,
DOMAIN as DECONZ_DOMAIN)
from homeassistant.const import ATTR_BATTERY_LEVEL
from homeassistant.core import callback
from homeassistant.helpers.device_registry import CONNECTION_ZIGBEE
@@ -24,6 +24,8 @@ async def async_setup_platform(hass, config, async_add_entities,
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the deCONZ binary sensor."""
gateway = hass.data[DECONZ_DOMAIN]
@callback
def async_add_sensor(sensors):
"""Add binary sensor from deCONZ."""
@@ -33,30 +35,35 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
for sensor in sensors:
if sensor.type in DECONZ_BINARY_SENSOR and \
not (not allow_clip_sensor and sensor.type.startswith('CLIP')):
entities.append(DeconzBinarySensor(sensor))
entities.append(DeconzBinarySensor(sensor, gateway))
async_add_entities(entities, True)
hass.data[DATA_DECONZ].listeners.append(
gateway.listeners.append(
async_dispatcher_connect(hass, 'deconz_new_sensor', async_add_sensor))
async_add_sensor(hass.data[DATA_DECONZ].api.sensors.values())
async_add_sensor(gateway.api.sensors.values())
class DeconzBinarySensor(BinarySensorDevice):
"""Representation of a binary sensor."""
def __init__(self, sensor):
def __init__(self, sensor, gateway):
"""Set up sensor and add update callback to get data from websocket."""
self._sensor = sensor
self.gateway = gateway
self.unsub_dispatcher = None
async def async_added_to_hass(self):
"""Subscribe sensors events."""
self._sensor.register_async_callback(self.async_update_callback)
self.hass.data[DATA_DECONZ].deconz_ids[self.entity_id] = \
self._sensor.deconz_id
self.gateway.deconz_ids[self.entity_id] = self._sensor.deconz_id
self.unsub_dispatcher = async_dispatcher_connect(
self.hass, DECONZ_REACHABLE, self.async_update_callback)
async def async_will_remove_from_hass(self) -> None:
"""Disconnect sensor object when removed."""
if self.unsub_dispatcher is not None:
self.unsub_dispatcher()
self._sensor.remove_callback(self.async_update_callback)
self._sensor = None
@@ -101,7 +108,7 @@ class DeconzBinarySensor(BinarySensorDevice):
@property
def available(self):
"""Return True if sensor is available."""
return self._sensor.reachable
return self.gateway.available and self._sensor.reachable
@property
def should_poll(self):
@@ -128,7 +135,7 @@ class DeconzBinarySensor(BinarySensorDevice):
self._sensor.uniqueid.count(':') != 7):
return None
serial = self._sensor.uniqueid.split('-', 1)[0]
bridgeid = self.hass.data[DATA_DECONZ].api.config.bridgeid
bridgeid = self.gateway.api.config.bridgeid
return {
'connections': {(CONNECTION_ZIGBEE, serial)},
'identifiers': {(DECONZ_DOMAIN, serial)},

View File

@@ -0,0 +1,76 @@
"""
Support for Fibaro binary sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.fibaro/
"""
import logging
from homeassistant.components.binary_sensor import (
BinarySensorDevice, ENTITY_ID_FORMAT)
from homeassistant.components.fibaro import (
FIBARO_CONTROLLER, FIBARO_DEVICES, FibaroDevice)
DEPENDENCIES = ['fibaro']
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPES = {
'com.fibaro.floodSensor': ['Flood', 'mdi:water', 'flood'],
'com.fibaro.motionSensor': ['Motion', 'mdi:run', 'motion'],
'com.fibaro.doorSensor': ['Door', 'mdi:window-open', 'door'],
'com.fibaro.windowSensor': ['Window', 'mdi:window-open', 'window'],
'com.fibaro.smokeSensor': ['Smoke', 'mdi:smoking', 'smoke'],
'com.fibaro.FGMS001': ['Motion', 'mdi:run', 'motion'],
'com.fibaro.heatDetector': ['Heat', 'mdi:fire', 'heat'],
}
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Perform the setup for Fibaro controller devices."""
if discovery_info is None:
return
add_entities(
[FibaroBinarySensor(device, hass.data[FIBARO_CONTROLLER])
for device in hass.data[FIBARO_DEVICES]['binary_sensor']], True)
class FibaroBinarySensor(FibaroDevice, BinarySensorDevice):
"""Representation of a Fibaro Binary Sensor."""
def __init__(self, fibaro_device, controller):
"""Initialize the binary_sensor."""
self._state = None
super().__init__(fibaro_device, controller)
self.entity_id = ENTITY_ID_FORMAT.format(self.ha_id)
stype = None
if fibaro_device.type in SENSOR_TYPES:
stype = fibaro_device.type
elif fibaro_device.baseType in SENSOR_TYPES:
stype = fibaro_device.baseType
if stype:
self._device_class = SENSOR_TYPES[stype][2]
self._icon = SENSOR_TYPES[stype][1]
else:
self._device_class = None
self._icon = None
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon
@property
def device_class(self):
"""Return the device class of the sensor."""
return self._device_class
@property
def is_on(self):
"""Return true if sensor is on."""
return self._state
def update(self):
"""Get the latest data and update the state."""
self._state = self.current_binary_state

View File

@@ -3,59 +3,39 @@
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.ihc/
"""
import voluptuous as vol
from homeassistant.components.binary_sensor import (
BinarySensorDevice, PLATFORM_SCHEMA, DEVICE_CLASSES_SCHEMA)
BinarySensorDevice)
from homeassistant.components.ihc import (
validate_name, IHC_DATA, IHC_CONTROLLER, IHC_INFO)
from homeassistant.components.ihc.const import CONF_INVERTING
IHC_DATA, IHC_CONTROLLER, IHC_INFO)
from homeassistant.components.ihc.const import (
CONF_INVERTING)
from homeassistant.components.ihc.ihcdevice import IHCDevice
from homeassistant.const import (
CONF_NAME, CONF_TYPE, CONF_ID, CONF_BINARY_SENSORS)
import homeassistant.helpers.config_validation as cv
CONF_TYPE)
DEPENDENCIES = ['ihc']
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_BINARY_SENSORS, default=[]):
vol.All(cv.ensure_list, [
vol.All({
vol.Required(CONF_ID): cv.positive_int,
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_TYPE): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_INVERTING, default=False): cv.boolean,
}, validate_name)
])
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the IHC binary sensor platform."""
ihc_controller = hass.data[IHC_DATA][IHC_CONTROLLER]
info = hass.data[IHC_DATA][IHC_INFO]
if discovery_info is None:
return
devices = []
if discovery_info:
for name, device in discovery_info.items():
ihc_id = device['ihc_id']
product_cfg = device['product_cfg']
product = device['product']
sensor = IHCBinarySensor(ihc_controller, name, ihc_id, info,
product_cfg.get(CONF_TYPE),
product_cfg[CONF_INVERTING],
product)
devices.append(sensor)
else:
binary_sensors = config[CONF_BINARY_SENSORS]
for sensor_cfg in binary_sensors:
ihc_id = sensor_cfg[CONF_ID]
name = sensor_cfg[CONF_NAME]
sensor_type = sensor_cfg.get(CONF_TYPE)
inverting = sensor_cfg[CONF_INVERTING]
sensor = IHCBinarySensor(ihc_controller, name, ihc_id, info,
sensor_type, inverting)
devices.append(sensor)
for name, device in discovery_info.items():
ihc_id = device['ihc_id']
product_cfg = device['product_cfg']
product = device['product']
# Find controller that corresponds with device id
ctrl_id = device['ctrl_id']
ihc_key = IHC_DATA.format(ctrl_id)
info = hass.data[ihc_key][IHC_INFO]
ihc_controller = hass.data[ihc_key][IHC_CONTROLLER]
sensor = IHCBinarySensor(ihc_controller, name, ihc_id, info,
product_cfg.get(CONF_TYPE),
product_cfg[CONF_INVERTING],
product)
devices.append(sensor)
add_entities(devices)

View File

@@ -57,7 +57,8 @@ class InsteonBinarySensor(InsteonEntity, BinarySensorDevice):
"""Return the boolean response if the node is on."""
on_val = bool(self._insteon_device_state.value)
if self._insteon_device_state.name == 'lightSensor':
if self._insteon_device_state.name in ['lightSensor',
'openClosedSensor']:
return not on_val
return on_val

View File

@@ -0,0 +1,53 @@
"""
This component provides HA binary_sensor support for Lupusec Security System.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.lupusec/
"""
import logging
from datetime import timedelta
from homeassistant.components.lupusec import (LupusecDevice,
DOMAIN as LUPUSEC_DOMAIN)
from homeassistant.components.binary_sensor import (BinarySensorDevice,
DEVICE_CLASSES)
DEPENDENCIES = ['lupusec']
SCAN_INTERVAL = timedelta(seconds=2)
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a sensor for an Lupusec device."""
if discovery_info is None:
return
import lupupy.constants as CONST
data = hass.data[LUPUSEC_DOMAIN]
device_types = [CONST.TYPE_OPENING]
devices = []
for device in data.lupusec.get_devices(generic_type=device_types):
devices.append(LupusecBinarySensor(data, device))
add_entities(devices)
class LupusecBinarySensor(LupusecDevice, BinarySensorDevice):
"""A binary sensor implementation for Lupusec device."""
@property
def is_on(self):
"""Return True if the binary sensor is on."""
return self._device.is_on
@property
def device_class(self):
"""Return the class of the binary sensor."""
if self._device.generic_type not in DEVICE_CLASSES:
return None
return self._device.generic_type

View File

@@ -5,7 +5,6 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.mqtt/
"""
import logging
from typing import Optional
import voluptuous as vol
@@ -19,7 +18,8 @@ from homeassistant.const import (
from homeassistant.components.mqtt import (
ATTR_DISCOVERY_HASH, CONF_STATE_TOPIC, CONF_AVAILABILITY_TOPIC,
CONF_PAYLOAD_AVAILABLE, CONF_PAYLOAD_NOT_AVAILABLE, CONF_QOS,
MqttAvailability, MqttDiscoveryUpdate, MqttEntityDeviceInfo)
MqttAvailability, MqttDiscoveryUpdate, MqttEntityDeviceInfo,
subscription)
from homeassistant.components.mqtt.discovery import MQTT_DISCOVERY_NEW
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect
@@ -45,8 +45,8 @@ PLATFORM_SCHEMA = mqtt.MQTT_RO_PLATFORM_SCHEMA.extend({
vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean,
vol.Optional(CONF_OFF_DELAY):
vol.All(vol.Coerce(int), vol.Range(min=0)),
# Integrations shouldn't never expose unique_id through configuration
# this here is an exception because MQTT is a msg transport, not a protocol
# Integrations should never expose unique_id through configuration.
# This is an exception because MQTT is a message transport, not a protocol
vol.Optional(CONF_UNIQUE_ID): cv.string,
vol.Optional(CONF_DEVICE): mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA,
}).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema)
@@ -55,7 +55,7 @@ PLATFORM_SCHEMA = mqtt.MQTT_RO_PLATFORM_SCHEMA.extend({
async def async_setup_platform(hass: HomeAssistantType, config: ConfigType,
async_add_entities, discovery_info=None):
"""Set up MQTT binary sensor through configuration.yaml."""
await _async_setup_entity(hass, config, async_add_entities)
await _async_setup_entity(config, async_add_entities)
async def async_setup_entry(hass, config_entry, async_add_entities):
@@ -63,7 +63,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
async def async_discover(discovery_payload):
"""Discover and add a MQTT binary sensor."""
config = PLATFORM_SCHEMA(discovery_payload)
await _async_setup_entity(hass, config, async_add_entities,
await _async_setup_entity(config, async_add_entities,
discovery_payload[ATTR_DISCOVERY_HASH])
async_dispatcher_connect(
@@ -71,64 +71,53 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
async_discover)
async def _async_setup_entity(hass, config, async_add_entities,
discovery_hash=None):
async def _async_setup_entity(config, async_add_entities, discovery_hash=None):
"""Set up the MQTT binary sensor."""
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
value_template.hass = hass
async_add_entities([MqttBinarySensor(
config.get(CONF_NAME),
config.get(CONF_STATE_TOPIC),
config.get(CONF_AVAILABILITY_TOPIC),
config.get(CONF_DEVICE_CLASS),
config.get(CONF_QOS),
config.get(CONF_FORCE_UPDATE),
config.get(CONF_OFF_DELAY),
config.get(CONF_PAYLOAD_ON),
config.get(CONF_PAYLOAD_OFF),
config.get(CONF_PAYLOAD_AVAILABLE),
config.get(CONF_PAYLOAD_NOT_AVAILABLE),
value_template,
config.get(CONF_UNIQUE_ID),
config.get(CONF_DEVICE),
discovery_hash,
)])
async_add_entities([MqttBinarySensor(config, discovery_hash)])
class MqttBinarySensor(MqttAvailability, MqttDiscoveryUpdate,
MqttEntityDeviceInfo, BinarySensorDevice):
"""Representation a binary sensor that is updated by MQTT."""
def __init__(self, name, state_topic, availability_topic, device_class,
qos, force_update, off_delay, payload_on, payload_off,
payload_available, payload_not_available, value_template,
unique_id: Optional[str], device_config: Optional[ConfigType],
discovery_hash):
def __init__(self, config, discovery_hash):
"""Initialize the MQTT binary sensor."""
self._config = config
self._unique_id = config.get(CONF_UNIQUE_ID)
self._state = None
self._sub_state = None
self._delay_listener = None
availability_topic = config.get(CONF_AVAILABILITY_TOPIC)
payload_available = config.get(CONF_PAYLOAD_AVAILABLE)
payload_not_available = config.get(CONF_PAYLOAD_NOT_AVAILABLE)
qos = config.get(CONF_QOS)
device_config = config.get(CONF_DEVICE)
MqttAvailability.__init__(self, availability_topic, qos,
payload_available, payload_not_available)
MqttDiscoveryUpdate.__init__(self, discovery_hash)
MqttDiscoveryUpdate.__init__(self, discovery_hash,
self.discovery_update)
MqttEntityDeviceInfo.__init__(self, device_config)
self._name = name
self._state = None
self._state_topic = state_topic
self._device_class = device_class
self._payload_on = payload_on
self._payload_off = payload_off
self._qos = qos
self._force_update = force_update
self._off_delay = off_delay
self._template = value_template
self._unique_id = unique_id
self._discovery_hash = discovery_hash
self._delay_listener = None
async def async_added_to_hass(self):
"""Subscribe mqtt events."""
await MqttAvailability.async_added_to_hass(self)
await MqttDiscoveryUpdate.async_added_to_hass(self)
await super().async_added_to_hass()
await self._subscribe_topics()
async def discovery_update(self, discovery_payload):
"""Handle updated discovery message."""
config = PLATFORM_SCHEMA(discovery_payload)
self._config = config
await self.availability_discovery_update(config)
await self._subscribe_topics()
self.async_schedule_update_ha_state()
async def _subscribe_topics(self):
"""(Re)Subscribe to topics."""
value_template = self._config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
value_template.hass = self.hass
@callback
def off_delay_listener(now):
@@ -140,30 +129,42 @@ class MqttBinarySensor(MqttAvailability, MqttDiscoveryUpdate,
@callback
def state_message_received(_topic, payload, _qos):
"""Handle a new received MQTT state message."""
if self._template is not None:
payload = self._template.async_render_with_possible_json_value(
value_template = self._config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
payload = value_template.async_render_with_possible_json_value(
payload)
if payload == self._payload_on:
if payload == self._config.get(CONF_PAYLOAD_ON):
self._state = True
elif payload == self._payload_off:
elif payload == self._config.get(CONF_PAYLOAD_OFF):
self._state = False
else: # Payload is not for this entity
_LOGGER.warning('No matching payload found'
' for entity: %s with state_topic: %s',
self._name, self._state_topic)
self._config.get(CONF_NAME),
self._config.get(CONF_STATE_TOPIC))
return
if self._delay_listener is not None:
self._delay_listener()
self._delay_listener = None
if (self._state and self._off_delay is not None):
off_delay = self._config.get(CONF_OFF_DELAY)
if (self._state and off_delay is not None):
self._delay_listener = evt.async_call_later(
self.hass, self._off_delay, off_delay_listener)
self.hass, off_delay, off_delay_listener)
self.async_schedule_update_ha_state()
await mqtt.async_subscribe(
self.hass, self._state_topic, state_message_received, self._qos)
self._sub_state = await subscription.async_subscribe_topics(
self.hass, self._sub_state,
{'state_topic': {'topic': self._config.get(CONF_STATE_TOPIC),
'msg_callback': state_message_received,
'qos': self._config.get(CONF_QOS)}})
async def async_will_remove_from_hass(self):
"""Unsubscribe when removed."""
await subscription.async_unsubscribe_topics(self.hass, self._sub_state)
await MqttAvailability.async_will_remove_from_hass(self)
@property
def should_poll(self):
@@ -173,7 +174,7 @@ class MqttBinarySensor(MqttAvailability, MqttDiscoveryUpdate,
@property
def name(self):
"""Return the name of the binary sensor."""
return self._name
return self._config.get(CONF_NAME)
@property
def is_on(self):
@@ -183,12 +184,12 @@ class MqttBinarySensor(MqttAvailability, MqttDiscoveryUpdate,
@property
def device_class(self):
"""Return the class of this sensor."""
return self._device_class
return self._config.get(CONF_DEVICE_CLASS)
@property
def force_update(self):
"""Force update."""
return self._force_update
return self._config.get(CONF_FORCE_UPDATE)
@property
def unique_id(self):

View File

@@ -0,0 +1,111 @@
"""
Support for Minut Point.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.point/
"""
import logging
from homeassistant.components.binary_sensor import (
DOMAIN as PARENT_DOMAIN, BinarySensorDevice)
from homeassistant.components.point import MinutPointEntity
from homeassistant.components.point.const import (
DOMAIN as POINT_DOMAIN, POINT_DISCOVERY_NEW, SIGNAL_WEBHOOK)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
_LOGGER = logging.getLogger(__name__)
EVENTS = {
'battery': # On means low, Off means normal
('battery_low', ''),
'button_press': # On means the button was pressed, Off means normal
('short_button_press', ''),
'cold': # On means cold, Off means normal
('temperature_low', 'temperature_risen_normal'),
'connectivity': # On means connected, Off means disconnected
('device_online', 'device_offline'),
'dry': # On means too dry, Off means normal
('humidity_low', 'humidity_risen_normal'),
'heat': # On means hot, Off means normal
('temperature_high', 'temperature_dropped_normal'),
'moisture': # On means wet, Off means dry
('humidity_high', 'humidity_dropped_normal'),
'sound': # On means sound detected, Off means no sound (clear)
('avg_sound_high', 'sound_level_dropped_normal'),
'tamper': # On means the point was removed or attached
('tamper', ''),
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up a Point's binary sensors based on a config entry."""
async def async_discover_sensor(device_id):
"""Discover and add a discovered sensor."""
client = hass.data[POINT_DOMAIN][config_entry.entry_id]
async_add_entities(
(MinutPointBinarySensor(client, device_id, device_class)
for device_class in EVENTS), True)
async_dispatcher_connect(
hass, POINT_DISCOVERY_NEW.format(PARENT_DOMAIN, POINT_DOMAIN),
async_discover_sensor)
class MinutPointBinarySensor(MinutPointEntity, BinarySensorDevice):
"""The platform class required by Home Assistant."""
def __init__(self, point_client, device_id, device_class):
"""Initialize the entity."""
super().__init__(point_client, device_id, device_class)
self._async_unsub_hook_dispatcher_connect = None
self._events = EVENTS[device_class]
self._is_on = None
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
await super().async_added_to_hass()
self._async_unsub_hook_dispatcher_connect = async_dispatcher_connect(
self.hass, SIGNAL_WEBHOOK, self._webhook_event)
async def async_will_remove_from_hass(self):
"""Disconnect dispatcher listener when removed."""
await super().async_will_remove_from_hass()
if self._async_unsub_hook_dispatcher_connect:
self._async_unsub_hook_dispatcher_connect()
@callback
def _update_callback(self):
"""Update the value of the sensor."""
if not self.is_updated:
return
if self._events[0] in self.device.ongoing_events:
self._is_on = True
else:
self._is_on = None
self.async_schedule_update_ha_state()
@callback
def _webhook_event(self, data, webhook):
"""Process new event from the webhook."""
if self.device.webhook != webhook:
return
_type = data.get('event', {}).get('type')
if _type not in self._events:
return
_LOGGER.debug("Recieved webhook: %s", _type)
if _type == self._events[0]:
self._is_on = True
if _type == self._events[1]:
self._is_on = None
self.async_schedule_update_ha_state()
@property
def is_on(self):
"""Return the state of the binary sensor."""
if self.device_class == 'connectivity':
# connectivity is the other way around.
return not self._is_on
return self._is_on

View File

@@ -8,28 +8,29 @@ import logging
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.rainmachine import (
BINARY_SENSORS, DATA_RAINMACHINE, SENSOR_UPDATE_TOPIC, TYPE_FREEZE,
TYPE_FREEZE_PROTECTION, TYPE_HOT_DAYS, TYPE_HOURLY, TYPE_MONTH,
TYPE_RAINDELAY, TYPE_RAINSENSOR, TYPE_WEEKDAY, RainMachineEntity)
from homeassistant.const import CONF_MONITORED_CONDITIONS
BINARY_SENSORS, DATA_CLIENT, DOMAIN as RAINMACHINE_DOMAIN,
SENSOR_UPDATE_TOPIC, TYPE_FREEZE, TYPE_FREEZE_PROTECTION, TYPE_HOT_DAYS,
TYPE_HOURLY, TYPE_MONTH, TYPE_RAINDELAY, TYPE_RAINSENSOR, TYPE_WEEKDAY,
RainMachineEntity)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
DEPENDENCIES = ['rainmachine']
_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the RainMachine Switch platform."""
if discovery_info is None:
return
"""Set up RainMachine binary sensors based on the old way."""
pass
rainmachine = hass.data[DATA_RAINMACHINE]
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up RainMachine binary sensors based on a config entry."""
rainmachine = hass.data[RAINMACHINE_DOMAIN][DATA_CLIENT][entry.entry_id]
binary_sensors = []
for sensor_type in discovery_info[CONF_MONITORED_CONDITIONS]:
for sensor_type in rainmachine.binary_sensor_conditions:
name, icon = BINARY_SENSORS[sensor_type]
binary_sensors.append(
RainMachineBinarySensor(rainmachine, sensor_type, name, icon))
@@ -70,15 +71,15 @@ class RainMachineBinarySensor(RainMachineEntity, BinarySensorDevice):
return '{0}_{1}'.format(
self.rainmachine.device_mac.replace(':', ''), self._sensor_type)
@callback
def _update_data(self):
"""Update the state."""
self.async_schedule_update_ha_state(True)
async def async_added_to_hass(self):
"""Register callbacks."""
async_dispatcher_connect(
self.hass, SENSOR_UPDATE_TOPIC, self._update_data)
@callback
def update():
"""Update the state."""
self.async_schedule_update_ha_state(True)
self._dispatcher_handlers.append(async_dispatcher_connect(
self.hass, SENSOR_UPDATE_TOPIC, update))
async def async_update(self):
"""Update the state."""

View File

@@ -14,66 +14,69 @@ DEPENDENCIES = ['sense']
_LOGGER = logging.getLogger(__name__)
BIN_SENSOR_CLASS = 'power'
MDI_ICONS = {'ac': 'air-conditioner',
'aquarium': 'fish',
'car': 'car-electric',
'computer': 'desktop-classic',
'cup': 'coffee',
'dehumidifier': 'water-off',
'dishes': 'dishwasher',
'drill': 'toolbox',
'fan': 'fan',
'freezer': 'fridge-top',
'fridge': 'fridge-bottom',
'game': 'gamepad-variant',
'garage': 'garage',
'grill': 'stove',
'heat': 'fire',
'heater': 'radiatior',
'humidifier': 'water',
'kettle': 'kettle',
'leafblower': 'leaf',
'lightbulb': 'lightbulb',
'media_console': 'set-top-box',
'modem': 'router-wireless',
'outlet': 'power-socket-us',
'papershredder': 'shredder',
'printer': 'printer',
'pump': 'water-pump',
'settings': 'settings',
'skillet': 'pot',
'smartcamera': 'webcam',
'socket': 'power-plug',
'sound': 'speaker',
'stove': 'stove',
'trash': 'trash-can',
'tv': 'television',
'vacuum': 'robot-vacuum',
'washer': 'washing-machine'}
MDI_ICONS = {
'ac': 'air-conditioner',
'aquarium': 'fish',
'car': 'car-electric',
'computer': 'desktop-classic',
'cup': 'coffee',
'dehumidifier': 'water-off',
'dishes': 'dishwasher',
'drill': 'toolbox',
'fan': 'fan',
'freezer': 'fridge-top',
'fridge': 'fridge-bottom',
'game': 'gamepad-variant',
'garage': 'garage',
'grill': 'stove',
'heat': 'fire',
'heater': 'radiatior',
'humidifier': 'water',
'kettle': 'kettle',
'leafblower': 'leaf',
'lightbulb': 'lightbulb',
'media_console': 'set-top-box',
'modem': 'router-wireless',
'outlet': 'power-socket-us',
'papershredder': 'shredder',
'printer': 'printer',
'pump': 'water-pump',
'settings': 'settings',
'skillet': 'pot',
'smartcamera': 'webcam',
'socket': 'power-plug',
'sound': 'speaker',
'stove': 'stove',
'trash': 'trash-can',
'tv': 'television',
'vacuum': 'robot-vacuum',
'washer': 'washing-machine',
}
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Sense sensor."""
"""Set up the Sense binary sensor."""
if discovery_info is None:
return
data = hass.data[SENSE_DATA]
sense_devices = data.get_discovered_device_data()
devices = [SenseDevice(data, device) for device in sense_devices]
devices = [SenseDevice(data, device) for device in sense_devices
if device['tags']['DeviceListAllowed'] == 'true']
add_entities(devices)
def sense_to_mdi(sense_icon):
"""Convert sense icon to mdi icon."""
return 'mdi:' + MDI_ICONS.get(sense_icon, 'power-plug')
return 'mdi:{}'.format(MDI_ICONS.get(sense_icon, 'power-plug'))
class SenseDevice(BinarySensorDevice):
"""Implementation of a Sense energy device binary sensor."""
def __init__(self, data, device):
"""Initialize the sensor."""
"""Initialize the Sense binary sensor."""
self._name = device['name']
self._id = device['id']
self._icon = sense_to_mdi(device['icon'])

View File

@@ -41,6 +41,7 @@ class TahomaBinarySensor(TahomaDevice, BinarySensorDevice):
self._state = None
self._icon = None
self._battery = None
self._available = False
@property
def is_on(self):
@@ -71,6 +72,11 @@ class TahomaBinarySensor(TahomaDevice, BinarySensorDevice):
attr[ATTR_BATTERY_LEVEL] = self._battery
return attr
@property
def available(self):
"""Return True if entity is available."""
return self._available
def update(self):
"""Update the state."""
self.controller.get_states([self.tahoma_device])
@@ -82,11 +88,13 @@ class TahomaBinarySensor(TahomaDevice, BinarySensorDevice):
self._state = STATE_ON
if 'core:SensorDefectState' in self.tahoma_device.active_states:
# Set to 'lowBattery' for low battery warning.
# 'lowBattery' for low battery warning. 'dead' for not available.
self._battery = self.tahoma_device.active_states[
'core:SensorDefectState']
self._available = bool(self._battery != 'dead')
else:
self._battery = None
self._available = True
if self._state == STATE_ON:
self._icon = "mdi:fire"

View File

@@ -9,8 +9,9 @@ https://home-assistant.io/components/binary_sensor.tellduslive/
"""
import logging
from homeassistant.components.tellduslive import TelldusLiveEntity
from homeassistant.components import tellduslive
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.tellduslive.entry import TelldusLiveEntity
_LOGGER = logging.getLogger(__name__)
@@ -19,8 +20,9 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up Tellstick sensors."""
if discovery_info is None:
return
client = hass.data[tellduslive.DOMAIN]
add_entities(
TelldusLiveSensor(hass, binary_sensor)
TelldusLiveSensor(client, binary_sensor)
for binary_sensor in discovery_info
)

View File

@@ -58,10 +58,12 @@ async def async_setup_platform(hass, config, async_add_entities,
entity_ids = set()
manual_entity_ids = device_config.get(ATTR_ENTITY_ID)
for template in (
value_template,
icon_template,
entity_picture_template,
invalid_templates = []
for tpl_name, template in (
(CONF_VALUE_TEMPLATE, value_template),
(CONF_ICON_TEMPLATE, icon_template),
(CONF_ENTITY_PICTURE_TEMPLATE, entity_picture_template),
):
if template is None:
continue
@@ -73,6 +75,8 @@ async def async_setup_platform(hass, config, async_add_entities,
template_entity_ids = template.extract_entities()
if template_entity_ids == MATCH_ALL:
entity_ids = MATCH_ALL
# Cut off _template from name
invalid_templates.append(tpl_name[:-9])
elif entity_ids != MATCH_ALL:
entity_ids |= set(template_entity_ids)
@@ -81,6 +85,14 @@ async def async_setup_platform(hass, config, async_add_entities,
elif entity_ids != MATCH_ALL:
entity_ids = list(entity_ids)
if invalid_templates:
_LOGGER.warning(
'Template binary sensor %s has no entity ids configured to'
' track nor were we able to extract the entities to track'
' from the %s template(s). This entity will only be able'
' to be updated manually.',
device, ', '.join(invalid_templates))
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
device_class = device_config.get(CONF_DEVICE_CLASS)
delay_on = device_config.get(CONF_DELAY_ON)
@@ -132,10 +144,12 @@ class BinarySensorTemplate(BinarySensorDevice):
@callback
def template_bsensor_startup(event):
"""Update template on startup."""
async_track_state_change(
self.hass, self._entities, template_bsensor_state_listener)
if self._entities != MATCH_ALL:
# Track state change only for valid templates
async_track_state_change(
self.hass, self._entities, template_bsensor_state_listener)
self.hass.async_add_job(self.async_check_state)
self.async_check_state()
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, template_bsensor_startup)
@@ -233,3 +247,7 @@ class BinarySensorTemplate(BinarySensorDevice):
async_track_same_state(
self.hass, period, set_state, entity_ids=self._entities,
async_check_same_func=lambda *args: self._async_render() == state)
async def async_update(self):
"""Force update of the state from the template."""
self.async_check_state()

View File

@@ -22,7 +22,7 @@ from homeassistant.helpers.entity import generate_entity_id
from homeassistant.helpers.event import async_track_state_change
from homeassistant.util import utcnow
REQUIREMENTS = ['numpy==1.15.3']
REQUIREMENTS = ['numpy==1.15.4']
_LOGGER = logging.getLogger(__name__)

View File

@@ -6,17 +6,19 @@ https://home-assistant.io/components/binary_sensor.volvooncall/
"""
import logging
from homeassistant.components.volvooncall import VolvoEntity
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.volvooncall import VolvoEntity, DATA_KEY
from homeassistant.components.binary_sensor import (
BinarySensorDevice, DEVICE_CLASSES)
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the Volvo sensors."""
if discovery_info is None:
return
add_entities([VolvoSensor(hass, *discovery_info)])
async_add_entities([VolvoSensor(hass.data[DATA_KEY], *discovery_info)])
class VolvoSensor(VolvoEntity, BinarySensorDevice):
@@ -25,14 +27,11 @@ class VolvoSensor(VolvoEntity, BinarySensorDevice):
@property
def is_on(self):
"""Return True if the binary sensor is on."""
val = getattr(self.vehicle, self._attribute)
if self._attribute == 'bulb_failures':
return bool(val)
if self._attribute in ['doors', 'windows']:
return any([val[key] for key in val if 'Open' in key])
return val != 'Normal'
return self.instrument.is_on
@property
def device_class(self):
"""Return the class of this sensor, from DEVICE_CLASSES."""
return 'safety'
if self.instrument.device_class in DEVICE_CLASSES:
return self.instrument.device_class
return None

View File

@@ -0,0 +1,132 @@
"""
Support for w800rf32 binary sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.w800rf32/
"""
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import (
DEVICE_CLASSES_SCHEMA, PLATFORM_SCHEMA, BinarySensorDevice)
from homeassistant.components.w800rf32 import (W800RF32_DEVICE)
from homeassistant.const import (CONF_DEVICE_CLASS, CONF_NAME, CONF_DEVICES)
from homeassistant.core import callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers import event as evt
from homeassistant.util import dt as dt_util
from homeassistant.helpers.dispatcher import (async_dispatcher_connect)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['w800rf32']
CONF_OFF_DELAY = 'off_delay'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_DEVICES): {
cv.string: vol.Schema({
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_OFF_DELAY):
vol.All(cv.time_period, cv.positive_timedelta)
})
},
}, extra=vol.ALLOW_EXTRA)
async def async_setup_platform(hass, config,
add_entities, discovery_info=None):
"""Set up the Binary Sensor platform to w800rf32."""
binary_sensors = []
# device_id --> "c1 or a3" X10 device. entity (type dictionary)
# --> name, device_class etc
for device_id, entity in config[CONF_DEVICES].items():
_LOGGER.debug("Add %s w800rf32.binary_sensor (class %s)",
entity[CONF_NAME], entity.get(CONF_DEVICE_CLASS))
device = W800rf32BinarySensor(
device_id, entity.get(CONF_NAME), entity.get(CONF_DEVICE_CLASS),
entity.get(CONF_OFF_DELAY))
binary_sensors.append(device)
add_entities(binary_sensors)
class W800rf32BinarySensor(BinarySensorDevice):
"""A representation of a w800rf32 binary sensor."""
def __init__(self, device_id, name, device_class=None, off_delay=None):
"""Initialize the w800rf32 sensor."""
self._signal = W800RF32_DEVICE.format(device_id)
self._name = name
self._device_class = device_class
self._off_delay = off_delay
self._state = False
self._delay_listener = None
@callback
def _off_delay_listener(self, now):
"""Switch device off after a delay."""
self._delay_listener = None
self.update_state(False)
@property
def name(self):
"""Return the device name."""
return self._name
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def device_class(self):
"""Return the sensor class."""
return self._device_class
@property
def is_on(self):
"""Return true if the sensor state is True."""
return self._state
@callback
def binary_sensor_update(self, event):
"""Call for control updates from the w800rf32 gateway."""
import W800rf32 as w800rf32mod
if not isinstance(event, w800rf32mod.W800rf32Event):
return
dev_id = event.device
command = event.command
_LOGGER.debug(
"BinarySensor update (Device ID: %s Command %s ...)",
dev_id, command)
# Update the w800rf32 device state
if command in ('On', 'Off'):
is_on = command == 'On'
self.update_state(is_on)
if (self.is_on and self._off_delay is not None and
self._delay_listener is None):
self._delay_listener = evt.async_track_point_in_time(
self.hass, self._off_delay_listener,
dt_util.utcnow() + self._off_delay)
def update_state(self, state):
"""Update the state of the device."""
self._state = state
self.async_schedule_update_ha_state()
async def async_added_to_hass(self):
"""Register update callback."""
async_dispatcher_connect(self.hass, self._signal,
self.binary_sensor_update)

View File

@@ -209,7 +209,7 @@ class XiaomiMotionSensor(XiaomiBinarySensor):
else:
self._should_poll = True
if self.entity_id is not None:
self._hass.bus.fire('motion', {
self._hass.bus.fire('xiaomi_aqara.motion', {
'entity_id': self.entity_id
})
@@ -357,6 +357,9 @@ class XiaomiVibration(XiaomiBinarySensor):
def parse_data(self, data, raw_data):
"""Parse data sent by gateway."""
value = data.get(self._data_key)
if value is None:
return False
if value not in ('vibrate', 'tilt', 'free_fall'):
_LOGGER.warning("Unsupported movement_type detected: %s",
value)
@@ -414,7 +417,7 @@ class XiaomiButton(XiaomiBinarySensor):
_LOGGER.warning("Unsupported click_type detected: %s", value)
return False
self._hass.bus.fire('click', {
self._hass.bus.fire('xiaomi_aqara.click', {
'entity_id': self.entity_id,
'click_type': click_type
})
@@ -450,14 +453,14 @@ class XiaomiCube(XiaomiBinarySensor):
def parse_data(self, data, raw_data):
"""Parse data sent by gateway."""
if self._data_key in data:
self._hass.bus.fire('cube_action', {
self._hass.bus.fire('xiaomi_aqara.cube_action', {
'entity_id': self.entity_id,
'action_type': data[self._data_key]
})
self._last_action = data[self._data_key]
if 'rotate' in data:
self._hass.bus.fire('cube_action', {
self._hass.bus.fire('xiaomi_aqara.cube_action', {
'entity_id': self.entity_id,
'action_type': 'rotate',
'action_value': float(data['rotate'].replace(",", "."))

View File

@@ -7,7 +7,11 @@ at https://home-assistant.io/components/binary_sensor.zha/
import logging
from homeassistant.components.binary_sensor import DOMAIN, BinarySensorDevice
from homeassistant.components import zha
from homeassistant.components.zha import helpers
from homeassistant.components.zha.const import (
DATA_ZHA, DATA_ZHA_DISPATCHERS, ZHA_DISCOVERY_NEW)
from homeassistant.components.zha.entities import ZhaEntity
from homeassistant.helpers.dispatcher import async_dispatcher_connect
_LOGGER = logging.getLogger(__name__)
@@ -26,23 +30,43 @@ CLASS_MAPPING = {
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the Zigbee Home Automation binary sensors."""
discovery_info = zha.get_discovery_info(hass, discovery_info)
if discovery_info is None:
return
from zigpy.zcl.clusters.general import OnOff
from zigpy.zcl.clusters.security import IasZone
if IasZone.cluster_id in discovery_info['in_clusters']:
await _async_setup_iaszone(hass, config, async_add_entities,
discovery_info)
elif OnOff.cluster_id in discovery_info['out_clusters']:
await _async_setup_remote(hass, config, async_add_entities,
discovery_info)
"""Old way of setting up Zigbee Home Automation binary sensors."""
pass
async def _async_setup_iaszone(hass, config, async_add_entities,
discovery_info):
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Zigbee Home Automation binary sensor from config entry."""
async def async_discover(discovery_info):
await _async_setup_entities(hass, config_entry, async_add_entities,
[discovery_info])
unsub = async_dispatcher_connect(
hass, ZHA_DISCOVERY_NEW.format(DOMAIN), async_discover)
hass.data[DATA_ZHA][DATA_ZHA_DISPATCHERS].append(unsub)
binary_sensors = hass.data.get(DATA_ZHA, {}).get(DOMAIN)
if binary_sensors is not None:
await _async_setup_entities(hass, config_entry, async_add_entities,
binary_sensors.values())
del hass.data[DATA_ZHA][DOMAIN]
async def _async_setup_entities(hass, config_entry, async_add_entities,
discovery_infos):
"""Set up the ZHA binary sensors."""
entities = []
for discovery_info in discovery_infos:
from zigpy.zcl.clusters.general import OnOff
from zigpy.zcl.clusters.security import IasZone
if IasZone.cluster_id in discovery_info['in_clusters']:
entities.append(await _async_setup_iaszone(discovery_info))
elif OnOff.cluster_id in discovery_info['out_clusters']:
entities.append(await _async_setup_remote(discovery_info))
async_add_entities(entities, update_before_add=True)
async def _async_setup_iaszone(discovery_info):
device_class = None
from zigpy.zcl.clusters.security import IasZone
cluster = discovery_info['in_clusters'][IasZone.cluster_id]
@@ -58,13 +82,10 @@ async def _async_setup_iaszone(hass, config, async_add_entities,
# If we fail to read from the device, use a non-specific class
pass
sensor = BinarySensor(device_class, **discovery_info)
async_add_entities([sensor], update_before_add=True)
return BinarySensor(device_class, **discovery_info)
async def _async_setup_remote(hass, config, async_add_entities,
discovery_info):
async def _async_setup_remote(discovery_info):
remote = Remote(**discovery_info)
if discovery_info['new_join']:
@@ -72,21 +93,21 @@ async def _async_setup_remote(hass, config, async_add_entities,
out_clusters = discovery_info['out_clusters']
if OnOff.cluster_id in out_clusters:
cluster = out_clusters[OnOff.cluster_id]
await zha.configure_reporting(
await helpers.configure_reporting(
remote.entity_id, cluster, 0, min_report=0, max_report=600,
reportable_change=1
)
if LevelControl.cluster_id in out_clusters:
cluster = out_clusters[LevelControl.cluster_id]
await zha.configure_reporting(
await helpers.configure_reporting(
remote.entity_id, cluster, 0, min_report=1, max_report=600,
reportable_change=1
)
async_add_entities([remote], update_before_add=True)
return remote
class BinarySensor(zha.Entity, BinarySensorDevice):
class BinarySensor(ZhaEntity, BinarySensorDevice):
"""The ZHA Binary Sensor."""
_domain = DOMAIN
@@ -130,16 +151,16 @@ class BinarySensor(zha.Entity, BinarySensorDevice):
"""Retrieve latest state."""
from zigpy.types.basic import uint16_t
result = await zha.safe_read(self._endpoint.ias_zone,
['zone_status'],
allow_cache=False,
only_cache=(not self._initialized))
result = await helpers.safe_read(self._endpoint.ias_zone,
['zone_status'],
allow_cache=False,
only_cache=(not self._initialized))
state = result.get('zone_status', self._state)
if isinstance(state, (int, uint16_t)):
self._state = result.get('zone_status', self._state) & 3
class Remote(zha.Entity, BinarySensorDevice):
class Remote(ZhaEntity, BinarySensorDevice):
"""ZHA switch/remote controller/button."""
_domain = DOMAIN
@@ -252,7 +273,7 @@ class Remote(zha.Entity, BinarySensorDevice):
async def async_update(self):
"""Retrieve latest state."""
from zigpy.zcl.clusters.general import OnOff
result = await zha.safe_read(
result = await helpers.safe_read(
self._endpoint.out_clusters[OnOff.cluster_id],
['on_off'],
allow_cache=False,

View File

@@ -15,7 +15,7 @@ from homeassistant.const import (
CONF_BINARY_SENSORS, CONF_SENSORS, CONF_FILENAME,
CONF_MONITORED_CONDITIONS, TEMP_FAHRENHEIT)
REQUIREMENTS = ['blinkpy==0.10.1']
REQUIREMENTS = ['blinkpy==0.11.0']
_LOGGER = logging.getLogger(__name__)
@@ -111,7 +111,7 @@ def setup(hass, config):
def trigger_camera(call):
"""Trigger a camera."""
cameras = hass.data[BLINK_DATA].sync.cameras
cameras = hass.data[BLINK_DATA].cameras
name = call.data[CONF_NAME]
if name in cameras:
cameras[name].snap_picture()
@@ -148,7 +148,7 @@ async def async_handle_save_video_service(hass, call):
def _write_video(camera_name, video_path):
"""Call video write."""
all_cameras = hass.data[BLINK_DATA].sync.cameras
all_cameras = hass.data[BLINK_DATA].cameras
if camera_name in all_cameras:
all_cameras[camera_name].video_to_file(video_path)

View File

@@ -23,7 +23,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
return
data = hass.data[BLINK_DATA]
devs = []
for name, camera in data.sync.cameras.items():
for name, camera in data.cameras.items():
devs.append(BlinkCamera(data, name, camera))
add_entities(devs)

View File

@@ -60,13 +60,20 @@ async def async_setup_platform(hass, config, async_add_entities,
def extract_image_from_mjpeg(stream):
"""Take in a MJPEG stream object, return the jpg from it."""
data = b''
for chunk in stream:
data += chunk
jpg_start = data.find(b'\xff\xd8')
jpg_end = data.find(b'\xff\xd9')
if jpg_start != -1 and jpg_end != -1:
jpg = data[jpg_start:jpg_end + 2]
return jpg
if jpg_end == -1:
continue
jpg_start = data.find(b'\xff\xd8')
if jpg_start == -1:
continue
return data[jpg_start:jpg_end + 2]
class MjpegCamera(Camera):

View File

@@ -89,13 +89,12 @@ class MqttCamera(Camera):
"""Return a unique ID."""
return self._unique_id
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Subscribe MQTT events."""
@callback
def message_received(topic, payload, qos):
"""Handle new MQTT messages."""
self._last_image = payload
return mqtt.async_subscribe(
await mqtt.async_subscribe(
self.hass, self._topic, message_received, self._qos, None)

View File

@@ -10,14 +10,15 @@ import logging
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.const import CONF_ENTITY_ID, CONF_NAME, HTTP_HEADER_HA_AUTH
from homeassistant.const import CONF_ENTITY_ID, CONF_NAME, CONF_MODE, \
HTTP_HEADER_HA_AUTH
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.util.async_ import run_coroutine_threadsafe
import homeassistant.util.dt as dt_util
from . import async_get_still_stream
from homeassistant.components.camera import async_get_still_stream
REQUIREMENTS = ['pillow==5.2.0']
REQUIREMENTS = ['pillow==5.3.0']
_LOGGER = logging.getLogger(__name__)
@@ -26,21 +27,34 @@ CONF_FORCE_RESIZE = 'force_resize'
CONF_IMAGE_QUALITY = 'image_quality'
CONF_IMAGE_REFRESH_RATE = 'image_refresh_rate'
CONF_MAX_IMAGE_WIDTH = 'max_image_width'
CONF_MAX_IMAGE_HEIGHT = 'max_image_height'
CONF_MAX_STREAM_WIDTH = 'max_stream_width'
CONF_MAX_STREAM_HEIGHT = 'max_stream_height'
CONF_IMAGE_TOP = 'image_top'
CONF_IMAGE_LEFT = 'image_left'
CONF_STREAM_QUALITY = 'stream_quality'
MODE_RESIZE = 'resize'
MODE_CROP = 'crop'
DEFAULT_BASENAME = "Camera Proxy"
DEFAULT_QUALITY = 75
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_CACHE_IMAGES, False): cv.boolean,
vol.Optional(CONF_FORCE_RESIZE, False): cv.boolean,
vol.Optional(CONF_MODE, default=MODE_RESIZE):
vol.In([MODE_RESIZE, MODE_CROP]),
vol.Optional(CONF_IMAGE_QUALITY): int,
vol.Optional(CONF_IMAGE_REFRESH_RATE): float,
vol.Optional(CONF_MAX_IMAGE_WIDTH): int,
vol.Optional(CONF_MAX_IMAGE_HEIGHT): int,
vol.Optional(CONF_MAX_STREAM_WIDTH): int,
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_MAX_STREAM_HEIGHT): int,
vol.Optional(CONF_IMAGE_LEFT): int,
vol.Optional(CONF_IMAGE_TOP): int,
vol.Optional(CONF_STREAM_QUALITY): int,
})
@@ -51,26 +65,37 @@ async def async_setup_platform(
async_add_entities([ProxyCamera(hass, config)])
def _precheck_image(image, opts):
"""Perform some pre-checks on the given image."""
from PIL import Image
import io
if not opts:
raise ValueError()
try:
img = Image.open(io.BytesIO(image))
except IOError:
_LOGGER.warning("Failed to open image")
raise ValueError()
imgfmt = str(img.format)
if imgfmt not in ('PNG', 'JPEG'):
_LOGGER.warning("Image is of unsupported type: %s", imgfmt)
raise ValueError()
return img
def _resize_image(image, opts):
"""Resize image."""
from PIL import Image
import io
if not opts:
try:
img = _precheck_image(image, opts)
except ValueError:
return image
quality = opts.quality or DEFAULT_QUALITY
new_width = opts.max_width
try:
img = Image.open(io.BytesIO(image))
except IOError:
return image
imgfmt = str(img.format)
if imgfmt not in ('PNG', 'JPEG'):
_LOGGER.debug("Image is of unsupported type: %s", imgfmt)
return image
(old_width, old_height) = img.size
old_size = len(image)
if old_width <= new_width:
@@ -87,7 +112,7 @@ def _resize_image(image, opts):
img.save(imgbuf, 'JPEG', optimize=True, quality=quality)
newimage = imgbuf.getvalue()
if not opts.force_resize and len(newimage) >= old_size:
_LOGGER.debug("Using original image(%d bytes) "
_LOGGER.debug("Using original image (%d bytes) "
"because resized image (%d bytes) is not smaller",
old_size, len(newimage))
return image
@@ -98,12 +123,50 @@ def _resize_image(image, opts):
return newimage
def _crop_image(image, opts):
"""Crop image."""
import io
try:
img = _precheck_image(image, opts)
except ValueError:
return image
quality = opts.quality or DEFAULT_QUALITY
(old_width, old_height) = img.size
old_size = len(image)
if opts.top is None:
opts.top = 0
if opts.left is None:
opts.left = 0
if opts.max_width is None or opts.max_width > old_width - opts.left:
opts.max_width = old_width - opts.left
if opts.max_height is None or opts.max_height > old_height - opts.top:
opts.max_height = old_height - opts.top
img = img.crop((opts.left, opts.top,
opts.left+opts.max_width, opts.top+opts.max_height))
imgbuf = io.BytesIO()
img.save(imgbuf, 'JPEG', optimize=True, quality=quality)
newimage = imgbuf.getvalue()
_LOGGER.debug(
"Cropped image from (%dx%d - %d bytes) to (%dx%d - %d bytes)",
old_width, old_height, old_size, opts.max_width, opts.max_height,
len(newimage))
return newimage
class ImageOpts():
"""The representation of image options."""
def __init__(self, max_width, quality, force_resize):
def __init__(self, max_width, max_height, left, top,
quality, force_resize):
"""Initialize image options."""
self.max_width = max_width
self.max_height = max_height
self.left = left
self.top = top
self.quality = quality
self.force_resize = force_resize
@@ -125,11 +188,18 @@ class ProxyCamera(Camera):
"{} - {}".format(DEFAULT_BASENAME, self._proxied_camera))
self._image_opts = ImageOpts(
config.get(CONF_MAX_IMAGE_WIDTH),
config.get(CONF_MAX_IMAGE_HEIGHT),
config.get(CONF_IMAGE_LEFT),
config.get(CONF_IMAGE_TOP),
config.get(CONF_IMAGE_QUALITY),
config.get(CONF_FORCE_RESIZE))
self._stream_opts = ImageOpts(
config.get(CONF_MAX_STREAM_WIDTH), config.get(CONF_STREAM_QUALITY),
config.get(CONF_MAX_STREAM_WIDTH),
config.get(CONF_MAX_STREAM_HEIGHT),
config.get(CONF_IMAGE_LEFT),
config.get(CONF_IMAGE_TOP),
config.get(CONF_STREAM_QUALITY),
True)
self._image_refresh_rate = config.get(CONF_IMAGE_REFRESH_RATE)
@@ -141,6 +211,7 @@ class ProxyCamera(Camera):
self._headers = (
{HTTP_HEADER_HA_AUTH: self.hass.config.api.api_password}
if self.hass.config.api.api_password is not None else None)
self._mode = config.get(CONF_MODE)
def camera_image(self):
"""Return camera image."""
@@ -162,8 +233,12 @@ class ProxyCamera(Camera):
_LOGGER.error("Error getting original camera image")
return self._last_image
image = await self.hass.async_add_job(
_resize_image, image.content, self._image_opts)
if self._mode == MODE_RESIZE:
job = _resize_image
else:
job = _crop_image
image = await self.hass.async_add_executor_job(
job, image.content, self._image_opts)
if self._cache_images:
self._last_image = image
@@ -192,7 +267,11 @@ class ProxyCamera(Camera):
if not image:
return None
except HomeAssistantError:
raise asyncio.CancelledError
raise asyncio.CancelledError()
return await self.hass.async_add_job(
_resize_image, image.content, self._stream_opts)
if self._mode == MODE_RESIZE:
job = _resize_image
else:
job = _crop_image
return await self.hass.async_add_executor_job(
job, image.content, self._stream_opts)

View File

@@ -5,35 +5,33 @@ For more details about this platform, please refer to the documentation
https://home-assistant.io/components/camera.push/
"""
import logging
import asyncio
from collections import deque
from datetime import timedelta
import voluptuous as vol
import aiohttp
import async_timeout
from homeassistant.components.camera import Camera, PLATFORM_SCHEMA,\
STATE_IDLE, STATE_RECORDING
STATE_IDLE, STATE_RECORDING, DOMAIN
from homeassistant.core import callback
from homeassistant.components.http.view import KEY_AUTHENTICATED,\
HomeAssistantView
from homeassistant.const import CONF_NAME, CONF_TIMEOUT,\
HTTP_NOT_FOUND, HTTP_UNAUTHORIZED, HTTP_BAD_REQUEST
from homeassistant.const import CONF_NAME, CONF_TIMEOUT, CONF_WEBHOOK_ID
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.event import async_track_point_in_utc_time
import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['webhook']
DEPENDENCIES = ['http']
_LOGGER = logging.getLogger(__name__)
CONF_BUFFER_SIZE = 'buffer'
CONF_IMAGE_FIELD = 'field'
CONF_TOKEN = 'token'
DEFAULT_NAME = "Push Camera"
ATTR_FILENAME = 'filename'
ATTR_LAST_TRIP = 'last_trip'
ATTR_TOKEN = 'token'
PUSH_CAMERA_DATA = 'push_camera'
@@ -43,7 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_TIMEOUT, default=timedelta(seconds=5)): vol.All(
cv.time_period, cv.positive_timedelta),
vol.Optional(CONF_IMAGE_FIELD, default='image'): cv.string,
vol.Optional(CONF_TOKEN): vol.All(cv.string, vol.Length(min=8)),
vol.Required(CONF_WEBHOOK_ID): cv.string,
})
@@ -53,69 +51,43 @@ async def async_setup_platform(hass, config, async_add_entities,
if PUSH_CAMERA_DATA not in hass.data:
hass.data[PUSH_CAMERA_DATA] = {}
cameras = [PushCamera(config[CONF_NAME],
webhook_id = config.get(CONF_WEBHOOK_ID)
cameras = [PushCamera(hass,
config[CONF_NAME],
config[CONF_BUFFER_SIZE],
config[CONF_TIMEOUT],
config.get(CONF_TOKEN))]
hass.http.register_view(CameraPushReceiver(hass,
config[CONF_IMAGE_FIELD]))
config[CONF_IMAGE_FIELD],
webhook_id)]
async_add_entities(cameras)
class CameraPushReceiver(HomeAssistantView):
"""Handle pushes from remote camera."""
async def handle_webhook(hass, webhook_id, request):
"""Handle incoming webhook POST with image files."""
try:
with async_timeout.timeout(5, loop=hass.loop):
data = dict(await request.post())
except (asyncio.TimeoutError, aiohttp.web.HTTPException) as error:
_LOGGER.error("Could not get information from POST <%s>", error)
return
url = "/api/camera_push/{entity_id}"
name = 'api:camera_push:camera_entity'
requires_auth = False
camera = hass.data[PUSH_CAMERA_DATA][webhook_id]
def __init__(self, hass, image_field):
"""Initialize CameraPushReceiver with camera entity."""
self._cameras = hass.data[PUSH_CAMERA_DATA]
self._image = image_field
if camera.image_field not in data:
_LOGGER.warning("Webhook call without POST parameter <%s>",
camera.image_field)
return
async def post(self, request, entity_id):
"""Accept the POST from Camera."""
_camera = self._cameras.get(entity_id)
if _camera is None:
_LOGGER.error("Unknown %s", entity_id)
status = HTTP_NOT_FOUND if request[KEY_AUTHENTICATED]\
else HTTP_UNAUTHORIZED
return self.json_message('Unknown {}'.format(entity_id),
status)
# Supports HA authentication and token based
# when token has been configured
authenticated = (request[KEY_AUTHENTICATED] or
(_camera.token is not None and
request.query.get('token') == _camera.token))
if not authenticated:
return self.json_message(
'Invalid authorization credentials for {}'.format(entity_id),
HTTP_UNAUTHORIZED)
try:
data = await request.post()
_LOGGER.debug("Received Camera push: %s", data[self._image])
await _camera.update_image(data[self._image].file.read(),
data[self._image].filename)
except ValueError as value_error:
_LOGGER.error("Unknown value %s", value_error)
return self.json_message('Invalid POST', HTTP_BAD_REQUEST)
except KeyError as key_error:
_LOGGER.error('In your POST message %s', key_error)
return self.json_message('{} missing'.format(self._image),
HTTP_BAD_REQUEST)
await camera.update_image(data[camera.image_field].file.read(),
data[camera.image_field].filename)
class PushCamera(Camera):
"""The representation of a Push camera."""
def __init__(self, name, buffer_size, timeout, token):
def __init__(self, hass, name, buffer_size, timeout, image_field,
webhook_id):
"""Initialize push camera component."""
super().__init__()
self._name = name
@@ -126,11 +98,28 @@ class PushCamera(Camera):
self._timeout = timeout
self.queue = deque([], buffer_size)
self._current_image = None
self.token = token
self._image_field = image_field
self.webhook_id = webhook_id
self.webhook_url = \
hass.components.webhook.async_generate_url(webhook_id)
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self.hass.data[PUSH_CAMERA_DATA][self.entity_id] = self
self.hass.data[PUSH_CAMERA_DATA][self.webhook_id] = self
try:
self.hass.components.webhook.async_register(DOMAIN,
self.name,
self.webhook_id,
handle_webhook)
except ValueError:
_LOGGER.error("In <%s>, webhook_id <%s> already used",
self.name, self.webhook_id)
@property
def image_field(self):
"""HTTP field containing the image file."""
return self._image_field
@property
def state(self):
@@ -189,6 +178,5 @@ class PushCamera(Camera):
name: value for name, value in (
(ATTR_LAST_TRIP, self._last_trip),
(ATTR_FILENAME, self._filename),
(ATTR_TOKEN, self.token),
) if value is not None
}

View File

@@ -10,12 +10,12 @@ import socket
import requests
import voluptuous as vol
from homeassistant.const import CONF_PORT
from homeassistant.const import CONF_PORT, CONF_SSL
from homeassistant.components.camera import Camera, PLATFORM_SCHEMA
import homeassistant.helpers.config_validation as cv
from homeassistant.exceptions import PlatformNotReady
REQUIREMENTS = ['uvcclient==0.10.1']
REQUIREMENTS = ['uvcclient==0.11.0']
_LOGGER = logging.getLogger(__name__)
@@ -25,12 +25,14 @@ CONF_PASSWORD = 'password'
DEFAULT_PASSWORD = 'ubnt'
DEFAULT_PORT = 7080
DEFAULT_SSL = False
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_NVR): cv.string,
vol.Required(CONF_KEY): cv.string,
vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean,
})
@@ -40,11 +42,12 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
key = config[CONF_KEY]
password = config[CONF_PASSWORD]
port = config[CONF_PORT]
ssl = config[CONF_SSL]
from uvcclient import nvr
try:
# Exceptions may be raised in all method calls to the nvr library.
nvrconn = nvr.UVCRemote(addr, port, key)
nvrconn = nvr.UVCRemote(addr, port, key, ssl=ssl)
cameras = nvrconn.index()
identifier = 'id' if nvrconn.server_version >= (3, 2, 0) else 'uuid'

View File

@@ -1,5 +1,15 @@
{
"config": {
"abort": {
"no_devices_found": "No se encontraron dispositivos de Google Cast en la red.",
"single_instance_allowed": "S\u00f3lo es necesaria una \u00fanica configuraci\u00f3n de Google Cast."
},
"step": {
"confirm": {
"description": "\u00bfQuieres configurar Google Cast?",
"title": "Google Cast"
}
},
"title": "Google Cast"
}
}

View File

@@ -249,9 +249,11 @@ class ClimateDevice(Entity):
self.hass, self.target_temperature_low, self.temperature_unit,
self.precision)
if self.current_humidity is not None:
data[ATTR_CURRENT_HUMIDITY] = self.current_humidity
if supported_features & SUPPORT_TARGET_HUMIDITY:
data[ATTR_HUMIDITY] = self.target_humidity
data[ATTR_CURRENT_HUMIDITY] = self.current_humidity
if supported_features & SUPPORT_TARGET_HUMIDITY_LOW:
data[ATTR_MIN_HUMIDITY] = self.min_humidity

View File

@@ -22,7 +22,7 @@ from homeassistant.const import (
ATTR_TEMPERATURE, CONF_HOST, CONF_NAME, TEMP_CELSIUS)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pydaikin==0.4']
REQUIREMENTS = ['pydaikin==0.8']
_LOGGER = logging.getLogger(__name__)
@@ -82,7 +82,6 @@ class DaikinClimate(ClimateDevice):
from pydaikin import appliance
self._api = api
self._force_refresh = False
self._list = {
ATTR_OPERATION_MODE: list(HA_STATE_TO_DAIKIN),
ATTR_FAN_MODE: list(
@@ -102,19 +101,11 @@ class DaikinClimate(ClimateDevice):
self._supported_features = SUPPORT_TARGET_TEMPERATURE \
| SUPPORT_OPERATION_MODE
daikin_attr = HA_ATTR_TO_DAIKIN[ATTR_FAN_MODE]
if self._api.device.values.get(daikin_attr) is not None:
if self._api.device.support_fan_mode:
self._supported_features |= SUPPORT_FAN_MODE
else:
# even devices without support must have a default valid value
self._api.device.values[daikin_attr] = 'A'
daikin_attr = HA_ATTR_TO_DAIKIN[ATTR_SWING_MODE]
if self._api.device.values.get(daikin_attr) is not None:
if self._api.device.support_swing_mode:
self._supported_features |= SUPPORT_SWING_MODE
else:
# even devices without support must have a default valid value
self._api.device.values[daikin_attr] = '0'
def get(self, key):
"""Retrieve device settings from API library cache."""
@@ -189,7 +180,6 @@ class DaikinClimate(ClimateDevice):
_LOGGER.error("Invalid temperature %s", value)
if values:
self._force_refresh = True
self._api.device.set(values)
@property
@@ -202,6 +192,11 @@ class DaikinClimate(ClimateDevice):
"""Return the name of the thermostat, if any."""
return self._api.name
@property
def unique_id(self):
"""Return a unique ID."""
return self._api.mac
@property
def temperature_unit(self):
"""Return the unit of measurement which this thermostat uses."""
@@ -270,5 +265,4 @@ class DaikinClimate(ClimateDevice):
def update(self):
"""Retrieve latest state."""
self._api.update(no_throttle=self._force_refresh)
self._force_refresh = False
self._api.update()

View File

@@ -1,7 +1,7 @@
"""Support for Honeywell evohome (EMEA/EU-based systems only).
"""Support for Climate devices of (EMEA/EU-based) Honeywell evohome systems.
Support for a temperature control system (TCS, controller) with 0+ heating
zones (e.g. TRVs, relays) and, optionally, a DHW controller.
zones (e.g. TRVs, relays).
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.evohome/
@@ -13,29 +13,34 @@ import logging
from requests.exceptions import HTTPError
from homeassistant.components.climate import (
ClimateDevice,
STATE_AUTO,
STATE_ECO,
STATE_OFF,
SUPPORT_OPERATION_MODE,
STATE_AUTO, STATE_ECO, STATE_MANUAL, STATE_OFF,
SUPPORT_AWAY_MODE,
SUPPORT_ON_OFF,
SUPPORT_OPERATION_MODE,
SUPPORT_TARGET_TEMPERATURE,
ClimateDevice
)
from homeassistant.components.evohome import (
CONF_LOCATION_IDX,
DATA_EVOHOME,
MAX_TEMP,
MIN_TEMP,
SCAN_INTERVAL_MAX
DATA_EVOHOME, DISPATCHER_EVOHOME,
CONF_LOCATION_IDX, SCAN_INTERVAL_DEFAULT,
EVO_PARENT, EVO_CHILD,
GWS, TCS,
)
from homeassistant.const import (
CONF_SCAN_INTERVAL,
PRECISION_TENTHS,
TEMP_CELSIUS,
HTTP_TOO_MANY_REQUESTS,
PRECISION_HALVES,
TEMP_CELSIUS
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import (
dispatcher_send,
async_dispatcher_connect
)
_LOGGER = logging.getLogger(__name__)
# these are for the controller's opmode/state and the zone's state
# the Controller's opmode/state and the zone's (inherited) state
EVO_RESET = 'AutoWithReset'
EVO_AUTO = 'Auto'
EVO_AUTOECO = 'AutoWithEco'
@@ -44,7 +49,14 @@ EVO_DAYOFF = 'DayOff'
EVO_CUSTOM = 'Custom'
EVO_HEATOFF = 'HeatingOff'
EVO_STATE_TO_HA = {
# these are for Zones' opmode, and state
EVO_FOLLOW = 'FollowSchedule'
EVO_TEMPOVER = 'TemporaryOverride'
EVO_PERMOVER = 'PermanentOverride'
# for the Controller. NB: evohome treats Away mode as a mode in/of itself,
# where HA considers it to 'override' the exising operating mode
TCS_STATE_TO_HA = {
EVO_RESET: STATE_AUTO,
EVO_AUTO: STATE_AUTO,
EVO_AUTOECO: STATE_ECO,
@@ -53,171 +65,150 @@ EVO_STATE_TO_HA = {
EVO_CUSTOM: STATE_AUTO,
EVO_HEATOFF: STATE_OFF
}
HA_STATE_TO_EVO = {
HA_STATE_TO_TCS = {
STATE_AUTO: EVO_AUTO,
STATE_ECO: EVO_AUTOECO,
STATE_OFF: EVO_HEATOFF
}
TCS_OP_LIST = list(HA_STATE_TO_TCS)
HA_OP_LIST = list(HA_STATE_TO_EVO)
# the Zones' opmode; their state is usually 'inherited' from the TCS
EVO_FOLLOW = 'FollowSchedule'
EVO_TEMPOVER = 'TemporaryOverride'
EVO_PERMOVER = 'PermanentOverride'
# these are used to help prevent E501 (line too long) violations
GWS = 'gateways'
TCS = 'temperatureControlSystems'
# debug codes - these happen occasionally, but the cause is unknown
EVO_DEBUG_NO_RECENT_UPDATES = '0x01'
EVO_DEBUG_NO_STATUS = '0x02'
# for the Zones...
ZONE_STATE_TO_HA = {
EVO_FOLLOW: STATE_AUTO,
EVO_TEMPOVER: STATE_MANUAL,
EVO_PERMOVER: STATE_MANUAL
}
HA_STATE_TO_ZONE = {
STATE_AUTO: EVO_FOLLOW,
STATE_MANUAL: EVO_PERMOVER
}
ZONE_OP_LIST = list(HA_STATE_TO_ZONE)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Create a Honeywell (EMEA/EU) evohome CH/DHW system.
An evohome system consists of: a controller, with 0-12 heating zones (e.g.
TRVs, relays) and, optionally, a DHW controller (a HW boiler).
Here, we add the controller only.
"""
async def async_setup_platform(hass, hass_config, async_add_entities,
discovery_info=None):
"""Create the evohome Controller, and its Zones, if any."""
evo_data = hass.data[DATA_EVOHOME]
client = evo_data['client']
loc_idx = evo_data['params'][CONF_LOCATION_IDX]
# evohomeclient has no defined way of accessing non-default location other
# than using a protected member, such as below
# evohomeclient has exposed no means of accessing non-default location
# (i.e. loc_idx > 0) other than using a protected member, such as below
tcs_obj_ref = client.locations[loc_idx]._gateways[0]._control_systems[0] # noqa E501; pylint: disable=protected-access
_LOGGER.debug(
"setup_platform(): Found Controller: id: %s [%s], type: %s",
"setup_platform(): Found Controller, id=%s [%s], "
"name=%s (location_idx=%s)",
tcs_obj_ref.systemId,
tcs_obj_ref.modelType,
tcs_obj_ref.location.name,
tcs_obj_ref.modelType
loc_idx
)
parent = EvoController(evo_data, client, tcs_obj_ref)
add_entities([parent], update_before_add=True)
controller = EvoController(evo_data, client, tcs_obj_ref)
zones = []
for zone_idx in tcs_obj_ref.zones:
zone_obj_ref = tcs_obj_ref.zones[zone_idx]
_LOGGER.debug(
"setup_platform(): Found Zone, id=%s [%s], "
"name=%s",
zone_obj_ref.zoneId,
zone_obj_ref.zone_type,
zone_obj_ref.name
)
zones.append(EvoZone(evo_data, client, zone_obj_ref))
entities = [controller] + zones
async_add_entities(entities, update_before_add=False)
class EvoController(ClimateDevice):
"""Base for a Honeywell evohome hub/Controller device.
class EvoClimateDevice(ClimateDevice):
"""Base for a Honeywell evohome Climate device."""
The Controller (aka TCS, temperature control system) is the parent of all
the child (CH/DHW) devices.
"""
# pylint: disable=no-member
def __init__(self, evo_data, client, obj_ref):
"""Initialize the evohome entity.
Most read-only properties are set here. So are pseudo read-only,
for example name (which _could_ change between update()s).
"""
self.client = client
"""Initialize the evohome entity."""
self._client = client
self._obj = obj_ref
self._id = obj_ref.systemId
self._name = evo_data['config']['locationInfo']['name']
self._config = evo_data['config'][GWS][0][TCS][0]
self._params = evo_data['params']
self._timers = evo_data['timers']
self._timers['statusUpdated'] = datetime.min
self._status = {}
self._available = False # should become True after first update()
def _handle_requests_exceptions(self, err):
# evohomeclient v2 api (>=0.2.7) exposes requests exceptions, incl.:
# - HTTP_BAD_REQUEST, is usually Bad user credentials
# - HTTP_TOO_MANY_REQUESTS, is api usuage limit exceeded
# - HTTP_SERVICE_UNAVAILABLE, is often Vendor's fault
async def async_added_to_hass(self):
"""Run when entity about to be added."""
async_dispatcher_connect(self.hass, DISPATCHER_EVOHOME, self._connect)
@callback
def _connect(self, packet):
if packet['to'] & self._type and packet['signal'] == 'refresh':
self.async_schedule_update_ha_state(force_refresh=True)
def _handle_requests_exceptions(self, err):
if err.response.status_code == HTTP_TOO_MANY_REQUESTS:
# execute a back off: pause, and reduce rate
old_scan_interval = self._params[CONF_SCAN_INTERVAL]
new_scan_interval = min(old_scan_interval * 2, SCAN_INTERVAL_MAX)
self._params[CONF_SCAN_INTERVAL] = new_scan_interval
# execute a backoff: pause, and also reduce rate
old_interval = self._params[CONF_SCAN_INTERVAL]
new_interval = min(old_interval, SCAN_INTERVAL_DEFAULT) * 2
self._params[CONF_SCAN_INTERVAL] = new_interval
_LOGGER.warning(
"API rate limit has been exceeded: increasing '%s' from %s to "
"%s seconds, and suspending polling for %s seconds.",
"API rate limit has been exceeded. Suspending polling for %s "
"seconds, and increasing '%s' from %s to %s seconds.",
new_interval * 3,
CONF_SCAN_INTERVAL,
old_scan_interval,
new_scan_interval,
new_scan_interval * 3
old_interval,
new_interval,
)
self._timers['statusUpdated'] = datetime.now() + \
timedelta(seconds=new_scan_interval * 3)
self._timers['statusUpdated'] = datetime.now() + new_interval * 3
else:
raise err
raise err # we dont handle any other HTTPErrors
@property
def name(self):
def name(self) -> str:
"""Return the name to use in the frontend UI."""
return self._name
@property
def available(self):
"""Return True if the device is available.
def icon(self):
"""Return the icon to use in the frontend UI."""
return self._icon
All evohome entities are initially unavailable. Once HA has started,
state data is then retrieved by the Controller, and then the children
will get a state (e.g. operating_mode, current_temperature).
@property
def device_state_attributes(self):
"""Return the device state attributes of the evohome Climate device.
However, evohome entities can become unavailable for other reasons.
This is state data that is not available otherwise, due to the
restrictions placed upon ClimateDevice properties, etc. by HA.
"""
return {'status': self._status}
@property
def available(self) -> bool:
"""Return True if the device is currently available."""
return self._available
@property
def supported_features(self):
"""Get the list of supported features of the Controller."""
return SUPPORT_OPERATION_MODE | SUPPORT_AWAY_MODE
@property
def device_state_attributes(self):
"""Return the device state attributes of the controller.
This is operating mode state data that is not available otherwise, due
to the restrictions placed upon ClimateDevice properties, etc by HA.
"""
data = {}
data['systemMode'] = self._status['systemModeStatus']['mode']
data['isPermanent'] = self._status['systemModeStatus']['isPermanent']
if 'timeUntil' in self._status['systemModeStatus']:
data['timeUntil'] = self._status['systemModeStatus']['timeUntil']
data['activeFaults'] = self._status['activeFaults']
return data
"""Get the list of supported features of the device."""
return self._supported_features
@property
def operation_list(self):
"""Return the list of available operations."""
return HA_OP_LIST
@property
def current_operation(self):
"""Return the operation mode of the evohome entity."""
return EVO_STATE_TO_HA.get(self._status['systemModeStatus']['mode'])
@property
def target_temperature(self):
"""Return the average target temperature of the Heating/DHW zones."""
temps = [zone['setpointStatus']['targetHeatTemperature']
for zone in self._status['zones']]
avg_temp = round(sum(temps) / len(temps), 1) if temps else None
return avg_temp
@property
def current_temperature(self):
"""Return the average current temperature of the Heating/DHW zones."""
tmp_list = [x for x in self._status['zones']
if x['temperatureStatus']['isAvailable'] is True]
temps = [zone['temperatureStatus']['temperature'] for zone in tmp_list]
avg_temp = round(sum(temps) / len(temps), 1) if temps else None
return avg_temp
return self._operation_list
@property
def temperature_unit(self):
@@ -227,47 +218,313 @@ class EvoController(ClimateDevice):
@property
def precision(self):
"""Return the temperature precision to use in the frontend UI."""
return PRECISION_TENTHS
return PRECISION_HALVES
class EvoZone(EvoClimateDevice):
"""Base for a Honeywell evohome Zone device."""
def __init__(self, evo_data, client, obj_ref):
"""Initialize the evohome Zone."""
super().__init__(evo_data, client, obj_ref)
self._id = obj_ref.zoneId
self._name = obj_ref.name
self._icon = "mdi:radiator"
self._type = EVO_CHILD
for _zone in evo_data['config'][GWS][0][TCS][0]['zones']:
if _zone['zoneId'] == self._id:
self._config = _zone
break
self._status = {}
self._operation_list = ZONE_OP_LIST
self._supported_features = \
SUPPORT_OPERATION_MODE | \
SUPPORT_TARGET_TEMPERATURE | \
SUPPORT_ON_OFF
@property
def min_temp(self):
"""Return the minimum target temp (setpoint) of a evohome entity."""
return MIN_TEMP
"""Return the minimum target temperature of a evohome Zone.
The default is 5 (in Celsius), but it is configurable within 5-35.
"""
return self._config['setpointCapabilities']['minHeatSetpoint']
@property
def max_temp(self):
"""Return the maximum target temp (setpoint) of a evohome entity."""
return MAX_TEMP
"""Return the minimum target temperature of a evohome Zone.
The default is 35 (in Celsius), but it is configurable within 5-35.
"""
return self._config['setpointCapabilities']['maxHeatSetpoint']
@property
def is_on(self):
"""Return true as evohome controllers are always on.
def target_temperature(self):
"""Return the target temperature of the evohome Zone."""
return self._status['setpointStatus']['targetHeatTemperature']
Operating modes can include 'HeatingOff', but (for example) DHW would
remain on.
@property
def current_temperature(self):
"""Return the current temperature of the evohome Zone."""
return self._status['temperatureStatus']['temperature']
@property
def current_operation(self):
"""Return the current operating mode of the evohome Zone.
The evohome Zones that are in 'FollowSchedule' mode inherit their
actual operating mode from the Controller.
"""
evo_data = self.hass.data[DATA_EVOHOME]
system_mode = evo_data['status']['systemModeStatus']['mode']
setpoint_mode = self._status['setpointStatus']['setpointMode']
if setpoint_mode == EVO_FOLLOW:
# then inherit state from the controller
if system_mode == EVO_RESET:
current_operation = TCS_STATE_TO_HA.get(EVO_AUTO)
else:
current_operation = TCS_STATE_TO_HA.get(system_mode)
else:
current_operation = ZONE_STATE_TO_HA.get(setpoint_mode)
return current_operation
@property
def is_on(self) -> bool:
"""Return True if the evohome Zone is off.
A Zone is considered off if its target temp is set to its minimum, and
it is not following its schedule (i.e. not in 'FollowSchedule' mode).
"""
is_off = \
self.target_temperature == self.min_temp and \
self._status['setpointStatus']['setpointMode'] == EVO_PERMOVER
return not is_off
def _set_temperature(self, temperature, until=None):
"""Set the new target temperature of a Zone.
temperature is required, until can be:
- strftime('%Y-%m-%dT%H:%M:%SZ') for TemporaryOverride, or
- None for PermanentOverride (i.e. indefinitely)
"""
try:
self._obj.set_temperature(temperature, until)
except HTTPError as err:
self._handle_exception("HTTPError", str(err)) # noqa: E501; pylint: disable=no-member
def set_temperature(self, **kwargs):
"""Set new target temperature, indefinitely."""
self._set_temperature(kwargs['temperature'], until=None)
def turn_on(self):
"""Turn the evohome Zone on.
This is achieved by setting the Zone to its 'FollowSchedule' mode.
"""
self._set_operation_mode(EVO_FOLLOW)
def turn_off(self):
"""Turn the evohome Zone off.
This is achieved by setting the Zone to its minimum temperature,
indefinitely (i.e. 'PermanentOverride' mode).
"""
self._set_temperature(self.min_temp, until=None)
def set_operation_mode(self, operation_mode):
"""Set an operating mode for a Zone.
Currently limited to 'Auto' & 'Manual'. If 'Off' is needed, it can be
enabled via turn_off method.
NB: evohome Zones do not have an operating mode as understood by HA.
Instead they usually 'inherit' an operating mode from their controller.
More correctly, these Zones are in a follow mode, 'FollowSchedule',
where their setpoint temperatures are a function of their schedule, and
the Controller's operating_mode, e.g. Economy mode is their scheduled
setpoint less (usually) 3C.
Thus, you cannot set a Zone to Away mode, but the location (i.e. the
Controller) is set to Away and each Zones's setpoints are adjusted
accordingly to some lower temperature.
However, Zones can override these setpoints, either for a specified
period of time, 'TemporaryOverride', after which they will revert back
to 'FollowSchedule' mode, or indefinitely, 'PermanentOverride'.
"""
self._set_operation_mode(HA_STATE_TO_ZONE.get(operation_mode))
def _set_operation_mode(self, operation_mode):
if operation_mode == EVO_FOLLOW:
try:
self._obj.cancel_temp_override(self._obj)
except HTTPError as err:
self._handle_exception("HTTPError", str(err)) # noqa: E501; pylint: disable=no-member
elif operation_mode == EVO_TEMPOVER:
_LOGGER.error(
"_set_operation_mode(op_mode=%s): mode not yet implemented",
operation_mode
)
elif operation_mode == EVO_PERMOVER:
self._set_temperature(self.target_temperature, until=None)
else:
_LOGGER.error(
"_set_operation_mode(op_mode=%s): mode not valid",
operation_mode
)
@property
def should_poll(self) -> bool:
"""Return False as evohome child devices should never be polled.
The evohome Controller will inform its children when to update().
"""
return False
def update(self):
"""Process the evohome Zone's state data."""
evo_data = self.hass.data[DATA_EVOHOME]
for _zone in evo_data['status']['zones']:
if _zone['zoneId'] == self._id:
self._status = _zone
break
self._available = True
class EvoController(EvoClimateDevice):
"""Base for a Honeywell evohome hub/Controller device.
The Controller (aka TCS, temperature control system) is the parent of all
the child (CH/DHW) devices. It is also a Climate device.
"""
def __init__(self, evo_data, client, obj_ref):
"""Initialize the evohome Controller (hub)."""
super().__init__(evo_data, client, obj_ref)
self._id = obj_ref.systemId
self._name = '_{}'.format(obj_ref.location.name)
self._icon = "mdi:thermostat"
self._type = EVO_PARENT
self._config = evo_data['config'][GWS][0][TCS][0]
self._status = evo_data['status']
self._timers['statusUpdated'] = datetime.min
self._operation_list = TCS_OP_LIST
self._supported_features = \
SUPPORT_OPERATION_MODE | \
SUPPORT_AWAY_MODE
@property
def device_state_attributes(self):
"""Return the device state attributes of the evohome Controller.
This is state data that is not available otherwise, due to the
restrictions placed upon ClimateDevice properties, etc. by HA.
"""
status = dict(self._status)
if 'zones' in status:
del status['zones']
if 'dhw' in status:
del status['dhw']
return {'status': status}
@property
def current_operation(self):
"""Return the current operating mode of the evohome Controller."""
return TCS_STATE_TO_HA.get(self._status['systemModeStatus']['mode'])
@property
def min_temp(self):
"""Return the minimum target temperature of a evohome Controller.
Although evohome Controllers do not have a minimum target temp, one is
expected by the HA schema; the default for an evohome HR92 is used.
"""
return 5
@property
def max_temp(self):
"""Return the minimum target temperature of a evohome Controller.
Although evohome Controllers do not have a maximum target temp, one is
expected by the HA schema; the default for an evohome HR92 is used.
"""
return 35
@property
def target_temperature(self):
"""Return the average target temperature of the Heating/DHW zones.
Although evohome Controllers do not have a target temp, one is
expected by the HA schema.
"""
temps = [zone['setpointStatus']['targetHeatTemperature']
for zone in self._status['zones']]
avg_temp = round(sum(temps) / len(temps), 1) if temps else None
return avg_temp
@property
def current_temperature(self):
"""Return the average current temperature of the Heating/DHW zones.
Although evohome Controllers do not have a target temp, one is
expected by the HA schema.
"""
tmp_list = [x for x in self._status['zones']
if x['temperatureStatus']['isAvailable'] is True]
temps = [zone['temperatureStatus']['temperature'] for zone in tmp_list]
avg_temp = round(sum(temps) / len(temps), 1) if temps else None
return avg_temp
@property
def is_on(self) -> bool:
"""Return True as evohome Controllers are always on.
For example, evohome Controllers have a 'HeatingOff' mode, but even
then the DHW would remain on.
"""
return True
@property
def is_away_mode_on(self):
"""Return true if away mode is on."""
def is_away_mode_on(self) -> bool:
"""Return True if away mode is on."""
return self._status['systemModeStatus']['mode'] == EVO_AWAY
def turn_away_mode_on(self):
"""Turn away mode on."""
"""Turn away mode on.
The evohome Controller will not remember is previous operating mode.
"""
self._set_operation_mode(EVO_AWAY)
def turn_away_mode_off(self):
"""Turn away mode off."""
"""Turn away mode off.
The evohome Controller can not recall its previous operating mode (as
intimated by the HA schema), so this method is achieved by setting the
Controller's mode back to Auto.
"""
self._set_operation_mode(EVO_AUTO)
def _set_operation_mode(self, operation_mode):
# Set new target operation mode for the TCS.
_LOGGER.debug(
"_set_operation_mode(): API call [1 request(s)]: "
"tcs._set_status(%s)...",
operation_mode
)
try:
self._obj._set_status(operation_mode) # noqa: E501; pylint: disable=protected-access
except HTTPError as err:
@@ -279,93 +536,45 @@ class EvoController(ClimateDevice):
Currently limited to 'Auto', 'AutoWithEco' & 'HeatingOff'. If 'Away'
mode is needed, it can be enabled via turn_away_mode_on method.
"""
self._set_operation_mode(HA_STATE_TO_EVO.get(operation_mode))
self._set_operation_mode(HA_STATE_TO_TCS.get(operation_mode))
def _update_state_data(self, evo_data):
client = evo_data['client']
loc_idx = evo_data['params'][CONF_LOCATION_IDX]
_LOGGER.debug(
"_update_state_data(): API call [1 request(s)]: "
"client.locations[loc_idx].status()..."
)
try:
evo_data['status'].update(
client.locations[loc_idx].status()[GWS][0][TCS][0])
except HTTPError as err: # check if we've exceeded the api rate limit
self._handle_requests_exceptions(err)
else:
evo_data['timers']['statusUpdated'] = datetime.now()
_LOGGER.debug(
"_update_state_data(): evo_data['status'] = %s",
evo_data['status']
)
@property
def should_poll(self) -> bool:
"""Return True as the evohome Controller should always be polled."""
return True
def update(self):
"""Get the latest state data of the installation.
"""Get the latest state data of the entire evohome Location.
This includes state data for the Controller and its child devices, such
as the operating_mode of the Controller and the current_temperature
of its children.
This is not asyncio-friendly due to the underlying client api.
This includes state data for the Controller and all its child devices,
such as the operating mode of the Controller and the current temp of
its children (e.g. Zones, DHW controller).
"""
evo_data = self.hass.data[DATA_EVOHOME]
# should the latest evohome state data be retreived this cycle?
timeout = datetime.now() + timedelta(seconds=55)
expired = timeout > self._timers['statusUpdated'] + \
timedelta(seconds=evo_data['params'][CONF_SCAN_INTERVAL])
self._params[CONF_SCAN_INTERVAL]
if not expired:
return
was_available = self._available or \
self._timers['statusUpdated'] == datetime.min
self._update_state_data(evo_data)
self._status = evo_data['status']
if _LOGGER.isEnabledFor(logging.DEBUG):
tmp_dict = dict(self._status)
if 'zones' in tmp_dict:
tmp_dict['zones'] = '...'
if 'dhw' in tmp_dict:
tmp_dict['dhw'] = '...'
_LOGGER.debug(
"update(%s), self._status = %s",
self._id + " [" + self._name + "]",
tmp_dict
)
no_recent_updates = self._timers['statusUpdated'] < datetime.now() - \
timedelta(seconds=self._params[CONF_SCAN_INTERVAL] * 3.1)
if no_recent_updates:
self._available = False
debug_code = EVO_DEBUG_NO_RECENT_UPDATES
elif not self._status:
# unavailable because no status (but how? other than at startup?)
self._available = False
debug_code = EVO_DEBUG_NO_STATUS
# Retreive the latest state data via the client api
loc_idx = self._params[CONF_LOCATION_IDX]
try:
self._status.update(
self._client.locations[loc_idx].status()[GWS][0][TCS][0])
except HTTPError as err: # check if we've exceeded the api rate limit
self._handle_requests_exceptions(err)
else:
self._timers['statusUpdated'] = datetime.now()
self._available = True
if not self._available and was_available:
# only warn if available went from True to False
_LOGGER.warning(
"The entity, %s, has become unavailable, debug code is: %s",
self._id + " [" + self._name + "]",
debug_code
)
_LOGGER.debug(
"_update_state_data(): self._status = %s",
self._status
)
elif self._available and not was_available:
# this isn't the first re-available (e.g. _after_ STARTUP)
_LOGGER.debug(
"The entity, %s, has become available",
self._id + " [" + self._name + "]"
)
# inform the child devices that state data has been updated
pkt = {'sender': 'controller', 'signal': 'refresh', 'to': EVO_CHILD}
dispatcher_send(self.hass, DISPATCHER_EVOHOME, pkt)

View File

@@ -17,12 +17,13 @@ from homeassistant.components.climate import (
SUPPORT_AWAY_MODE, SUPPORT_TARGET_TEMPERATURE, PLATFORM_SCHEMA)
from homeassistant.const import (
STATE_ON, STATE_OFF, ATTR_TEMPERATURE, CONF_NAME, ATTR_ENTITY_ID,
SERVICE_TURN_ON, SERVICE_TURN_OFF, STATE_UNKNOWN)
SERVICE_TURN_ON, SERVICE_TURN_OFF, STATE_UNKNOWN, PRECISION_HALVES,
PRECISION_TENTHS, PRECISION_WHOLE)
from homeassistant.helpers import condition
from homeassistant.helpers.event import (
async_track_state_change, async_track_time_interval)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.restore_state import async_get_last_state
from homeassistant.helpers.restore_state import RestoreEntity
_LOGGER = logging.getLogger(__name__)
@@ -43,6 +44,7 @@ CONF_HOT_TOLERANCE = 'hot_tolerance'
CONF_KEEP_ALIVE = 'keep_alive'
CONF_INITIAL_OPERATION_MODE = 'initial_operation_mode'
CONF_AWAY_TEMP = 'away_temp'
CONF_PRECISION = 'precision'
SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE |
SUPPORT_OPERATION_MODE)
@@ -63,7 +65,9 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
cv.time_period, cv.positive_timedelta),
vol.Optional(CONF_INITIAL_OPERATION_MODE):
vol.In([STATE_AUTO, STATE_OFF]),
vol.Optional(CONF_AWAY_TEMP): vol.Coerce(float)
vol.Optional(CONF_AWAY_TEMP): vol.Coerce(float),
vol.Optional(CONF_PRECISION): vol.In(
[PRECISION_TENTHS, PRECISION_HALVES, PRECISION_WHOLE]),
})
@@ -83,20 +87,22 @@ async def async_setup_platform(hass, config, async_add_entities,
keep_alive = config.get(CONF_KEEP_ALIVE)
initial_operation_mode = config.get(CONF_INITIAL_OPERATION_MODE)
away_temp = config.get(CONF_AWAY_TEMP)
precision = config.get(CONF_PRECISION)
async_add_entities([GenericThermostat(
hass, name, heater_entity_id, sensor_entity_id, min_temp, max_temp,
target_temp, ac_mode, min_cycle_duration, cold_tolerance,
hot_tolerance, keep_alive, initial_operation_mode, away_temp)])
hot_tolerance, keep_alive, initial_operation_mode, away_temp,
precision)])
class GenericThermostat(ClimateDevice):
class GenericThermostat(ClimateDevice, RestoreEntity):
"""Representation of a Generic Thermostat device."""
def __init__(self, hass, name, heater_entity_id, sensor_entity_id,
min_temp, max_temp, target_temp, ac_mode, min_cycle_duration,
cold_tolerance, hot_tolerance, keep_alive,
initial_operation_mode, away_temp):
initial_operation_mode, away_temp, precision):
"""Initialize the thermostat."""
self.hass = hass
self._name = name
@@ -109,6 +115,7 @@ class GenericThermostat(ClimateDevice):
self._initial_operation_mode = initial_operation_mode
self._saved_target_temp = target_temp if target_temp is not None \
else away_temp
self._temp_precision = precision
if self.ac_mode:
self._current_operation = STATE_COOL
self._operation_list = [STATE_COOL, STATE_OFF]
@@ -148,8 +155,9 @@ class GenericThermostat(ClimateDevice):
async def async_added_to_hass(self):
"""Run when entity about to be added."""
await super().async_added_to_hass()
# Check If we have an old state
old_state = await async_get_last_state(self.hass, self.entity_id)
old_state = await self.async_get_last_state()
if old_state is not None:
# If we have no initial temperature, restore
if self._target_temp is None:
@@ -202,6 +210,13 @@ class GenericThermostat(ClimateDevice):
"""Return the name of the thermostat."""
return self._name
@property
def precision(self):
"""Return the precision of the system."""
if self._temp_precision is not None:
return self._temp_precision
return super().precision
@property
def temperature_unit(self):
"""Return the unit of measurement."""

View File

@@ -7,17 +7,16 @@ https://home-assistant.io/components/climate.homematic/
import logging
from homeassistant.components.climate import (
STATE_AUTO, SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE,
ClimateDevice)
STATE_AUTO, STATE_MANUAL, SUPPORT_OPERATION_MODE,
SUPPORT_TARGET_TEMPERATURE, ClimateDevice)
from homeassistant.components.homematic import (
ATTR_DISCOVER_DEVICES, HM_ATTRIBUTE_SUPPORT, HMDevice)
from homeassistant.const import ATTR_TEMPERATURE, STATE_UNKNOWN, TEMP_CELSIUS
from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS
DEPENDENCIES = ['homematic']
_LOGGER = logging.getLogger(__name__)
STATE_MANUAL = 'manual'
STATE_BOOST = 'boost'
STATE_COMFORT = 'comfort'
STATE_LOWERING = 'lowering'
@@ -41,7 +40,7 @@ HM_HUMI_MAP = [
]
HM_CONTROL_MODE = 'CONTROL_MODE'
HM_IP_CONTROL_MODE = 'SET_POINT_MODE'
HMIP_CONTROL_MODE = 'SET_POINT_MODE'
SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE
@@ -78,21 +77,17 @@ class HMThermostat(HMDevice, ClimateDevice):
if HM_CONTROL_MODE not in self._data:
return None
set_point_mode = self._data.get('SET_POINT_MODE', -1)
control_mode = self._data.get('CONTROL_MODE', -1)
boost_mode = self._data.get('BOOST_MODE', False)
# boost mode is active
if boost_mode:
if self._data.get('BOOST_MODE', False):
return STATE_BOOST
# HM ip etrv 2 uses the set_point_mode to say if its
# HmIP uses the set_point_mode to say if its
# auto or manual
if not set_point_mode == -1:
code = set_point_mode
if HMIP_CONTROL_MODE in self._data:
code = self._data[HMIP_CONTROL_MODE]
# Other devices use the control_mode
else:
code = control_mode
code = self._data['CONTROL_MODE']
# get the name of the mode
name = HM_ATTRIBUTE_SUPPORT[HM_CONTROL_MODE][1][code]
@@ -101,12 +96,15 @@ class HMThermostat(HMDevice, ClimateDevice):
@property
def operation_list(self):
"""Return the list of available operation modes."""
op_list = []
# HMIP use set_point_mode for operation
if HMIP_CONTROL_MODE in self._data:
return [STATE_MANUAL, STATE_AUTO, STATE_BOOST]
# HM
op_list = []
for mode in self._hmdevice.ACTIONNODE:
if mode in HM_STATE_MAP:
op_list.append(HM_STATE_MAP.get(mode))
return op_list
@property
@@ -157,11 +155,11 @@ class HMThermostat(HMDevice, ClimateDevice):
def _init_data_struct(self):
"""Generate a data dict (self._data) from the Homematic metadata."""
self._state = next(iter(self._hmdevice.WRITENODE.keys()))
self._data[self._state] = STATE_UNKNOWN
self._data[self._state] = None
if HM_CONTROL_MODE in self._hmdevice.ATTRIBUTENODE or \
HM_IP_CONTROL_MODE in self._hmdevice.ATTRIBUTENODE:
self._data[HM_CONTROL_MODE] = STATE_UNKNOWN
HMIP_CONTROL_MODE in self._hmdevice.ATTRIBUTENODE:
self._data[HM_CONTROL_MODE] = None
for node in self._hmdevice.SENSORNODE.keys():
self._data[node] = STATE_UNKNOWN
self._data[node] = None

View File

@@ -20,7 +20,7 @@ from homeassistant.const import (
CONF_PASSWORD, CONF_USERNAME, TEMP_CELSIUS, TEMP_FAHRENHEIT,
ATTR_TEMPERATURE, CONF_REGION)
REQUIREMENTS = ['evohomeclient==0.2.7', 'somecomfort==0.5.2']
REQUIREMENTS = ['evohomeclient==0.2.8', 'somecomfort==0.5.2']
_LOGGER = logging.getLogger(__name__)

View File

@@ -88,6 +88,12 @@ class MelissaClimate(ClimateDevice):
if self._data:
return self._data[self._api.TEMP]
@property
def current_humidity(self):
"""Return the current humidity value."""
if self._data:
return self._data[self._api.HUMIDITY]
@property
def target_temperature_step(self):
"""Return the supported step of target temperature."""
@@ -113,8 +119,9 @@ class MelissaClimate(ClimateDevice):
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
if self._cur_settings is not None:
return self._cur_settings[self._api.TEMP]
if self._cur_settings is None:
return None
return self._cur_settings[self._api.TEMP]
@property
def state(self):

View File

@@ -19,7 +19,7 @@ from homeassistant.const import (
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
REQUIREMENTS = ['millheater==0.2.2']
REQUIREMENTS = ['millheater==0.2.9']
_LOGGER = logging.getLogger(__name__)
@@ -32,8 +32,7 @@ MIN_TEMP = 5
SERVICE_SET_ROOM_TEMP = 'mill_set_room_temperature'
SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE |
SUPPORT_FAN_MODE | SUPPORT_ON_OFF |
SUPPORT_OPERATION_MODE)
SUPPORT_FAN_MODE)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_USERNAME): cv.string,
@@ -92,12 +91,14 @@ class MillHeater(ClimateDevice):
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS
if self._heater.is_gen1:
return SUPPORT_FLAGS
return SUPPORT_FLAGS | SUPPORT_ON_OFF | SUPPORT_OPERATION_MODE
@property
def available(self):
"""Return True if entity is available."""
return self._heater.device_status == 0 # weird api choice
return self._heater.available
@property
def unique_id(self):
@@ -112,16 +113,18 @@ class MillHeater(ClimateDevice):
@property
def device_state_attributes(self):
"""Return the state attributes."""
if self._heater.room:
room = self._heater.room.name
else:
room = "Independent device"
return {
"room": room,
res = {
"open_window": self._heater.open_window,
"heating": self._heater.is_heating,
"controlled_by_tibber": self._heater.tibber_control,
"heater_generation": 1 if self._heater.is_gen1 else 2,
}
if self._heater.room:
res['room'] = self._heater.room.name
res['avg_room_temp'] = self._heater.room.avg_temp
else:
res['room'] = "Independent device"
return res
@property
def temperature_unit(self):
@@ -156,6 +159,8 @@ class MillHeater(ClimateDevice):
@property
def is_on(self):
"""Return true if heater is on."""
if self._heater.is_gen1:
return True
return self._heater.power_status == 1
@property
@@ -176,6 +181,8 @@ class MillHeater(ClimateDevice):
@property
def operation_list(self):
"""List of available operation modes."""
if self._heater.is_gen1:
return None
return [STATE_HEAT, STATE_OFF]
async def async_set_temperature(self, **kwargs):
@@ -210,7 +217,7 @@ class MillHeater(ClimateDevice):
"""Set operation mode."""
if operation_mode == STATE_HEAT:
await self.async_turn_on()
elif operation_mode == STATE_OFF:
elif operation_mode == STATE_OFF and not self._heater.is_gen1:
await self.async_turn_off()
else:
_LOGGER.error("Unrecognized operation mode: %s", operation_mode)

View File

@@ -22,7 +22,8 @@ from homeassistant.const import (
from homeassistant.components.mqtt import (
ATTR_DISCOVERY_HASH, CONF_AVAILABILITY_TOPIC, CONF_QOS, CONF_RETAIN,
CONF_PAYLOAD_AVAILABLE, CONF_PAYLOAD_NOT_AVAILABLE,
MQTT_BASE_PLATFORM_SCHEMA, MqttAvailability, MqttDiscoveryUpdate)
MQTT_BASE_PLATFORM_SCHEMA, MqttAvailability, MqttDiscoveryUpdate,
subscription)
from homeassistant.components.mqtt.discovery import MQTT_DISCOVERY_NEW
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect
@@ -77,6 +78,18 @@ CONF_MIN_TEMP = 'min_temp'
CONF_MAX_TEMP = 'max_temp'
CONF_TEMP_STEP = 'temp_step'
TEMPLATE_KEYS = (
CONF_POWER_STATE_TEMPLATE,
CONF_MODE_STATE_TEMPLATE,
CONF_TEMPERATURE_STATE_TEMPLATE,
CONF_FAN_MODE_STATE_TEMPLATE,
CONF_SWING_MODE_STATE_TEMPLATE,
CONF_AWAY_MODE_STATE_TEMPLATE,
CONF_HOLD_STATE_TEMPLATE,
CONF_AUX_STATE_TEMPLATE,
CONF_CURRENT_TEMPERATURE_TEMPLATE
)
SCHEMA_BASE = CLIMATE_PLATFORM_SCHEMA.extend(MQTT_BASE_PLATFORM_SCHEMA.schema)
PLATFORM_SCHEMA = SCHEMA_BASE.extend({
vol.Optional(CONF_POWER_COMMAND_TOPIC): mqtt.valid_publish_topic,
@@ -153,69 +166,10 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
async def _async_setup_entity(hass, config, async_add_entities,
discovery_hash=None):
"""Set up the MQTT climate devices."""
template_keys = (
CONF_POWER_STATE_TEMPLATE,
CONF_MODE_STATE_TEMPLATE,
CONF_TEMPERATURE_STATE_TEMPLATE,
CONF_FAN_MODE_STATE_TEMPLATE,
CONF_SWING_MODE_STATE_TEMPLATE,
CONF_AWAY_MODE_STATE_TEMPLATE,
CONF_HOLD_STATE_TEMPLATE,
CONF_AUX_STATE_TEMPLATE,
CONF_CURRENT_TEMPERATURE_TEMPLATE
)
value_templates = {}
if CONF_VALUE_TEMPLATE in config:
value_template = config.get(CONF_VALUE_TEMPLATE)
value_template.hass = hass
value_templates = {key: value_template for key in template_keys}
for key in template_keys & config.keys():
value_templates[key] = config.get(key)
value_templates[key].hass = hass
async_add_entities([
MqttClimate(
hass,
config.get(CONF_NAME),
{
key: config.get(key) for key in (
CONF_POWER_COMMAND_TOPIC,
CONF_MODE_COMMAND_TOPIC,
CONF_TEMPERATURE_COMMAND_TOPIC,
CONF_FAN_MODE_COMMAND_TOPIC,
CONF_SWING_MODE_COMMAND_TOPIC,
CONF_AWAY_MODE_COMMAND_TOPIC,
CONF_HOLD_COMMAND_TOPIC,
CONF_AUX_COMMAND_TOPIC,
CONF_POWER_STATE_TOPIC,
CONF_MODE_STATE_TOPIC,
CONF_TEMPERATURE_STATE_TOPIC,
CONF_FAN_MODE_STATE_TOPIC,
CONF_SWING_MODE_STATE_TOPIC,
CONF_AWAY_MODE_STATE_TOPIC,
CONF_HOLD_STATE_TOPIC,
CONF_AUX_STATE_TOPIC,
CONF_CURRENT_TEMPERATURE_TOPIC
)
},
value_templates,
config.get(CONF_QOS),
config.get(CONF_RETAIN),
config.get(CONF_MODE_LIST),
config.get(CONF_FAN_MODE_LIST),
config.get(CONF_SWING_MODE_LIST),
config.get(CONF_INITIAL),
False, None, SPEED_LOW,
STATE_OFF, STATE_OFF, False,
config.get(CONF_SEND_IF_OFF),
config.get(CONF_PAYLOAD_ON),
config.get(CONF_PAYLOAD_OFF),
config.get(CONF_AVAILABILITY_TOPIC),
config.get(CONF_PAYLOAD_AVAILABLE),
config.get(CONF_PAYLOAD_NOT_AVAILABLE),
config.get(CONF_MIN_TEMP),
config.get(CONF_MAX_TEMP),
config.get(CONF_TEMP_STEP),
config,
discovery_hash,
)])
@@ -223,54 +177,103 @@ async def _async_setup_entity(hass, config, async_add_entities,
class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
"""Representation of an MQTT climate device."""
def __init__(self, hass, name, topic, value_templates, qos, retain,
mode_list, fan_mode_list, swing_mode_list,
target_temperature, away, hold, current_fan_mode,
current_swing_mode, current_operation, aux, send_if_off,
payload_on, payload_off, availability_topic,
payload_available, payload_not_available,
min_temp, max_temp, temp_step, discovery_hash):
def __init__(self, hass, config, discovery_hash):
"""Initialize the climate device."""
self._config = config
self._sub_state = None
self.hass = hass
self._topic = None
self._value_templates = None
self._target_temperature = None
self._current_fan_mode = None
self._current_operation = None
self._current_swing_mode = None
self._unit_of_measurement = hass.config.units.temperature_unit
self._away = False
self._hold = None
self._current_temperature = None
self._aux = False
self._setup_from_config(config)
availability_topic = config.get(CONF_AVAILABILITY_TOPIC)
payload_available = config.get(CONF_PAYLOAD_AVAILABLE)
payload_not_available = config.get(CONF_PAYLOAD_NOT_AVAILABLE)
qos = config.get(CONF_QOS)
MqttAvailability.__init__(self, availability_topic, qos,
payload_available, payload_not_available)
MqttDiscoveryUpdate.__init__(self, discovery_hash)
self.hass = hass
self._name = name
self._topic = topic
self._value_templates = value_templates
self._qos = qos
self._retain = retain
MqttDiscoveryUpdate.__init__(self, discovery_hash,
self.discovery_update)
async def async_added_to_hass(self):
"""Handle being added to home assistant."""
await super().async_added_to_hass()
await self._subscribe_topics()
async def discovery_update(self, discovery_payload):
"""Handle updated discovery message."""
config = PLATFORM_SCHEMA(discovery_payload)
self._config = config
self._setup_from_config(config)
await self.availability_discovery_update(config)
await self._subscribe_topics()
self.async_schedule_update_ha_state()
def _setup_from_config(self, config):
"""(Re)Setup the entity."""
self._topic = {
key: config.get(key) for key in (
CONF_POWER_COMMAND_TOPIC,
CONF_MODE_COMMAND_TOPIC,
CONF_TEMPERATURE_COMMAND_TOPIC,
CONF_FAN_MODE_COMMAND_TOPIC,
CONF_SWING_MODE_COMMAND_TOPIC,
CONF_AWAY_MODE_COMMAND_TOPIC,
CONF_HOLD_COMMAND_TOPIC,
CONF_AUX_COMMAND_TOPIC,
CONF_POWER_STATE_TOPIC,
CONF_MODE_STATE_TOPIC,
CONF_TEMPERATURE_STATE_TOPIC,
CONF_FAN_MODE_STATE_TOPIC,
CONF_SWING_MODE_STATE_TOPIC,
CONF_AWAY_MODE_STATE_TOPIC,
CONF_HOLD_STATE_TOPIC,
CONF_AUX_STATE_TOPIC,
CONF_CURRENT_TEMPERATURE_TOPIC
)
}
# set to None in non-optimistic mode
self._target_temperature = self._current_fan_mode = \
self._current_operation = self._current_swing_mode = None
if self._topic[CONF_TEMPERATURE_STATE_TOPIC] is None:
self._target_temperature = target_temperature
self._unit_of_measurement = hass.config.units.temperature_unit
self._away = away
self._hold = hold
self._current_temperature = None
self._target_temperature = config.get(CONF_INITIAL)
if self._topic[CONF_FAN_MODE_STATE_TOPIC] is None:
self._current_fan_mode = current_fan_mode
if self._topic[CONF_MODE_STATE_TOPIC] is None:
self._current_operation = current_operation
self._aux = aux
self._current_fan_mode = SPEED_LOW
if self._topic[CONF_SWING_MODE_STATE_TOPIC] is None:
self._current_swing_mode = current_swing_mode
self._fan_list = fan_mode_list
self._operation_list = mode_list
self._swing_list = swing_mode_list
self._target_temperature_step = temp_step
self._send_if_off = send_if_off
self._payload_on = payload_on
self._payload_off = payload_off
self._min_temp = min_temp
self._max_temp = max_temp
self._discovery_hash = discovery_hash
self._current_swing_mode = STATE_OFF
if self._topic[CONF_MODE_STATE_TOPIC] is None:
self._current_operation = STATE_OFF
self._away = False
self._hold = None
self._aux = False
async def async_added_to_hass(self):
"""Handle being added to home assistant."""
await MqttAvailability.async_added_to_hass(self)
await MqttDiscoveryUpdate.async_added_to_hass(self)
value_templates = {}
if CONF_VALUE_TEMPLATE in config:
value_template = config.get(CONF_VALUE_TEMPLATE)
value_template.hass = self.hass
value_templates = {key: value_template for key in TEMPLATE_KEYS}
for key in TEMPLATE_KEYS & config.keys():
value_templates[key] = config.get(key)
value_templates[key].hass = self.hass
self._value_templates = value_templates
async def _subscribe_topics(self):
"""(Re)Subscribe to topics."""
topics = {}
qos = self._config.get(CONF_QOS)
@callback
def handle_current_temp_received(topic, payload, qos):
@@ -287,9 +290,10 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
_LOGGER.error("Could not parse temperature from %s", payload)
if self._topic[CONF_CURRENT_TEMPERATURE_TOPIC] is not None:
await mqtt.async_subscribe(
self.hass, self._topic[CONF_CURRENT_TEMPERATURE_TOPIC],
handle_current_temp_received, self._qos)
topics[CONF_CURRENT_TEMPERATURE_TOPIC] = {
'topic': self._topic[CONF_CURRENT_TEMPERATURE_TOPIC],
'msg_callback': handle_current_temp_received,
'qos': qos}
@callback
def handle_mode_received(topic, payload, qos):
@@ -298,16 +302,17 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
payload = self._value_templates[CONF_MODE_STATE_TEMPLATE].\
async_render_with_possible_json_value(payload)
if payload not in self._operation_list:
if payload not in self._config.get(CONF_MODE_LIST):
_LOGGER.error("Invalid mode: %s", payload)
else:
self._current_operation = payload
self.async_schedule_update_ha_state()
if self._topic[CONF_MODE_STATE_TOPIC] is not None:
await mqtt.async_subscribe(
self.hass, self._topic[CONF_MODE_STATE_TOPIC],
handle_mode_received, self._qos)
topics[CONF_MODE_STATE_TOPIC] = {
'topic': self._topic[CONF_MODE_STATE_TOPIC],
'msg_callback': handle_mode_received,
'qos': qos}
@callback
def handle_temperature_received(topic, payload, qos):
@@ -324,9 +329,10 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
_LOGGER.error("Could not parse temperature from %s", payload)
if self._topic[CONF_TEMPERATURE_STATE_TOPIC] is not None:
await mqtt.async_subscribe(
self.hass, self._topic[CONF_TEMPERATURE_STATE_TOPIC],
handle_temperature_received, self._qos)
topics[CONF_TEMPERATURE_STATE_TOPIC] = {
'topic': self._topic[CONF_TEMPERATURE_STATE_TOPIC],
'msg_callback': handle_temperature_received,
'qos': qos}
@callback
def handle_fan_mode_received(topic, payload, qos):
@@ -336,16 +342,17 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
self._value_templates[CONF_FAN_MODE_STATE_TEMPLATE].\
async_render_with_possible_json_value(payload)
if payload not in self._fan_list:
if payload not in self._config.get(CONF_FAN_MODE_LIST):
_LOGGER.error("Invalid fan mode: %s", payload)
else:
self._current_fan_mode = payload
self.async_schedule_update_ha_state()
if self._topic[CONF_FAN_MODE_STATE_TOPIC] is not None:
await mqtt.async_subscribe(
self.hass, self._topic[CONF_FAN_MODE_STATE_TOPIC],
handle_fan_mode_received, self._qos)
topics[CONF_FAN_MODE_STATE_TOPIC] = {
'topic': self._topic[CONF_FAN_MODE_STATE_TOPIC],
'msg_callback': handle_fan_mode_received,
'qos': qos}
@callback
def handle_swing_mode_received(topic, payload, qos):
@@ -355,32 +362,35 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
self._value_templates[CONF_SWING_MODE_STATE_TEMPLATE].\
async_render_with_possible_json_value(payload)
if payload not in self._swing_list:
if payload not in self._config.get(CONF_SWING_MODE_LIST):
_LOGGER.error("Invalid swing mode: %s", payload)
else:
self._current_swing_mode = payload
self.async_schedule_update_ha_state()
if self._topic[CONF_SWING_MODE_STATE_TOPIC] is not None:
await mqtt.async_subscribe(
self.hass, self._topic[CONF_SWING_MODE_STATE_TOPIC],
handle_swing_mode_received, self._qos)
topics[CONF_SWING_MODE_STATE_TOPIC] = {
'topic': self._topic[CONF_SWING_MODE_STATE_TOPIC],
'msg_callback': handle_swing_mode_received,
'qos': qos}
@callback
def handle_away_mode_received(topic, payload, qos):
"""Handle receiving away mode via MQTT."""
payload_on = self._config.get(CONF_PAYLOAD_ON)
payload_off = self._config.get(CONF_PAYLOAD_OFF)
if CONF_AWAY_MODE_STATE_TEMPLATE in self._value_templates:
payload = \
self._value_templates[CONF_AWAY_MODE_STATE_TEMPLATE].\
async_render_with_possible_json_value(payload)
if payload == "True":
payload = self._payload_on
payload = payload_on
elif payload == "False":
payload = self._payload_off
payload = payload_off
if payload == self._payload_on:
if payload == payload_on:
self._away = True
elif payload == self._payload_off:
elif payload == payload_off:
self._away = False
else:
_LOGGER.error("Invalid away mode: %s", payload)
@@ -388,24 +398,27 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
self.async_schedule_update_ha_state()
if self._topic[CONF_AWAY_MODE_STATE_TOPIC] is not None:
await mqtt.async_subscribe(
self.hass, self._topic[CONF_AWAY_MODE_STATE_TOPIC],
handle_away_mode_received, self._qos)
topics[CONF_AWAY_MODE_STATE_TOPIC] = {
'topic': self._topic[CONF_AWAY_MODE_STATE_TOPIC],
'msg_callback': handle_away_mode_received,
'qos': qos}
@callback
def handle_aux_mode_received(topic, payload, qos):
"""Handle receiving aux mode via MQTT."""
payload_on = self._config.get(CONF_PAYLOAD_ON)
payload_off = self._config.get(CONF_PAYLOAD_OFF)
if CONF_AUX_STATE_TEMPLATE in self._value_templates:
payload = self._value_templates[CONF_AUX_STATE_TEMPLATE].\
async_render_with_possible_json_value(payload)
if payload == "True":
payload = self._payload_on
payload = payload_on
elif payload == "False":
payload = self._payload_off
payload = payload_off
if payload == self._payload_on:
if payload == payload_on:
self._aux = True
elif payload == self._payload_off:
elif payload == payload_off:
self._aux = False
else:
_LOGGER.error("Invalid aux mode: %s", payload)
@@ -413,9 +426,10 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
self.async_schedule_update_ha_state()
if self._topic[CONF_AUX_STATE_TOPIC] is not None:
await mqtt.async_subscribe(
self.hass, self._topic[CONF_AUX_STATE_TOPIC],
handle_aux_mode_received, self._qos)
topics[CONF_AUX_STATE_TOPIC] = {
'topic': self._topic[CONF_AUX_STATE_TOPIC],
'msg_callback': handle_aux_mode_received,
'qos': qos}
@callback
def handle_hold_mode_received(topic, payload, qos):
@@ -428,9 +442,19 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
self.async_schedule_update_ha_state()
if self._topic[CONF_HOLD_STATE_TOPIC] is not None:
await mqtt.async_subscribe(
self.hass, self._topic[CONF_HOLD_STATE_TOPIC],
handle_hold_mode_received, self._qos)
topics[CONF_HOLD_STATE_TOPIC] = {
'topic': self._topic[CONF_HOLD_STATE_TOPIC],
'msg_callback': handle_hold_mode_received,
'qos': qos}
self._sub_state = await subscription.async_subscribe_topics(
self.hass, self._sub_state,
topics)
async def async_will_remove_from_hass(self):
"""Unsubscribe when removed."""
await subscription.async_unsubscribe_topics(self.hass, self._sub_state)
await MqttAvailability.async_will_remove_from_hass(self)
@property
def should_poll(self):
@@ -440,7 +464,7 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
@property
def name(self):
"""Return the name of the climate device."""
return self._name
return self._config.get(CONF_NAME)
@property
def temperature_unit(self):
@@ -465,12 +489,12 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
@property
def operation_list(self):
"""Return the list of available operation modes."""
return self._operation_list
return self._config.get(CONF_MODE_LIST)
@property
def target_temperature_step(self):
"""Return the supported step of target temperature."""
return self._target_temperature_step
return self._config.get(CONF_TEMP_STEP)
@property
def is_away_mode_on(self):
@@ -495,7 +519,7 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
@property
def fan_list(self):
"""Return the list of available fan modes."""
return self._fan_list
return self._config.get(CONF_FAN_MODE_LIST)
async def async_set_temperature(self, **kwargs):
"""Set new target temperatures."""
@@ -508,19 +532,23 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
# optimistic mode
self._target_temperature = kwargs.get(ATTR_TEMPERATURE)
if self._send_if_off or self._current_operation != STATE_OFF:
if (self._config.get(CONF_SEND_IF_OFF) or
self._current_operation != STATE_OFF):
mqtt.async_publish(
self.hass, self._topic[CONF_TEMPERATURE_COMMAND_TOPIC],
kwargs.get(ATTR_TEMPERATURE), self._qos, self._retain)
kwargs.get(ATTR_TEMPERATURE), self._config.get(CONF_QOS),
self._config.get(CONF_RETAIN))
self.async_schedule_update_ha_state()
async def async_set_swing_mode(self, swing_mode):
"""Set new swing mode."""
if self._send_if_off or self._current_operation != STATE_OFF:
if (self._config.get(CONF_SEND_IF_OFF) or
self._current_operation != STATE_OFF):
mqtt.async_publish(
self.hass, self._topic[CONF_SWING_MODE_COMMAND_TOPIC],
swing_mode, self._qos, self._retain)
swing_mode, self._config.get(CONF_QOS),
self._config.get(CONF_RETAIN))
if self._topic[CONF_SWING_MODE_STATE_TOPIC] is None:
self._current_swing_mode = swing_mode
@@ -528,10 +556,12 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
async def async_set_fan_mode(self, fan_mode):
"""Set new target temperature."""
if self._send_if_off or self._current_operation != STATE_OFF:
if (self._config.get(CONF_SEND_IF_OFF) or
self._current_operation != STATE_OFF):
mqtt.async_publish(
self.hass, self._topic[CONF_FAN_MODE_COMMAND_TOPIC],
fan_mode, self._qos, self._retain)
fan_mode, self._config.get(CONF_QOS),
self._config.get(CONF_RETAIN))
if self._topic[CONF_FAN_MODE_STATE_TOPIC] is None:
self._current_fan_mode = fan_mode
@@ -539,22 +569,24 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
async def async_set_operation_mode(self, operation_mode) -> None:
"""Set new operation mode."""
qos = self._config.get(CONF_QOS)
retain = self._config.get(CONF_RETAIN)
if self._topic[CONF_POWER_COMMAND_TOPIC] is not None:
if (self._current_operation == STATE_OFF and
operation_mode != STATE_OFF):
mqtt.async_publish(
self.hass, self._topic[CONF_POWER_COMMAND_TOPIC],
self._payload_on, self._qos, self._retain)
self._config.get(CONF_PAYLOAD_ON), qos, retain)
elif (self._current_operation != STATE_OFF and
operation_mode == STATE_OFF):
mqtt.async_publish(
self.hass, self._topic[CONF_POWER_COMMAND_TOPIC],
self._payload_off, self._qos, self._retain)
self._config.get(CONF_PAYLOAD_OFF), qos, retain)
if self._topic[CONF_MODE_COMMAND_TOPIC] is not None:
mqtt.async_publish(
self.hass, self._topic[CONF_MODE_COMMAND_TOPIC],
operation_mode, self._qos, self._retain)
operation_mode, qos, retain)
if self._topic[CONF_MODE_STATE_TOPIC] is None:
self._current_operation = operation_mode
@@ -568,14 +600,16 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
@property
def swing_list(self):
"""List of available swing modes."""
return self._swing_list
return self._config.get(CONF_SWING_MODE_LIST)
async def async_turn_away_mode_on(self):
"""Turn away mode on."""
if self._topic[CONF_AWAY_MODE_COMMAND_TOPIC] is not None:
mqtt.async_publish(self.hass,
self._topic[CONF_AWAY_MODE_COMMAND_TOPIC],
self._payload_on, self._qos, self._retain)
self._config.get(CONF_PAYLOAD_ON),
self._config.get(CONF_QOS),
self._config.get(CONF_RETAIN))
if self._topic[CONF_AWAY_MODE_STATE_TOPIC] is None:
self._away = True
@@ -586,7 +620,9 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
if self._topic[CONF_AWAY_MODE_COMMAND_TOPIC] is not None:
mqtt.async_publish(self.hass,
self._topic[CONF_AWAY_MODE_COMMAND_TOPIC],
self._payload_off, self._qos, self._retain)
self._config.get(CONF_PAYLOAD_OFF),
self._config.get(CONF_QOS),
self._config.get(CONF_RETAIN))
if self._topic[CONF_AWAY_MODE_STATE_TOPIC] is None:
self._away = False
@@ -597,7 +633,8 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
if self._topic[CONF_HOLD_COMMAND_TOPIC] is not None:
mqtt.async_publish(self.hass,
self._topic[CONF_HOLD_COMMAND_TOPIC],
hold_mode, self._qos, self._retain)
hold_mode, self._config.get(CONF_QOS),
self._config.get(CONF_RETAIN))
if self._topic[CONF_HOLD_STATE_TOPIC] is None:
self._hold = hold_mode
@@ -607,7 +644,9 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
"""Turn auxiliary heater on."""
if self._topic[CONF_AUX_COMMAND_TOPIC] is not None:
mqtt.async_publish(self.hass, self._topic[CONF_AUX_COMMAND_TOPIC],
self._payload_on, self._qos, self._retain)
self._config.get(CONF_PAYLOAD_ON),
self._config.get(CONF_QOS),
self._config.get(CONF_RETAIN))
if self._topic[CONF_AUX_STATE_TOPIC] is None:
self._aux = True
@@ -617,7 +656,9 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
"""Turn auxiliary heater off."""
if self._topic[CONF_AUX_COMMAND_TOPIC] is not None:
mqtt.async_publish(self.hass, self._topic[CONF_AUX_COMMAND_TOPIC],
self._payload_off, self._qos, self._retain)
self._config.get(CONF_PAYLOAD_OFF),
self._config.get(CONF_QOS),
self._config.get(CONF_RETAIN))
if self._topic[CONF_AUX_STATE_TOPIC] is None:
self._aux = False
@@ -661,9 +702,9 @@ class MqttClimate(MqttAvailability, MqttDiscoveryUpdate, ClimateDevice):
@property
def min_temp(self):
"""Return the minimum temperature."""
return self._min_temp
return self._config.get(CONF_MIN_TEMP)
@property
def max_temp(self):
"""Return the maximum temperature."""
return self._max_temp
return self._config.get(CONF_MAX_TEMP)

View File

@@ -168,18 +168,14 @@ class NestThermostat(ClimateDevice):
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
if self._mode != NEST_MODE_HEAT_COOL and \
self._mode != STATE_ECO and \
not self.is_away_mode_on:
if self._mode not in (NEST_MODE_HEAT_COOL, STATE_ECO):
return self._target_temperature
return None
@property
def target_temperature_low(self):
"""Return the lower bound temperature we try to reach."""
if (self.is_away_mode_on or self._mode == STATE_ECO) and \
self._eco_temperature[0]:
# eco_temperature is always a low, high tuple
if self._mode == STATE_ECO:
return self._eco_temperature[0]
if self._mode == NEST_MODE_HEAT_COOL:
return self._target_temperature[0]
@@ -188,9 +184,7 @@ class NestThermostat(ClimateDevice):
@property
def target_temperature_high(self):
"""Return the upper bound temperature we try to reach."""
if (self.is_away_mode_on or self._mode == STATE_ECO) and \
self._eco_temperature[1]:
# eco_temperature is always a low, high tuple
if self._mode == STATE_ECO:
return self._eco_temperature[1]
if self._mode == NEST_MODE_HEAT_COOL:
return self._target_temperature[1]

View File

@@ -15,6 +15,14 @@ from homeassistant.const import TEMP_CELSIUS
SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE
HA_TOON = {
STATE_AUTO: 'Comfort',
STATE_HEAT: 'Home',
STATE_ECO: 'Away',
STATE_COOL: 'Sleep',
}
TOON_HA = {value: key for key, value in HA_TOON.items()}
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Toon climate device."""
@@ -58,8 +66,7 @@ class ThermostatDevice(ClimateDevice):
@property
def current_operation(self):
"""Return current operation i.e. comfort, home, away."""
state = self.thermos.get_data('state')
return state
return TOON_HA.get(self.thermos.get_data('state'))
@property
def operation_list(self):
@@ -83,14 +90,7 @@ class ThermostatDevice(ClimateDevice):
def set_operation_mode(self, operation_mode):
"""Set new operation mode."""
toonlib_values = {
STATE_AUTO: 'Comfort',
STATE_HEAT: 'Home',
STATE_ECO: 'Away',
STATE_COOL: 'Sleep',
}
self.thermos.set_state(toonlib_values[operation_mode])
self.thermos.set_state(HA_TOON[operation_mode])
def update(self):
"""Update local state."""

View File

@@ -7,18 +7,17 @@ https://home-assistant.io/components/climate.velbus/
import logging
from homeassistant.components.climate import (
SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, ClimateDevice)
STATE_HEAT, SUPPORT_TARGET_TEMPERATURE, ClimateDevice)
from homeassistant.components.velbus import (
DOMAIN as VELBUS_DOMAIN, VelbusEntity)
from homeassistant.const import ATTR_TEMPERATURE
from homeassistant.const import (
TEMP_CELSIUS, TEMP_FAHRENHEIT, ATTR_TEMPERATURE)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['velbus']
OPERATION_LIST = ['comfort', 'day', 'night', 'safe']
SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE)
SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE)
async def async_setup_platform(
@@ -47,7 +46,9 @@ class VelbusClimate(VelbusEntity, ClimateDevice):
@property
def temperature_unit(self):
"""Return the unit this state is expressed in."""
return self._module.get_unit(self._channel)
if self._module.get_unit(self._channel) == '°C':
return TEMP_CELSIUS
return TEMP_FAHRENHEIT
@property
def current_temperature(self):
@@ -56,26 +57,18 @@ class VelbusClimate(VelbusEntity, ClimateDevice):
@property
def current_operation(self):
"""Return current operation ie. heat, cool, idle."""
return self._module.get_climate_mode()
@property
def operation_list(self):
"""Return the list of available operation modes."""
return OPERATION_LIST
"""Return current operation."""
return STATE_HEAT
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._module.get_climate_target()
def set_operation_mode(self, operation_mode):
"""Set new target operation mode."""
self._module.set_mode(operation_mode)
self.schedule_update_ha_state()
def set_temperature(self, **kwargs):
"""Set new target temperatures."""
if kwargs.get(ATTR_TEMPERATURE) is not None:
self._module.set_temp(kwargs.get(ATTR_TEMPERATURE))
self.schedule_update_ha_state()
temp = kwargs.get(ATTR_TEMPERATURE)
if temp is None:
return
self._module.set_temp(temp)
self.schedule_update_ha_state()

View File

@@ -12,24 +12,20 @@ import os
import voluptuous as vol
from homeassistant.const import (
EVENT_HOMEASSISTANT_START, CONF_REGION, CONF_MODE, CONF_NAME)
EVENT_HOMEASSISTANT_START, CLOUD_NEVER_EXPOSED_ENTITIES, CONF_REGION,
CONF_MODE, CONF_NAME)
from homeassistant.helpers import entityfilter, config_validation as cv
from homeassistant.util import dt as dt_util
from homeassistant.components.alexa import smart_home as alexa_sh
from homeassistant.components.google_assistant import helpers as ga_h
from homeassistant.components.google_assistant import const as ga_c
from . import http_api, iot, auth_api
from . import http_api, iot, auth_api, prefs, cloudhooks
from .const import CONFIG_DIR, DOMAIN, SERVERS
REQUIREMENTS = ['warrant==0.6.1']
STORAGE_KEY = DOMAIN
STORAGE_VERSION = 1
STORAGE_ENABLE_ALEXA = 'alexa_enabled'
STORAGE_ENABLE_GOOGLE = 'google_enabled'
_LOGGER = logging.getLogger(__name__)
_UNDEF = object()
CONF_ALEXA = 'alexa'
CONF_ALIASES = 'aliases'
@@ -41,6 +37,7 @@ CONF_RELAYER = 'relayer'
CONF_USER_POOL_ID = 'user_pool_id'
CONF_GOOGLE_ACTIONS_SYNC_URL = 'google_actions_sync_url'
CONF_SUBSCRIPTION_INFO_URL = 'subscription_info_url'
CONF_CLOUDHOOK_CREATE_URL = 'cloudhook_create_url'
DEFAULT_MODE = 'production'
DEPENDENCIES = ['http']
@@ -68,7 +65,7 @@ ALEXA_SCHEMA = ASSISTANT_SCHEMA.extend({
})
GACTIONS_SCHEMA = ASSISTANT_SCHEMA.extend({
vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: GOOGLE_ENTITY_SCHEMA}
vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: GOOGLE_ENTITY_SCHEMA},
})
CONFIG_SCHEMA = vol.Schema({
@@ -82,6 +79,7 @@ CONFIG_SCHEMA = vol.Schema({
vol.Optional(CONF_RELAYER): str,
vol.Optional(CONF_GOOGLE_ACTIONS_SYNC_URL): str,
vol.Optional(CONF_SUBSCRIPTION_INFO_URL): str,
vol.Optional(CONF_CLOUDHOOK_CREATE_URL): str,
vol.Optional(CONF_ALEXA): ALEXA_SCHEMA,
vol.Optional(CONF_GOOGLE_ACTIONS): GACTIONS_SCHEMA,
}),
@@ -117,19 +115,19 @@ class Cloud:
def __init__(self, hass, mode, alexa, google_actions,
cognito_client_id=None, user_pool_id=None, region=None,
relayer=None, google_actions_sync_url=None,
subscription_info_url=None):
subscription_info_url=None, cloudhook_create_url=None):
"""Create an instance of Cloud."""
self.hass = hass
self.mode = mode
self.alexa_config = alexa
self.google_actions_user_conf = google_actions
self._gactions_config = None
self._prefs = None
self.prefs = prefs.CloudPreferences(hass)
self.id_token = None
self.access_token = None
self.refresh_token = None
self.iot = iot.CloudIoT(self)
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
self.cloudhooks = cloudhooks.Cloudhooks(self)
if mode == MODE_DEV:
self.cognito_client_id = cognito_client_id
@@ -138,6 +136,7 @@ class Cloud:
self.relayer = relayer
self.google_actions_sync_url = google_actions_sync_url
self.subscription_info_url = subscription_info_url
self.cloudhook_create_url = cloudhook_create_url
else:
info = SERVERS[mode]
@@ -148,6 +147,7 @@ class Cloud:
self.relayer = info['relayer']
self.google_actions_sync_url = info['google_actions_sync_url']
self.subscription_info_url = info['subscription_info_url']
self.cloudhook_create_url = info['cloudhook_create_url']
@property
def is_logged_in(self):
@@ -184,26 +184,20 @@ class Cloud:
def should_expose(entity):
"""If an entity should be exposed."""
if entity.entity_id in CLOUD_NEVER_EXPOSED_ENTITIES:
return False
return conf['filter'](entity.entity_id)
self._gactions_config = ga_h.Config(
should_expose=should_expose,
allow_unlock=self.prefs.google_allow_unlock,
agent_user_id=self.claims['cognito:username'],
entity_config=conf.get(CONF_ENTITY_CONFIG),
)
return self._gactions_config
@property
def alexa_enabled(self):
"""Return if Alexa is enabled."""
return self._prefs[STORAGE_ENABLE_ALEXA]
@property
def google_enabled(self):
"""Return if Google is enabled."""
return self._prefs[STORAGE_ENABLE_GOOGLE]
def path(self, *parts):
"""Get config path inside cloud dir.
@@ -243,20 +237,6 @@ class Cloud:
async def async_start(self, _):
"""Start the cloud component."""
prefs = await self._store.async_load()
if prefs is None:
prefs = {}
if self.mode not in prefs:
# Default to True if already logged in to make this not a
# breaking change.
enabled = await self.hass.async_add_executor_job(
os.path.isfile, self.user_info_path)
prefs = {
STORAGE_ENABLE_ALEXA: enabled,
STORAGE_ENABLE_GOOGLE: enabled,
}
self._prefs = prefs
def load_config():
"""Load config."""
# Ensure config dir exists
@@ -272,6 +252,7 @@ class Cloud:
return json.loads(file.read())
info = await self.hass.async_add_job(load_config)
await self.prefs.async_initialize()
if info is None:
return
@@ -282,15 +263,6 @@ class Cloud:
self.hass.add_job(self.iot.connect())
async def update_preferences(self, *, google_enabled=_UNDEF,
alexa_enabled=_UNDEF):
"""Update user preferences."""
if google_enabled is not _UNDEF:
self._prefs[STORAGE_ENABLE_GOOGLE] = google_enabled
if alexa_enabled is not _UNDEF:
self._prefs[STORAGE_ENABLE_ALEXA] = alexa_enabled
await self._store.async_save(self._prefs)
def _decode_claims(self, token): # pylint: disable=no-self-use
"""Decode the claims in a token."""
from jose import jwt

View File

@@ -0,0 +1,42 @@
"""Cloud APIs."""
from functools import wraps
import logging
from . import auth_api
_LOGGER = logging.getLogger(__name__)
def _check_token(func):
"""Decorate a function to verify valid token."""
@wraps(func)
async def check_token(cloud, *args):
"""Validate token, then call func."""
await cloud.hass.async_add_executor_job(auth_api.check_token, cloud)
return await func(cloud, *args)
return check_token
def _log_response(func):
"""Decorate a function to log bad responses."""
@wraps(func)
async def log_response(*args):
"""Log response if it's bad."""
resp = await func(*args)
meth = _LOGGER.debug if resp.status < 400 else _LOGGER.warning
meth('Fetched %s (%s)', resp.url, resp.status)
return resp
return log_response
@_check_token
@_log_response
async def async_create_cloudhook(cloud):
"""Create a cloudhook."""
websession = cloud.hass.helpers.aiohttp_client.async_get_clientsession()
return await websession.post(
cloud.cloudhook_create_url, headers={
'authorization': cloud.id_token
})

View File

@@ -0,0 +1,66 @@
"""Manage cloud cloudhooks."""
import async_timeout
from . import cloud_api
class Cloudhooks:
"""Class to help manage cloudhooks."""
def __init__(self, cloud):
"""Initialize cloudhooks."""
self.cloud = cloud
self.cloud.iot.register_on_connect(self.async_publish_cloudhooks)
async def async_publish_cloudhooks(self):
"""Inform the Relayer of the cloudhooks that we support."""
cloudhooks = self.cloud.prefs.cloudhooks
await self.cloud.iot.async_send_message('webhook-register', {
'cloudhook_ids': [info['cloudhook_id'] for info
in cloudhooks.values()]
}, expect_answer=False)
async def async_create(self, webhook_id):
"""Create a cloud webhook."""
cloudhooks = self.cloud.prefs.cloudhooks
if webhook_id in cloudhooks:
raise ValueError('Hook is already enabled for the cloud.')
if not self.cloud.iot.connected:
raise ValueError("Cloud is not connected")
# Create cloud hook
with async_timeout.timeout(10):
resp = await cloud_api.async_create_cloudhook(self.cloud)
data = await resp.json()
cloudhook_id = data['cloudhook_id']
cloudhook_url = data['url']
# Store hook
cloudhooks = dict(cloudhooks)
hook = cloudhooks[webhook_id] = {
'webhook_id': webhook_id,
'cloudhook_id': cloudhook_id,
'cloudhook_url': cloudhook_url
}
await self.cloud.prefs.async_update(cloudhooks=cloudhooks)
await self.async_publish_cloudhooks()
return hook
async def async_delete(self, webhook_id):
"""Delete a cloud webhook."""
cloudhooks = self.cloud.prefs.cloudhooks
if webhook_id not in cloudhooks:
raise ValueError('Hook is not enabled for the cloud.')
# Remove hook
cloudhooks = dict(cloudhooks)
cloudhooks.pop(webhook_id)
await self.cloud.prefs.async_update(cloudhooks=cloudhooks)
await self.async_publish_cloudhooks()

View File

@@ -3,6 +3,11 @@ DOMAIN = 'cloud'
CONFIG_DIR = '.cloud'
REQUEST_TIMEOUT = 10
PREF_ENABLE_ALEXA = 'alexa_enabled'
PREF_ENABLE_GOOGLE = 'google_enabled'
PREF_GOOGLE_ALLOW_UNLOCK = 'google_allow_unlock'
PREF_CLOUDHOOKS = 'cloudhooks'
SERVERS = {
'production': {
'cognito_client_id': '60i2uvhvbiref2mftj7rgcrt9u',
@@ -12,7 +17,8 @@ SERVERS = {
'google_actions_sync_url': ('https://24ab3v80xd.execute-api.us-east-1.'
'amazonaws.com/prod/smart_home_sync'),
'subscription_info_url': ('https://stripe-api.nabucasa.com/payments/'
'subscription_info')
'subscription_info'),
'cloudhook_create_url': 'https://webhooks-api.nabucasa.com/generate'
}
}

View File

@@ -3,6 +3,7 @@ import asyncio
from functools import wraps
import logging
import aiohttp
import async_timeout
import voluptuous as vol
@@ -15,7 +16,9 @@ from homeassistant.components.alexa import smart_home as alexa_sh
from homeassistant.components.google_assistant import smart_home as google_sh
from . import auth_api
from .const import DOMAIN, REQUEST_TIMEOUT
from .const import (
DOMAIN, REQUEST_TIMEOUT, PREF_ENABLE_ALEXA, PREF_ENABLE_GOOGLE,
PREF_GOOGLE_ALLOW_UNLOCK)
from .iot import STATE_DISCONNECTED, STATE_CONNECTED
_LOGGER = logging.getLogger(__name__)
@@ -30,8 +33,9 @@ SCHEMA_WS_STATUS = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
WS_TYPE_UPDATE_PREFS = 'cloud/update_prefs'
SCHEMA_WS_UPDATE_PREFS = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
vol.Required('type'): WS_TYPE_UPDATE_PREFS,
vol.Optional('google_enabled'): bool,
vol.Optional('alexa_enabled'): bool,
vol.Optional(PREF_ENABLE_GOOGLE): bool,
vol.Optional(PREF_ENABLE_ALEXA): bool,
vol.Optional(PREF_GOOGLE_ALLOW_UNLOCK): bool,
})
@@ -41,6 +45,20 @@ SCHEMA_WS_SUBSCRIPTION = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
})
WS_TYPE_HOOK_CREATE = 'cloud/cloudhook/create'
SCHEMA_WS_HOOK_CREATE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
vol.Required('type'): WS_TYPE_HOOK_CREATE,
vol.Required('webhook_id'): str
})
WS_TYPE_HOOK_DELETE = 'cloud/cloudhook/delete'
SCHEMA_WS_HOOK_DELETE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
vol.Required('type'): WS_TYPE_HOOK_DELETE,
vol.Required('webhook_id'): str
})
async def async_setup(hass):
"""Initialize the HTTP API."""
hass.components.websocket_api.async_register_command(
@@ -55,6 +73,14 @@ async def async_setup(hass):
WS_TYPE_UPDATE_PREFS, websocket_update_prefs,
SCHEMA_WS_UPDATE_PREFS
)
hass.components.websocket_api.async_register_command(
WS_TYPE_HOOK_CREATE, websocket_hook_create,
SCHEMA_WS_HOOK_CREATE
)
hass.components.websocket_api.async_register_command(
WS_TYPE_HOOK_DELETE, websocket_hook_delete,
SCHEMA_WS_HOOK_DELETE
)
hass.http.register_view(GoogleActionsSyncView)
hass.http.register_view(CloudLoginView)
hass.http.register_view(CloudLogoutView)
@@ -73,7 +99,7 @@ _CLOUD_ERRORS = {
def _handle_cloud_errors(handler):
"""Handle auth errors."""
"""Webview decorator to handle auth errors."""
@wraps(handler)
async def error_handler(view, request, *args, **kwargs):
"""Handle exceptions that raise from the wrapped request handler."""
@@ -237,17 +263,49 @@ def websocket_cloud_status(hass, connection, msg):
websocket_api.result_message(msg['id'], _account_data(cloud)))
def _require_cloud_login(handler):
"""Websocket decorator that requires cloud to be logged in."""
@wraps(handler)
def with_cloud_auth(hass, connection, msg):
"""Require to be logged into the cloud."""
cloud = hass.data[DOMAIN]
if not cloud.is_logged_in:
connection.send_message(websocket_api.error_message(
msg['id'], 'not_logged_in',
'You need to be logged in to the cloud.'))
return
handler(hass, connection, msg)
return with_cloud_auth
def _handle_aiohttp_errors(handler):
"""Websocket decorator that handlers aiohttp errors.
Can only wrap async handlers.
"""
@wraps(handler)
async def with_error_handling(hass, connection, msg):
"""Handle aiohttp errors."""
try:
await handler(hass, connection, msg)
except asyncio.TimeoutError:
connection.send_message(websocket_api.error_message(
msg['id'], 'timeout', 'Command timed out.'))
except aiohttp.ClientError:
connection.send_message(websocket_api.error_message(
msg['id'], 'unknown', 'Error making request.'))
return with_error_handling
@_require_cloud_login
@websocket_api.async_response
async def websocket_subscription(hass, connection, msg):
"""Handle request for account info."""
cloud = hass.data[DOMAIN]
if not cloud.is_logged_in:
connection.send_message(websocket_api.error_message(
msg['id'], 'not_logged_in',
'You need to be logged in to the cloud.'))
return
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop):
response = await cloud.fetch_subscription_info()
@@ -274,24 +332,37 @@ async def websocket_subscription(hass, connection, msg):
connection.send_message(websocket_api.result_message(msg['id'], data))
@_require_cloud_login
@websocket_api.async_response
async def websocket_update_prefs(hass, connection, msg):
"""Handle request for account info."""
cloud = hass.data[DOMAIN]
if not cloud.is_logged_in:
connection.send_message(websocket_api.error_message(
msg['id'], 'not_logged_in',
'You need to be logged in to the cloud.'))
return
changes = dict(msg)
changes.pop('id')
changes.pop('type')
await cloud.update_preferences(**changes)
await cloud.prefs.async_update(**changes)
connection.send_message(websocket_api.result_message(
msg['id'], {'success': True}))
connection.send_message(websocket_api.result_message(msg['id']))
@_require_cloud_login
@websocket_api.async_response
@_handle_aiohttp_errors
async def websocket_hook_create(hass, connection, msg):
"""Handle request for account info."""
cloud = hass.data[DOMAIN]
hook = await cloud.cloudhooks.async_create(msg['webhook_id'])
connection.send_message(websocket_api.result_message(msg['id'], hook))
@_require_cloud_login
@websocket_api.async_response
async def websocket_hook_delete(hass, connection, msg):
"""Handle request for account info."""
cloud = hass.data[DOMAIN]
await cloud.cloudhooks.async_delete(msg['webhook_id'])
connection.send_message(websocket_api.result_message(msg['id']))
def _account_data(cloud):
@@ -308,10 +379,9 @@ def _account_data(cloud):
'logged_in': True,
'email': claims['email'],
'cloud': cloud.iot.state,
'google_enabled': cloud.google_enabled,
'prefs': cloud.prefs.as_dict(),
'google_entities': cloud.google_actions_user_conf['filter'].config,
'google_domains': list(google_sh.DOMAIN_TO_GOOGLE_TYPES),
'alexa_enabled': cloud.alexa_enabled,
'alexa_entities': cloud.alexa_config.should_expose.config,
'alexa_domains': list(alexa_sh.ENTITY_ADAPTERS),
}

View File

@@ -2,13 +2,16 @@
import asyncio
import logging
import pprint
import uuid
from aiohttp import hdrs, client_exceptions, WSMsgType
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.components.alexa import smart_home as alexa
from homeassistant.components.google_assistant import smart_home as ga
from homeassistant.core import callback
from homeassistant.util.decorator import Registry
from homeassistant.util.aiohttp import MockRequest, serialize_response
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from . import auth_api
from .const import MESSAGE_EXPIRATION, MESSAGE_AUTH_FAIL
@@ -25,6 +28,19 @@ class UnknownHandler(Exception):
"""Exception raised when trying to handle unknown handler."""
class NotConnected(Exception):
"""Exception raised when trying to handle unknown handler."""
class ErrorMessage(Exception):
"""Exception raised when there was error handling message in the cloud."""
def __init__(self, error):
"""Initialize Error Message."""
super().__init__(self, "Error in Cloud")
self.error = error
class CloudIoT:
"""Class to manage the IoT connection."""
@@ -41,6 +57,19 @@ class CloudIoT:
self.tries = 0
# Current state of the connection
self.state = STATE_DISCONNECTED
# Local code waiting for a response
self._response_handler = {}
self._on_connect = []
@callback
def register_on_connect(self, on_connect_cb):
"""Register an async on_connect callback."""
self._on_connect.append(on_connect_cb)
@property
def connected(self):
"""Return if we're currently connected."""
return self.state == STATE_CONNECTED
@asyncio.coroutine
def connect(self):
@@ -91,6 +120,30 @@ class CloudIoT:
if remove_hass_stop_listener is not None:
remove_hass_stop_listener()
async def async_send_message(self, handler, payload,
expect_answer=True):
"""Send a message."""
if self.state != STATE_CONNECTED:
raise NotConnected
msgid = uuid.uuid4().hex
if expect_answer:
fut = self._response_handler[msgid] = asyncio.Future()
message = {
'msgid': msgid,
'handler': handler,
'payload': payload,
}
if _LOGGER.isEnabledFor(logging.DEBUG):
_LOGGER.debug("Publishing message:\n%s\n",
pprint.pformat(message))
await self.client.send_json(message)
if expect_answer:
return await fut
@asyncio.coroutine
def _handle_connection(self):
"""Connect to the IoT broker."""
@@ -134,6 +187,9 @@ class CloudIoT:
_LOGGER.info("Connected")
self.state = STATE_CONNECTED
if self._on_connect:
yield from asyncio.wait([cb() for cb in self._on_connect])
while not client.closed:
msg = yield from client.receive()
@@ -159,6 +215,17 @@ class CloudIoT:
_LOGGER.debug("Received message:\n%s\n",
pprint.pformat(msg))
response_handler = self._response_handler.pop(msg['msgid'],
None)
if response_handler is not None:
if 'payload' in msg:
response_handler.set_result(msg["payload"])
else:
response_handler.set_exception(
ErrorMessage(msg['error']))
continue
response = {
'msgid': msg['msgid'],
}
@@ -229,7 +296,7 @@ def async_handle_alexa(hass, cloud, payload):
"""Handle an incoming IoT message for Alexa."""
result = yield from alexa.async_handle_message(
hass, cloud.alexa_config, payload,
enabled=cloud.alexa_enabled)
enabled=cloud.prefs.alexa_enabled)
return result
@@ -237,7 +304,7 @@ def async_handle_alexa(hass, cloud, payload):
@asyncio.coroutine
def async_handle_google_actions(hass, cloud, payload):
"""Handle an incoming IoT message for Google Actions."""
if not cloud.google_enabled:
if not cloud.prefs.google_enabled:
return ga.turned_off_response(payload)
result = yield from ga.async_handle_message(
@@ -257,3 +324,43 @@ def async_handle_cloud(hass, cloud, payload):
payload['reason'])
else:
_LOGGER.warning("Received unknown cloud action: %s", action)
@HANDLERS.register('webhook')
async def async_handle_webhook(hass, cloud, payload):
"""Handle an incoming IoT message for cloud webhooks."""
cloudhook_id = payload['cloudhook_id']
found = None
for cloudhook in cloud.prefs.cloudhooks.values():
if cloudhook['cloudhook_id'] == cloudhook_id:
found = cloudhook
break
if found is None:
return {
'status': 200
}
request = MockRequest(
content=payload['body'].encode('utf-8'),
headers=payload['headers'],
method=payload['method'],
query_string=payload['query'],
)
response = await hass.components.webhook.async_handle_webhook(
found['webhook_id'], request)
response_dict = serialize_response(response)
body = response_dict.get('body')
if body:
body = body.decode('utf-8')
return {
'body': body,
'status': response_dict['status'],
'headers': {
'Content-Type': response.content_type
}
}

View File

@@ -0,0 +1,70 @@
"""Preference management for cloud."""
from .const import (
DOMAIN, PREF_ENABLE_ALEXA, PREF_ENABLE_GOOGLE,
PREF_GOOGLE_ALLOW_UNLOCK, PREF_CLOUDHOOKS)
STORAGE_KEY = DOMAIN
STORAGE_VERSION = 1
_UNDEF = object()
class CloudPreferences:
"""Handle cloud preferences."""
def __init__(self, hass):
"""Initialize cloud prefs."""
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
self._prefs = None
async def async_initialize(self):
"""Finish initializing the preferences."""
prefs = await self._store.async_load()
if prefs is None:
prefs = {
PREF_ENABLE_ALEXA: True,
PREF_ENABLE_GOOGLE: True,
PREF_GOOGLE_ALLOW_UNLOCK: False,
PREF_CLOUDHOOKS: {}
}
self._prefs = prefs
async def async_update(self, *, google_enabled=_UNDEF,
alexa_enabled=_UNDEF, google_allow_unlock=_UNDEF,
cloudhooks=_UNDEF):
"""Update user preferences."""
for key, value in (
(PREF_ENABLE_GOOGLE, google_enabled),
(PREF_ENABLE_ALEXA, alexa_enabled),
(PREF_GOOGLE_ALLOW_UNLOCK, google_allow_unlock),
(PREF_CLOUDHOOKS, cloudhooks),
):
if value is not _UNDEF:
self._prefs[key] = value
await self._store.async_save(self._prefs)
def as_dict(self):
"""Return dictionary version."""
return self._prefs
@property
def alexa_enabled(self):
"""Return if Alexa is enabled."""
return self._prefs[PREF_ENABLE_ALEXA]
@property
def google_enabled(self):
"""Return if Google is enabled."""
return self._prefs[PREF_ENABLE_GOOGLE]
@property
def google_allow_unlock(self):
"""Return if Google is allowed to unlock locks."""
return self._prefs.get(PREF_GOOGLE_ALLOW_UNLOCK, False)
@property
def cloudhooks(self):
"""Return the published cloud webhooks."""
return self._prefs.get(PREF_CLOUDHOOKS, {})

View File

@@ -21,6 +21,7 @@ _LOGGER = logging.getLogger(__name__)
DOMAIN = 'coinbase'
CONF_API_SECRET = 'api_secret'
CONF_ACCOUNT_CURRENCIES = 'account_balance_currencies'
CONF_EXCHANGE_CURRENCIES = 'exchange_rate_currencies'
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
@@ -31,6 +32,8 @@ CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_API_SECRET): cv.string,
vol.Optional(CONF_ACCOUNT_CURRENCIES):
vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_EXCHANGE_CURRENCIES, default=[]):
vol.All(cv.ensure_list, [cv.string])
})
@@ -45,6 +48,7 @@ def setup(hass, config):
"""
api_key = config[DOMAIN].get(CONF_API_KEY)
api_secret = config[DOMAIN].get(CONF_API_SECRET)
account_currencies = config[DOMAIN].get(CONF_ACCOUNT_CURRENCIES)
exchange_currencies = config[DOMAIN].get(CONF_EXCHANGE_CURRENCIES)
hass.data[DATA_COINBASE] = coinbase_data = CoinbaseData(
@@ -53,7 +57,13 @@ def setup(hass, config):
if not hasattr(coinbase_data, 'accounts'):
return False
for account in coinbase_data.accounts.data:
load_platform(hass, 'sensor', DOMAIN, {'account': account}, config)
if (account_currencies is None or
account.currency in account_currencies):
load_platform(hass,
'sensor',
DOMAIN,
{'account': account},
config)
for currency in exchange_currencies:
if currency not in coinbase_data.exchange_rates.rates:
_LOGGER.warning("Currency %s not found", currency)

View File

@@ -14,6 +14,8 @@ from homeassistant.util.yaml import load_yaml, dump
DOMAIN = 'config'
DEPENDENCIES = ['http']
SECTIONS = (
'auth',
'auth_provider_homeassistant',
'automation',
'config_entries',
'core',
@@ -58,10 +60,6 @@ async def async_setup(hass, config):
tasks = [setup_panel(panel_name) for panel_name in SECTIONS]
if hass.auth.active:
tasks.append(setup_panel('auth'))
tasks.append(setup_panel('auth_provider_homeassistant'))
for panel_name in ON_DEMAND:
if panel_name in hass.config.components:
tasks.append(setup_panel(panel_name))

View File

@@ -10,9 +10,8 @@ import voluptuous as vol
from homeassistant.const import ATTR_ENTITY_ID, CONF_ICON, CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.restore_state import async_get_last_state
from homeassistant.helpers.restore_state import RestoreEntity
_LOGGER = logging.getLogger(__name__)
@@ -86,7 +85,7 @@ async def async_setup(hass, config):
return True
class Counter(Entity):
class Counter(RestoreEntity):
"""Representation of a counter."""
def __init__(self, object_id, name, initial, restore, step, icon):
@@ -128,10 +127,11 @@ class Counter(Entity):
async def async_added_to_hass(self):
"""Call when entity about to be added to Home Assistant."""
await super().async_added_to_hass()
# __init__ will set self._state to self._initial, only override
# if needed.
if self._restore:
state = await async_get_last_state(self.hass, self.entity_id)
state = await self.async_get_last_state()
if state is not None:
self._state = int(state.state)

View File

@@ -5,7 +5,8 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/cover.deconz/
"""
from homeassistant.components.deconz.const import (
COVER_TYPES, DAMPERS, DOMAIN as DATA_DECONZ, DECONZ_DOMAIN, WINDOW_COVERS)
COVER_TYPES, DAMPERS, DECONZ_REACHABLE, DOMAIN as DECONZ_DOMAIN,
WINDOW_COVERS)
from homeassistant.components.cover import (
ATTR_POSITION, CoverDevice, SUPPORT_CLOSE, SUPPORT_OPEN, SUPPORT_STOP,
SUPPORT_SET_POSITION)
@@ -29,6 +30,8 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
Covers are based on same device class as lights in deCONZ.
"""
gateway = hass.data[DECONZ_DOMAIN]
@callback
def async_add_cover(lights):
"""Add cover from deCONZ."""
@@ -36,23 +39,26 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
for light in lights:
if light.type in COVER_TYPES:
if light.modelid in ZIGBEE_SPEC:
entities.append(DeconzCoverZigbeeSpec(light))
entities.append(DeconzCoverZigbeeSpec(light, gateway))
else:
entities.append(DeconzCover(light))
entities.append(DeconzCover(light, gateway))
async_add_entities(entities, True)
hass.data[DATA_DECONZ].listeners.append(
gateway.listeners.append(
async_dispatcher_connect(hass, 'deconz_new_light', async_add_cover))
async_add_cover(hass.data[DATA_DECONZ].api.lights.values())
async_add_cover(gateway.api.lights.values())
class DeconzCover(CoverDevice):
"""Representation of a deCONZ cover."""
def __init__(self, cover):
def __init__(self, cover, gateway):
"""Set up cover and add update callback to get data from websocket."""
self._cover = cover
self.gateway = gateway
self.unsub_dispatcher = None
self._features = SUPPORT_OPEN
self._features |= SUPPORT_CLOSE
self._features |= SUPPORT_STOP
@@ -61,11 +67,14 @@ class DeconzCover(CoverDevice):
async def async_added_to_hass(self):
"""Subscribe to covers events."""
self._cover.register_async_callback(self.async_update_callback)
self.hass.data[DATA_DECONZ].deconz_ids[self.entity_id] = \
self._cover.deconz_id
self.gateway.deconz_ids[self.entity_id] = self._cover.deconz_id
self.unsub_dispatcher = async_dispatcher_connect(
self.hass, DECONZ_REACHABLE, self.async_update_callback)
async def async_will_remove_from_hass(self) -> None:
"""Disconnect cover object when removed."""
if self.unsub_dispatcher is not None:
self.unsub_dispatcher()
self._cover.remove_callback(self.async_update_callback)
self._cover = None
@@ -112,7 +121,7 @@ class DeconzCover(CoverDevice):
@property
def available(self):
"""Return True if light is available."""
return self._cover.reachable
return self.gateway.available and self._cover.reachable
@property
def should_poll(self):
@@ -150,7 +159,7 @@ class DeconzCover(CoverDevice):
self._cover.uniqueid.count(':') != 7):
return None
serial = self._cover.uniqueid.split('-', 1)[0]
bridgeid = self.hass.data[DATA_DECONZ].api.config.bridgeid
bridgeid = self.gateway.api.config.bridgeid
return {
'connections': {(CONNECTION_ZIGBEE, serial)},
'identifiers': {(DECONZ_DOMAIN, serial)},

Some files were not shown because too many files have changed in this diff Show More