Compare commits

...

307 Commits

Author SHA1 Message Date
Paulus Schoutsen
c9498d9f09 Version bump to 0.70.0b4 2018-05-26 08:35:18 -04:00
Paulus Schoutsen
2f0435ebd8 No longer use backports for ffmpeg (#14626) 2018-05-26 08:34:56 -04:00
Paulus Schoutsen
19351fc429 Use libsodium18 (#14624) 2018-05-26 08:34:55 -04:00
Paulus Schoutsen
bfc16428da Bump frontend to 20180526.1 2018-05-26 08:34:40 -04:00
Paulus Schoutsen
43d2e436b9 Version bump to 0.70.0b3 2018-05-24 14:25:15 -04:00
Paulus Schoutsen
ef35b8d428 Fix hue discovery popping up (#14614)
* Fix hue discovery popping up

* Fix result

* Fix tests
2018-05-24 14:24:58 -04:00
Tom Harris
69e86c29a6 Bump insteonplm version to fix device hanging (#14582)
* Update inteonplm to 0.9.2

* Change to force Travis CI

* Change to force Travis CI
2018-05-24 14:24:58 -04:00
Greg Laabs
a4d45c46e8 Fix ISY moisure sensors showing unknown until a leak is detected (#14496)
* Fix ISY leak sensors always showing UNKNOWN until a leak is detected

Added some logic that handles both moisture sensors and door/window sensors

* Handle edge case of leak sensor status update after ISY reboot

If a leak sensor is unknown, due to a recent reboot of the ISY, the status will get updated to dry upon the first heartbeat. This status update is the only way that a leak sensor's status changes without an accompanying Control event, so we need to watch for it.

* Fixes from overnight testing

State was checking the incorrect parameter, and wasn't calling schedule update

* Remove leftover debug log line

* Remove unnecessary pylint instruction

* Remove access of protected property

We can't cast _.status directly to a bool for some unknown reason (possibly with the VarEvents library), but casting to an int then bool does work.
2018-05-24 14:24:57 -04:00
Paulus Schoutsen
45d1d30a8b Update frontend to 20180524.0 2018-05-24 14:24:37 -04:00
Paulus Schoutsen
4671bd95c6 Version bump to 0.70.0b2 2018-05-21 11:10:53 -04:00
Marco Orovecchia
1bc916927c fix nanoleaf aurora lights min and max temperature (#14571)
* fixed nanoleaf aurora lights min and max temperature

* review changes
2018-05-21 11:10:36 -04:00
cdce8p
2f8865d6cb Homekit style cleanup (#14556)
* Style cleanup

* Sorted imports
* Harmonized service calls

* Test improvements

* Small update
2018-05-21 11:10:35 -04:00
Martin Hjelmare
cfdea8d20f Wait for future mysensors gateway ready (#14398)
* Wait for future mysensors gateway ready

* Add an asyncio future that is done when the gateway reports the
  gateway ready message, I_GATEWAY_READY.
* This will make sure that the gateway is ready before home assistant
  fires the home assistant start event. Automations can now send
  messages to the gateway when home assistant is started.
* Use async timeout to wait max 15 seconds for ready gateway.

* Address comments
2018-05-21 11:10:35 -04:00
Paulus Schoutsen
ba9bb90cf7 Update frontend to 20180521.0 2018-05-21 11:01:47 -04:00
Paulus Schoutsen
8854efd685 Version bump to 0.70.0b1 2018-05-19 10:45:18 -04:00
Paulus Schoutsen
b0e850ba5d Bump frontend to 20180519.0 2018-05-19 10:45:03 -04:00
Paulus Schoutsen
f2dfc84d52 Version bump to 0.70.0b0 2018-05-18 19:31:16 -04:00
Paulus Schoutsen
e55f7ebf81 Merge branch 'master' into dev 2018-05-18 19:30:48 -04:00
Paulus Schoutsen
8d06469efe Bump frontend to 20180518.1 2018-05-18 18:15:49 -04:00
Fabian Affolter
c1127133ea Set certifi to >=2018.04.16 (#14536) 2018-05-18 18:14:40 -04:00
Sean Dague
25970027c6 Update mychevy to 0.4.0 (#14372)
After 2 months of being offline, the my.chevy website seems to be
working again. Some data structures changed in the mean time. The new
library will handle multiple cars. This involves a breaking change in
slug urls for devices where these now include the car make, model, and
year in them.

Discovery has to be delayed until after the initial site login to get
the car metadata.
2018-05-18 13:37:43 -04:00
Greg Laabs
d7640e6ec3 Fix some ISY sensors not getting detected as binary sensors (#14497)
Sensors that were defined via sensor_string were not getting properly identified as binary sensors when they had a uom defining them as binary (the other three methods of detecting binary sensors worked though.)
2018-05-18 08:42:09 -07:00
cdce8p
12e76ef7c1 Update HAP-python to 2.1.0 (#14528) 2018-05-18 16:32:57 +02:00
hanzoh
d36996c8f0 Add Homematic IP RotaryHandleSensor support (#14522)
* Add Homematic IP RotaryHandleSensor support

HmIP-SRH was in the RotaryHandleSensor class and threw errors that LOWBAT and ERROR could not be found (they are LOW_BAT and SABOTAGE).

* Revert REQUIREMENTS change
2018-05-18 16:20:30 +02:00
Fabian Affolter
e929f45ab8 Set pytz to >=2018.04 (#14520) 2018-05-18 09:42:41 -04:00
cdce8p
4c328baaa6 Add code to HomeKit lock (#14524) 2018-05-18 13:52:52 +02:00
Fabian Affolter
cc5edf69e3 Show warning if no locations are shared (fixes #14177) (#14511) 2018-05-18 09:04:47 +02:00
Matt Snyder
909f2448ca Flux bug fix (#14476)
* Simplify conditionals.

* Send white_value on service call.

* Remove extra blank line

* Further simplification of conditionals

* Requested changes

* Do not call getRgb if not needed

* Update log message
2018-05-18 08:50:57 +02:00
Diogo Gomes
97076aa3fd Fix probability_threshold in binary_sensor.bayesian (#14512) (Closes: #14362) 2018-05-18 07:48:16 +02:00
Malte Franken
a3777c4ea8 Feedreader configurable update interval and max entries (#14487) 2018-05-18 07:25:08 +02:00
Paulus Schoutsen
1c3293ac85 Update frontend to 20180518.0 (#14510)
* Update frontend to 20180517.0

* Update requirements

* Bump frontend to 20180518.0
2018-05-17 21:29:37 -04:00
thelittlefireman
f06a0ba373 Bump locationsharinglib to 2.0.2 (#14359)
* Bump locationsharinglib to 2.0.2

* Bump locationsharinglib to 2.0.2
2018-05-17 23:06:39 +02:00
Anders Melchiorsen
9afc2634c6 Adjust LimitlessLED properties for running effects (#14481) 2018-05-17 20:54:25 +02:00
Nate Clark
ed3efc8712 Konnected component follow up (#14491)
* make device_discovered synchronous

* small fixes from code review

* use dispatcher to update sensor state

* update switch state based on response from the device

* interpolate entity_id into dispatcher signal

* cleanup lint

* change coroutine to callback
2018-05-17 20:19:05 +02:00
Mike
144524fbbb Update hitron_coda.py (#14506)
missed a typo that wasn't caught with testing since I don't have a Rogers router.
2018-05-17 19:44:01 +02:00
ChristianKuehnel
298d31e42b New Sensor FinTS (#14334) 2018-05-17 02:45:47 +02:00
Paulus Schoutsen
3e7d4fc902 Bump frontend to 20180516.1 2018-05-16 09:39:14 -04:00
Paulus Schoutsen
64223cea72 Update frontend to 20180516.0 2018-05-16 09:01:30 -04:00
Nathan Henrie
1053473111 Add stdout and stderr to debug output for shell_command (#14465) 2018-05-16 13:47:41 +02:00
Matt Schmitt
25dcddfeef Add HomeKit support for fans (#14351) 2018-05-16 13:15:59 +02:00
Ville Skyttä
e20f88c143 Use "Returns" consistently to avoid being treated as section (#14448)
Otherwise, by side effect, results in error D413 by recent pydocstyle.
2018-05-16 10:01:48 +02:00
William Scanlon
1533a68c06 Added option to invert aREST pin switch logic for active low relays (#14467)
* Added option to invert aREST pin switch logic for active low relays

* Fixed line lengths

* Changed naming and set optional invert default value.

* Fixed line length

* Removed default from get
2018-05-16 09:58:49 +02:00
Greg Laabs
5ff5c73e2b "unavailable" Media players should be considered off in Universal player (#14466)
The Universal media player inherits the states of the first child player that is not in some sort of "Off" state (including idle.) It was not considering the "unavailable" state to be off. Now it does.
2018-05-16 08:00:57 +02:00
Anders Melchiorsen
6ba49e12a2 Improve handling of offline Sonos devices (#14479) 2018-05-16 07:35:43 +02:00
nordlead2005
852ce9f990 Added temperature (apparent) high/low, deprecated max/min (#12233) 2018-05-15 21:26:41 +02:00
Paulus Schoutsen
df69680d24 Don't add a url to built-in panels (#14456)
* Don't add a url to built-in panels

* Add url_path back

* Lint

* Frontend bump to 20180515.0

* Fix tests
2018-05-15 14:47:46 -04:00
Gerard
2e7b5dcd19 BMW code cleanup (#14424)
* Some cleanup for BMW sensors

* Changed dict sort

* Updates based on review and Travis
2018-05-15 20:47:32 +02:00
Malte Franken
e49e0b5a13 Make Feedreader component more extendable (#14342)
* moved regular updates definition to own method to be able to override behaviour in subclass

* moved filter by max entries to own method to be able to override behaviour in subclass

* event type used when firing events to the bus now based on variable to be able to override behaviour in subclass

* feed id introduced instead of url for storing meta-data about the feed to be able to fetch the same feed from different configs with different filtering rules applied

* keep the status of the last update; continue processing the entries retrieved even if a recoverable error was detected while fetching the feed

* added test cases for feedreader component

* better explanation around breaking change

* fixing lint issues and hound violations

* fixing lint issue

* using assert_called_once_with instead of assert_called_once to make it compatible with python 3.5
2018-05-15 20:43:26 +02:00
Nate Clark
de50d5d9c1 Add Konnected component with support for discovery, binary sensor and switch (#13670)
* Add Konnected component with support for discovery, binary sensor, and switch

Co-authored-by: Eitan Mosenkis <eitan@mosenkis.net>

* Use more built-in constants from const.py

* Fix switch actuation with low-level trigger

* Quiet logging; Improve schema validation.

* Execute sync request outside of event loop

* Whitespace cleanup

* Cleanup config validation; async device setup

* Update API endpoint for Konnected 2.2.0 changes

* Update async coroutines via @OttoWinter

* Make backwards compatible with Konnected < 2.2.0

* Add constants suggested by @syssi

* Add to CODEOWNERS

* Remove TODO comment
2018-05-15 19:58:00 +02:00
c727
612a37b2dd Remove simplepush.io (#14358) 2018-05-15 16:57:51 +02:00
Diogo Gomes
d47006c98f Optimistic MQTT light (#14401)
* Restores light state, case the light is optimistic

* lint

* hound

* hound

* Added mqtt_json

* hound

* added mqtt_template

* lint

* cleanup

* use ATTR
2018-05-15 12:25:50 +02:00
Sebastian Muszynski
16bf10b1a2 Don't poll the Samsung Family hub camera (#14473) 2018-05-15 08:50:07 +02:00
William Scanlon
710533ae8a Minor Wink fixes (#14468)
* Updated Wink light supported feature to reflect what features a given light support.

* Fix typo in wink climate
2018-05-15 07:53:12 +02:00
Matthew Garrett
11c57f9345 Bump lakeside version (#14471)
This should fix a couple of issues with T1013 bulbs, and also handle
accounts that contain unknown devices.
2018-05-15 07:51:32 +02:00
Martin Hjelmare
7562b4164b Fix key error upon missing node (#14460)
* This is needed after gateway ready message generates an update while
  persistence is off, or while the gateway node hasn't been presented
  yet.
2018-05-14 22:52:44 +02:00
Gregory Benner
cf44b77225 Samsung Family hub camera component (#14458)
* add familyhub.py camera

* fix import and REQUIREMENTS

* add to coveragerc

* fix formatting to make houndci-bot happy

* ran scripts/gen_requirements_all.py

* use CONF_IP_ADDRESS

* Revert "ran scripts/gen_requirements_all.py"

This reverts commit 3a38681d8a084e6d4811771ae7a18819477885bc.

* fix library name

* add missing docstrings and enable polling

* Sort imports
2018-05-14 22:52:35 +02:00
Matt Schmitt
44e9783c7c Add support for direction to fan template (#14371)
* Initial commit

* Update and add tests
2018-05-14 22:37:49 +02:00
Fabian Affolter
1b5c02ff67 Upgrade pygatt to 3.2.0 (#14447) 2018-05-14 21:52:54 +02:00
Russell Cloran
2f74ffcf81 zha: Fix cluster class check in single-cluster device type (#14303)
zigpy now allows custom devices, which might mean that devices have cluster
objects which are not instances of the default, but may be instances of
sub-classes of the default. This fixes the check for finding single-cluster
device entities to handle sub-classes properly.
2018-05-14 16:50:09 +02:00
Fabian Affolter
954e4796b8 Use ATTR_NAME from const.py (#14450) 2018-05-14 13:05:52 +02:00
Fabian Affolter
fb501282cc Add SpaceAPI support (#14204)
* Add SpaceAPI support

* Changes according PR comments

* Add tests

* Remove print

* Minor changes
2018-05-14 09:13:59 +02:00
Robert Svensson
c06351f2a9 Bump requirement to pydeconz v38 (#14452) 2018-05-14 08:41:17 +02:00
Johann Kellerman
6b9c65c9ce Allow qwikswitch sensors as part of devices (#14454) 2018-05-14 08:40:25 +02:00
Philip Rosenberg-Watt
8ae3caa292 Add priority and cycles to LaMetric (#14414)
* Add priority and cycles to LaMetric

Priority can be "info", "warning" (default), or "critical" and
cycles is the number of times the message is displayed. If cycles
is set to 0 we get a persistent notification that has to be dismissed
manually.

* Fix for schema and style

* Fix for style
2018-05-13 18:04:21 +02:00
Fabian Affolter
391e3196ea Upgrade distro to 1.3.0 (#14436) 2018-05-13 18:01:10 +02:00
Fabian Affolter
cb709931e4 Upgrade youtube_dl to 2018.05.09 (#14438) 2018-05-13 18:00:37 +02:00
Fabian Affolter
a750f8444e Upgrade Sphinx to 1.7.4 (#14439) 2018-05-13 18:00:08 +02:00
Fabian Affolter
a5bff4cd8d Upgrade python-telegram-bot to 10.1.0 (#14441) 2018-05-13 17:59:25 +02:00
Fabian Affolter
e0bc894cbb Upgrade pyota to 2.0.5 (#14442)
* Use constants

* Upgrade pyota to 2.0.5
2018-05-13 17:58:57 +02:00
Fabian Affolter
3ec56d55c5 Upgrade requests_mock to 1.5 (#14444) 2018-05-13 17:58:18 +02:00
Martin Hjelmare
b904a4e770 Remove universal wheel setting (#14445)
* Home assistant should not build a universal wheel since we don't
  support Python 2.
2018-05-13 17:57:52 +02:00
Ville Skyttä
146a9492ec Clean up some Python 3.4 remnants (#14433) 2018-05-13 17:56:42 +02:00
cdce8p
e5d714ef52 Fix fan service description (#14423) 2018-05-13 14:41:42 +02:00
Ville Skyttä
4d63baf705 Invoke pytest instead of py.test per upstream recommendation, #dropthedot (#14434)
http://blog.pytest.org/2016/whats-new-in-pytest-30/
https://twitter.com/hashtag/dropthedot
2018-05-13 12:11:55 +02:00
Ville Skyttä
234bf1f0ea Spelling, grammar etc fixes (#14432)
* Spelling, grammar etc fixes

* s/an api data/data of an api/
2018-05-13 12:09:28 +02:00
Ville Skyttä
843789528e Remove extra quotes from docstrings (#14431) 2018-05-13 11:06:15 +02:00
Krasimir Chariyski
ea2c073612 Add Bulgarian to Google TTS (#14422) 2018-05-12 17:46:00 -04:00
Andrey
d1228d5cf4 Look at registry before pulling zwave config values (#14408)
* Look at registry before deciding on ID for zwave values

* Reuse the new function
2018-05-12 17:45:36 -04:00
Andrey
7aec098a05 Bring back typing check. Meanwhile just for homeassistant/*.py (#14410)
* Bring back typing check. Meanwhile just for homeassistant/.py

* Change follow-imports to silent. Add a few more checks.
2018-05-12 17:44:53 -04:00
Ville Skyttä
70af7e5fad Update pylint to 1.8.4 (#14421) 2018-05-12 22:22:20 +02:00
Daniel Høyer Iversen
99e272fc8d Upgrade PyXiaomiGatewa to 0.9.3 (#14420) (Closes: #14417) 2018-05-12 21:12:53 +02:00
cdce8p
990f476ac9 Homekit test cleanup (#14416) 2018-05-12 17:10:19 +02:00
Paulus Schoutsen
9abc13aaa6 Merge pull request #14413 from home-assistant/rc
0.69.1
2018-05-12 09:35:30 -04:00
Paulus Schoutsen
d17186a8b7 Version bump to 0.69.1 2018-05-12 09:34:28 -04:00
Lukas Barth
6fedad7890 Fix waiting for setup that never happens (#14346) 2018-05-12 09:34:13 -04:00
Sebastian Muszynski
b371bf700f Bump PyXiaomiGateway version (#14412) 2018-05-12 15:09:48 +02:00
damarco
01ce43ec7c Use None as initial state in zha component (#14389)
* Return None if state is unknown

* Use None as initial state
2018-05-12 14:41:44 +02:00
Lukas Barth
b903bbc042 Fix waiting for setup that never happens (#14346) 2018-05-12 10:30:21 +02:00
Martin Hjelmare
304137e7ff Fix name of tox pylint env (#14402) 2018-05-12 10:07:10 +02:00
Matthew Treinish
e80628d45b Bump pycmus version (#14395)
This commit bumps the pycmus version used by the cmus component. There
was a bug in the previous version used, 1.0.0, when running in local
mode. This was caused by a mtreinish/pycmus#1 and also was reported in
the home-assistant forums (but not as an issue):

https://community.home-assistant.io/t/cant-install-cmus-component/7961

Version 0.1.1 of pycmus fixes this issue so it should work properly for
users running cmus and home-assistant on the same machine.
2018-05-12 07:51:48 +02:00
Sebastian Muszynski
d6b81fb345 Xiaomi Aqara: Add new cube model (sensor_cube.aqgl01) (#14393) 2018-05-11 22:40:32 +02:00
Paulus Schoutsen
c5cac04e54 Merge pull request #14392 from home-assistant/rc
0.69
2018-05-11 12:38:08 -04:00
Matt Schmitt
621c653fed Allow HomeKit name to be customized (#14159) 2018-05-11 14:22:45 +02:00
Malte Franken
48d70e520f more detailed error message (#14385) 2018-05-11 12:28:28 +02:00
Robin
528ad56530 Adds facebox (#14356)
* Adds facebox

* Update .coveragerc

* Remove facebox

* Add test of faces attribute

* Add event test

* Adds more tests

* Adds tests to increase coverage

* Rename MOCK_FACES to MOCK_FACE

* Adds STATE_UNKNOWN
2018-05-11 09:57:00 +02:00
Martin Hjelmare
be3b227a87 Make mysensors component async (#13641)
* Make mysensors component async

* Use async dispatcher and discovery.
* Run I/O in executor.
* Make mysensors actuator methods async.
* Upgrade pymysensors to 0.13.0.
* Use async serial gateway.
* Use async TCP gateway.
* Use async mqtt gateway.

* Start gateway before hass start event

* Make sure gateway is started after discovery of persistent devices
  and after corresponding platforms have been loaded.
* Don't wait to start gateway until after hass start.

* Bump pymysensors to 0.14.0
2018-05-11 09:39:18 +02:00
damarco
ef8fc1f201 Update sensor state before adding device (#14357) 2018-05-10 22:32:16 -07:00
Paulus Schoutsen
8c0b45af1e Version bump to 0.69.0 2018-05-10 22:40:04 -04:00
Paulus Schoutsen
3b39ab5b94 Remove domain expiry sensor (#14381) 2018-05-10 22:39:35 -04:00
cdce8p
8fcf085829 Rewritten HomeKit tests (#14377)
* Use pytest fixtures and parametrize
* Use async
2018-05-11 01:21:59 +02:00
Abílio Costa
6843893d9f Add "framerate" parameter to generic camera (#14079)
* add "framerate" parameter to generic camera

* fix lint
2018-05-11 00:22:02 +02:00
damarco
e963fc5acf Add support for pressure sensors (#14361) 2018-05-10 23:55:32 +02:00
Paulus Schoutsen
bc664c276c Bump frontend to 20180510.1 2018-05-10 17:38:41 -04:00
Paulus Schoutsen
f192ef8219 Remove domain expiry sensor (#14381) 2018-05-10 23:13:00 +02:00
damarco
db31cdf075 Fix binary_sensor device_state_attributes (#14375) 2018-05-10 21:28:57 +02:00
Andrey
f168226be9 Update to sensibo 1.0.3 with better error reporting (#14380) 2018-05-10 21:11:02 +02:00
Paulus Schoutsen
ea01b127c2 Add local auth provider (#14365)
* Add local auth provider

* Lint

* Docstring
2018-05-10 14:09:22 -04:00
damarco
6e831138b4 Fix binary_sensor async_update (#14376) 2018-05-10 10:59:23 -07:00
Pascal Vizeli
eb2671f4bb Update .coveragerc (#14368) 2018-05-10 13:18:13 +02:00
cdce8p
8d017b7678 script/lint: Ensure there are files to test with pylint (#14363) 2018-05-10 12:47:04 +02:00
Paulus Schoutsen
5ec7fc7ddb Backend tweaks to make authorization work (#14339)
* Backend tweaks to make authorization work

* Lint

* Add test

* Validate redirect uris

* Fix tests

* Fix tests

* Lint
2018-05-10 10:38:11 +02:00
Teemu R
0f3ec94fba debug++ for multiple volume controls (#14349)
Be less noisy for those who have more volume controls than one, mentioned in #13022.
2018-05-09 13:44:42 +02:00
Fabian Affolter
2c566072f5 Upgrade keyring to 12.2.0 and keyrings.alt to 3.1 (#14355) 2018-05-09 11:31:18 +02:00
Nash Kaminski
cf8562a030 Support control of away mode and hold mode in Venstar component. Correctly detect humidifiers. (#14256)
* Implement support for away mode and hold mode in Venstar component

* Fix Venstar humidifier capability detection

* Add option to configure humidifier control in Venstar component

* style fix: add missing space and resolve pylint issues

* Remove quotes
2018-05-09 11:26:29 +02:00
Mal Curtis
a91c1bc668 Add zone 3 for Onkyo media player (#14295)
* Add zone 3 for Onkyo media player

* CR Updates

* Fix travis lint errors
2018-05-08 22:33:38 -04:00
Paulus Schoutsen
f406fd57ac Version bump to 0.69.0b3 2018-05-08 20:55:35 -04:00
Anders Melchiorsen
2d0e3c1402 Ignore NaN values for influxdb (#14347)
* Ignore NaN values for influxdb

* Catch TypeError
2018-05-08 20:55:12 -04:00
Paulus Schoutsen
01ec4a7afd Bump frontend to 20180509.0 2018-05-08 20:54:49 -04:00
Anders Melchiorsen
d43e6a2888 Ignore NaN values for influxdb (#14347)
* Ignore NaN values for influxdb

* Catch TypeError
2018-05-08 20:54:38 -04:00
Paulus Schoutsen
50cea77887 Bump frontend to 20180509.0 2018-05-08 20:48:46 -04:00
Mario Di Raimondo
6231394614 Waze Travel Time: optional inclusive/exclusive filters (#14000)
* Waze Travel Time: optional inclusive/exclusive filters

Added optional `inc_filter` and `excl_filter' params that allow to refine the reported routes: the first is not always the best/desired. A simple case-insensitive filtering (no regular expression) is used.

* fix line lenght

* fix spaces

* Rename var

* Fix typo

* Fix missing var
2018-05-09 00:35:03 +02:00
Aaron Bach
f516cc7dc6 Adds useful attributes to RainMachine programs and zones (#14087)
* Starting to add attributes

* All attributes added to programs

* Basic zone attributes in place

* Added advanced properties for zones

* Working to move common logic into component + dispatcher

* We shouldn't calculate the MAC with every entity

* Small fixes

* Small adjustments

* Owner-requested changes

* Restart

* Restart part 2

* Added ID attribute to each switch

* Collaborator-requested changes
2018-05-08 18:10:03 -04:00
Evgeniy
9c7523d7b0 Improving icloud device tracker (#14078)
* Improving icloud device tracker

* Adding config validations for new values

* Adding config validations for new values

* Moving icloud specific setup to platform schema. Setting default in platform schema.
2018-05-08 23:42:57 +02:00
Andrey
10505d542a Make sure zwave nodes/entities enter the registry is proper state. (#14251)
* When zwave node's info is parsed remove it and re-add back.

* Delay value entity if not ready

* If node is ready consider it parsed even if manufacturer/product are missing.

* Add annotations
2018-05-08 15:30:28 -04:00
Nick Whyte
e12994a0cd Fix BOM weather '-' value (#14042) 2018-05-08 13:35:55 -04:00
stephanerosi
ff01aa40c9 Add help for conversation/process service (#14323)
* Add help for conversation/process service

* Add logging to debug text received when service is called

* Move conversation to specific folder
2018-05-08 13:24:27 -04:00
Paulus Schoutsen
6199e50e80 Fix Insteon PLM coverage 2018-05-08 11:55:04 -04:00
Tod Schmidt
c664c20165 Snips: Added slot values for siteId and probability (#14315)
* Added solt values for siteId and probability

* Update snips.py

* Update test_snips.py
2018-05-08 11:43:31 -04:00
David Broadfoot
eb551a6d5a Gogogate2 0.1.1 (#14294)
* Gogogate2 - bump version

Uses latest version of library which ensures commands to device are idempotent

* Update requirements_all

* Expose sensor temperature

* update version

* import attribute

* Set temperature

* Remove temperature attribute

Removed temperature attribute until it can be re-implemented as a separate sensor.

* Update ordering

* Fix copy-&-paste issue
2018-05-08 11:42:18 -04:00
m4dmin
4343659742 add 2 devices (#14321)
* add 2 devices

io:RollerShutterUnoIOComponent
io:ExteriorVenetianBlindIOComponent

* add 2 devices

* Update tahoma.py

* Fix hounci-bot violation

* Fixed Travis CI build failure

./homeassistant/components/cover/tahoma.py:83:13: E125 continuation line with same indent as next logical line

* Fixed Travis CI build failure

E125 continuation line with same indent as next logical line

* Fixed Travis CI build failure

E127 continuation line over-indented for visual indent

* Fix indent

* Change check
2018-05-08 13:43:07 +02:00
Mattias Welponer
230bd3929c Add more homematicip cloud components (#14084)
* Add support for shutter contact and motion detector device

* Add support for power switch devices

* Add support for light switch device

* Cleanup binary_switch and light platform

* Update comment
2018-05-08 09:57:51 +02:00
Gerard
ba7333e804 Add sensors for BMW electric cars (#14293)
* Add sensors for electric cars

* Updates based on review of @MartinHjelmare

* Fix Travis error

* Another fix for Travis
2018-05-08 09:52:21 +02:00
Mike
48b13cc865 Update hitron_coda.py to fix login for Shaw modems (#14306)
I have a Hitron modem provided by Shaw communications rather than from Rogers as the Docs specify for this device_tracker but it seems like the api/code is all the same except that the login failed due to the password being passed as "pws" instead of "pwd". Making that one character change allowed HASS to read the connected device details from my Hitron modem. If this difference is actually one that stands between the Rogers-provided Hitron modems and the Shaw-provided variant, I am happy to create another device-tracker file for the Shaw modem. I just figured I would go with the simplest solution first.
2018-05-08 09:26:46 +02:00
Aaron Bach
e7c7b9b2a9 Adds unique ID to Roku for entity registry inclusion (#14325)
* Adds unique ID to Roku for entity registry inclusion

* Owner-requested changes
2018-05-07 13:18:51 -04:00
Paulus Schoutsen
8d24541ffe Version bump to 0.69.0b2 2018-05-07 13:12:54 -04:00
Paulus Schoutsen
b1eb35ee11 Ignore more loading errors (#14331) 2018-05-07 13:12:43 -04:00
Paulus Schoutsen
c7166241f7 Ignore more loading errors (#14331) 2018-05-07 13:12:12 -04:00
Paulus Schoutsen
a4e1615127 Version bump to 0.69.0b1 2018-05-07 10:05:34 -04:00
Javier Gonel
3e5d76efb2 fix(hbmqtt): partial packets breaking hbmqtt (#14329)
This issue was fixed in hbmqtt/issues#95 that was released in hbmqtt 0.9.2
2018-05-07 10:01:23 -04:00
Paulus Schoutsen
6a74fa344d Revert custom component loading logic (#14327)
* Revert custom component loading logic

* Lint

* Fix tests

* Guard for infinite inserts into sys.path
2018-05-07 10:01:22 -04:00
Paulus Schoutsen
c4ec2e3434 Fix module names for custom components (#14317)
* Fix module names for custom components

* Also set __package__ correctly

* bla

* Remove print
2018-05-07 10:01:22 -04:00
cdce8p
c48986a467 Add debounce to move_cover (#14314)
* Add debounce to move_cover

* Fix spelling mistake
2018-05-07 10:01:22 -04:00
Justin Loutsenhizer
ab621808bd Add missing 'sensor' to ABODE_PLATFORMS (#14313)
This fixes missing light, humidity, temperature sensors from abode component.
2018-05-07 10:01:21 -04:00
Paulus Schoutsen
5c88e897af Update netdisco to 1.4.1 2018-05-07 10:01:06 -04:00
Paulus Schoutsen
6318178a8b Update netdisco to 1.4.1 2018-05-07 10:00:54 -04:00
Javier Gonel
a2b8ad50f2 fix(hbmqtt): partial packets breaking hbmqtt (#14329)
This issue was fixed in hbmqtt/issues#95 that was released in hbmqtt 0.9.2
2018-05-07 09:52:33 -04:00
Paulus Schoutsen
5c95c53c6c Revert custom component loading logic (#14327)
* Revert custom component loading logic

* Lint

* Fix tests

* Guard for infinite inserts into sys.path
2018-05-07 11:25:48 +02:00
Jerad Meisner
e60d066514 Converted SABnzbd to a component (#12915)
* Converted SABnzbd to a component

* fixed async issues

* Made sabnzbd scan interval static. More async fixes.

* Sabnzbd component code cleanup

* Skip sensor platform setup if discovery_info is None
2018-05-07 09:35:55 +02:00
cdce8p
91fe6e4e56 Add debounce to move_cover (#14314)
* Add debounce to move_cover

* Fix spelling mistake
2018-05-06 20:55:38 -04:00
Paulus Schoutsen
34727be5ac Fix module names for custom components (#14317)
* Fix module names for custom components

* Also set __package__ correctly

* bla

* Remove print
2018-05-06 20:54:56 -04:00
Justin Loutsenhizer
107769ab81 Add missing 'sensor' to ABODE_PLATFORMS (#14313)
This fixes missing light, humidity, temperature sensors from abode component.
2018-05-06 19:18:26 +02:00
Russell Cloran
63cc179ea2 zha: Bump to zigpy 0.1.0 (#14305) 2018-05-06 11:17:05 +02:00
thepotoo
2bb1a95098 Add unique_id to MQTT switch (#13719) 2018-05-06 08:21:02 +02:00
Paulus Schoutsen
f3411f8db2 Version bump to 0.70.0.dev0 2018-05-05 11:42:32 -04:00
Paulus Schoutsen
1e31af77de Version bump to 0.69.0b0 2018-05-05 11:41:55 -04:00
Paulus Schoutsen
2326312bee Merge branch 'master' into dev 2018-05-05 11:41:29 -04:00
Paulus Schoutsen
83e342daf2 Update frontend to 20180505.0 2018-05-05 11:35:42 -04:00
Paulus Schoutsen
a4b69833d4 Update translations 2018-05-05 11:35:02 -04:00
Tom Harris
64ba2c63c7 Add All-Linking capabilities (#14065)
* Setup all-linking service

* Remove extra line

* Remove linefeed and tab escape chars

* Add services delete_all_link, load_all_link_database and print_all_link_database

* Check if reload is set

* Confirm entity is InsteonPLMEntity before attempting to load or print ALDB

* Debug load and print ALDB

* Debug print aldb

* Debug print_aldb

* Get entity via platform

* Track Insteon entities in component

* Store entity list in hass.data

* Add entity to hass.data

* Add ref to hass in InsteonPLMEntity

* Pass hass correctly to InsteonPLMBinarySensor

* Fix reference to ALDBStatus.PARTIAL

* Print ALDB record as string

* Get ALDB record from memory address

* Reformat ALDB log output

* Add print_im_aldb service

* Remove reference to self in print_aldb_to_log

* Remove reference to self in print_aldb_to_log

* Fix spelling issue with load_all_link_database service

* Bump insteonplm to 0.9.1

* Changes from code review

* Code review changes

* Fix syntax error

* Correct reference to cv.boolean and update requirements

* Update requirements

* Fix flake8 errors

* Reload as boolean test

* Remove hass from entity init
2018-05-05 11:15:20 -04:00
Ron Šmeral
2e8eaf40f7 Onkyo: SUPPORT_VOLUME_STEP (#14299) 2018-05-05 17:06:32 +02:00
Robin
b9e893184a Refactor ImageProcessingFaceEntity (#14296)
* Refactor ImageProcessingFaceEntity

* Replace STATE_UNKNOWN with None
2018-05-05 16:57:53 +02:00
Jason Kingsbury
4d085882d5 Add support for max_volume (#13822)
* onkyo: add support for max volume range

* onkyo: make flake8 happy

* onkyo: fix PEP8 D205 on line 181

* onkyo: use range for max_volume configuration

* onkyo: fix line too long
2018-05-05 10:30:54 -04:00
Jesse Newland
f6e29a6647 Add domain to labels and count state changes to Prometheus (#14253)
* Add domain to labels

* Count state changes
2018-05-05 10:23:01 -04:00
Jesse Newland
1a936220e9 Add alarmdotcom sensor status (#14254)
* bump to match Xorso/pyalarmdotcom#9

* Load additional status attributes

* missed a spot
2018-05-05 10:21:58 -04:00
Robert Svensson
8410b63d9c deCONZ add new device without restart (#14221)
* Add new device without restarting hass

* Remove debug prints

* Fix copy paste error

* Fix comments from balloob
Add tests to verify signalling with new added devices

* Fix hound comments
Add test to verify when new sensor is added

* Fix tests

* Unload entry should unsubscribe all deconz dispatchers

* Make sure mock setup also creates unsub in hass data

* Fix copy paste issue

* Lint
2018-05-05 10:11:00 -04:00
Lukas Barth
af8cd63838 Matrix Chatbot (#13355)
* Add first version of the Matrix bot

* It's a stupid but necessary change…

* Dont list it twice

* All hail the linter!

* More linter-pleasing

* Use the correct user ID

* Add expression commands

* Add tests for new validators

* Fix room alias handling

* Wording

* Defer setup

* Simplify commands

* Handle exceptions

* Update requirements

* Review

* Move login back to constructor

* Fix review comments
2018-05-05 10:00:36 -04:00
cdce8p
95d27bd1fa Sensor device classes (#14282)
* Added light device class, moved device classes to const

* Removed unnecessary icons

* Replace 'lux' with 'lx'

* Fix comment

* Changed device_class name
2018-05-05 09:37:40 -04:00
blackwind
ec3ce4c80d Publish attributes unconditionally (#14179)
* Publish attributes unconditionally

Because the attribute publish command was previously hidden behind `if val:`, falsy values like False and 0.0 weren't being published, thereby making Statestream -- particularly in the case of booleans, where the first True would be retained indefinitely -- a completely worthless indicator of state.

* Change bool test to False to confirm falsy values pass
2018-05-05 09:31:39 -04:00
Nick Whyte
5ade84d75f BOM Weather throttle fix (#14234) 2018-05-05 11:17:27 +02:00
Fabian Affolter
75bf483071 Upgrade astral to 1.6.1 (#14297) 2018-05-05 10:45:09 +02:00
Diogo Gomes
354470469f Fix filter sensor missing window_size argument (#14252)
* missing window_size argument

* test throttle filter configuration
2018-05-05 03:10:08 +02:00
Matt Schmitt
255a85ad02 HomeKit: Support triggered state for alarm_control_panel (#14285) 2018-05-05 00:09:16 +02:00
cdce8p
bb76ba67f3 Homekit: Changed device_class requirement Humidity Sensor (#14277) 2018-05-04 22:48:38 +02:00
Fabian Affolter
7900ba30bf Upgrade holidays to 0.9.5 (#14274) 2018-05-04 17:09:05 +02:00
cdce8p
e37fd5b132 Update HAP-python to 2.0.0 (#14278)
* Fixed async (added 'async_add_job' and 'add_job')

* Driver status

* Use pyhap category constants

* Changed 'set_broker' to 'set_driver'

* Changed loader method names

* Use 'serv.configure_char'

* Use 'self.set_info_service'

* Use 'self.add_preload_service'

* Fix hound issue

* Updated HAP-python to 2.0.0
2018-05-04 16:46:00 +02:00
Fabian Affolter
f98525acbf Upgrade attrs to 18.1.0 (#14281) 2018-05-04 08:58:34 -04:00
Otto Winter
36cf2125ce Issue Template Fix CRLF (#14283) 2018-05-04 13:49:13 +02:00
Boyi C
c80b752d0e fix check config not working after #14211 (#14259) 2018-05-04 12:29:07 +02:00
Anders Melchiorsen
fa0ad7b317 Color fixes for Wink lights (#14263) 2018-05-04 12:28:56 +02:00
Fabian Affolter
b49d98407c Remove feature request 2018-05-04 10:56:35 +02:00
Fabian Affolter
5f8f6666e6 Update issue templates 2018-05-04 10:55:55 +02:00
Fabian Affolter
54ccbbcb64 Update issue templates 2018-05-04 10:54:55 +02:00
Fabian Affolter
a7a3cff0f1 Update issue templates 2018-05-04 10:52:20 +02:00
Fabian Affolter
9859840b9c Update issue templates 2018-05-04 10:48:13 +02:00
cdce8p
8cabec7ac1 Fix ZWave light brightness (#14261)
* Fix ZWave light brightness
* The brightness should always be an integer
* Changed to round
2018-05-03 23:28:03 +02:00
Paulus Schoutsen
15e75b07d8 Allow fetching media player covers via websocket connection (#14233)
Lint
2018-05-03 22:03:26 +02:00
Paulus Schoutsen
58257af289 Add fetching camera thumbnails over websocket (#14231)
* Add fetching camera thumbnails over websocket

* Lint
2018-05-03 22:02:59 +02:00
Erik Eriksson
4ecce2598a Re-enable eliqonline requirement (#14265) 2018-05-03 19:54:37 +02:00
cdce8p
e68b52d50d Demo Sensor - Added device_class support (#14269) 2018-05-03 19:51:36 +02:00
roiff
c9de2f015b HomeKit - Climate: power state on/off support (#14082)
* add power state  support on off
* Added check for current operation mode
* Extended 'set_heat_cool'
* Added tests
2018-05-03 18:22:43 +02:00
giangvo
ef4498ec27 Issue/add template fans (#12027)
* add template fan

* add-template: address PR comments

* add-template: remove unused import

* add-template: revert async_track_state_change change

* add-template: use yield from

* Revert "add-template: use yield from"

This reverts commit 1e053714a7c75c29367e3d04cf52161ebfaabba1.

* add-template: use yield

* add-template: remove unused import

* add-template: remove async_add_job usages

* use components

* add-template: use async/await

* add-template: fix style

* add-template: remove str()

* address pr comments

* fix style
2018-05-02 17:45:31 -04:00
Diogo Gomes
c851dfa2c7 Restores switch state, case the switch is optimistic (#14151)
* Add restore_state to optimistic switch

* no need to schedule update

* test added

* lint

* new async syntax

* lint
2018-05-02 17:29:07 -04:00
Mark Coombes
64b9fbd8d9 Add prereqs for HomeKit Controller (#14172) 2018-05-02 16:28:43 -04:00
Andrey
f72d568374 Add unique_id to zwave node entity (#14201)
* Add unique_id to zwave node entity

* Wait 30s before adding zwave node if its unique_id is not ready

* Use only node_id in unique_id. Update name, manufacturer, and product attributes on node update.
2018-05-02 16:10:26 -04:00
Per Osbäck
351e8921fa python_openzwave update config service (#12060)
* update python-openzwave to 4.1.0

* add service which updates the configuration files from github

* 0.4.3
2018-05-02 15:06:09 -04:00
Mick Vleeshouwer
b66be59598 Add PostNL sensor (Dutch Postal Services) (#12366)
* Add basic PostNL sensor (WIP)

* Update PostNL sensor

* Bump version

* Small updates to PostNL package based on feedback

* Remove unused import

* Pass api to sensor

* Refactor based on feedback

* Update based on feedback

* Fix feedback

* Clean up

* Bugfiix

* Bugfix

* SCAN_INTERVAL fix

* Remove unused import

* Refactor for new wrapper implementation

* Update postnl package requirement

* Change throttle logic

* Update package version

* Add new line

* Minor changes

* Change refresh time to 30 minutes

* Update requirements_all.txt
2018-05-02 14:37:41 -04:00
Otto Winter
14c7fa8882 WUnderground unique ids (#13311)
* WUnderground unique_id

* Remove async_generate_entity_id

* Lint

* Address comment
2018-05-02 14:23:07 -04:00
Mathieu Velten
ce98dfe395 Add support for tracking devices on Netgear access points (#13331)
* Netgear: add support for tracking devices on access points

* Netgear: add SSL support and autodetection
2018-05-02 09:38:24 -04:00
Anders Melchiorsen
bf056b6f01 Fix Hue color state for missing xy (#14230) 2018-05-02 09:25:08 -04:00
Sebastian Muszynski
8b13658d3b Improve config schema of the blackbird component (#14007)
* Import moved, return values removed and redundant log message removed

* Improve config schema of the blackbird component

* Tests updated

* Handle updated

* Schema fixed
2018-05-02 09:21:50 -04:00
Diogo Gomes
e968b1a0f4 UPnP code cleanup (#14235)
* missing async calls

* lint

* cleanup
2018-05-02 09:15:30 -04:00
Mohamad Tarbin
6453ea4e61 Add Social Blade Sensor (#14060)
* Adding Dominion Energy Sensor

* Update : remove white spacves and set the update time to be daily

* Update : update spacing as per hound suggestions, Move imports

* Update :  Fix  Travis CI build errors

* Update Documentations on method levels

* Update Documentations on method levels

* Update Documentations on method levels

* Add Exception Handeling if login failed, add PLATFORM_SCHEMA

* Add Exception Handeling if login failed, add PLATFORM_SCHEMA

* Add Exception Handeling if login failed, add PLATFORM_SCHEMA

* Update dominionenergy.py

* Adding Selenium to requirements_all.txt

* Checking the username/password while setup

* Checking the username/password while setup

* removing extra white space

* Update : Adding the Platform only if credentials works

* Update : Add PlatformNotReady exception

* Update : Add PlatformNotReady exception

* Update .coveragerc

* Remove change

* Adding USCIS component

* Adding Line after the class DOC

* Update : Extract USCIS logic code to Component

* Update : Extract USCIS logic code to Component

* Adding CURRENT_STATUS

* Change Error handling, remove date from attributes

* Update the Version for USCIS

* Add Social Blade Sensor

* Update class documentation

* Update coverage and requirements_all

* Update : houndci error with intent

* Update : Add coverage

* Update uscis.py

* Add comments

* Add comments

* Delete dominionenergy.py

* Update requirements_all.txt

* Update .coveragerc

* Update .coveragerc

* Update .coveragerc

* Update : update after code review

* Fix remaining issues
2018-05-01 22:27:20 +02:00
Matt Snyder
c2d00be91e Allow independent control of white level on flux_led component (#13985)
* Allow independent control of white level on flux_led component.

Also preserve brightness on color change.

* Limit white value support to RGBW mode.

* Requested changes.

* Correct liniting issues

* Formatting
2018-05-01 15:38:45 -04:00
Otto Winter
e4655a7e63 Add MQTT Sensor device_class (#14033)
* Add MQTT Sensor device_class

* Add test
2018-05-01 15:38:08 -04:00
Aaron Bach
7a05471912 Converts RainMachine to hub model (part 2) (#14225)
* Converts RainMachine to hub model (part 2)

* Small style adjustments for consistency

* Moving MAC calculation to one-time call in component

* Removing unneeded attribute

* Bumping Travis

* Lint
2018-05-01 15:36:43 -04:00
escoand
8d5c3a2b91 add volumio discovery (#14220)
* add volumio discovery

* add missing library

* Update volumio.py
2018-05-01 15:20:38 -04:00
corneyl
2f0fc0934f Buienradar improvements: continuous sensors and unique ID's (#13249)
* Force update continuous sensors when new measurement available.

* Added unique ID's based on coordinates, sensor type and client name.

* Fixed over-indentation (hound review)

* Revert "Added unique ID's based on coordinates, sensor type and client name."

This reverts commit 3345e67a155c7953afc42c1b1b676616a7a77e56.

* Fix lint errors.

* Re-added unique ID's based on location.

* Removed wrong error logging.

* Removed creating UUID from unique id

* Lint
2018-05-01 15:06:41 -04:00
Paulus Schoutsen
83d300fd11 Custom component loading cleanup (#14211)
* Clean up custom component loading

* Fix some tests

* Fix some stuff

* Make imports work again

* Fix tests

* Remove debug print

* Lint
2018-05-01 20:57:30 +02:00
Ville Skyttä
5d96751168 panasonic_viera: Provide unique_id from SSDP UDN, if available (#13541) 2018-05-01 14:54:06 -04:00
NovapaX
38560cda1c Allow to set a desired update interval for camera_proxy_stream view (#13350)
* allow to set a desired update interval for camera_proxy_stream view

* lint

* refactor into a seperate method.
Keep the handle_async_mjpeg_stream method to be overridden by platforms
so they can keep proxying the direct streams from the camera

* change descriptions

* consolidate

* lint

* travis

* async/await and force min stream interval for fallback stream.

* guard clause. Let the method raise error on interval.

* is is not =

* what to except when you're excepting

* raise ValueError, remove unnecessary 500 response
2018-05-01 14:49:33 -04:00
blackwind
bf53cbe08d Support setting explicit mute value for Panasonic Viera TV (#13954)
* Use module's methods instead of API calls

* Use module's methods instead of API calls for media commands
2018-05-01 14:41:36 -04:00
Ruben
b00f771541 Add more parameters for DSMR sensor (#13967)
* Add more parameters for DSMR component

* Add suiting icon for power failure

* Add suiting icon for swells & sags

* Fix tab indentation -> spaces

* Fix too long lines (PEP8)
2018-05-01 14:40:48 -04:00
Otto Winter
9bc8f6649b Template Sensor add device_class support (#14034)
* Template Sensor Device Class Support

* Lint

* Add tests
2018-05-01 14:32:44 -04:00
Fabian Affolter
b0cccbfd9f Upgrade mypy to 0.590 (#14207) 2018-05-01 14:14:28 -04:00
Simon Hörrle
e78497789b Change the divisor for total consumption output (#14215)
According to my observations, the "switch_energy" value displayed by Pyfritzhome is the sum of Wh over the last week since measurement.
As a result, the correct divisor for representing output as kWh would be 1000 instead of 10000.
2018-05-01 14:13:35 -04:00
Paulus Schoutsen
d82693b460 Allow easy extension of websocket API (#14186)
* Allow easy extension of websocket API

* Lint

* Move panel test to frontend

* Register websocket commands

* Simplify test

* Lint
2018-05-01 13:35:23 -04:00
Paulus Schoutsen
cdd45e7878 Foundation for users (#13968)
* Add initial user foundation to Home Assistant

* Address comments

* Address comments

* Allow non-ascii passwords

* One more utf-8 hmac compare digest

* Add new line
2018-05-01 18:20:41 +02:00
sander76
b994c10d7f HomematicIP cloud: Add logic to check accesspoint connection state (#14203)
* Add logic to check accesspoint connection state

* lint

* changes as per @balloobs comments.

* pylint fix
2018-05-01 11:01:13 -04:00
Russell Cloran
9d4d1c8233 zha: Clean up binary_sensor listener registration/state updates (#14197)
- Instead of registering listeners in the entity __init__, do it in
   async_added_to_hass to avoid errors updating an entity which isn't fully
   set up yet
 - Change from schedule_update_ha_state to async_schedule_update_ha_state
2018-05-01 08:55:25 -04:00
Diogo Gomes
a4e0c9c251 Fixes #14169 (Upgrade pyupnp-async to 0.1.0.2) (#14210)
* Fixes #14169 (upstream version bump)

* bump pyupnp-async version
2018-05-01 08:51:47 -04:00
Philipp Schmitt
626d6df545 Update CODEOWNERS (#14214) 2018-05-01 10:14:33 +02:00
Paulus Schoutsen
12dff5baa8 Add room hint support to Google Assistant cloud (#14180) 2018-04-30 21:05:29 +02:00
Paulus Schoutsen
d1460de89b Merge pull request #14199 from home-assistant/rc
0.68.1
2018-04-30 14:04:29 -04:00
Paulus Schoutsen
c23cc0e827 Disable eliqonline requirement (#14156)
* Disable eliqonline requirement

* Disable pylint import error
2018-04-30 13:46:47 -04:00
Paulus Schoutsen
c704ceaeb7 Version bump to 0.68.1 2018-04-30 13:37:12 -04:00
Paulus Schoutsen
daeccfe764 Fix poorly formatted automations (#14196) 2018-04-30 13:36:56 -04:00
Otto Winter
7f1b591fbb Improve chromecast disconnection logic (#14190)
* Attempt Cast Fix

* Cleanup
2018-04-30 13:36:55 -04:00
Paulus Schoutsen
aba143ac9f Do not sync entities with an empty name (#14181) 2018-04-30 13:36:55 -04:00
cdce8p
03c34804bc Added CONF_IP_ADDRESS to HomeKit (#14163) 2018-04-30 13:36:54 -04:00
Matthew Garrett
f2a17a5462 Fix Python 3.6 compatibility for HomeKit controller (#14160)
Python 3.6's http client passes an additional argument to _send_output,
so add that to the function definition.
2018-04-30 13:36:54 -04:00
Anders Melchiorsen
b5bae17c66 Revert Hue color state to be xy-based (#14154) 2018-04-30 13:36:54 -04:00
Anders Melchiorsen
52a48b3ac9 Improve precision of Hue color state (#14113) 2018-04-30 13:36:53 -04:00
Anders Melchiorsen
a06f61034c Fix color setting of tplink lights (#14108) 2018-04-30 13:36:53 -04:00
mvn23
6e0a3abf66 Fix TypeError on round(self.humidity) (fixes #13116) (#14174)
* Fix TypeError on round(self.humidity)

Some weather platforms postpone the first data fetch for a while on init. As a result round(self.humidity is called before it is assigned a value, producing an error. This is a fix for that.

* Rewrite to avoid false negative evaluation

As per the suggestion from @OttoWinter, rewrite to avoid matching e.g. 0.0 as false.
2018-04-30 13:27:45 -04:00
Mahesh Subramaniya
eceece866d Updating darksky default update interval to 5 mins (#14195)
With Darksky allowing only 1000 API requests per day, 2 minutes retry seems to be bit closer to running over the limit and actually it did for 5 days in my account. Hence proposing a change to 5 minutes to keep the API happy and also it doesn't hurt to check the weather for every 5 mins than 2 mins someone lives in Jupiter :-P
2018-04-30 11:48:51 -04:00
Paulus Schoutsen
853a16938b Fix poorly formatted automations (#14196) 2018-04-30 09:56:42 -04:00
Paulus Schoutsen
5dcad89a0d Do not sync entities with an empty name (#14181) 2018-04-30 09:18:18 -04:00
cdce8p
46c260fd85 Added CONF_IP_ADDRESS to HomeKit (#14163) 2018-04-30 08:58:17 -04:00
Otto Winter
76c9c0179b Improve chromecast disconnection logic (#14190)
* Attempt Cast Fix

* Cleanup
2018-04-30 08:46:44 -04:00
Fabian Affolter
d7eced95fa Upgrade numpy to 1.14.3 (#14187) 2018-04-30 09:28:00 +02:00
Russell Cloran
02a12a0bb4 zha: Support remotes/buttons (#12528) 2018-04-29 23:31:27 -07:00
Anders Melchiorsen
30d987f59f Revert Hue color state to be xy-based (#14154) 2018-04-30 00:49:19 +02:00
Jens Østergaard Nielsen
aa8bd37143 Added update_interval to maxcube (#14143) 2018-04-29 20:57:57 +02:00
Paulus Schoutsen
4c0024fd97 Another coverage fix 2018-04-29 14:15:39 -04:00
Paulus Schoutsen
74320306a1 Add mitemp_bt to coverage 2018-04-29 14:08:33 -04:00
Hate-Usernames
113bdc493a Allow transitioning to colour temp for tradfri (#14157) 2018-04-29 16:54:44 +01:00
escoand
8e7f500f28 Add precipitation to OpenWeatherMap forecast (#13971)
* add initial precipitation support

* move attr to component

* remove blank line

* add forecast attributes to platform and update demo

* add tests

* break long lines

* calc lower temp correctly

* move all new attributes to component

* convert temp low only when existing
2018-04-29 17:50:49 +02:00
Fabian Affolter
d352dee9b7 Upgrade netdisco to 1.4.0 (#14152) 2018-04-29 16:21:46 +02:00
Kane610
3fd4987baf deCONZ allow unloading of config entry (#14115)
* Working but incomplete

* Remove events on unload

* Add unload test

* Fix failing sensor test

* Improve unload test

* Move DeconzEvent to init

* Fix visual under-indentation
2018-04-29 10:16:20 -04:00
Matthew Garrett
ef48a7ca2c Fix Python 3.6 compatibility for HomeKit controller (#14160)
Python 3.6's http client passes an additional argument to _send_output,
so add that to the function definition.
2018-04-29 09:46:36 +02:00
Paulus Schoutsen
fd038b6de9 Disable eliqonline requirement (#14156)
* Disable eliqonline requirement

* Disable pylint import error
2018-04-28 20:15:00 -04:00
Otto Winter
a4bf421044 Convert more files to async/await syntax (#14142)
* Move more files to async/await syntax

* Attempt Work around pylint bug

Using lazytox :P
2018-04-28 19:26:20 -04:00
Otto Winter
a0b14c2913 Light mqtt_json: Add HS color support (#14029)
* Light mqtt_json HS color support

* Lint

* Catch float ValueError
2018-04-29 00:33:10 +02:00
engrbm87
44ddc6ba62 deluge-components-update (#14016) 2018-04-29 00:16:22 +02:00
Gabe
07f94eaa92 Fixed datetime values (#14153) 2018-04-29 00:12:40 +02:00
Fabian Affolter
4205dc0f7c Upgrade psutil to 5.4.5 (#14135) 2018-04-28 23:17:38 +02:00
Matt Schmitt
2091f86e25 Clean up HomeKit accessory information characteristics (#14114)
* Update accessory information characteristics
* Add firmware revision characteristic
2018-04-28 23:17:30 +02:00
Fabian Affolter
84f163252a Upgrade youtube_dl to 2018.04.25 (#14136) 2018-04-28 23:17:10 +02:00
Fabian Affolter
9a9161477f Upgrade python-telegram-bot to 10.0.2 (#14144) 2018-04-28 23:16:51 +02:00
Fabian Affolter
449085313b Upgrade tapsaff to 0.2.0 (#14137) 2018-04-28 23:16:34 +02:00
Fabian Affolter
95f2ad2299 Upgrade sqlalchemy to 1.2.7 (#14138) 2018-04-28 23:16:01 +02:00
Fabian Affolter
7bdd4dd960 Upgrade pylast to 2.2.0 (#14139) 2018-04-28 23:15:32 +02:00
Anders Melchiorsen
e6d4501ee3 Fix color setting of tplink lights (#14108) 2018-04-28 17:12:11 -04:00
Paulus Schoutsen
93fe61bf13 System log: make firing event optional (#14102)
* Syste log: make firing event optional

* Add test

* Lint

* Doc string
2018-04-28 17:09:38 -04:00
Charles Garwood
b352b761f3 Bump pyvizio to 0.0.3 (#14147)
* Bumping pyvizio version

* Bump pyvizio version
2018-04-28 21:05:27 +02:00
Marcus
8d87b9fed5 Logitech Pop support for emulated_hue component (#12833)
* Update hue_api.py

add dummy group handler for logitech-pop

* Update __init__.py

add HueGroupView for logitech pop

* Update __init__.py

removed whitespace on blankline

* fix line limit and space

* fix indents

* fix more docstring and formatting issues.

* fix more whitespace issues

* Fix pylint issue
2018-04-28 20:39:21 +02:00
Fabian Affolter
ea5c336ab4 Upgrade restrictedpython to 4.0b3 (#14140) 2018-04-28 19:21:37 +02:00
Maciej Bieniek
c78e8eb578 Add support for light sensors with 'lx' unit to HomeKit (#14131)
* add support for light sensors with lx unit

* add test for light sensor with 'lx' unit
2018-04-28 17:14:34 +02:00
Aaron Bach
8bc497ba1d Move RainMachine to component/hub model (#14085)
* Moves RainMachine to component/hub model

* Updated requirements

* Updated coverage

* Hound violations

* Collaborator-requested changes

* Small formatting updates

* Removed references to remote API

* Collaborator-requested changes

* Collaborator-requested changes

* Fixed attribution
2018-04-28 15:46:58 +02:00
Fabian Affolter
1d41321f8f Upgrade colorlog to 3.1.4 (#14132) 2018-04-28 14:03:09 +02:00
ratcash
00706ad90c Support Xiaomi Mijia Bluetooth Wireless Temperature and Humidity Sensor (#13955) 2018-04-28 13:35:51 +02:00
Colin O'Dell
2749ca4ef4 Update QNAP lib to 0.2.6; handle null temps gracefully (#14117)
There's one particular QNAP model which sometimes return empty/null temperatures
for certain disks. This commit ensures that this model can be integrated with HASS
without causing KeyErrors or other exceptions - if this edge case is hit, the
sensor will simply show `0` instead.
2018-04-28 12:39:45 +02:00
Sebastian Muszynski
58ae8d91f9 Fix the optional friendly name of the Yeelight (Closes: #14088) (#14110) 2018-04-28 12:35:19 +02:00
Matthew Garrett
7e39a5c4d5 Change Eufy brightness handling (#14111)
Eufy device state isn't reported if the bulb is off, so avoid stamping on
the previous values if the bulb isn't going to give us useful information.
In addition, improve handling of bulb turn on if we aren't provided with a
brightness - this should avoid the bulb tending to end up with a brightness of
1 after power cycling.
2018-04-27 16:39:06 -04:00
Anders Melchiorsen
0b350993b5 Improve precision of Hue color state (#14113) 2018-04-27 13:18:58 +02:00
Otto Winter
9d1f9fe204 Improve MQTT topic validation (#14099)
* Improve MQTT topic validation

* Fix test

* Improve length check
2018-04-27 13:15:45 +02:00
Kane610
4b06392442 Zone component config entry support (#14059)
* Initial commit

* Add error handling to config flow
Change unique identifyer to name
Clean up hound comments

* Ensure hass home zone is created with correct entity id
Fix failing tests

* Fix rest of tests

* Move zone tests to zone folder
Create config flow tests

* Add possibility to unload entry

* Use hass.data instead of globas

* Don't calculate configures zones every loop iteration

* No need to know about home zone during setup of entry

* Only use name as title

* Don't cache hass home zone

* Add new tests for setup and setup entry

* Break out functionality from init to zone.py

* Make hass home zone be created directly

* Make sure that config flow doesn't override hass home zone

* A newline was missing in const

* Configured zones shall not be imported
Removed config flow import functionality
Improved tests
2018-04-26 17:59:22 -04:00
Paulus Schoutsen
f5de2b9e5b Bump frontend to 20180426 2018-04-26 16:39:14 -04:00
Robin
3e18078700 Adds update file_path service to local_file camera (#13976)
* WIP: Add update_file service to local_file camera

* Add event on update

* Update local_file.py

* Update services.yaml

* Fix indent

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update local_file.py

* Update test_local_file.py

* Update local_file.py

* Adds file_path to device_state_attributes

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update local_file.py

* Update test_local_file.py

* fixed test_update_file_path

* Update local_file.py

* Update test_local_file.py

* Update test_local_file.py

* Update services.yaml

* Update local_file.py

* Update local_file.py

* Update test_local_file.py

* Update local_file.py
2018-04-26 15:01:58 -04:00
GotoCode
ff7b51259e Updated list of AWS regions for Amazon Polly (#14097)
Fixes #14052
2018-04-26 19:35:28 +02:00
Daniel Perna
47e143d5a1 Update pyhomematic to 0.1.42 (#14095)
* Updated pyhomematic to 0.1.42

* Updated pyhomematic to 0.1.42
2018-04-26 19:30:28 +02:00
Daniel Høyer Iversen
d7f7735490 Fix timezone issue when calculating min/max values in tibber #14009 (#14080)
* fix timezone issue in tibber #14009

* remove debug print
2018-04-26 09:49:35 +02:00
Mattias Welponer
8c2dedab52 Re-implement HomematicIP cloud to async (#13468)
* Recode to async version of homematicip-rest-api

* Remove blank line

* Cleanup of access point status class

* Fix to loong line

* Fix import errors

* Bugfix missing wait the _retry_task for sleep command

* Update comment

* Updates after review

* Small updates of logging and property name

* Fix DOMAIN and revert back to lowercase snakecase strings

* Fix intention and tripple double quotes

* Fix travis build

* Remove unnecessary state attributes

* Fix optional name in configuration

* Further reduction of state attributes
2018-04-25 15:57:44 -04:00
Anders Melchiorsen
241a0793bb Add Sonos device attribute with grouping information (#13553) 2018-04-25 20:31:42 +02:00
c727
a94864c86f Modify weather components for "new" frontend card (#14076)
* Enable weather condition for all forecasts (OWM)

* Remove entity_picture from BR

* Remove summary texts from Dark Sky

* Update test_darksky.py
2018-04-25 12:37:57 +02:00
Mitko Masarliev
f23f9465d3 New sensor domain expiry (#14067)
* domain expiry

* domain expiry

* domain expiry

* scan interval

* change host to domain
2018-04-25 12:33:47 +02:00
Thijs de Jong
558b659f7c Add devices to Tahoma (#14075) 2018-04-25 07:09:45 +02:00
Kerwin Bryant
0a0d34d394 Support new Xiaomi Aqara device model names and LAN protocol 2.0 (#13540) 2018-04-25 07:05:00 +02:00
Paulus Schoutsen
75fffb6a86 Bump frontend to 20180425.0 2018-04-24 23:18:28 -04:00
stephanerosi
4e97954bbe Remove excessive debugging in webostv module (#14056) 2018-04-24 22:45:57 -04:00
Daniel Høyer Iversen
18137733f9 Upgrade broadlink lib (#14074) 2018-04-24 22:45:16 -04:00
thelittlefireman
ca29224846 Bump locationsharinglib to 1.2.2 (#14070)
* Bump locationsharinglib to 1.2.2

* Bump locationsharinglib to 1.2.2
2018-04-24 18:46:17 +02:00
John Mihalic
31554e8368 Bump pyEight version to update API & reduce connection issues (#14058) 2018-04-23 22:43:59 +02:00
Paulus Schoutsen
5ed73fecd3 Order the output of the automation editor (#14019)
* Order the output of the automation editor

* Lint
2018-04-23 13:47:06 -04:00
Kane610
8a10fcd985 deCONZ use forward entry setup (#13990)
* Use forward entry setup with light platform

* Move sensor to forward entry setup

* Use forward entry setup with binary sensors

* Use forward entry setup with scene platform

* Remove import of unused functionality

* Move deconz setup in to setup entry
Create initial negative tests for setup entry

* Fix hound comment

* Improved tests

* Add test for scene platform

* Add test for binary sensor platform

* Add test for light platform

* Add test for light platform

* Add test for sensor platform

* Fix hound comment

* More asserts on sensor types
2018-04-23 12:00:16 -04:00
Mark Coombes
5fe4053021 Update device classes for contact sensor HomeKit (#14051) 2018-04-23 13:52:39 +02:00
Matthew Garrett
e4cb3af76d Handle HomeKit configuration failure more cleanly (#14041)
* Handle HomeKit configuration failure more cleanly

Add support for handling cases where HomeKit configuration fails, and give
the user more information about what to do.

* Don't consume the exception for a homekit.UnknownError

If we get an UnknownError then we should alert the user but also still
generate the backtrace so there's actually something for them to file in
a bug report.
2018-04-22 16:38:01 -04:00
Otto Winter
7f634c6ed0 Revert cast platform polling mode (#14027) 2018-04-22 16:32:15 -04:00
Paulus Schoutsen
5d3471269a Show a notification when a config entry is discovered (#14022)
* Show a notification when a config entry is discovered

* update comment

* Inline functions

* Lint
2018-04-22 21:00:24 +02:00
Stijn Tintel
1fbc650871 device_tracker.ubus: catch ConnectionError (#14045)
When an OpenWrt device monitored via ubus is offline, this causes the
log to be flooded with several exceptions. Avoid this by catching
requests.exceptions.ConnectionError in addition to
requests.exceptions.Timeout.

Signed-off-by: Stijn Tintel <stijn@linux-ipv6.be>
2018-04-22 12:55:45 +02:00
David Broadfoot
86374ad809 bump gogogate2 version (#14044)
* bump gogogate2 version

* Update - requirements_all
2018-04-22 12:54:48 +02:00
Ryan Bahm
c2bee496e2 Add Accuracy to Google Location Sharing (#14039)
* Update locationsharinglib to 1.2.1 and add accuracy.

* Change indents to match HA style
2018-04-22 08:42:18 +02:00
Matt Schmitt
51f55bddb7 HomeKit Alarm Control Panel Code Exception Fix (#14025)
* Catch exception for KeyError
* Use get and added test
2018-04-21 16:16:46 +02:00
Daniel Høyer Iversen
4c23a61853 upgrade rfxtrx lib, dimming support for Lighting3 (#14026) 2018-04-21 10:54:11 +02:00
Jon Maddox
f12ff6f297 Expose the condition code on condition sensors (#14011)
* expose the condition code on condition sensors

* 💄

* like thisss duh

* add test for condition_code

* It’s a string
2018-04-21 10:20:33 +02:00
Aaron Bach
cb490780c9 Pollen.com: Added attributes on top 3 allergens (#14018) 2018-04-21 10:16:52 +02:00
Johann Kellerman
6ccb83584e Qwikswitch binary sensors (#14008) 2018-04-21 08:34:42 +02:00
501 changed files with 16220 additions and 5798 deletions

View File

@@ -4,6 +4,8 @@ source = homeassistant
omit =
homeassistant/__main__.py
homeassistant/scripts/*.py
homeassistant/util/async.py
homeassistant/monkey_patch.py
homeassistant/helpers/typing.py
homeassistant/helpers/signal.py
@@ -29,7 +31,7 @@ omit =
homeassistant/components/arduino.py
homeassistant/components/*/arduino.py
homeassistant/components/bmw_connected_drive.py
homeassistant/components/bmw_connected_drive/*.py
homeassistant/components/*/bmw_connected_drive.py
homeassistant/components/android_ip_webcam.py
@@ -127,7 +129,7 @@ omit =
homeassistant/components/insteon_local.py
homeassistant/components/*/insteon_local.py
homeassistant/components/insteon_plm.py
homeassistant/components/insteon_plm/*
homeassistant/components/*/insteon_plm.py
homeassistant/components/ios.py
@@ -151,6 +153,9 @@ omit =
homeassistant/components/knx.py
homeassistant/components/*/knx.py
homeassistant/components/konnected.py
homeassistant/components/*/konnected.py
homeassistant/components/lametric.py
homeassistant/components/*/lametric.py
@@ -166,6 +171,9 @@ omit =
homeassistant/components/mailgun.py
homeassistant/components/*/mailgun.py
homeassistant/components/matrix.py
homeassistant/components/*/matrix.py
homeassistant/components/maxcube.py
homeassistant/components/*/maxcube.py
@@ -208,6 +216,9 @@ omit =
homeassistant/components/raincloud.py
homeassistant/components/*/raincloud.py
homeassistant/components/rainmachine.py
homeassistant/components/*/rainmachine.py
homeassistant/components/raspihats.py
homeassistant/components/*/raspihats.py
@@ -220,6 +231,9 @@ omit =
homeassistant/components/rpi_pfio.py
homeassistant/components/*/rpi_pfio.py
homeassistant/components/sabnzbd.py
homeassistant/components/*/sabnzbd.py
homeassistant/components/satel_integra.py
homeassistant/components/*/satel_integra.py
@@ -336,6 +350,7 @@ omit =
homeassistant/components/calendar/todoist.py
homeassistant/components/camera/bloomsky.py
homeassistant/components/camera/canary.py
homeassistant/components/camera/familyhub.py
homeassistant/components/camera/ffmpeg.py
homeassistant/components/camera/foscam.py
homeassistant/components/camera/mjpeg.py
@@ -406,7 +421,6 @@ omit =
homeassistant/components/emoncms_history.py
homeassistant/components/emulated_hue/upnp.py
homeassistant/components/fan/mqtt.py
homeassistant/components/feedreader.py
homeassistant/components/folder_watcher.py
homeassistant/components/foursquare.py
homeassistant/components/goalfeed.py
@@ -516,7 +530,6 @@ omit =
homeassistant/components/notify/lannouncer.py
homeassistant/components/notify/llamalab_automate.py
homeassistant/components/notify/mastodon.py
homeassistant/components/notify/matrix.py
homeassistant/components/notify/message_bird.py
homeassistant/components/notify/mycroft.py
homeassistant/components/notify/nfandroidtv.py
@@ -529,7 +542,6 @@ omit =
homeassistant/components/notify/rest.py
homeassistant/components/notify/rocketchat.py
homeassistant/components/notify/sendgrid.py
homeassistant/components/notify/simplepush.py
homeassistant/components/notify/slack.py
homeassistant/components/notify/smtp.py
homeassistant/components/notify/stride.py
@@ -574,6 +586,7 @@ omit =
homeassistant/components/sensor/discogs.py
homeassistant/components/sensor/dnsip.py
homeassistant/components/sensor/dovado.py
homeassistant/components/sensor/domain_expiry.py
homeassistant/components/sensor/dte_energy_bridge.py
homeassistant/components/sensor/dublin_bus_transport.py
homeassistant/components/sensor/dwd_weather_warnings.py
@@ -586,6 +599,7 @@ omit =
homeassistant/components/sensor/fastdotcom.py
homeassistant/components/sensor/fedex.py
homeassistant/components/sensor/filesize.py
homeassistant/components/sensor/fints.py
homeassistant/components/sensor/fitbit.py
homeassistant/components/sensor/fixer.py
homeassistant/components/sensor/folder.py
@@ -615,6 +629,7 @@ omit =
homeassistant/components/sensor/lyft.py
homeassistant/components/sensor/metoffice.py
homeassistant/components/sensor/miflora.py
homeassistant/components/sensor/mitemp_bt.py
homeassistant/components/sensor/modem_callerid.py
homeassistant/components/sensor/mopar.py
homeassistant/components/sensor/mqtt_room.py
@@ -635,6 +650,7 @@ omit =
homeassistant/components/sensor/plex.py
homeassistant/components/sensor/pocketcasts.py
homeassistant/components/sensor/pollen.py
homeassistant/components/sensor/postnl.py
homeassistant/components/sensor/pushbullet.py
homeassistant/components/sensor/pvoutput.py
homeassistant/components/sensor/pyload.py
@@ -642,7 +658,6 @@ omit =
homeassistant/components/sensor/radarr.py
homeassistant/components/sensor/rainbird.py
homeassistant/components/sensor/ripple.py
homeassistant/components/sensor/sabnzbd.py
homeassistant/components/sensor/scrape.py
homeassistant/components/sensor/sense.py
homeassistant/components/sensor/sensehat.py
@@ -656,6 +671,7 @@ omit =
homeassistant/components/sensor/sma.py
homeassistant/components/sensor/snmp.py
homeassistant/components/sensor/sochain.py
homeassistant/components/sensor/socialblade.py
homeassistant/components/sensor/sonarr.py
homeassistant/components/sensor/speedtest.py
homeassistant/components/sensor/spotcrime.py
@@ -710,7 +726,6 @@ omit =
homeassistant/components/switch/orvibo.py
homeassistant/components/switch/pulseaudio_loopback.py
homeassistant/components/switch/rainbird.py
homeassistant/components/switch/rainmachine.py
homeassistant/components/switch/rest.py
homeassistant/components/switch/rpi_rf.py
homeassistant/components/switch/snmp.py

50
.github/ISSUE_TEMPLATE/Bug_report.md vendored Normal file
View File

@@ -0,0 +1,50 @@
---
name: Bug report
about: Create a report to help us improve
---
<!-- READ THIS FIRST:
- If you need additional help with this template please refer to https://www.home-assistant.io/help/reporting_issues/
- Make sure you are running the latest version of Home Assistant before reporting an issue: https://github.com/home-assistant/home-assistant/releases
- Do not report issues for components if you are using custom components: files in <config-dir>/custom_components
- This is for bugs only. Feature and enhancement requests should go in our community forum: https://community.home-assistant.io/c/feature-requests
- Provide as many details as possible. Paste logs, configuration sample and code into the backticks. Do not delete any text from this template!
-->
**Home Assistant release with the issue:**
<!--
- Frontend -> Developer tools -> Info
- Or use this command: hass --version
-->
**Last working Home Assistant release (if known):**
**Operating environment (Hass.io/Docker/Windows/etc.):**
<!--
Please provide details about your environment.
-->
**Component/platform:**
<!--
Please add the link to the documentation at https://www.home-assistant.io/components/ of the component/platform in question.
-->
**Description of problem:**
**Problem-relevant `configuration.yaml` entries and (fill out even if it seems unimportant):**
```yaml
```
**Traceback (if applicable):**
```
```
**Additional information:**

View File

@@ -10,8 +10,8 @@ matrix:
env: TOXENV=lint
- python: "3.5.3"
env: TOXENV=pylint
# - python: "3.5"
# env: TOXENV=typing
- python: "3.5.3"
env: TOXENV=typing
- python: "3.5.3"
env: TOXENV=py35
- python: "3.6"

View File

@@ -54,8 +54,11 @@ homeassistant/components/device_tracker/tile.py @bachya
homeassistant/components/history_graph.py @andrey-git
homeassistant/components/light/tplink.py @rytilahti
homeassistant/components/light/yeelight.py @rytilahti
homeassistant/components/lock/nello.py @pschmitt
homeassistant/components/lock/nuki.py @pschmitt
homeassistant/components/media_player/emby.py @mezz64
homeassistant/components/media_player/kodi.py @armills
homeassistant/components/media_player/liveboxplaytv.py @pschmitt
homeassistant/components/media_player/mediaroom.py @dgomes
homeassistant/components/media_player/monoprice.py @etsinko
homeassistant/components/media_player/sonos.py @amelchio
@@ -77,6 +80,7 @@ homeassistant/components/sensor/upnp.py @dgomes
homeassistant/components/sensor/waqi.py @andrey-git
homeassistant/components/switch/rainmachine.py @bachya
homeassistant/components/switch/tplink.py @rytilahti
homeassistant/components/vacuum/roomba.py @pschmitt
homeassistant/components/xiaomi_aqara.py @danielhiversen @syssi
homeassistant/components/*/axis.py @kane610
@@ -90,6 +94,10 @@ homeassistant/components/*/hive.py @Rendili @KJonline
homeassistant/components/homekit/* @cdce8p
homeassistant/components/knx.py @Julius2342
homeassistant/components/*/knx.py @Julius2342
homeassistant/components/konnected.py @heythisisnate
homeassistant/components/*/konnected.py @heythisisnate
homeassistant/components/matrix.py @tinloaf
homeassistant/components/*/matrix.py @tinloaf
homeassistant/components/qwikswitch.py @kellerza
homeassistant/components/*/qwikswitch.py @kellerza
homeassistant/components/*/rfxtrx.py @danielhiversen

View File

@@ -8,7 +8,8 @@ import subprocess
import sys
import threading
from typing import Optional, List
from typing import Optional, List, Dict, Any # noqa #pylint: disable=unused-import
from homeassistant import monkey_patch
from homeassistant.const import (
@@ -259,7 +260,7 @@ def setup_and_run_hass(config_dir: str,
config = {
'frontend': {},
'demo': {}
}
} # type: Dict[str, Any]
hass = bootstrap.from_config_dict(
config, config_dir=config_dir, verbose=args.verbose,
skip_pip=args.skip_pip, log_rotate_days=args.log_rotate_days,

503
homeassistant/auth.py Normal file
View File

@@ -0,0 +1,503 @@
"""Provide an authentication layer for Home Assistant."""
import asyncio
import binascii
from collections import OrderedDict
from datetime import datetime, timedelta
import os
import importlib
import logging
import uuid
import attr
import voluptuous as vol
from voluptuous.humanize import humanize_error
from homeassistant import data_entry_flow, requirements
from homeassistant.core import callback
from homeassistant.const import CONF_TYPE, CONF_NAME, CONF_ID
from homeassistant.util.decorator import Registry
from homeassistant.util import dt as dt_util
_LOGGER = logging.getLogger(__name__)
AUTH_PROVIDERS = Registry()
AUTH_PROVIDER_SCHEMA = vol.Schema({
vol.Required(CONF_TYPE): str,
vol.Optional(CONF_NAME): str,
# Specify ID if you have two auth providers for same type.
vol.Optional(CONF_ID): str,
}, extra=vol.ALLOW_EXTRA)
ACCESS_TOKEN_EXPIRATION = timedelta(minutes=30)
DATA_REQS = 'auth_reqs_processed'
def generate_secret(entropy: int = 32) -> str:
"""Generate a secret.
Backport of secrets.token_hex from Python 3.6
Event loop friendly.
"""
return binascii.hexlify(os.urandom(entropy)).decode('ascii')
class AuthProvider:
"""Provider of user authentication."""
DEFAULT_TITLE = 'Unnamed auth provider'
initialized = False
def __init__(self, hass, store, config):
"""Initialize an auth provider."""
self.hass = hass
self.store = store
self.config = config
@property
def id(self): # pylint: disable=invalid-name
"""Return id of the auth provider.
Optional, can be None.
"""
return self.config.get(CONF_ID)
@property
def type(self):
"""Return type of the provider."""
return self.config[CONF_TYPE]
@property
def name(self):
"""Return the name of the auth provider."""
return self.config.get(CONF_NAME, self.DEFAULT_TITLE)
async def async_credentials(self):
"""Return all credentials of this provider."""
return await self.store.credentials_for_provider(self.type, self.id)
@callback
def async_create_credentials(self, data):
"""Create credentials."""
return Credentials(
auth_provider_type=self.type,
auth_provider_id=self.id,
data=data,
)
# Implement by extending class
async def async_initialize(self):
"""Initialize the auth provider.
Optional.
"""
async def async_credential_flow(self):
"""Return the data flow for logging in with auth provider."""
raise NotImplementedError
async def async_get_or_create_credentials(self, flow_result):
"""Get credentials based on the flow result."""
raise NotImplementedError
async def async_user_meta_for_credentials(self, credentials):
"""Return extra user metadata for credentials.
Will be used to populate info when creating a new user.
"""
return {}
@attr.s(slots=True)
class User:
"""A user."""
id = attr.ib(type=str, default=attr.Factory(lambda: uuid.uuid4().hex))
is_owner = attr.ib(type=bool, default=False)
is_active = attr.ib(type=bool, default=False)
name = attr.ib(type=str, default=None)
# For persisting and see if saved?
# store = attr.ib(type=AuthStore, default=None)
# List of credentials of a user.
credentials = attr.ib(type=list, default=attr.Factory(list))
# Tokens associated with a user.
refresh_tokens = attr.ib(type=dict, default=attr.Factory(dict))
def as_dict(self):
"""Convert user object to a dictionary."""
return {
'id': self.id,
'is_owner': self.is_owner,
'is_active': self.is_active,
'name': self.name,
}
@attr.s(slots=True)
class RefreshToken:
"""RefreshToken for a user to grant new access tokens."""
user = attr.ib(type=User)
client_id = attr.ib(type=str)
id = attr.ib(type=str, default=attr.Factory(lambda: uuid.uuid4().hex))
created_at = attr.ib(type=datetime, default=attr.Factory(dt_util.utcnow))
access_token_expiration = attr.ib(type=timedelta,
default=ACCESS_TOKEN_EXPIRATION)
token = attr.ib(type=str,
default=attr.Factory(lambda: generate_secret(64)))
access_tokens = attr.ib(type=list, default=attr.Factory(list))
@attr.s(slots=True)
class AccessToken:
"""Access token to access the API.
These will only ever be stored in memory and not be persisted.
"""
refresh_token = attr.ib(type=RefreshToken)
created_at = attr.ib(type=datetime, default=attr.Factory(dt_util.utcnow))
token = attr.ib(type=str,
default=attr.Factory(generate_secret))
@property
def expires(self):
"""Return datetime when this token expires."""
return self.created_at + self.refresh_token.access_token_expiration
@attr.s(slots=True)
class Credentials:
"""Credentials for a user on an auth provider."""
auth_provider_type = attr.ib(type=str)
auth_provider_id = attr.ib(type=str)
# Allow the auth provider to store data to represent their auth.
data = attr.ib(type=dict)
id = attr.ib(type=str, default=attr.Factory(lambda: uuid.uuid4().hex))
is_new = attr.ib(type=bool, default=True)
@attr.s(slots=True)
class Client:
"""Client that interacts with Home Assistant on behalf of a user."""
name = attr.ib(type=str)
id = attr.ib(type=str, default=attr.Factory(lambda: uuid.uuid4().hex))
secret = attr.ib(type=str, default=attr.Factory(generate_secret))
redirect_uris = attr.ib(type=list, default=attr.Factory(list))
async def load_auth_provider_module(hass, provider):
"""Load an auth provider."""
try:
module = importlib.import_module(
'homeassistant.auth_providers.{}'.format(provider))
except ImportError:
_LOGGER.warning('Unable to find auth provider %s', provider)
return None
if hass.config.skip_pip or not hasattr(module, 'REQUIREMENTS'):
return module
processed = hass.data.get(DATA_REQS)
if processed is None:
processed = hass.data[DATA_REQS] = set()
elif provider in processed:
return module
req_success = await requirements.async_process_requirements(
hass, 'auth provider {}'.format(provider), module.REQUIREMENTS)
if not req_success:
return None
return module
async def auth_manager_from_config(hass, provider_configs):
"""Initialize an auth manager from config."""
store = AuthStore(hass)
if provider_configs:
providers = await asyncio.gather(
*[_auth_provider_from_config(hass, store, config)
for config in provider_configs])
else:
providers = []
# So returned auth providers are in same order as config
provider_hash = OrderedDict()
for provider in providers:
if provider is None:
continue
key = (provider.type, provider.id)
if key in provider_hash:
_LOGGER.error(
'Found duplicate provider: %s. Please add unique IDs if you '
'want to have the same provider twice.', key)
continue
provider_hash[key] = provider
manager = AuthManager(hass, store, provider_hash)
return manager
async def _auth_provider_from_config(hass, store, config):
"""Initialize an auth provider from a config."""
provider_name = config[CONF_TYPE]
module = await load_auth_provider_module(hass, provider_name)
if module is None:
return None
try:
config = module.CONFIG_SCHEMA(config)
except vol.Invalid as err:
_LOGGER.error('Invalid configuration for auth provider %s: %s',
provider_name, humanize_error(config, err))
return None
return AUTH_PROVIDERS[provider_name](hass, store, config)
class AuthManager:
"""Manage the authentication for Home Assistant."""
def __init__(self, hass, store, providers):
"""Initialize the auth manager."""
self._store = store
self._providers = providers
self.login_flow = data_entry_flow.FlowManager(
hass, self._async_create_login_flow,
self._async_finish_login_flow)
self.access_tokens = {}
@property
def async_auth_providers(self):
"""Return a list of available auth providers."""
return self._providers.values()
async def async_get_user(self, user_id):
"""Retrieve a user."""
return await self._store.async_get_user(user_id)
async def async_get_or_create_user(self, credentials):
"""Get or create a user."""
return await self._store.async_get_or_create_user(
credentials, self._async_get_auth_provider(credentials))
async def async_link_user(self, user, credentials):
"""Link credentials to an existing user."""
await self._store.async_link_user(user, credentials)
async def async_remove_user(self, user):
"""Remove a user."""
await self._store.async_remove_user(user)
async def async_create_refresh_token(self, user, client_id):
"""Create a new refresh token for a user."""
return await self._store.async_create_refresh_token(user, client_id)
async def async_get_refresh_token(self, token):
"""Get refresh token by token."""
return await self._store.async_get_refresh_token(token)
@callback
def async_create_access_token(self, refresh_token):
"""Create a new access token."""
access_token = AccessToken(refresh_token)
self.access_tokens[access_token.token] = access_token
return access_token
@callback
def async_get_access_token(self, token):
"""Get an access token."""
return self.access_tokens.get(token)
async def async_create_client(self, name, *, redirect_uris=None,
no_secret=False):
"""Create a new client."""
return await self._store.async_create_client(
name, redirect_uris, no_secret)
async def async_get_client(self, client_id):
"""Get a client."""
return await self._store.async_get_client(client_id)
async def _async_create_login_flow(self, handler, *, source, data):
"""Create a login flow."""
auth_provider = self._providers[handler]
if not auth_provider.initialized:
auth_provider.initialized = True
await auth_provider.async_initialize()
return await auth_provider.async_credential_flow()
async def _async_finish_login_flow(self, result):
"""Result of a credential login flow."""
if result['type'] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY:
return None
auth_provider = self._providers[result['handler']]
return await auth_provider.async_get_or_create_credentials(
result['data'])
@callback
def _async_get_auth_provider(self, credentials):
"""Helper to get auth provider from a set of credentials."""
auth_provider_key = (credentials.auth_provider_type,
credentials.auth_provider_id)
return self._providers[auth_provider_key]
class AuthStore:
"""Stores authentication info.
Any mutation to an object should happen inside the auth store.
The auth store is lazy. It won't load the data from disk until a method is
called that needs it.
"""
def __init__(self, hass):
"""Initialize the auth store."""
self.hass = hass
self.users = None
self.clients = None
self._load_lock = asyncio.Lock(loop=hass.loop)
async def credentials_for_provider(self, provider_type, provider_id):
"""Return credentials for specific auth provider type and id."""
if self.users is None:
await self.async_load()
return [
credentials
for user in self.users.values()
for credentials in user.credentials
if (credentials.auth_provider_type == provider_type and
credentials.auth_provider_id == provider_id)
]
async def async_get_user(self, user_id):
"""Retrieve a user."""
if self.users is None:
await self.async_load()
return self.users.get(user_id)
async def async_get_or_create_user(self, credentials, auth_provider):
"""Get or create a new user for given credentials.
If link_user is passed in, the credentials will be linked to the passed
in user if the credentials are new.
"""
if self.users is None:
await self.async_load()
# New credentials, store in user
if credentials.is_new:
info = await auth_provider.async_user_meta_for_credentials(
credentials)
# Make owner and activate user if it's the first user.
if self.users:
is_owner = False
is_active = False
else:
is_owner = True
is_active = True
new_user = User(
is_owner=is_owner,
is_active=is_active,
name=info.get('name'),
)
self.users[new_user.id] = new_user
await self.async_link_user(new_user, credentials)
return new_user
for user in self.users.values():
for creds in user.credentials:
if (creds.auth_provider_type == credentials.auth_provider_type
and creds.auth_provider_id ==
credentials.auth_provider_id):
return user
raise ValueError('We got credentials with ID but found no user')
async def async_link_user(self, user, credentials):
"""Add credentials to an existing user."""
user.credentials.append(credentials)
await self.async_save()
credentials.is_new = False
async def async_remove_user(self, user):
"""Remove a user."""
self.users.pop(user.id)
await self.async_save()
async def async_create_refresh_token(self, user, client_id):
"""Create a new token for a user."""
refresh_token = RefreshToken(user, client_id)
user.refresh_tokens[refresh_token.token] = refresh_token
await self.async_save()
return refresh_token
async def async_get_refresh_token(self, token):
"""Get refresh token by token."""
if self.users is None:
await self.async_load()
for user in self.users.values():
refresh_token = user.refresh_tokens.get(token)
if refresh_token is not None:
return refresh_token
return None
async def async_create_client(self, name, redirect_uris, no_secret):
"""Create a new client."""
if self.clients is None:
await self.async_load()
kwargs = {
'name': name,
'redirect_uris': redirect_uris
}
if no_secret:
kwargs['secret'] = None
client = Client(**kwargs)
self.clients[client.id] = client
await self.async_save()
return client
async def async_get_client(self, client_id):
"""Get a client."""
if self.clients is None:
await self.async_load()
return self.clients.get(client_id)
async def async_load(self):
"""Load the users."""
async with self._load_lock:
self.users = {}
self.clients = {}
async def async_save(self):
"""Save users."""
pass

View File

@@ -0,0 +1 @@
"""Auth providers for Home Assistant."""

View File

@@ -0,0 +1,181 @@
"""Home Assistant auth provider."""
import base64
from collections import OrderedDict
import hashlib
import hmac
import voluptuous as vol
from homeassistant import auth, data_entry_flow
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util import json
PATH_DATA = '.users.json'
CONFIG_SCHEMA = auth.AUTH_PROVIDER_SCHEMA.extend({
}, extra=vol.PREVENT_EXTRA)
class InvalidAuth(HomeAssistantError):
"""Raised when we encounter invalid authentication."""
class InvalidUser(HomeAssistantError):
"""Raised when invalid user is specified.
Will not be raised when validating authentication.
"""
class Data:
"""Hold the user data."""
def __init__(self, path, data):
"""Initialize the user data store."""
self.path = path
if data is None:
data = {
'salt': auth.generate_secret(),
'users': []
}
self._data = data
@property
def users(self):
"""Return users."""
return self._data['users']
def validate_login(self, username, password):
"""Validate a username and password.
Raises InvalidAuth if auth invalid.
"""
password = self.hash_password(password)
found = None
# Compare all users to avoid timing attacks.
for user in self._data['users']:
if username == user['username']:
found = user
if found is None:
# Do one more compare to make timing the same as if user was found.
hmac.compare_digest(password, password)
raise InvalidAuth
if not hmac.compare_digest(password,
base64.b64decode(found['password'])):
raise InvalidAuth
def hash_password(self, password, for_storage=False):
"""Encode a password."""
hashed = hashlib.pbkdf2_hmac(
'sha512', password.encode(), self._data['salt'].encode(), 100000)
if for_storage:
hashed = base64.b64encode(hashed).decode()
return hashed
def add_user(self, username, password):
"""Add a user."""
if any(user['username'] == username for user in self.users):
raise InvalidUser
self.users.append({
'username': username,
'password': self.hash_password(password, True),
})
def change_password(self, username, new_password):
"""Update the password of a user.
Raises InvalidUser if user cannot be found.
"""
for user in self.users:
if user['username'] == username:
user['password'] = self.hash_password(new_password, True)
break
else:
raise InvalidUser
def save(self):
"""Save data."""
json.save_json(self.path, self._data)
def load_data(path):
"""Load auth data."""
return Data(path, json.load_json(path, None))
@auth.AUTH_PROVIDERS.register('homeassistant')
class HassAuthProvider(auth.AuthProvider):
"""Auth provider based on a local storage of users in HASS config dir."""
DEFAULT_TITLE = 'Home Assistant Local'
async def async_credential_flow(self):
"""Return a flow to login."""
return LoginFlow(self)
async def async_validate_login(self, username, password):
"""Helper to validate a username and password."""
def validate():
"""Validate creds."""
data = self._auth_data()
data.validate_login(username, password)
await self.hass.async_add_job(validate)
async def async_get_or_create_credentials(self, flow_result):
"""Get credentials based on the flow result."""
username = flow_result['username']
for credential in await self.async_credentials():
if credential.data['username'] == username:
return credential
# Create new credentials.
return self.async_create_credentials({
'username': username
})
def _auth_data(self):
"""Return the auth provider data."""
return load_data(self.hass.config.path(PATH_DATA))
class LoginFlow(data_entry_flow.FlowHandler):
"""Handler for the login flow."""
def __init__(self, auth_provider):
"""Initialize the login flow."""
self._auth_provider = auth_provider
async def async_step_init(self, user_input=None):
"""Handle the step of the form."""
errors = {}
if user_input is not None:
try:
await self._auth_provider.async_validate_login(
user_input['username'], user_input['password'])
except InvalidAuth:
errors['base'] = 'invalid_auth'
if not errors:
return self.async_create_entry(
title=self._auth_provider.name,
data=user_input
)
schema = OrderedDict()
schema['username'] = str
schema['password'] = str
return self.async_show_form(
step_id='init',
data_schema=vol.Schema(schema),
errors=errors,
)

View File

@@ -0,0 +1,118 @@
"""Example auth provider."""
from collections import OrderedDict
import hmac
import voluptuous as vol
from homeassistant.exceptions import HomeAssistantError
from homeassistant import auth, data_entry_flow
from homeassistant.core import callback
USER_SCHEMA = vol.Schema({
vol.Required('username'): str,
vol.Required('password'): str,
vol.Optional('name'): str,
})
CONFIG_SCHEMA = auth.AUTH_PROVIDER_SCHEMA.extend({
vol.Required('users'): [USER_SCHEMA]
}, extra=vol.PREVENT_EXTRA)
class InvalidAuthError(HomeAssistantError):
"""Raised when submitting invalid authentication."""
@auth.AUTH_PROVIDERS.register('insecure_example')
class ExampleAuthProvider(auth.AuthProvider):
"""Example auth provider based on hardcoded usernames and passwords."""
async def async_credential_flow(self):
"""Return a flow to login."""
return LoginFlow(self)
@callback
def async_validate_login(self, username, password):
"""Helper to validate a username and password."""
user = None
# Compare all users to avoid timing attacks.
for usr in self.config['users']:
if hmac.compare_digest(username.encode('utf-8'),
usr['username'].encode('utf-8')):
user = usr
if user is None:
# Do one more compare to make timing the same as if user was found.
hmac.compare_digest(password.encode('utf-8'),
password.encode('utf-8'))
raise InvalidAuthError
if not hmac.compare_digest(user['password'].encode('utf-8'),
password.encode('utf-8')):
raise InvalidAuthError
async def async_get_or_create_credentials(self, flow_result):
"""Get credentials based on the flow result."""
username = flow_result['username']
for credential in await self.async_credentials():
if credential.data['username'] == username:
return credential
# Create new credentials.
return self.async_create_credentials({
'username': username
})
async def async_user_meta_for_credentials(self, credentials):
"""Return extra user metadata for credentials.
Will be used to populate info when creating a new user.
"""
username = credentials.data['username']
for user in self.config['users']:
if user['username'] == username:
return {
'name': user.get('name')
}
return {}
class LoginFlow(data_entry_flow.FlowHandler):
"""Handler for the login flow."""
def __init__(self, auth_provider):
"""Initialize the login flow."""
self._auth_provider = auth_provider
async def async_step_init(self, user_input=None):
"""Handle the step of the form."""
errors = {}
if user_input is not None:
try:
self._auth_provider.async_validate_login(
user_input['username'], user_input['password'])
except InvalidAuthError:
errors['base'] = 'invalid_auth'
if not errors:
return self.async_create_entry(
title=self._auth_provider.name,
data=user_input
)
schema = OrderedDict()
schema['username'] = str
schema['password'] = str
return self.async_show_form(
step_id='init',
data_schema=vol.Schema(schema),
errors=errors,
)

View File

@@ -12,8 +12,7 @@ from typing import Any, Optional, Dict
import voluptuous as vol
from homeassistant import (
core, config as conf_util, config_entries, loader,
components as core_components)
core, config as conf_util, config_entries, components as core_components)
from homeassistant.components import persistent_notification
from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE
from homeassistant.setup import async_setup_component
@@ -67,16 +66,15 @@ def from_config_dict(config: Dict[str, Any],
return hass
@asyncio.coroutine
def async_from_config_dict(config: Dict[str, Any],
hass: core.HomeAssistant,
config_dir: Optional[str] = None,
enable_log: bool = True,
verbose: bool = False,
skip_pip: bool = False,
log_rotate_days: Any = None,
log_file: Any = None,
log_no_color: bool = False) \
async def async_from_config_dict(config: Dict[str, Any],
hass: core.HomeAssistant,
config_dir: Optional[str] = None,
enable_log: bool = True,
verbose: bool = False,
skip_pip: bool = False,
log_rotate_days: Any = None,
log_file: Any = None,
log_no_color: bool = False) \
-> Optional[core.HomeAssistant]:
"""Try to configure Home Assistant from a configuration dictionary.
@@ -92,27 +90,24 @@ def async_from_config_dict(config: Dict[str, Any],
core_config = config.get(core.DOMAIN, {})
try:
yield from conf_util.async_process_ha_core_config(hass, core_config)
await conf_util.async_process_ha_core_config(hass, core_config)
except vol.Invalid as ex:
conf_util.async_log_exception(ex, 'homeassistant', core_config, hass)
return None
yield from hass.async_add_job(conf_util.process_ha_config_upgrade, hass)
await hass.async_add_job(conf_util.process_ha_config_upgrade, hass)
hass.config.skip_pip = skip_pip
if skip_pip:
_LOGGER.warning("Skipping pip installation of required modules. "
"This may cause issues")
if not loader.PREPARED:
yield from hass.async_add_job(loader.prepare, hass)
# Make a copy because we are mutating it.
config = OrderedDict(config)
# Merge packages
conf_util.merge_packages_config(
config, core_config.get(conf_util.CONF_PACKAGES, {}))
hass, config, core_config.get(conf_util.CONF_PACKAGES, {}))
# Ensure we have no None values after merge
for key, value in config.items():
@@ -120,7 +115,7 @@ def async_from_config_dict(config: Dict[str, Any],
config[key] = {}
hass.config_entries = config_entries.ConfigEntries(hass, config)
yield from hass.config_entries.async_load()
await hass.config_entries.async_load()
# Filter out the repeating and common config section [homeassistant]
components = set(key.split(' ')[0] for key in config.keys()
@@ -129,13 +124,13 @@ def async_from_config_dict(config: Dict[str, Any],
# setup components
# pylint: disable=not-an-iterable
res = yield from core_components.async_setup(hass, config)
res = await core_components.async_setup(hass, config)
if not res:
_LOGGER.error("Home Assistant core failed to initialize. "
"further initialization aborted")
return hass
yield from persistent_notification.async_setup(hass, config)
await persistent_notification.async_setup(hass, config)
_LOGGER.info("Home Assistant core initialized")
@@ -145,7 +140,7 @@ def async_from_config_dict(config: Dict[str, Any],
continue
hass.async_add_job(async_setup_component(hass, component, config))
yield from hass.async_block_till_done()
await hass.async_block_till_done()
# stage 2
for component in components:
@@ -153,7 +148,7 @@ def async_from_config_dict(config: Dict[str, Any],
continue
hass.async_add_job(async_setup_component(hass, component, config))
yield from hass.async_block_till_done()
await hass.async_block_till_done()
stop = time()
_LOGGER.info("Home Assistant initialized in %.2fs", stop-start)
@@ -187,14 +182,13 @@ def from_config_file(config_path: str,
return hass
@asyncio.coroutine
def async_from_config_file(config_path: str,
hass: core.HomeAssistant,
verbose: bool = False,
skip_pip: bool = True,
log_rotate_days: Any = None,
log_file: Any = None,
log_no_color: bool = False):
async def async_from_config_file(config_path: str,
hass: core.HomeAssistant,
verbose: bool = False,
skip_pip: bool = True,
log_rotate_days: Any = None,
log_file: Any = None,
log_no_color: bool = False):
"""Read the configuration file and try to start all the functionality.
Will add functionality to 'hass' parameter.
@@ -203,13 +197,13 @@ def async_from_config_file(config_path: str,
# Set config dir to directory holding config file
config_dir = os.path.abspath(os.path.dirname(config_path))
hass.config.config_dir = config_dir
yield from async_mount_local_lib_path(config_dir, hass.loop)
await async_mount_local_lib_path(config_dir, hass.loop)
async_enable_logging(hass, verbose, log_rotate_days, log_file,
log_no_color)
try:
config_dict = yield from hass.async_add_job(
config_dict = await hass.async_add_job(
conf_util.load_yaml_config_file, config_path)
except HomeAssistantError as err:
_LOGGER.error("Error loading %s: %s", config_path, err)
@@ -217,7 +211,7 @@ def async_from_config_file(config_path: str,
finally:
clear_secret_cache()
hass = yield from async_from_config_dict(
hass = await async_from_config_dict(
config_dict, hass, enable_log=False, skip_pip=skip_pip)
return hass
@@ -284,7 +278,8 @@ def async_enable_logging(hass: core.HomeAssistant,
if log_rotate_days:
err_handler = logging.handlers.TimedRotatingFileHandler(
err_log_path, when='midnight', backupCount=log_rotate_days)
err_log_path, when='midnight',
backupCount=log_rotate_days) # type: logging.FileHandler
else:
err_handler = logging.FileHandler(
err_log_path, mode='w', delay=True)
@@ -294,17 +289,16 @@ def async_enable_logging(hass: core.HomeAssistant,
async_handler = AsyncHandler(hass.loop, err_handler)
@asyncio.coroutine
def async_stop_async_handler(event):
async def async_stop_async_handler(event):
"""Cleanup async handler."""
logging.getLogger('').removeHandler(async_handler)
yield from async_handler.async_close(blocking=True)
await async_handler.async_close(blocking=True)
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_CLOSE, async_stop_async_handler)
logger = logging.getLogger('')
logger.addHandler(async_handler)
logger.addHandler(async_handler) # type: ignore
logger.setLevel(logging.INFO)
# Save the log file location for access by other components.
@@ -323,15 +317,14 @@ def mount_local_lib_path(config_dir: str) -> str:
return deps_dir
@asyncio.coroutine
def async_mount_local_lib_path(config_dir: str,
loop: asyncio.AbstractEventLoop) -> str:
async def async_mount_local_lib_path(config_dir: str,
loop: asyncio.AbstractEventLoop) -> str:
"""Add local library to Python Path.
This function is a coroutine.
"""
deps_dir = os.path.join(config_dir, 'deps')
lib_dir = yield from async_get_user_site(deps_dir, loop=loop)
lib_dir = await async_get_user_site(deps_dir, loop=loop)
if lib_dir not in sys.path:
sys.path.insert(0, lib_dir)
return deps_dir

View File

@@ -81,7 +81,7 @@ TRIGGER_SCHEMA = vol.Schema({
ABODE_PLATFORMS = [
'alarm_control_panel', 'binary_sensor', 'lock', 'switch', 'cover',
'camera', 'light'
'camera', 'light', 'sensor'
]

View File

@@ -17,7 +17,7 @@ from homeassistant.const import (
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pyalarmdotcom==0.3.1']
REQUIREMENTS = ['pyalarmdotcom==0.3.2']
_LOGGER = logging.getLogger(__name__)
@@ -93,6 +93,13 @@ class AlarmDotCom(alarm.AlarmControlPanel):
return STATE_ALARM_ARMED_AWAY
return STATE_UNKNOWN
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {
'sensor_status': self._alarm.sensor_status
}
@asyncio.coroutine
def async_alarm_disarm(self, code=None):
"""Send disarm command."""

View File

@@ -76,8 +76,7 @@ class APIEventStream(HomeAssistantView):
url = URL_API_STREAM
name = "api:stream"
@asyncio.coroutine
def get(self, request):
async def get(self, request):
"""Provide a streaming interface for the event bus."""
# pylint: disable=no-self-use
hass = request.app['hass']
@@ -88,8 +87,7 @@ class APIEventStream(HomeAssistantView):
if restrict:
restrict = restrict.split(',') + [EVENT_HOMEASSISTANT_STOP]
@asyncio.coroutine
def forward_events(event):
async def forward_events(event):
"""Forward events to the open request."""
if event.event_type == EVENT_TIME_CHANGED:
return
@@ -104,11 +102,11 @@ class APIEventStream(HomeAssistantView):
else:
data = json.dumps(event, cls=rem.JSONEncoder)
yield from to_write.put(data)
await to_write.put(data)
response = web.StreamResponse()
response.content_type = 'text/event-stream'
yield from response.prepare(request)
await response.prepare(request)
unsub_stream = hass.bus.async_listen(MATCH_ALL, forward_events)
@@ -116,13 +114,13 @@ class APIEventStream(HomeAssistantView):
_LOGGER.debug('STREAM %s ATTACHED', id(stop_obj))
# Fire off one message so browsers fire open event right away
yield from to_write.put(STREAM_PING_PAYLOAD)
await to_write.put(STREAM_PING_PAYLOAD)
while True:
try:
with async_timeout.timeout(STREAM_PING_INTERVAL,
loop=hass.loop):
payload = yield from to_write.get()
payload = await to_write.get()
if payload is stop_obj:
break
@@ -130,9 +128,9 @@ class APIEventStream(HomeAssistantView):
msg = "data: {}\n\n".format(payload)
_LOGGER.debug('STREAM %s WRITING %s', id(stop_obj),
msg.strip())
yield from response.write(msg.encode("UTF-8"))
await response.write(msg.encode("UTF-8"))
except asyncio.TimeoutError:
yield from to_write.put(STREAM_PING_PAYLOAD)
await to_write.put(STREAM_PING_PAYLOAD)
except asyncio.CancelledError:
_LOGGER.debug('STREAM %s ABORT', id(stop_obj))
@@ -200,12 +198,11 @@ class APIEntityStateView(HomeAssistantView):
return self.json(state)
return self.json_message('Entity not found', HTTP_NOT_FOUND)
@asyncio.coroutine
def post(self, request, entity_id):
async def post(self, request, entity_id):
"""Update state of entity."""
hass = request.app['hass']
try:
data = yield from request.json()
data = await request.json()
except ValueError:
return self.json_message('Invalid JSON specified',
HTTP_BAD_REQUEST)
@@ -257,10 +254,9 @@ class APIEventView(HomeAssistantView):
url = '/api/events/{event_type}'
name = "api:event"
@asyncio.coroutine
def post(self, request, event_type):
async def post(self, request, event_type):
"""Fire events."""
body = yield from request.text()
body = await request.text()
try:
event_data = json.loads(body) if body else None
except ValueError:
@@ -292,10 +288,9 @@ class APIServicesView(HomeAssistantView):
url = URL_API_SERVICES
name = "api:services"
@asyncio.coroutine
def get(self, request):
async def get(self, request):
"""Get registered services."""
services = yield from async_services_json(request.app['hass'])
services = await async_services_json(request.app['hass'])
return self.json(services)
@@ -305,14 +300,13 @@ class APIDomainServicesView(HomeAssistantView):
url = "/api/services/{domain}/{service}"
name = "api:domain-services"
@asyncio.coroutine
def post(self, request, domain, service):
async def post(self, request, domain, service):
"""Call a service.
Returns a list of changed states.
"""
hass = request.app['hass']
body = yield from request.text()
body = await request.text()
try:
data = json.loads(body) if body else None
except ValueError:
@@ -320,7 +314,7 @@ class APIDomainServicesView(HomeAssistantView):
HTTP_BAD_REQUEST)
with AsyncTrackStates(hass) as changed_states:
yield from hass.services.async_call(domain, service, data, True)
await hass.services.async_call(domain, service, data, True)
return self.json(changed_states)
@@ -343,11 +337,10 @@ class APITemplateView(HomeAssistantView):
url = URL_API_TEMPLATE
name = "api:template"
@asyncio.coroutine
def post(self, request):
async def post(self, request):
"""Render a template."""
try:
data = yield from request.json()
data = await request.json()
tpl = template.Template(data['template'], request.app['hass'])
return tpl.async_render(data.get('variables'))
except (ValueError, TemplateError) as ex:
@@ -363,13 +356,13 @@ class APIErrorLog(HomeAssistantView):
async def get(self, request):
"""Retrieve API error log."""
return await self.file(request, request.app['hass'].data[DATA_LOGGING])
return web.FileResponse(
request.app['hass'].data[DATA_LOGGING])
@asyncio.coroutine
def async_services_json(hass):
async def async_services_json(hass):
"""Generate services data to JSONify."""
descriptions = yield from async_get_all_descriptions(hass)
descriptions = await async_get_all_descriptions(hass)
return [{"domain": key, "services": value}
for key, value in descriptions.items()]

View File

@@ -0,0 +1,351 @@
"""Component to allow users to login and get tokens.
All requests will require passing in a valid client ID and secret via HTTP
Basic Auth.
# GET /auth/providers
Return a list of auth providers. Example:
[
{
"name": "Local",
"id": null,
"type": "local_provider",
}
]
# POST /auth/login_flow
Create a login flow. Will return the first step of the flow.
Pass in parameter 'handler' to specify the auth provider to use. Auth providers
are identified by type and id.
{
"handler": ["local_provider", null]
}
Return value will be a step in a data entry flow. See the docs for data entry
flow for details.
{
"data_schema": [
{"name": "username", "type": "string"},
{"name": "password", "type": "string"}
],
"errors": {},
"flow_id": "8f7e42faab604bcab7ac43c44ca34d58",
"handler": ["insecure_example", null],
"step_id": "init",
"type": "form"
}
# POST /auth/login_flow/{flow_id}
Progress the flow. Most flows will be 1 page, but could optionally add extra
login challenges, like TFA. Once the flow has finished, the returned step will
have type "create_entry" and "result" key will contain an authorization code.
{
"flow_id": "8f7e42faab604bcab7ac43c44ca34d58",
"handler": ["insecure_example", null],
"result": "411ee2f916e648d691e937ae9344681e",
"source": "user",
"title": "Example",
"type": "create_entry",
"version": 1
}
# POST /auth/token
This is an OAuth2 endpoint for granting tokens. We currently support the grant
types "authorization_code" and "refresh_token". Because we follow the OAuth2
spec, data should be send in formatted as x-www-form-urlencoded. Examples will
be in JSON as it's more readable.
## Grant type authorization_code
Exchange the authorization code retrieved from the login flow for tokens.
{
"grant_type": "authorization_code",
"code": "411ee2f916e648d691e937ae9344681e"
}
Return value will be the access and refresh tokens. The access token will have
a limited expiration. New access tokens can be requested using the refresh
token.
{
"access_token": "ABCDEFGH",
"expires_in": 1800,
"refresh_token": "IJKLMNOPQRST",
"token_type": "Bearer"
}
## Grant type refresh_token
Request a new access token using a refresh token.
{
"grant_type": "refresh_token",
"refresh_token": "IJKLMNOPQRST"
}
Return value will be a new access token. The access token will have
a limited expiration.
{
"access_token": "ABCDEFGH",
"expires_in": 1800,
"token_type": "Bearer"
}
"""
import logging
import uuid
import aiohttp.web
import voluptuous as vol
from homeassistant import data_entry_flow
from homeassistant.core import callback
from homeassistant.helpers.data_entry_flow import (
FlowManagerIndexView, FlowManagerResourceView)
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.components.http.data_validator import RequestDataValidator
from .client import verify_client
DOMAIN = 'auth'
DEPENDENCIES = ['http']
_LOGGER = logging.getLogger(__name__)
async def async_setup(hass, config):
"""Component to allow users to login."""
store_credentials, retrieve_credentials = _create_cred_store()
hass.http.register_view(AuthProvidersView)
hass.http.register_view(LoginFlowIndexView(hass.auth.login_flow))
hass.http.register_view(
LoginFlowResourceView(hass.auth.login_flow, store_credentials))
hass.http.register_view(GrantTokenView(retrieve_credentials))
hass.http.register_view(LinkUserView(retrieve_credentials))
return True
class AuthProvidersView(HomeAssistantView):
"""View to get available auth providers."""
url = '/auth/providers'
name = 'api:auth:providers'
requires_auth = False
@verify_client
async def get(self, request, client):
"""Get available auth providers."""
return self.json([{
'name': provider.name,
'id': provider.id,
'type': provider.type,
} for provider in request.app['hass'].auth.async_auth_providers])
class LoginFlowIndexView(FlowManagerIndexView):
"""View to create a config flow."""
url = '/auth/login_flow'
name = 'api:auth:login_flow'
requires_auth = False
async def get(self, request):
"""Do not allow index of flows in progress."""
return aiohttp.web.Response(status=405)
# pylint: disable=arguments-differ
@verify_client
@RequestDataValidator(vol.Schema({
vol.Required('handler'): vol.Any(str, list),
vol.Required('redirect_uri'): str,
}))
async def post(self, request, client, data):
"""Create a new login flow."""
if data['redirect_uri'] not in client.redirect_uris:
return self.json_message('invalid redirect uri', )
# pylint: disable=no-value-for-parameter
return await super().post(request)
class LoginFlowResourceView(FlowManagerResourceView):
"""View to interact with the flow manager."""
url = '/auth/login_flow/{flow_id}'
name = 'api:auth:login_flow:resource'
requires_auth = False
def __init__(self, flow_mgr, store_credentials):
"""Initialize the login flow resource view."""
super().__init__(flow_mgr)
self._store_credentials = store_credentials
# pylint: disable=arguments-differ
async def get(self, request):
"""Do not allow getting status of a flow in progress."""
return self.json_message('Invalid flow specified', 404)
# pylint: disable=arguments-differ
@verify_client
@RequestDataValidator(vol.Schema(dict), allow_empty=True)
async def post(self, request, client, flow_id, data):
"""Handle progressing a login flow request."""
try:
result = await self._flow_mgr.async_configure(flow_id, data)
except data_entry_flow.UnknownFlow:
return self.json_message('Invalid flow specified', 404)
except vol.Invalid:
return self.json_message('User input malformed', 400)
if result['type'] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY:
return self.json(self._prepare_result_json(result))
result.pop('data')
result['result'] = self._store_credentials(client.id, result['result'])
return self.json(result)
class GrantTokenView(HomeAssistantView):
"""View to grant tokens."""
url = '/auth/token'
name = 'api:auth:token'
requires_auth = False
def __init__(self, retrieve_credentials):
"""Initialize the grant token view."""
self._retrieve_credentials = retrieve_credentials
@verify_client
async def post(self, request, client):
"""Grant a token."""
hass = request.app['hass']
data = await request.post()
grant_type = data.get('grant_type')
if grant_type == 'authorization_code':
return await self._async_handle_auth_code(
hass, client.id, data)
elif grant_type == 'refresh_token':
return await self._async_handle_refresh_token(
hass, client.id, data)
return self.json({
'error': 'unsupported_grant_type',
}, status_code=400)
async def _async_handle_auth_code(self, hass, client_id, data):
"""Handle authorization code request."""
code = data.get('code')
if code is None:
return self.json({
'error': 'invalid_request',
}, status_code=400)
credentials = self._retrieve_credentials(client_id, code)
if credentials is None:
return self.json({
'error': 'invalid_request',
}, status_code=400)
user = await hass.auth.async_get_or_create_user(credentials)
refresh_token = await hass.auth.async_create_refresh_token(user,
client_id)
access_token = hass.auth.async_create_access_token(refresh_token)
return self.json({
'access_token': access_token.token,
'token_type': 'Bearer',
'refresh_token': refresh_token.token,
'expires_in':
int(refresh_token.access_token_expiration.total_seconds()),
})
async def _async_handle_refresh_token(self, hass, client_id, data):
"""Handle authorization code request."""
token = data.get('refresh_token')
if token is None:
return self.json({
'error': 'invalid_request',
}, status_code=400)
refresh_token = await hass.auth.async_get_refresh_token(token)
if refresh_token is None or refresh_token.client_id != client_id:
return self.json({
'error': 'invalid_grant',
}, status_code=400)
access_token = hass.auth.async_create_access_token(refresh_token)
return self.json({
'access_token': access_token.token,
'token_type': 'Bearer',
'expires_in':
int(refresh_token.access_token_expiration.total_seconds()),
})
class LinkUserView(HomeAssistantView):
"""View to link existing users to new credentials."""
url = '/auth/link_user'
name = 'api:auth:link_user'
def __init__(self, retrieve_credentials):
"""Initialize the link user view."""
self._retrieve_credentials = retrieve_credentials
@RequestDataValidator(vol.Schema({
'code': str,
'client_id': str,
}))
async def post(self, request, data):
"""Link a user."""
hass = request.app['hass']
user = request['hass_user']
credentials = self._retrieve_credentials(
data['client_id'], data['code'])
if credentials is None:
return self.json_message('Invalid code', status_code=400)
await hass.auth.async_link_user(user, credentials)
return self.json_message('User linked')
@callback
def _create_cred_store():
"""Create a credential store."""
temp_credentials = {}
@callback
def store_credentials(client_id, credentials):
"""Store credentials and return a code to retrieve it."""
code = uuid.uuid4().hex
temp_credentials[(client_id, code)] = credentials
return code
@callback
def retrieve_credentials(client_id, code):
"""Retrieve credentials."""
return temp_credentials.pop((client_id, code), None)
return store_credentials, retrieve_credentials

View File

@@ -0,0 +1,79 @@
"""Helpers to resolve client ID/secret."""
import base64
from functools import wraps
import hmac
import aiohttp.hdrs
def verify_client(method):
"""Decorator to verify client id/secret on requests."""
@wraps(method)
async def wrapper(view, request, *args, **kwargs):
"""Verify client id/secret before doing request."""
client = await _verify_client(request)
if client is None:
return view.json({
'error': 'invalid_client',
}, status_code=401)
return await method(
view, request, *args, **kwargs, client=client)
return wrapper
async def _verify_client(request):
"""Method to verify the client id/secret in consistent time.
By using a consistent time for looking up client id and comparing the
secret, we prevent attacks by malicious actors trying different client ids
and are able to derive from the time it takes to process the request if
they guessed the client id correctly.
"""
if aiohttp.hdrs.AUTHORIZATION not in request.headers:
return None
auth_type, auth_value = \
request.headers.get(aiohttp.hdrs.AUTHORIZATION).split(' ', 1)
if auth_type != 'Basic':
return None
decoded = base64.b64decode(auth_value).decode('utf-8')
try:
client_id, client_secret = decoded.split(':', 1)
except ValueError:
# If no ':' in decoded
client_id, client_secret = decoded, None
return await async_secure_get_client(
request.app['hass'], client_id, client_secret)
async def async_secure_get_client(hass, client_id, client_secret):
"""Get a client id/secret in consistent time."""
client = await hass.auth.async_get_client(client_id)
if client is None:
if client_secret is not None:
# Still do a compare so we run same time as if a client was found.
hmac.compare_digest(client_secret.encode('utf-8'),
client_secret.encode('utf-8'))
return None
if client.secret is None:
return client
elif client_secret is None:
# Still do a compare so we run same time as if a secret was passed.
hmac.compare_digest(client.secret.encode('utf-8'),
client.secret.encode('utf-8'))
return None
elif hmac.compare_digest(client_secret.encode('utf-8'),
client.secret.encode('utf-8')):
return client
return None

View File

@@ -6,6 +6,7 @@ https://home-assistant.io/components/automation/
"""
import asyncio
from functools import partial
import importlib
import logging
import voluptuous as vol
@@ -22,7 +23,6 @@ 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.loader import get_platform
from homeassistant.util.dt import utcnow
import homeassistant.helpers.config_validation as cv
@@ -58,12 +58,14 @@ _LOGGER = logging.getLogger(__name__)
def _platform_validator(config):
"""Validate it is a valid platform."""
platform = get_platform(DOMAIN, config[CONF_PLATFORM])
try:
platform = importlib.import_module(
'homeassistant.components.automation.{}'.format(
config[CONF_PLATFORM]))
except ImportError:
raise vol.Invalid('Invalid platform specified') from None
if not hasattr(platform, 'TRIGGER_SCHEMA'):
return config
return getattr(platform, 'TRIGGER_SCHEMA')(config)
return platform.TRIGGER_SCHEMA(config)
_TRIGGER_SCHEMA = vol.All(
@@ -71,7 +73,7 @@ _TRIGGER_SCHEMA = vol.All(
[
vol.All(
vol.Schema({
vol.Required(CONF_PLATFORM): cv.platform_validator(DOMAIN)
vol.Required(CONF_PLATFORM): str
}, extra=vol.ALLOW_EXTRA),
_platform_validator
),

View File

@@ -50,13 +50,23 @@ DEVICE_CLASSES_SCHEMA = vol.All(vol.Lower, vol.In(DEVICE_CLASSES))
async def async_setup(hass, config):
"""Track states and offer events for binary sensors."""
component = EntityComponent(
component = hass.data[DOMAIN] = EntityComponent(
logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL)
await component.async_setup(config)
return True
async def async_setup_entry(hass, entry):
"""Setup a config entry."""
return await hass.data[DOMAIN].async_setup_entry(entry)
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
return await hass.data[DOMAIN].async_unload_entry(entry)
# pylint: disable=no-self-use
class BinarySensorDevice(Entity):
"""Represent a binary sensor."""

View File

@@ -217,4 +217,4 @@ class BayesianBinarySensor(BinarySensorDevice):
@asyncio.coroutine
def async_update(self):
"""Get the latest data and update the states."""
self._deviation = bool(self.probability > self._probability_threshold)
self._deviation = bool(self.probability >= self._probability_threshold)

View File

@@ -11,7 +11,6 @@ import voluptuous as vol
from homeassistant.components.binary_sensor import (
BinarySensorDevice, PLATFORM_SCHEMA)
from homeassistant.const import CONF_MONITORED_CONDITIONS
from homeassistant.loader import get_component
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
@@ -31,7 +30,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the available BloomSky weather binary sensors."""
bloomsky = get_component('bloomsky')
bloomsky = hass.components.bloomsky
# Default needed in case of discovery
sensors = config.get(CONF_MONITORED_CONDITIONS, SENSOR_TYPES)

View File

@@ -17,9 +17,19 @@ _LOGGER = logging.getLogger(__name__)
SENSOR_TYPES = {
'lids': ['Doors', 'opening'],
'windows': ['Windows', 'opening'],
'door_lock_state': ['Door lock state', 'safety']
'door_lock_state': ['Door lock state', 'safety'],
'lights_parking': ['Parking lights', 'light'],
'condition_based_services': ['Condition based services', 'problem'],
'check_control_messages': ['Control messages', 'problem']
}
SENSOR_TYPES_ELEC = {
'charging_status': ['Charging status', 'power'],
'connection_status': ['Connection status', 'plug']
}
SENSOR_TYPES_ELEC.update(SENSOR_TYPES)
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the BMW sensors."""
@@ -29,10 +39,18 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
devices = []
for account in accounts:
for vehicle in account.account.vehicles:
for key, value in sorted(SENSOR_TYPES.items()):
device = BMWConnectedDriveSensor(account, vehicle, key,
value[0], value[1])
devices.append(device)
if vehicle.has_hv_battery:
_LOGGER.debug('BMW with a high voltage battery')
for key, value in sorted(SENSOR_TYPES_ELEC.items()):
device = BMWConnectedDriveSensor(account, vehicle, key,
value[0], value[1])
devices.append(device)
elif vehicle.has_internal_combustion_engine:
_LOGGER.debug('BMW with an internal combustion engine')
for key, value in sorted(SENSOR_TYPES.items()):
device = BMWConnectedDriveSensor(account, vehicle, key,
value[0], value[1])
devices.append(device)
add_devices(devices, True)
@@ -92,12 +110,34 @@ class BMWConnectedDriveSensor(BinarySensorDevice):
result[window.name] = window.state.value
elif self._attribute == 'door_lock_state':
result['door_lock_state'] = vehicle_state.door_lock_state.value
result['last_update_reason'] = vehicle_state.last_update_reason
elif self._attribute == 'lights_parking':
result['lights_parking'] = vehicle_state.parking_lights.value
elif self._attribute == 'condition_based_services':
for report in vehicle_state.condition_based_services:
result.update(self._format_cbs_report(report))
elif self._attribute == 'check_control_messages':
check_control_messages = vehicle_state.check_control_messages
if not check_control_messages:
result['check_control_messages'] = 'OK'
else:
result['check_control_messages'] = check_control_messages
elif self._attribute == 'charging_status':
result['charging_status'] = vehicle_state.charging_status.value
# pylint: disable=W0212
result['last_charging_end_result'] = \
vehicle_state._attributes['lastChargingEndResult']
if self._attribute == 'connection_status':
# pylint: disable=W0212
result['connection_status'] = \
vehicle_state._attributes['connectionStatus']
return result
return sorted(result.items())
def update(self):
"""Read new state data from the library."""
from bimmer_connected.state import LockState
from bimmer_connected.state import ChargingState
vehicle_state = self._vehicle.state
# device class opening: On means open, Off means closed
@@ -111,6 +151,37 @@ class BMWConnectedDriveSensor(BinarySensorDevice):
# Possible values: LOCKED, SECURED, SELECTIVE_LOCKED, UNLOCKED
self._state = vehicle_state.door_lock_state not in \
[LockState.LOCKED, LockState.SECURED]
# device class light: On means light detected, Off means no light
if self._attribute == 'lights_parking':
self._state = vehicle_state.are_parking_lights_on
# device class problem: On means problem detected, Off means no problem
if self._attribute == 'condition_based_services':
self._state = not vehicle_state.are_all_cbs_ok
if self._attribute == 'check_control_messages':
self._state = vehicle_state.has_check_control_messages
# device class power: On means power detected, Off means no power
if self._attribute == 'charging_status':
self._state = vehicle_state.charging_status in \
[ChargingState.CHARGING]
# device class plug: On means device is plugged in,
# Off means device is unplugged
if self._attribute == 'connection_status':
# pylint: disable=W0212
self._state = (vehicle_state._attributes['connectionStatus'] ==
'CONNECTED')
@staticmethod
def _format_cbs_report(report):
result = {}
service_type = report.service_type.lower().replace('_', ' ')
result['{} status'.format(service_type)] = report.state.value
if report.due_date is not None:
result['{} date'.format(service_type)] = \
report.due_date.strftime('%Y-%m-%d')
if report.due_distance is not None:
result['{} distance'.format(service_type)] = \
'{} km'.format(report.due_distance)
return result
def update_callback(self):
"""Schedule a state update."""

View File

@@ -6,27 +6,35 @@ https://home-assistant.io/components/binary_sensor.deconz/
"""
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.deconz import (
DOMAIN as DATA_DECONZ, DATA_DECONZ_ID)
DOMAIN as DATA_DECONZ, DATA_DECONZ_ID, DATA_DECONZ_UNSUB)
from homeassistant.const import ATTR_BATTERY_LEVEL
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
DEPENDENCIES = ['deconz']
async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Old way of setting up deCONZ binary sensors."""
pass
async def async_setup_entry(hass, config_entry, async_add_devices):
"""Set up the deCONZ binary sensor."""
if discovery_info is None:
return
@callback
def async_add_sensor(sensors):
"""Add binary sensor from deCONZ."""
from pydeconz.sensor import DECONZ_BINARY_SENSOR
entities = []
for sensor in sensors:
if sensor.type in DECONZ_BINARY_SENSOR:
entities.append(DeconzBinarySensor(sensor))
async_add_devices(entities, True)
hass.data[DATA_DECONZ_UNSUB].append(
async_dispatcher_connect(hass, 'deconz_new_sensor', async_add_sensor))
from pydeconz.sensor import DECONZ_BINARY_SENSOR
sensors = hass.data[DATA_DECONZ].sensors
entities = []
for sensor in sensors.values():
if sensor and sensor.type in DECONZ_BINARY_SENSOR:
entities.append(DeconzBinarySensor(sensor))
async_add_devices(entities, True)
async_add_sensor(hass.data[DATA_DECONZ].sensors.values())
class DeconzBinarySensor(BinarySensorDevice):

View File

@@ -0,0 +1,85 @@
"""
Support for HomematicIP binary sensor.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.homematicip_cloud/
"""
import logging
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.homematicip_cloud import (
HomematicipGenericDevice, DOMAIN as HOMEMATICIP_CLOUD_DOMAIN,
ATTR_HOME_ID)
DEPENDENCIES = ['homematicip_cloud']
_LOGGER = logging.getLogger(__name__)
ATTR_WINDOW_STATE = 'window_state'
ATTR_EVENT_DELAY = 'event_delay'
ATTR_MOTION_DETECTED = 'motion_detected'
ATTR_ILLUMINATION = 'illumination'
HMIP_OPEN = 'open'
async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Set up the HomematicIP binary sensor devices."""
from homematicip.device import (ShutterContact, MotionDetectorIndoor)
if discovery_info is None:
return
home = hass.data[HOMEMATICIP_CLOUD_DOMAIN][discovery_info[ATTR_HOME_ID]]
devices = []
for device in home.devices:
if isinstance(device, ShutterContact):
devices.append(HomematicipShutterContact(home, device))
elif isinstance(device, MotionDetectorIndoor):
devices.append(HomematicipMotionDetector(home, device))
if devices:
async_add_devices(devices)
class HomematicipShutterContact(HomematicipGenericDevice, BinarySensorDevice):
"""HomematicIP shutter contact."""
def __init__(self, home, device):
"""Initialize the shutter contact."""
super().__init__(home, device)
@property
def device_class(self):
"""Return the class of this sensor."""
return 'door'
@property
def is_on(self):
"""Return true if the shutter contact is on/open."""
if self._device.sabotage:
return True
if self._device.windowState is None:
return None
return self._device.windowState.lower() == HMIP_OPEN
class HomematicipMotionDetector(HomematicipGenericDevice, BinarySensorDevice):
"""MomematicIP motion detector."""
def __init__(self, home, device):
"""Initialize the shutter contact."""
super().__init__(home, device)
@property
def device_class(self):
"""Return the class of this sensor."""
return 'motion'
@property
def is_on(self):
"""Return true if motion is detected."""
if self._device.sabotage:
return True
return self._device.motionDetected

View File

@@ -23,7 +23,7 @@ SENSOR_TYPES = {'openClosedSensor': 'opening',
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up the INSTEON PLM device class for the hass platform."""
plm = hass.data['insteon_plm']
plm = hass.data['insteon_plm'].get('plm')
address = discovery_info['address']
device = plm.devices[address]

View File

@@ -117,8 +117,10 @@ class ISYBinarySensorDevice(ISYDevice, BinarySensorDevice):
# pylint: disable=protected-access
if _is_val_unknown(self._node.status._val):
self._computed_state = None
self._status_was_unknown = True
else:
self._computed_state = bool(self._node.status._val)
self._status_was_unknown = False
@asyncio.coroutine
def async_added_to_hass(self) -> None:
@@ -156,9 +158,13 @@ class ISYBinarySensorDevice(ISYDevice, BinarySensorDevice):
# pylint: disable=protected-access
if not _is_val_unknown(self._negative_node.status._val):
# If the negative node has a value, it means the negative node is
# in use for this device. Therefore, we cannot determine the state
# of the sensor until we receive our first ON event.
self._computed_state = None
# in use for this device. Next we need to check to see if the
# negative and positive nodes disagree on the state (both ON or
# both OFF).
if self._negative_node.status._val == self._node.status._val:
# The states disagree, therefore we cannot determine the state
# of the sensor until we receive our first ON event.
self._computed_state = None
def _negative_node_control_handler(self, event: object) -> None:
"""Handle an "On" control event from the "negative" node."""
@@ -189,14 +195,21 @@ class ISYBinarySensorDevice(ISYDevice, BinarySensorDevice):
self.schedule_update_ha_state()
self._heartbeat()
# pylint: disable=unused-argument
def on_update(self, event: object) -> None:
"""Ignore primary node status updates.
"""Primary node status updates.
We listen directly to the Control events on all nodes for this
device.
We MOSTLY ignore these updates, as we listen directly to the Control
events on all nodes for this device. However, there is one edge case:
If a leak sensor is unknown, due to a recent reboot of the ISY, the
status will get updated to dry upon the first heartbeat. This status
update is the only way that a leak sensor's status changes without
an accompanying Control event, so we need to watch for it.
"""
pass
if self._status_was_unknown and self._computed_state is None:
self._computed_state = bool(int(self._node.status))
self._status_was_unknown = False
self.schedule_update_ha_state()
self._heartbeat()
@property
def value(self) -> object:

View File

@@ -0,0 +1,82 @@
"""
Support for wired binary sensors attached to a Konnected device.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.konnected/
"""
import logging
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.konnected import (
DOMAIN as KONNECTED_DOMAIN, PIN_TO_ZONE, SIGNAL_SENSOR_UPDATE)
from homeassistant.const import (
CONF_DEVICES, CONF_TYPE, CONF_NAME, CONF_BINARY_SENSORS, ATTR_ENTITY_ID,
ATTR_STATE)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['konnected']
async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Set up binary sensors attached to a Konnected device."""
if discovery_info is None:
return
data = hass.data[KONNECTED_DOMAIN]
device_id = discovery_info['device_id']
sensors = [KonnectedBinarySensor(device_id, pin_num, pin_data)
for pin_num, pin_data in
data[CONF_DEVICES][device_id][CONF_BINARY_SENSORS].items()]
async_add_devices(sensors)
class KonnectedBinarySensor(BinarySensorDevice):
"""Representation of a Konnected binary sensor."""
def __init__(self, device_id, pin_num, data):
"""Initialize the binary sensor."""
self._data = data
self._device_id = device_id
self._pin_num = pin_num
self._state = self._data.get(ATTR_STATE)
self._device_class = self._data.get(CONF_TYPE)
self._name = self._data.get(CONF_NAME, 'Konnected {} Zone {}'.format(
device_id, PIN_TO_ZONE[pin_num]))
_LOGGER.debug('Created new Konnected sensor: %s', self._name)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def is_on(self):
"""Return the state of the sensor."""
return self._state
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def device_class(self):
"""Return the device class."""
return self._device_class
async def async_added_to_hass(self):
"""Store entity_id and register state change callback."""
self._data[ATTR_ENTITY_ID] = self.entity_id
async_dispatcher_connect(
self.hass, SIGNAL_SENSOR_UPDATE.format(self.entity_id),
self.async_set_state)
@callback
def async_set_state(self, state):
"""Update the sensor's state."""
self._state = state
self.async_schedule_update_ha_state()

View File

@@ -31,7 +31,8 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
sensors = []
hub = hass.data[MYCHEVY_DOMAIN]
for sconfig in SENSORS:
sensors.append(EVBinarySensor(hub, sconfig))
for car in hub.cars:
sensors.append(EVBinarySensor(hub, sconfig, car.vid))
async_add_devices(sensors)
@@ -45,16 +46,18 @@ class EVBinarySensor(BinarySensorDevice):
"""
def __init__(self, connection, config):
def __init__(self, connection, config, car_vid):
"""Initialize sensor with car connection."""
self._conn = connection
self._name = config.name
self._attr = config.attr
self._type = config.device_class
self._is_on = None
self._car_vid = car_vid
self.entity_id = ENTITY_ID_FORMAT.format(
'{}_{}'.format(MYCHEVY_DOMAIN, slugify(self._name)))
'{}_{}_{}'.format(MYCHEVY_DOMAIN,
slugify(self._car.name),
slugify(self._name)))
@property
def name(self):
@@ -66,6 +69,11 @@ class EVBinarySensor(BinarySensorDevice):
"""Return if on."""
return self._is_on
@property
def _car(self):
"""Return the car."""
return self._conn.get_car(self._car_vid)
@asyncio.coroutine
def async_added_to_hass(self):
"""Register callbacks."""
@@ -75,8 +83,8 @@ class EVBinarySensor(BinarySensorDevice):
@callback
def async_update_callback(self):
"""Update state."""
if self._conn.car is not None:
self._is_on = getattr(self._conn.car, self._attr, None)
if self._car is not None:
self._is_on = getattr(self._car, self._attr, None)
self.async_schedule_update_ha_state()
@property

View File

@@ -13,7 +13,6 @@ import voluptuous as vol
from homeassistant.components.binary_sensor import (
BinarySensorDevice, PLATFORM_SCHEMA)
from homeassistant.components.netatmo import CameraData
from homeassistant.loader import get_component
from homeassistant.const import CONF_TIMEOUT
from homeassistant.helpers import config_validation as cv
@@ -61,7 +60,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the access to Netatmo binary sensor."""
netatmo = get_component('netatmo')
netatmo = hass.components.netatmo
home = config.get(CONF_HOME)
timeout = config.get(CONF_TIMEOUT)
if timeout is None:

View File

@@ -10,7 +10,7 @@ import voluptuous as vol
from homeassistant.components import rfxtrx
from homeassistant.components.binary_sensor import (
PLATFORM_SCHEMA, DEVICE_CLASSES_SCHEMA, BinarySensorDevice)
DEVICE_CLASSES_SCHEMA, PLATFORM_SCHEMA, BinarySensorDevice)
from homeassistant.components.rfxtrx import (
ATTR_NAME, CONF_AUTOMATIC_ADD, CONF_DATA_BITS, CONF_DEVICES,
CONF_FIRE_EVENT, CONF_OFF_DELAY)
@@ -29,8 +29,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_DEVICES, default={}): {
cv.string: vol.Schema({
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_DEVICE_CLASS):
DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_FIRE_EVENT, default=False): cv.boolean,
vol.Optional(CONF_OFF_DELAY):
vol.Any(cv.time_period, cv.positive_timedelta),

View File

@@ -14,7 +14,7 @@ from homeassistant.components.binary_sensor import (
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['tapsaff==0.1.3']
REQUIREMENTS = ['tapsaff==0.2.0']
_LOGGER = logging.getLogger(__name__)

View File

@@ -23,7 +23,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.14.2']
REQUIREMENTS = ['numpy==1.14.3']
_LOGGER = logging.getLogger(__name__)

View File

@@ -7,7 +7,6 @@ https://home-assistant.io/components/binary_sensor.wemo/
import logging
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.loader import get_component
DEPENDENCIES = ['wemo']
@@ -25,18 +24,18 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
device = discovery.device_from_description(location, mac)
if device:
add_devices_callback([WemoBinarySensor(device)])
add_devices_callback([WemoBinarySensor(hass, device)])
class WemoBinarySensor(BinarySensorDevice):
"""Representation a WeMo binary sensor."""
def __init__(self, device):
def __init__(self, hass, device):
"""Initialize the WeMo sensor."""
self.wemo = device
self._state = None
wemo = get_component('wemo')
wemo = hass.components.wemo
wemo.SUBSCRIPTION_REGISTRY.register(self.wemo)
wemo.SUBSCRIPTION_REGISTRY.on(self.wemo, None, self._update_callback)

View File

@@ -17,16 +17,17 @@ import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['holidays==0.9.4']
REQUIREMENTS = ['holidays==0.9.5']
# List of all countries currently supported by holidays
# There seems to be no way to get the list out at runtime
ALL_COUNTRIES = ['Australia', 'AU', 'Austria', 'AT', 'Belgium', 'BE', 'Canada',
'CA', 'Colombia', 'CO', 'Czech', 'CZ', 'Denmark', 'DK',
'England', 'EuropeanCentralBank', 'ECB', 'TAR', 'Finland',
'FI', 'France', 'FRA', 'Germany', 'DE', 'Ireland',
'Isle of Man', 'Italy', 'IT', 'Japan', 'JP', 'Mexico', 'MX',
'Netherlands', 'NL', 'NewZealand', 'NZ', 'Northern Ireland',
ALL_COUNTRIES = ['Argentina', 'AR', 'Australia', 'AU', 'Austria', 'AT',
'Belgium', 'BE', 'Canada', 'CA', 'Colombia', 'CO', 'Czech',
'CZ', 'Denmark', 'DK', 'England', 'EuropeanCentralBank',
'ECB', 'TAR', 'Finland', 'FI', 'France', 'FRA', 'Germany',
'DE', 'Hungary', 'HU', 'Ireland', 'Isle of Man', 'Italy',
'IT', 'Japan', 'JP', 'Mexico', 'MX', 'Netherlands', 'NL',
'NewZealand', 'NZ', 'Northern Ireland',
'Norway', 'NO', 'Polish', 'PL', 'Portugal', 'PT',
'PortugalExt', 'PTE', 'Scotland', 'Slovenia', 'SI',
'Slovakia', 'SK', 'South Africa', 'ZA', 'Spain', 'ES',

View File

@@ -25,30 +25,35 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
for (_, gateway) in hass.data[PY_XIAOMI_GATEWAY].gateways.items():
for device in gateway.devices['binary_sensor']:
model = device['model']
if model in ['motion', 'sensor_motion.aq2']:
if model in ['motion', 'sensor_motion', 'sensor_motion.aq2']:
devices.append(XiaomiMotionSensor(device, hass, gateway))
elif model in ['magnet', 'sensor_magnet.aq2']:
elif model in ['magnet', 'sensor_magnet', 'sensor_magnet.aq2']:
devices.append(XiaomiDoorSensor(device, gateway))
elif model == 'sensor_wleak.aq1':
devices.append(XiaomiWaterLeakSensor(device, gateway))
elif model == 'smoke':
elif model in ['smoke', 'sensor_smoke']:
devices.append(XiaomiSmokeSensor(device, gateway))
elif model == 'natgas':
elif model in ['natgas', 'sensor_natgas']:
devices.append(XiaomiNatgasSensor(device, gateway))
elif model in ['switch', 'sensor_switch.aq2', 'sensor_switch.aq3']:
devices.append(XiaomiButton(device, 'Switch', 'status',
elif model in ['switch', 'sensor_switch',
'sensor_switch.aq2', 'sensor_switch.aq3']:
if 'proto' not in device or int(device['proto'][0:1]) == 1:
data_key = 'status'
else:
data_key = 'channel_0'
devices.append(XiaomiButton(device, 'Switch', data_key,
hass, gateway))
elif model == '86sw1':
elif model in ['86sw1', 'sensor_86sw1.aq1']:
devices.append(XiaomiButton(device, 'Wall Switch', 'channel_0',
hass, gateway))
elif model == '86sw2':
elif model in ['86sw2', 'sensor_86sw2.aq1']:
devices.append(XiaomiButton(device, 'Wall Switch (Left)',
'channel_0', hass, gateway))
devices.append(XiaomiButton(device, 'Wall Switch (Right)',
'channel_1', hass, gateway))
devices.append(XiaomiButton(device, 'Wall Switch (Both)',
'dual_channel', hass, gateway))
elif model == 'cube':
elif model in ['cube', 'sensor_cube', 'sensor_cube.aqgl01']:
devices.append(XiaomiCube(device, hass, gateway))
add_devices(devices)
@@ -129,8 +134,12 @@ class XiaomiMotionSensor(XiaomiBinarySensor):
"""Initialize the XiaomiMotionSensor."""
self._hass = hass
self._no_motion_since = 0
if 'proto' not in device or int(device['proto'][0:1]) == 1:
data_key = 'status'
else:
data_key = 'motion_status'
XiaomiBinarySensor.__init__(self, device, 'Motion Sensor', xiaomi_hub,
'status', 'motion')
data_key, 'motion')
@property
def device_state_attributes(self):

View File

@@ -31,12 +31,21 @@ async def async_setup_platform(hass, config, async_add_devices,
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_devices,
discovery_info)
elif OnOff.cluster_id in discovery_info['out_clusters']:
await _async_setup_remote(hass, config, async_add_devices,
discovery_info)
in_clusters = discovery_info['in_clusters']
async def _async_setup_iaszone(hass, config, async_add_devices,
discovery_info):
device_class = None
cluster = in_clusters[IasZone.cluster_id]
from zigpy.zcl.clusters.security import IasZone
cluster = discovery_info['in_clusters'][IasZone.cluster_id]
if discovery_info['new_join']:
await cluster.bind()
ieee = cluster.endpoint.device.application.ieee
@@ -53,8 +62,34 @@ async def async_setup_platform(hass, config, async_add_devices,
async_add_devices([sensor], update_before_add=True)
async def _async_setup_remote(hass, config, async_add_devices, discovery_info):
async def safe(coro):
"""Run coro, catching ZigBee delivery errors, and ignoring them."""
import zigpy.exceptions
try:
await coro
except zigpy.exceptions.DeliveryError as exc:
_LOGGER.warning("Ignoring error during setup: %s", exc)
if discovery_info['new_join']:
from zigpy.zcl.clusters.general import OnOff, LevelControl
out_clusters = discovery_info['out_clusters']
if OnOff.cluster_id in out_clusters:
cluster = out_clusters[OnOff.cluster_id]
await safe(cluster.bind())
await safe(cluster.configure_reporting(0, 0, 600, 1))
if LevelControl.cluster_id in out_clusters:
cluster = out_clusters[LevelControl.cluster_id]
await safe(cluster.bind())
await safe(cluster.configure_reporting(0, 1, 600, 1))
sensor = Switch(**discovery_info)
async_add_devices([sensor], update_before_add=True)
class BinarySensor(zha.Entity, BinarySensorDevice):
"""THe ZHA Binary Sensor."""
"""The ZHA Binary Sensor."""
_domain = DOMAIN
@@ -73,7 +108,7 @@ class BinarySensor(zha.Entity, BinarySensorDevice):
@property
def is_on(self) -> bool:
"""Return True if entity is on."""
if self._state == 'unknown':
if self._state is None:
return False
return bool(self._state)
@@ -98,7 +133,121 @@ class BinarySensor(zha.Entity, BinarySensorDevice):
from bellows.types.basic import uint16_t
result = await zha.safe_read(self._endpoint.ias_zone,
['zone_status'])
['zone_status'],
allow_cache=False)
state = result.get('zone_status', self._state)
if isinstance(state, (int, uint16_t)):
self._state = result.get('zone_status', self._state) & 3
class Switch(zha.Entity, BinarySensorDevice):
"""ZHA switch/remote controller/button."""
_domain = DOMAIN
class OnOffListener:
"""Listener for the OnOff ZigBee cluster."""
def __init__(self, entity):
"""Initialize OnOffListener."""
self._entity = entity
def cluster_command(self, tsn, command_id, args):
"""Handle commands received to this cluster."""
if command_id in (0x0000, 0x0040):
self._entity.set_state(False)
elif command_id in (0x0001, 0x0041, 0x0042):
self._entity.set_state(True)
elif command_id == 0x0002:
self._entity.set_state(not self._entity.is_on)
def attribute_updated(self, attrid, value):
"""Handle attribute updates on this cluster."""
if attrid == 0:
self._entity.set_state(value)
def zdo_command(self, *args, **kwargs):
"""Handle ZDO commands on this cluster."""
pass
class LevelListener:
"""Listener for the LevelControl ZigBee cluster."""
def __init__(self, entity):
"""Initialize LevelListener."""
self._entity = entity
def cluster_command(self, tsn, command_id, args):
"""Handle commands received to this cluster."""
if command_id in (0x0000, 0x0004): # move_to_level, -with_on_off
self._entity.set_level(args[0])
elif command_id in (0x0001, 0x0005): # move, -with_on_off
# We should dim slowly -- for now, just step once
rate = args[1]
if args[0] == 0xff:
rate = 10 # Should read default move rate
self._entity.move_level(-rate if args[0] else rate)
elif command_id == 0x0002: # step
# Step (technically shouldn't change on/off)
self._entity.move_level(-args[1] if args[0] else args[1])
def attribute_update(self, attrid, value):
"""Handle attribute updates on this cluster."""
if attrid == 0:
self._entity.set_level(value)
def zdo_command(self, *args, **kwargs):
"""Handle ZDO commands on this cluster."""
pass
def __init__(self, **kwargs):
"""Initialize Switch."""
super().__init__(**kwargs)
self._state = True
self._level = 255
from zigpy.zcl.clusters import general
self._out_listeners = {
general.OnOff.cluster_id: self.OnOffListener(self),
general.LevelControl.cluster_id: self.LevelListener(self),
}
@property
def is_on(self) -> bool:
"""Return true if the binary sensor is on."""
return self._state
@property
def device_state_attributes(self):
"""Return the device state attributes."""
self._device_state_attributes.update({
'level': self._state and self._level or 0
})
return self._device_state_attributes
def move_level(self, change):
"""Increment the level, setting state if appropriate."""
if not self._state and change > 0:
self._level = 0
self._level = min(255, max(0, self._level + change))
self._state = bool(self._level)
self.async_schedule_update_ha_state()
def set_level(self, level):
"""Set the level, setting state if appropriate."""
self._level = level
self._state = bool(self._level)
self.async_schedule_update_ha_state()
def set_state(self, state):
"""Set the state."""
self._state = state
if self._level == 0:
self._level = 255
self.async_schedule_update_ha_state()
async def async_update(self):
"""Retrieve latest state."""
from zigpy.zcl.clusters.general import OnOff
result = await zha.safe_read(
self._endpoint.out_clusters[OnOff.cluster_id], ['on_off'])
self._state = result.get('on_off', self._state)

View File

@@ -14,7 +14,7 @@ from homeassistant.helpers import discovery
from homeassistant.helpers.event import track_utc_time_change
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['bimmer_connected==0.5.0']
REQUIREMENTS = ['bimmer_connected==0.5.1']
_LOGGER = logging.getLogger(__name__)

View File

@@ -27,7 +27,7 @@ activate_air_conditioning:
description: >
Start the air conditioning of the vehicle. What exactly is started here
depends on the type of vehicle. It might range from just ventilation over
auxilary heating to real air conditioning. The vehicle is identified via
auxiliary heating to real air conditioning. The vehicle is identified via
the vin (see below).
fields:
vin:
@@ -39,4 +39,4 @@ update_state:
description: >
Fetch the last state of the vehicles of all your accounts from the BMW
server. This does *not* trigger an update from the vehicle, it just gets
the data from the BMW servers. This service does not require any attributes.
the data from the BMW servers. This service does not require any attributes.

View File

@@ -6,6 +6,7 @@ For more details about this component, please refer to the documentation at
https://home-assistant.io/components/camera/
"""
import asyncio
import base64
import collections
from contextlib import suppress
from datetime import timedelta
@@ -13,20 +14,20 @@ import logging
import hashlib
from random import SystemRandom
import aiohttp
import attr
from aiohttp import web
import async_timeout
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.const import (ATTR_ENTITY_ID, ATTR_ENTITY_PICTURE)
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.exceptions import HomeAssistantError
from homeassistant.loader import bind_hass
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA # noqa
from homeassistant.components.http import HomeAssistantView, KEY_AUTHENTICATED
from homeassistant.components import websocket_api
import homeassistant.helpers.config_validation as cv
DOMAIN = 'camera'
@@ -53,6 +54,9 @@ ENTITY_IMAGE_URL = '/api/camera_proxy/{0}?token={1}'
TOKEN_CHANGE_INTERVAL = timedelta(minutes=5)
_RND = SystemRandom()
FALLBACK_STREAM_INTERVAL = 1 # seconds
MIN_STREAM_INTERVAL = 0.5 # seconds
CAMERA_SERVICE_SCHEMA = vol.Schema({
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
})
@@ -61,6 +65,20 @@ CAMERA_SERVICE_SNAPSHOT = CAMERA_SERVICE_SCHEMA.extend({
vol.Required(ATTR_FILENAME): cv.template
})
WS_TYPE_CAMERA_THUMBNAIL = 'camera_thumbnail'
SCHEMA_WS_CAMERA_THUMBNAIL = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
'type': WS_TYPE_CAMERA_THUMBNAIL,
'entity_id': cv.entity_id
})
@attr.s
class Image:
"""Represent an image."""
content_type = attr.ib(type=str)
content = attr.ib(type=bytes)
@bind_hass
def enable_motion_detection(hass, entity_id=None):
@@ -89,43 +107,40 @@ def async_snapshot(hass, filename, entity_id=None):
@bind_hass
@asyncio.coroutine
def async_get_image(hass, entity_id, timeout=10):
async def async_get_image(hass, entity_id, timeout=10):
"""Fetch an image from a camera entity."""
websession = async_get_clientsession(hass)
state = hass.states.get(entity_id)
component = hass.data.get(DOMAIN)
if state is None:
raise HomeAssistantError(
"No entity '{0}' for grab an image".format(entity_id))
if component is None:
raise HomeAssistantError('Camera component not setup')
url = "{0}{1}".format(
hass.config.api.base_url,
state.attributes.get(ATTR_ENTITY_PICTURE)
)
camera = component.get_entity(entity_id)
try:
if camera is None:
raise HomeAssistantError('Camera not found')
with suppress(asyncio.CancelledError, asyncio.TimeoutError):
with async_timeout.timeout(timeout, loop=hass.loop):
response = yield from websession.get(url)
image = await camera.async_camera_image()
if response.status != 200:
raise HomeAssistantError("Error {0} on {1}".format(
response.status, url))
if image:
return Image(camera.content_type, image)
image = yield from response.read()
return image
except (asyncio.TimeoutError, aiohttp.ClientError):
raise HomeAssistantError("Can't connect to {0}".format(url))
raise HomeAssistantError('Unable to get image')
@asyncio.coroutine
def async_setup(hass, config):
"""Set up the camera component."""
component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL)
component = hass.data[DOMAIN] = \
EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL)
hass.http.register_view(CameraImageView(component))
hass.http.register_view(CameraMjpegStream(component))
hass.components.websocket_api.async_register_command(
WS_TYPE_CAMERA_THUMBNAIL, websocket_camera_thumbnail,
SCHEMA_WS_CAMERA_THUMBNAIL
)
yield from component.async_setup(config)
@@ -241,6 +256,11 @@ class Camera(Entity):
"""Return the camera model."""
return None
@property
def frame_interval(self):
"""Return the interval between frames of the mjpeg stream."""
return 0.5
def camera_image(self):
"""Return bytes of camera image."""
raise NotImplementedError()
@@ -252,19 +272,17 @@ class Camera(Entity):
"""
return self.hass.async_add_job(self.camera_image)
@asyncio.coroutine
def handle_async_mjpeg_stream(self, request):
async def handle_async_still_stream(self, request, interval):
"""Generate an HTTP MJPEG stream from camera images.
This method must be run in the event loop.
"""
response = web.StreamResponse()
response.content_type = ('multipart/x-mixed-replace; '
'boundary=--frameboundary')
yield from response.prepare(request)
await response.prepare(request)
async def write(img_bytes):
async def write_to_mjpeg_stream(img_bytes):
"""Write image to stream."""
await response.write(bytes(
'--frameboundary\r\n'
@@ -277,21 +295,21 @@ class Camera(Entity):
try:
while True:
img_bytes = yield from self.async_camera_image()
img_bytes = await self.async_camera_image()
if not img_bytes:
break
if img_bytes and img_bytes != last_image:
yield from write(img_bytes)
await write_to_mjpeg_stream(img_bytes)
# Chrome seems to always ignore first picture,
# print it twice.
if last_image is None:
yield from write(img_bytes)
await write_to_mjpeg_stream(img_bytes)
last_image = img_bytes
yield from asyncio.sleep(.5)
await asyncio.sleep(interval)
except asyncio.CancelledError:
_LOGGER.debug("Stream closed by frontend.")
@@ -299,7 +317,16 @@ class Camera(Entity):
finally:
if response is not None:
yield from response.write_eof()
await response.write_eof()
async def handle_async_mjpeg_stream(self, request):
"""Serve an HTTP MJPEG stream from the camera.
This method can be overridden by camera plaforms to proxy
a direct stream from the camera.
This method must be run in the event loop.
"""
await self.handle_async_still_stream(request, self.frame_interval)
@property
def state(self):
@@ -329,20 +356,20 @@ class Camera(Entity):
@property
def state_attributes(self):
"""Return the camera state attributes."""
attr = {
attrs = {
'access_token': self.access_tokens[-1],
}
if self.model:
attr['model_name'] = self.model
attrs['model_name'] = self.model
if self.brand:
attr['brand'] = self.brand
attrs['brand'] = self.brand
if self.motion_detection_enabled:
attr['motion_detection'] = self.motion_detection_enabled
attrs['motion_detection'] = self.motion_detection_enabled
return attr
return attrs
@callback
def async_update_token(self):
@@ -411,7 +438,43 @@ class CameraMjpegStream(CameraView):
url = '/api/camera_proxy_stream/{entity_id}'
name = 'api:camera:stream'
@asyncio.coroutine
def handle(self, request, camera):
"""Serve camera image."""
yield from camera.handle_async_mjpeg_stream(request)
async def handle(self, request, camera):
"""Serve camera stream, possibly with interval."""
interval = request.query.get('interval')
if interval is None:
await camera.handle_async_mjpeg_stream(request)
return
try:
# Compose camera stream from stills
interval = float(request.query.get('interval'))
if interval < MIN_STREAM_INTERVAL:
raise ValueError("Stream interval must be be > {}"
.format(MIN_STREAM_INTERVAL))
await camera.handle_async_still_stream(request, interval)
return
except ValueError:
return web.Response(status=400)
@callback
def websocket_camera_thumbnail(hass, connection, msg):
"""Handle get camera thumbnail websocket command.
Async friendly.
"""
async def send_camera_still():
"""Send a camera still."""
try:
image = await async_get_image(hass, msg['entity_id'])
connection.send_message_outside(websocket_api.result_message(
msg['id'], {
'content_type': image.content_type,
'content': base64.b64encode(image.content).decode('utf-8')
}
))
except HomeAssistantError:
connection.send_message_outside(websocket_api.error_message(
msg['id'], 'image_fetch_failed', 'Unable to fetch image'))
hass.async_add_job(send_camera_still())

View File

@@ -9,7 +9,6 @@ import logging
import requests
from homeassistant.components.camera import Camera
from homeassistant.loader import get_component
DEPENDENCIES = ['bloomsky']
@@ -17,7 +16,7 @@ DEPENDENCIES = ['bloomsky']
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up access to BloomSky cameras."""
bloomsky = get_component('bloomsky')
bloomsky = hass.components.bloomsky
for device in bloomsky.BLOOMSKY.devices.values():
add_devices([BloomSkyCamera(bloomsky.BLOOMSKY, device)])

View File

@@ -0,0 +1,58 @@
"""
Family Hub camera for Samsung Refrigerators.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/camera.familyhub/
"""
import logging
import voluptuous as vol
from homeassistant.components.camera import Camera
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_IP_ADDRESS, CONF_NAME
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['python-family-hub-local==0.0.2']
DEFAULT_NAME = 'FamilyHub Camera'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_IP_ADDRESS): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
async def async_setup_platform(
hass, config, async_add_devices, discovery_info=None):
"""Set up the Family Hub Camera."""
from pyfamilyhublocal import FamilyHubCam
address = config.get(CONF_IP_ADDRESS)
name = config.get(CONF_NAME)
session = async_get_clientsession(hass)
family_hub_cam = FamilyHubCam(address, hass.loop, session)
async_add_devices([FamilyHubCamera(name, family_hub_cam)], True)
class FamilyHubCamera(Camera):
"""The representation of a Family Hub camera."""
def __init__(self, name, family_hub_cam):
"""Initialize camera component."""
super().__init__()
self._name = name
self.family_hub_cam = family_hub_cam
async def async_camera_image(self):
"""Return a still image response."""
return await self.family_hub_cam.async_get_cam_image()
@property
def name(self):
"""Return the name of this camera."""
return self._name

View File

@@ -28,6 +28,7 @@ _LOGGER = logging.getLogger(__name__)
CONF_CONTENT_TYPE = 'content_type'
CONF_LIMIT_REFETCH_TO_URL_CHANGE = 'limit_refetch_to_url_change'
CONF_STILL_IMAGE_URL = 'still_image_url'
CONF_FRAMERATE = 'framerate'
DEFAULT_NAME = 'Generic Camera'
@@ -40,6 +41,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_PASSWORD): cv.string,
vol.Optional(CONF_USERNAME): cv.string,
vol.Optional(CONF_CONTENT_TYPE, default=DEFAULT_CONTENT_TYPE): cv.string,
vol.Optional(CONF_FRAMERATE, default=2): cv.positive_int,
})
@@ -62,6 +64,7 @@ class GenericCamera(Camera):
self._still_image_url = device_info[CONF_STILL_IMAGE_URL]
self._still_image_url.hass = hass
self._limit_refetch = device_info[CONF_LIMIT_REFETCH_TO_URL_CHANGE]
self._frame_interval = 1 / device_info[CONF_FRAMERATE]
self.content_type = device_info[CONF_CONTENT_TYPE]
username = device_info.get(CONF_USERNAME)
@@ -78,6 +81,11 @@ class GenericCamera(Camera):
self._last_url = None
self._last_image = None
@property
def frame_interval(self):
"""Return the interval between frames of the mjpeg stream."""
return self._frame_interval
def camera_image(self):
"""Return bytes of camera image."""
return run_coroutine_threadsafe(

View File

@@ -11,31 +11,44 @@ import os
import voluptuous as vol
from homeassistant.const import CONF_NAME
from homeassistant.components.camera import Camera, PLATFORM_SCHEMA
from homeassistant.components.camera import (
Camera, CAMERA_SERVICE_SCHEMA, DOMAIN, PLATFORM_SCHEMA)
from homeassistant.helpers import config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_FILE_PATH = 'file_path'
DEFAULT_NAME = 'Local File'
SERVICE_UPDATE_FILE_PATH = 'local_file_update_file_path'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_FILE_PATH): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string
})
CAMERA_SERVICE_UPDATE_FILE_PATH = CAMERA_SERVICE_SCHEMA.extend({
vol.Required(CONF_FILE_PATH): cv.string
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Camera that works with local files."""
file_path = config[CONF_FILE_PATH]
camera = LocalFile(config[CONF_NAME], file_path)
# check filepath given is readable
if not os.access(file_path, os.R_OK):
_LOGGER.warning("Could not read camera %s image from file: %s",
config[CONF_NAME], file_path)
def update_file_path_service(call):
"""Update the file path."""
file_path = call.data.get(CONF_FILE_PATH)
camera.update_file_path(file_path)
return True
add_devices([LocalFile(config[CONF_NAME], file_path)])
hass.services.register(
DOMAIN,
SERVICE_UPDATE_FILE_PATH,
update_file_path_service,
schema=CAMERA_SERVICE_UPDATE_FILE_PATH)
add_devices([camera])
class LocalFile(Camera):
@@ -46,6 +59,7 @@ class LocalFile(Camera):
super().__init__()
self._name = name
self.check_file_path_access(file_path)
self._file_path = file_path
# Set content type of local file
content, _ = mimetypes.guess_type(file_path)
@@ -61,7 +75,26 @@ class LocalFile(Camera):
_LOGGER.warning("Could not read camera %s image from file: %s",
self._name, self._file_path)
def check_file_path_access(self, file_path):
"""Check that filepath given is readable."""
if not os.access(file_path, os.R_OK):
_LOGGER.warning("Could not read camera %s image from file: %s",
self._name, file_path)
def update_file_path(self, file_path):
"""Update the file_path."""
self.check_file_path_access(file_path)
self._file_path = file_path
self.schedule_update_ha_state()
@property
def name(self):
"""Return the name of this camera."""
return self._name
@property
def device_state_attributes(self):
"""Return the camera state attributes."""
return {
'file_path': self._file_path,
}

View File

@@ -12,7 +12,6 @@ import voluptuous as vol
from homeassistant.const import CONF_VERIFY_SSL
from homeassistant.components.netatmo import CameraData
from homeassistant.components.camera import (Camera, PLATFORM_SCHEMA)
from homeassistant.loader import get_component
from homeassistant.helpers import config_validation as cv
DEPENDENCIES = ['netatmo']
@@ -33,7 +32,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up access to Netatmo cameras."""
netatmo = get_component('netatmo')
netatmo = hass.components.netatmo
home = config.get(CONF_HOME)
verify_ssl = config.get(CONF_VERIFY_SSL, True)
import lnetatmo

View File

@@ -24,6 +24,16 @@ snapshot:
description: Template of a Filename. Variable is entity_id.
example: '/tmp/snapshot_{{ entity_id }}'
local_file_update_file_path:
description: Update the file_path for a local_file camera.
fields:
entity_id:
description: Name(s) of entities to update.
example: 'camera.local_file'
file_path:
description: Path to the new image file.
example: '/images/newimage.jpg'
onvif_ptz:
description: Pan/Tilt/Zoom service for ONVIF camera.
fields:
@@ -39,4 +49,3 @@ onvif_ptz:
zoom:
description: "Zoom. Allowed values: ZOOM_IN, ZOOM_OUT"
example: "ZOOM_IN"

View File

@@ -115,7 +115,7 @@ class MySensorsHVAC(mysensors.MySensorsEntity, ClimateDevice):
"""List of available fan modes."""
return ['Auto', 'Min', 'Normal', 'Max']
def set_temperature(self, **kwargs):
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
set_req = self.gateway.const.SetReq
temp = kwargs.get(ATTR_TEMPERATURE)
@@ -143,9 +143,9 @@ class MySensorsHVAC(mysensors.MySensorsEntity, ClimateDevice):
if self.gateway.optimistic:
# Optimistically assume that device has changed state
self._values[value_type] = value
self.schedule_update_ha_state()
self.async_schedule_update_ha_state()
def set_fan_mode(self, fan_mode):
async def async_set_fan_mode(self, fan_mode):
"""Set new target temperature."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
@@ -153,9 +153,9 @@ class MySensorsHVAC(mysensors.MySensorsEntity, ClimateDevice):
if self.gateway.optimistic:
# Optimistically assume that device has changed state
self._values[set_req.V_HVAC_SPEED] = fan_mode
self.schedule_update_ha_state()
self.async_schedule_update_ha_state()
def set_operation_mode(self, operation_mode):
async def async_set_operation_mode(self, operation_mode):
"""Set new target temperature."""
self.gateway.set_child_value(
self.node_id, self.child_id, self.value_type,
@@ -163,7 +163,7 @@ class MySensorsHVAC(mysensors.MySensorsEntity, ClimateDevice):
if self.gateway.optimistic:
# Optimistically assume that device has changed state
self._values[self.value_type] = operation_mode
self.schedule_update_ha_state()
self.async_schedule_update_ha_state()
async def async_update(self):
"""Update the controller with the latest value from a sensor."""

View File

@@ -13,7 +13,6 @@ from homeassistant.components.climate import (
STATE_HEAT, STATE_IDLE, ClimateDevice, PLATFORM_SCHEMA,
SUPPORT_TARGET_TEMPERATURE, SUPPORT_OPERATION_MODE, SUPPORT_AWAY_MODE)
from homeassistant.util import Throttle
from homeassistant.loader import get_component
import homeassistant.helpers.config_validation as cv
DEPENDENCIES = ['netatmo']
@@ -42,7 +41,7 @@ SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE | SUPPORT_OPERATION_MODE |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the NetAtmo Thermostat."""
netatmo = get_component('netatmo')
netatmo = hass.components.netatmo
device = config.get(CONF_RELAY)
import lnetatmo

View File

@@ -25,7 +25,7 @@ from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.util.temperature import convert as convert_temperature
REQUIREMENTS = ['pysensibo==1.0.2']
REQUIREMENTS = ['pysensibo==1.0.3']
_LOGGER = logging.getLogger(__name__)

View File

@@ -11,9 +11,11 @@ import voluptuous as vol
from homeassistant.components.climate import (
ATTR_OPERATION_MODE, ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW,
PLATFORM_SCHEMA, STATE_AUTO, STATE_COOL, STATE_HEAT, SUPPORT_FAN_MODE,
SUPPORT_OPERATION_MODE, SUPPORT_TARGET_HUMIDITY,
SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE_HIGH,
SUPPORT_TARGET_TEMPERATURE_LOW, ClimateDevice)
SUPPORT_OPERATION_MODE, SUPPORT_TARGET_HUMIDITY, SUPPORT_AWAY_MODE,
SUPPORT_TARGET_HUMIDITY_HIGH, SUPPORT_TARGET_HUMIDITY_LOW,
SUPPORT_HOLD_MODE, SUPPORT_TARGET_TEMPERATURE,
SUPPORT_TARGET_TEMPERATURE_HIGH, SUPPORT_TARGET_TEMPERATURE_LOW,
ClimateDevice)
from homeassistant.const import (
ATTR_TEMPERATURE, CONF_HOST, CONF_PASSWORD, CONF_SSL, CONF_TIMEOUT,
CONF_USERNAME, PRECISION_WHOLE, STATE_OFF, STATE_ON, TEMP_CELSIUS,
@@ -27,14 +29,20 @@ _LOGGER = logging.getLogger(__name__)
ATTR_FAN_STATE = 'fan_state'
ATTR_HVAC_STATE = 'hvac_state'
CONF_HUMIDIFIER = 'humidifier'
DEFAULT_SSL = False
VALID_FAN_STATES = [STATE_ON, STATE_AUTO]
VALID_THERMOSTAT_MODES = [STATE_HEAT, STATE_COOL, STATE_OFF, STATE_AUTO]
HOLD_MODE_OFF = 'off'
HOLD_MODE_TEMPERATURE = 'temperature'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_PASSWORD): cv.string,
vol.Optional(CONF_HUMIDIFIER, default=True): cv.boolean,
vol.Optional(CONF_SSL, default=DEFAULT_SSL): cv.boolean,
vol.Optional(CONF_TIMEOUT, default=5):
vol.All(vol.Coerce(int), vol.Range(min=1)),
@@ -50,6 +58,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
password = config.get(CONF_PASSWORD)
host = config.get(CONF_HOST)
timeout = config.get(CONF_TIMEOUT)
humidifier = config.get(CONF_HUMIDIFIER)
if config.get(CONF_SSL):
proto = 'https'
@@ -60,15 +69,16 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
addr=host, timeout=timeout, user=username, password=password,
proto=proto)
add_devices([VenstarThermostat(client)], True)
add_devices([VenstarThermostat(client, humidifier)], True)
class VenstarThermostat(ClimateDevice):
"""Representation of a Venstar thermostat."""
def __init__(self, client):
def __init__(self, client, humidifier):
"""Initialize the thermostat."""
self._client = client
self._humidifier = humidifier
def update(self):
"""Update the data from the thermostat."""
@@ -81,14 +91,18 @@ class VenstarThermostat(ClimateDevice):
def supported_features(self):
"""Return the list of supported features."""
features = (SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE |
SUPPORT_OPERATION_MODE)
SUPPORT_OPERATION_MODE | SUPPORT_AWAY_MODE |
SUPPORT_HOLD_MODE)
if self._client.mode == self._client.MODE_AUTO:
features |= (SUPPORT_TARGET_TEMPERATURE_HIGH |
SUPPORT_TARGET_TEMPERATURE_LOW)
if self._client.hum_active == 1:
features |= SUPPORT_TARGET_HUMIDITY
if (self._humidifier and
hasattr(self._client, 'hum_active')):
features |= (SUPPORT_TARGET_HUMIDITY |
SUPPORT_TARGET_HUMIDITY_HIGH |
SUPPORT_TARGET_HUMIDITY_LOW)
return features
@@ -197,6 +211,18 @@ class VenstarThermostat(ClimateDevice):
"""Return the maximum humidity. Hardcoded to 60 in API."""
return 60
@property
def is_away_mode_on(self):
"""Return the status of away mode."""
return self._client.away == self._client.AWAY_AWAY
@property
def current_hold_mode(self):
"""Return the status of hold mode."""
if self._client.schedule == 0:
return HOLD_MODE_TEMPERATURE
return HOLD_MODE_OFF
def _set_operation_mode(self, operation_mode):
"""Change the operation mode (internal)."""
if operation_mode == STATE_HEAT:
@@ -259,3 +285,30 @@ class VenstarThermostat(ClimateDevice):
if not success:
_LOGGER.error("Failed to change the target humidity level")
def set_hold_mode(self, hold_mode):
"""Set the hold mode."""
if hold_mode == HOLD_MODE_TEMPERATURE:
success = self._client.set_schedule(0)
elif hold_mode == HOLD_MODE_OFF:
success = self._client.set_schedule(1)
else:
_LOGGER.error("Unknown hold mode: %s", hold_mode)
success = False
if not success:
_LOGGER.error("Failed to change the schedule/hold state")
def turn_away_mode_on(self):
"""Activate away mode."""
success = self._client.set_away(self._client.AWAY_AWAY)
if not success:
_LOGGER.error("Failed to activate away mode")
def turn_away_mode_off(self):
"""Deactivate away mode."""
success = self._client.set_away(self._client.AWAY_HOME)
if not success:
_LOGGER.error("Failed to deactivate away mode")

View File

@@ -190,7 +190,7 @@ class WinkThermostat(WinkDevice, ClimateDevice):
@property
def cool_on(self):
"""Return whether or not the heat is actually heating."""
return self.wink.heat_on()
return self.wink.cool_on()
@property
def current_operation(self):

View File

@@ -21,6 +21,7 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession
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
from .const import CONFIG_DIR, DOMAIN, SERVERS
@@ -52,7 +53,8 @@ ALEXA_ENTITY_SCHEMA = vol.Schema({
GOOGLE_ENTITY_SCHEMA = vol.Schema({
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_ALIASES): vol.All(cv.ensure_list, [cv.string])
vol.Optional(CONF_ALIASES): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(ga_c.CONF_ROOM_HINT): cv.string,
})
ASSISTANT_SCHEMA = vol.Schema({

View File

@@ -1,6 +1,7 @@
"""Provide configuration end points for Automations."""
import asyncio
from collections import OrderedDict
import uuid
from homeassistant.const import CONF_ID
from homeassistant.components.config import EditIdBasedConfigView
@@ -29,7 +30,12 @@ class EditAutomationConfigView(EditIdBasedConfigView):
"""Set value."""
index = None
for index, cur_value in enumerate(data):
if cur_value[CONF_ID] == config_key:
# When people copy paste their automations to the config file,
# they sometimes forget to add IDs. Fix it here.
if CONF_ID not in cur_value:
cur_value[CONF_ID] = uuid.uuid4().hex
elif cur_value[CONF_ID] == config_key:
break
else:
cur_value = OrderedDict()

View File

@@ -96,6 +96,7 @@ async def async_setup(hass, config):
async def process(service):
"""Parse text into commands."""
text = service.data[ATTR_TEXT]
_LOGGER.debug('Processing: <%s>', text)
try:
await _process(hass, text)
except intent.IntentHandleError as err:

View File

@@ -0,0 +1,10 @@
# Describes the format for available component services
process:
description: Launch a conversation from a transcribed text.
fields:
text:
description: Transcribed text
example: Turn all lights on

View File

@@ -1,5 +1,5 @@
"""
Support for Gogogate2 Garage Doors.
Support for Gogogate2 garage Doors.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/cover.gogogate2/
@@ -15,7 +15,7 @@ from homeassistant.const import (
CONF_IP_ADDRESS, CONF_NAME)
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['pygogogate2==0.0.3']
REQUIREMENTS = ['pygogogate2==0.1.1']
_LOGGER = logging.getLogger(__name__)
@@ -25,9 +25,9 @@ NOTIFICATION_ID = 'gogogate2_notification'
NOTIFICATION_TITLE = 'Gogogate2 Cover Setup'
COVER_SCHEMA = vol.Schema({
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_IP_ADDRESS): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
@@ -36,10 +36,11 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Gogogate2 component."""
from pygogogate2 import Gogogate2API as pygogogate2
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
ip_address = config.get(CONF_IP_ADDRESS)
name = config.get(CONF_NAME)
password = config.get(CONF_PASSWORD)
username = config.get(CONF_USERNAME)
mygogogate2 = pygogogate2(username, password, ip_address)
try:

View File

@@ -42,7 +42,7 @@ class MySensorsCover(mysensors.MySensorsEntity, CoverDevice):
set_req = self.gateway.const.SetReq
return self._values.get(set_req.V_DIMMER)
def open_cover(self, **kwargs):
async def async_open_cover(self, **kwargs):
"""Move the cover up."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
@@ -53,9 +53,9 @@ class MySensorsCover(mysensors.MySensorsEntity, CoverDevice):
self._values[set_req.V_DIMMER] = 100
else:
self._values[set_req.V_LIGHT] = STATE_ON
self.schedule_update_ha_state()
self.async_schedule_update_ha_state()
def close_cover(self, **kwargs):
async def async_close_cover(self, **kwargs):
"""Move the cover down."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(
@@ -66,9 +66,9 @@ class MySensorsCover(mysensors.MySensorsEntity, CoverDevice):
self._values[set_req.V_DIMMER] = 0
else:
self._values[set_req.V_LIGHT] = STATE_OFF
self.schedule_update_ha_state()
self.async_schedule_update_ha_state()
def set_cover_position(self, **kwargs):
async def async_set_cover_position(self, **kwargs):
"""Move the cover to a specific position."""
position = kwargs.get(ATTR_POSITION)
set_req = self.gateway.const.SetReq
@@ -77,9 +77,9 @@ class MySensorsCover(mysensors.MySensorsEntity, CoverDevice):
if self.gateway.optimistic:
# Optimistically assume that cover has changed state.
self._values[set_req.V_DIMMER] = position
self.schedule_update_ha_state()
self.async_schedule_update_ha_state()
def stop_cover(self, **kwargs):
async def async_stop_cover(self, **kwargs):
"""Stop the device."""
set_req = self.gateway.const.SetReq
self.gateway.set_child_value(

View File

@@ -79,5 +79,9 @@ class TahomaCover(TahomaDevice, CoverDevice):
if self.tahoma_device.type == \
'io:RollerShutterWithLowSpeedManagementIOComponent':
self.apply_action('setPosition', 'secured')
elif self.tahoma_device.type in \
('rts:BlindRTSComponent',
'io:ExteriorVenetianBlindIOComponent'):
self.apply_action('my')
else:
self.apply_action('stopIdentify')

View File

@@ -0,0 +1,25 @@
{
"config": {
"abort": {
"no_bridges": "\u041d\u0435 \u0441\u0430 \u043e\u0442\u043a\u0440\u0438\u0442\u0438 \u043c\u043e\u0441\u0442\u043e\u0432\u0435 deCONZ",
"one_instance_only": "\u041a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442 \u043f\u043e\u0434\u0434\u044a\u0440\u0436\u0430 \u0441\u0430\u043c\u043e \u0435\u0434\u043d\u043e \u043a\u043e\u043f\u0438\u0435 \u043d\u0430 deCONZ"
},
"error": {
"no_key": "\u041d\u0435 \u043c\u043e\u0436\u0430 \u0434\u0430 \u0441\u0435 \u043f\u043e\u043b\u0443\u0447\u0438 API \u043a\u043b\u044e\u0447"
},
"step": {
"init": {
"data": {
"host": "\u0425\u043e\u0441\u0442",
"port": "\u041f\u043e\u0440\u0442 (\u0441\u0442\u043e\u0439\u043d\u043e\u0441\u0442 \u043f\u043e \u043f\u043e\u0434\u0440\u0430\u0437\u0431\u0438\u0440\u0430\u043d\u0435: '80')"
},
"title": "\u0414\u0435\u0444\u0438\u043d\u0438\u0440\u0430\u043d\u0435 \u043d\u0430 deCONZ \u0448\u043b\u044e\u0437"
},
"link": {
"description": "\u041e\u0442\u043a\u043b\u044e\u0447\u0438 deCONZ \u0448\u043b\u044e\u0437\u0430 \u0437\u0430 \u0434\u0430 \u0441\u0435 \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0438\u0440\u0430 \u0441 Home Assistant.\n\n1. \u041e\u0442\u0432\u043e\u0440\u0435\u0442\u0435 \u0441\u0438\u0441\u0442\u0435\u043c\u043d\u0438\u0442\u0435 \u043d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438 \u043d\u0430 deCONZ\n2. \u041d\u0430\u0442\u0438\u0441\u043d\u0435\u0442\u0435 \u0431\u0443\u0442\u043e\u043d\u0430 \"Unlock Gateway\"",
"title": "\u0412\u0440\u044a\u0437\u043a\u0430 \u0441 deCONZ"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"already_configured": "Pont eisoes wedi'i ffurfweddu",
"no_bridges": "Dim pontydd deCONZ wedi eu darganfod",
"one_instance_only": "Elfen dim ond yn cefnogi enghraifft deCONZ"
},
"error": {
"no_key": "Methu cael allwedd API"
},
"step": {
"init": {
"data": {
"host": "Gwesteiwr",
"port": "Port (gwerth diofyn: '80')"
},
"title": "Diffiniwch porth dad-adeiladu"
},
"link": {
"description": "Datgloi eich porth deCONZ i gofrestru gyda Cynorthwydd Cartref.\n\n1. Ewch i osodiadau system deCONZ \n2. Bwyso botwm \"Datgloi porth\"",
"title": "Cysylltu \u00e2 deCONZ"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,11 @@
{
"config": {
"step": {
"init": {
"data": {
"host": "V\u00e6rt"
}
}
}
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"already_configured": "Bridge ist bereits konfiguriert",
"no_bridges": "Keine deCON-Bridges entdeckt",
"one_instance_only": "Komponente unterst\u00fctzt nur eine deCONZ-Instanz"
},
"error": {
"no_key": "Es konnte kein API-Schl\u00fcssel abgerufen werden"
},
"step": {
"init": {
"data": {
"host": "Host",
"port": "Port (Standartwert : '80')"
},
"title": "Definieren Sie den deCONZ-Gateway"
},
"link": {
"description": "Entsperren Sie Ihr deCONZ-Gateway, um sich bei Home Assistant zu registrieren. \n\n 1. Gehen Sie zu den deCONZ-Systemeinstellungen \n 2. Dr\u00fccken Sie die Taste \"Gateway entsperren\"",
"title": "Mit deCONZ verbinden"
}
},
"title": "deCONZ"
}
}

View File

@@ -1,26 +1,26 @@
{
"config": {
"title": "deCONZ",
"step": {
"init": {
"title": "Define deCONZ gateway",
"data": {
"host": "Host",
"port": "Port (default value: '80')"
}
},
"link": {
"title": "Link with deCONZ",
"description": "Unlock your deCONZ gateway to register with Home Assistant.\n\n1. Go to deCONZ system settings\n2. Press \"Unlock Gateway\" button"
}
},
"error": {
"no_key": "Couldn't get an API key"
},
"abort": {
"already_configured": "Bridge is already configured",
"no_bridges": "No deCONZ bridges discovered",
"one_instance_only": "Component only supports one deCONZ instance"
}
},
"error": {
"no_key": "Couldn't get an API key"
},
"step": {
"init": {
"data": {
"host": "Host",
"port": "Port (default value: '80')"
},
"title": "Define deCONZ gateway"
},
"link": {
"description": "Unlock your deCONZ gateway to register with Home Assistant.\n\n1. Go to deCONZ system settings\n2. Press \"Unlock Gateway\" button",
"title": "Link with deCONZ"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,22 @@
{
"config": {
"abort": {
"one_instance_only": "Ez a komponens csak egy deCONZ egys\u00e9get t\u00e1mogat"
},
"error": {
"no_key": "API kulcs lek\u00e9r\u00e9se nem siker\u00fclt"
},
"step": {
"init": {
"data": {
"host": "H\u00e1zigazda (Host)",
"port": "Port (alap\u00e9rtelmezett \u00e9rt\u00e9k: '80')"
}
},
"link": {
"title": "Kapcsol\u00f3d\u00e1s a deCONZ-hoz"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"already_configured": "\ube0c\ub9bf\uc9c0\uac00 \uc774\ubbf8 \uad6c\uc131\ub418\uc5c8\uc2b5\ub2c8\ub2e4",
"no_bridges": "\ubc1c\uacac\ub41c deCONZ \ube0c\ub9bf\uc9c0\uac00 \uc5c6\uc2b5\ub2c8\ub2e4",
"one_instance_only": "\uad6c\uc131\uc694\uc18c\ub294 \ud558\ub098\uc758 deCONZ \uc778\uc2a4\ud134\uc2a4 \ub9cc \uc9c0\uc6d0\ud569\ub2c8\ub2e4"
},
"error": {
"no_key": "API \ud0a4\ub97c \uac00\uc838\uc62c \uc218 \uc5c6\uc2b5\ub2c8\ub2e4"
},
"step": {
"init": {
"data": {
"host": "\ud638\uc2a4\ud2b8",
"port": "\ud3ec\ud2b8 (\uae30\ubcf8\uac12: '80')"
},
"title": "deCONZ \uac8c\uc774\ud2b8\uc6e8\uc774 \uc815\uc758"
},
"link": {
"description": "deCONZ \uac8c\uc774\ud2b8\uc6e8\uc774\ub97c \uc5b8\ub77d\ud558\uc5ec Home Assistant \uc5d0 \uc5f0\uacb0\ud558\uae30\n\n1. deCONZ \uc2dc\uc2a4\ud15c \uc124\uc815\uc73c\ub85c \uc774\ub3d9\ud558\uc138\uc694\n2. \"Unlock Gateway\" \ubc84\ud2bc\uc744 \ub204\ub974\uc138\uc694 ",
"title": "deCONZ \uc640 \uc5f0\uacb0"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"already_configured": "Bridge ass schon konfigur\u00e9iert",
"no_bridges": "Keng dECONZ bridges fonnt",
"one_instance_only": "Komponent \u00ebnnerst\u00ebtzt n\u00ebmmen eng deCONZ Instanz"
},
"error": {
"no_key": "Konnt keen API Schl\u00ebssel kr\u00e9ien"
},
"step": {
"init": {
"data": {
"host": "Host",
"port": "Port (Standard Wert: '80')"
},
"title": "deCONZ gateway d\u00e9fin\u00e9ieren"
},
"link": {
"description": "Entsperrt \u00e4r deCONZ gateway fir se mat Home Assistant ze registr\u00e9ieren.\n\n1. Gidd op\u00a0deCONZ System Astellungen\n2. Dr\u00e9ckt \"Unlock\" Gateway Kn\u00e4ppchen",
"title": "Link mat deCONZ"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"already_configured": "Bridge is al geconfigureerd",
"no_bridges": "Geen deCONZ bruggen ontdekt",
"one_instance_only": "Component ondersteunt slechts \u00e9\u00e9n deCONZ instance"
},
"error": {
"no_key": "Kon geen API-sleutel ophalen"
},
"step": {
"init": {
"data": {
"host": "Host",
"port": "Poort (standaard: '80')"
},
"title": "Definieer deCONZ gateway"
},
"link": {
"description": "Ontgrendel je deCONZ gateway om te registreren met Home Assistant.\n\n1. Ga naar deCONZ systeeminstellingen\n2. Druk op de knop \"Gateway ontgrendelen\"",
"title": "Koppel met deCONZ"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"already_configured": "Broen er allerede konfigurert",
"no_bridges": "Ingen deCONZ broer oppdaget",
"one_instance_only": "Komponenten st\u00f8tter bare \u00e9n deCONZ forekomst"
},
"error": {
"no_key": "Kunne ikke f\u00e5 en API-n\u00f8kkel"
},
"step": {
"init": {
"data": {
"host": "Vert",
"port": "Port (standardverdi: '80')"
},
"title": "Definer deCONZ-gatewayen"
},
"link": {
"description": "L\u00e5s opp deCONZ-gatewayen din for \u00e5 registrere deg med Home Assistant. \n\n 1. G\u00e5 til deCONZ-systeminnstillinger \n 2. Trykk p\u00e5 \"L\u00e5s opp gateway\" knappen",
"title": "Koble til deCONZ"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"already_configured": "Mostek jest ju\u017c skonfigurowany",
"no_bridges": "Nie odkryto mostk\u00f3w deCONZ",
"one_instance_only": "Komponent obs\u0142uguje tylko jedn\u0105 instancj\u0119 deCONZ"
},
"error": {
"no_key": "Nie mo\u017cna uzyska\u0107 klucza API"
},
"step": {
"init": {
"data": {
"host": "Host",
"port": "Port (warto\u015b\u0107 domy\u015blna: \"80\")"
},
"title": "Zdefiniuj bramk\u0119 deCONZ"
},
"link": {
"description": "Odblokuj bramk\u0119 deCONZ, aby zarejestrowa\u0107 j\u0105 w Home Assistant. \n\n 1. Przejd\u017a do ustawie\u0144 systemu deCONZ \n 2. Naci\u015bnij przycisk \"Odblokuj bramk\u0119\"",
"title": "Po\u0142\u0105cz z deCONZ"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,7 @@
{
"config": {
"abort": {
"already_configured": "Bridge j\u00e1 est\u00e1 configurada"
}
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"already_configured": "\u0428\u043b\u044e\u0437 \u0443\u0436\u0435 \u043d\u0430\u0441\u0442\u0440\u043e\u0435\u043d",
"no_bridges": "\u0428\u043b\u044e\u0437\u044b deCONZ \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d\u044b",
"one_instance_only": "\u041a\u043e\u043c\u043f\u043e\u043d\u0435\u043d\u0442 \u043f\u043e\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442 \u0442\u043e\u043b\u044c\u043a\u043e \u043e\u0434\u0438\u043d \u044d\u043a\u0437\u0435\u043c\u043f\u043b\u044f\u0440 deCONZ"
},
"error": {
"no_key": "\u041d\u0435 \u0443\u0434\u0430\u043b\u043e\u0441\u044c \u043f\u043e\u043b\u0443\u0447\u0438\u0442\u044c \u043a\u043b\u044e\u0447 API"
},
"step": {
"init": {
"data": {
"host": "\u0425\u043e\u0441\u0442",
"port": "\u041f\u043e\u0440\u0442 (\u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e: '80')"
},
"title": "\u041e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u044c \u0448\u043b\u044e\u0437 deCONZ"
},
"link": {
"description": "\u0420\u0430\u0437\u0431\u043b\u043e\u043a\u0438\u0440\u0443\u0439\u0442\u0435 \u0448\u043b\u044e\u0437 deCONZ \u0434\u043b\u044f \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0432 Home Assistant:\n\n1. \u041f\u0435\u0440\u0435\u0439\u0434\u0438\u0442\u0435 \u043a \u043d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0430\u043c \u0441\u0438\u0441\u0442\u0435\u043c\u044b deCONZ\n2. \u041d\u0430\u0436\u043c\u0438\u0442\u0435 \u043a\u043d\u043e\u043f\u043a\u0443 \u00ab\u0420\u0430\u0437\u0431\u043b\u043e\u043a\u0438\u0440\u043e\u0432\u0430\u0442\u044c \u0448\u043b\u044e\u0437\u00bb",
"title": "\u0421\u0432\u044f\u0437\u044c \u0441 deCONZ"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"already_configured": "Most je \u017ee nastavljen",
"no_bridges": "Ni odkritih mostov deCONZ",
"one_instance_only": "Komponenta podpira le en primerek deCONZ"
},
"error": {
"no_key": "Klju\u010da API ni mogo\u010de dobiti"
},
"step": {
"init": {
"data": {
"host": "Gostitelj",
"port": "Vrata (privzeta vrednost: '80')"
},
"title": "Dolo\u010dite deCONZ prehod"
},
"link": {
"description": "Odklenite va\u0161 deCONZ gateway za registracijo z Home Assistant-om. \n1. Pojdite v deCONT sistemske nastavitve\n2. Pritisnite tipko \"odkleni prehod\"",
"title": "Povezava z deCONZ"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"already_configured": "\u6865\u63a5\u5668\u5df2\u914d\u7f6e\u5b8c\u6210",
"no_bridges": "\u6ca1\u6709\u53d1\u73b0 deCONZ \u7684\u6865\u63a5\u8bbe\u5907",
"one_instance_only": "\u7ec4\u4ef6\u53ea\u652f\u6301\u4e00\u4e2a deCONZ \u5b9e\u4f8b"
},
"error": {
"no_key": "\u65e0\u6cd5\u83b7\u53d6 API \u5bc6\u94a5"
},
"step": {
"init": {
"data": {
"host": "\u4e3b\u673a",
"port": "\u7aef\u53e3\uff08\u9ed8\u8ba4\u503c\uff1a'80'\uff09"
},
"title": "\u5b9a\u4e49 deCONZ \u7f51\u5173"
},
"link": {
"description": "\u89e3\u9501\u60a8\u7684 deCONZ \u7f51\u5173\u4ee5\u6ce8\u518c\u5230 Home Assistant\u3002 \n\n 1. \u524d\u5f80 deCONZ \u7cfb\u7edf\u8bbe\u7f6e\n 2. \u70b9\u51fb\u201c\u89e3\u9501\u7f51\u5173\u201d\u6309\u94ae",
"title": "\u8fde\u63a5 deCONZ"
}
},
"title": "deCONZ"
}
}

View File

@@ -0,0 +1,25 @@
{
"config": {
"abort": {
"no_bridges": "\u672a\u641c\u5c0b\u5230 deCONZ Bridfe",
"one_instance_only": "\u7d44\u4ef6\u50c5\u652f\u63f4\u4e00\u7d44 deCONZ \u5be6\u4f8b"
},
"error": {
"no_key": "\u7121\u6cd5\u53d6\u5f97 API key"
},
"step": {
"init": {
"data": {
"host": "\u4e3b\u6a5f\u7aef",
"port": "\u901a\u8a0a\u57e0\uff08\u9810\u8a2d\u503c\uff1a'80'\uff09"
},
"title": "\u5b9a\u7fa9 deCONZ \u7db2\u95dc"
},
"link": {
"description": "\u89e3\u9664 deCONZ \u7db2\u95dc\u9396\u5b9a\uff0c\u4ee5\u65bc Home Assistant \u9032\u884c\u8a3b\u518a\u3002\n\n1. \u9032\u5165 deCONZ \u7cfb\u7d71\u8a2d\u5b9a\n2. \u6309\u4e0b\u300c\u89e3\u9664\u7db2\u95dc\u9396\u5b9a\uff08Unlock Gateway\uff09\u300d\u6309\u9215",
"title": "\u9023\u7d50\u81f3 deCONZ"
}
},
"title": "deCONZ"
}
}

View File

@@ -7,17 +7,22 @@ https://home-assistant.io/components/deconz/
import voluptuous as vol
from homeassistant.const import (
CONF_API_KEY, CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP)
from homeassistant.core import callback
from homeassistant.helpers import (
aiohttp_client, discovery, config_validation as cv)
CONF_API_KEY, CONF_EVENT, CONF_HOST,
CONF_ID, CONF_PORT, EVENT_HOMEASSISTANT_STOP)
from homeassistant.core import EventOrigin, callback
from homeassistant.helpers import aiohttp_client, config_validation as cv
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect, async_dispatcher_send)
from homeassistant.util import slugify
from homeassistant.util.json import load_json
# Loading the config flow file will register the flow
from .config_flow import configured_hosts
from .const import CONFIG_FILE, DATA_DECONZ_ID, DOMAIN, _LOGGER
from .const import (
CONFIG_FILE, DATA_DECONZ_EVENT, DATA_DECONZ_ID,
DATA_DECONZ_UNSUB, DOMAIN, _LOGGER)
REQUIREMENTS = ['pydeconz==36']
REQUIREMENTS = ['pydeconz==38']
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
@@ -27,6 +32,8 @@ CONFIG_SCHEMA = vol.Schema({
})
}, extra=vol.ALLOW_EXTRA)
SERVICE_DECONZ = 'configure'
SERVICE_FIELD = 'field'
SERVICE_ENTITY = 'entity'
SERVICE_DATA = 'data'
@@ -58,28 +65,27 @@ async def async_setup(hass, config):
return True
async def async_setup_entry(hass, entry):
"""Set up a deCONZ bridge for a config entry."""
if DOMAIN in hass.data:
_LOGGER.error(
"Config entry failed since one deCONZ instance already exists")
return False
result = await async_setup_deconz(hass, None, entry.data)
if result:
return True
return False
async def async_setup_deconz(hass, config, deconz_config):
"""Set up a deCONZ session.
async def async_setup_entry(hass, config_entry):
"""Set up a deCONZ bridge for a config entry.
Load config, group, light and sensor data for server information.
Start websocket for push notification of state changes from deCONZ.
"""
_LOGGER.debug("deCONZ config %s", deconz_config)
from pydeconz import DeconzSession
if DOMAIN in hass.data:
_LOGGER.error(
"Config entry failed since one deCONZ instance already exists")
return False
@callback
def async_add_device_callback(device_type, device):
"""Called when a new device has been created in deCONZ."""
async_dispatcher_send(
hass, 'deconz_new_{}'.format(device_type), [device])
session = aiohttp_client.async_get_clientsession(hass)
deconz = DeconzSession(hass.loop, session, **deconz_config)
deconz = DeconzSession(hass.loop, session, **config_entry.data,
async_add_device=async_add_device_callback)
result = await deconz.async_load_parameters()
if result is False:
_LOGGER.error("Failed to communicate with deCONZ")
@@ -87,10 +93,25 @@ async def async_setup_deconz(hass, config, deconz_config):
hass.data[DOMAIN] = deconz
hass.data[DATA_DECONZ_ID] = {}
hass.data[DATA_DECONZ_EVENT] = []
hass.data[DATA_DECONZ_UNSUB] = []
for component in ['binary_sensor', 'light', 'scene', 'sensor']:
hass.async_add_job(discovery.async_load_platform(
hass, component, DOMAIN, {}, config))
hass.async_add_job(hass.config_entries.async_forward_entry_setup(
config_entry, component))
@callback
def async_add_remote(sensors):
"""Setup remote from deCONZ."""
from pydeconz.sensor import SWITCH as DECONZ_REMOTE
for sensor in sensors:
if sensor.type in DECONZ_REMOTE:
hass.data[DATA_DECONZ_EVENT].append(DeconzEvent(hass, sensor))
hass.data[DATA_DECONZ_UNSUB].append(
async_dispatcher_connect(hass, 'deconz_new_sensor', async_add_remote))
async_add_remote(deconz.sensors.values())
deconz.start()
async def async_configure(call):
@@ -121,7 +142,7 @@ async def async_setup_deconz(hass, config, deconz_config):
return
await deconz.async_put_state(field, data)
hass.services.async_register(
DOMAIN, 'configure', async_configure, schema=SERVICE_SCHEMA)
DOMAIN, SERVICE_DECONZ, async_configure, schema=SERVICE_SCHEMA)
@callback
def deconz_shutdown(event):
@@ -136,3 +157,43 @@ async def async_setup_deconz(hass, config, deconz_config):
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, deconz_shutdown)
return True
async def async_unload_entry(hass, config_entry):
"""Unload deCONZ config entry."""
deconz = hass.data.pop(DOMAIN)
hass.services.async_remove(DOMAIN, SERVICE_DECONZ)
deconz.close()
for component in ['binary_sensor', 'light', 'scene', 'sensor']:
await hass.config_entries.async_forward_entry_unload(
config_entry, component)
dispatchers = hass.data[DATA_DECONZ_UNSUB]
for unsub_dispatcher in dispatchers:
unsub_dispatcher()
hass.data[DATA_DECONZ_UNSUB] = []
hass.data[DATA_DECONZ_EVENT] = []
hass.data[DATA_DECONZ_ID] = []
return True
class DeconzEvent(object):
"""When you want signals instead of entities.
Stateless sensors such as remotes are expected to generate an event
instead of a sensor entity in hass.
"""
def __init__(self, hass, device):
"""Register callback that will be used for signals."""
self._hass = hass
self._device = device
self._device.register_async_callback(self.async_update_callback)
self._event = 'deconz_{}'.format(CONF_EVENT)
self._id = slugify(self._device.name)
@callback
def async_update_callback(self, reason):
"""Fire the event if reason is that state is updated."""
if reason['state']:
data = {CONF_ID: self._id, CONF_EVENT: self._device.state}
self._hass.bus.async_fire(self._event, data, EventOrigin.remote)

View File

@@ -5,4 +5,6 @@ _LOGGER = logging.getLogger('homeassistant.components.deconz')
DOMAIN = 'deconz'
CONFIG_FILE = 'deconz.conf'
DATA_DECONZ_EVENT = 'deconz_events'
DATA_DECONZ_ID = 'deconz_entities'
DATA_DECONZ_UNSUB = 'deconz_dispatchers'

View File

@@ -16,7 +16,6 @@ from homeassistant.const import STATE_HOME, STATE_NOT_HOME
from homeassistant.helpers.event import (
async_track_point_in_utc_time, async_track_state_change)
from homeassistant.helpers.sun import is_up, get_astral_event_next
from homeassistant.loader import get_component
import homeassistant.helpers.config_validation as cv
DOMAIN = 'device_sun_light_trigger'
@@ -48,9 +47,9 @@ CONFIG_SCHEMA = vol.Schema({
def async_setup(hass, config):
"""Set up the triggers to control lights based on device presence."""
logger = logging.getLogger(__name__)
device_tracker = get_component('device_tracker')
group = get_component('group')
light = get_component('light')
device_tracker = hass.components.device_tracker
group = hass.components.group
light = hass.components.light
conf = config[DOMAIN]
disable_turn_off = conf.get(CONF_DISABLE_TURN_OFF)
light_group = conf.get(CONF_LIGHT_GROUP, light.ENTITY_ID_ALL_LIGHTS)
@@ -58,14 +57,14 @@ def async_setup(hass, config):
device_group = conf.get(
CONF_DEVICE_GROUP, device_tracker.ENTITY_ID_ALL_DEVICES)
device_entity_ids = group.get_entity_ids(
hass, device_group, device_tracker.DOMAIN)
device_group, device_tracker.DOMAIN)
if not device_entity_ids:
logger.error("No devices found to track")
return False
# Get the light IDs from the specified group
light_ids = group.get_entity_ids(hass, light_group, light.DOMAIN)
light_ids = group.get_entity_ids(light_group, light.DOMAIN)
if not light_ids:
logger.error("No lights found to turn on")
@@ -85,9 +84,9 @@ def async_setup(hass, config):
def async_turn_on_before_sunset(light_id):
"""Turn on lights."""
if not device_tracker.is_on(hass) or light.is_on(hass, light_id):
if not device_tracker.is_on() or light.is_on(light_id):
return
light.async_turn_on(hass, light_id,
light.async_turn_on(light_id,
transition=LIGHT_TRANSITION_TIME.seconds,
profile=light_profile)
@@ -129,7 +128,7 @@ def async_setup(hass, config):
@callback
def check_light_on_dev_state_change(entity, old_state, new_state):
"""Handle tracked device state changes."""
lights_are_on = group.is_on(hass, light_group)
lights_are_on = group.is_on(light_group)
light_needed = not (lights_are_on or is_up(hass))
# These variables are needed for the elif check
@@ -139,7 +138,7 @@ def async_setup(hass, config):
# Do we need lights?
if light_needed:
logger.info("Home coming event for %s. Turning lights on", entity)
light.async_turn_on(hass, light_ids, profile=light_profile)
light.async_turn_on(light_ids, profile=light_profile)
# Are we in the time span were we would turn on the lights
# if someone would be home?
@@ -152,7 +151,7 @@ def async_setup(hass, config):
# when the fading in started and turn it on if so
for index, light_id in enumerate(light_ids):
if now > start_point + index * LIGHT_TRANSITION_TIME:
light.async_turn_on(hass, light_id)
light.async_turn_on(light_id)
else:
# If this light didn't happen to be turned on yet so
@@ -169,12 +168,12 @@ def async_setup(hass, config):
@callback
def turn_off_lights_when_all_leave(entity, old_state, new_state):
"""Handle device group state change."""
if not group.is_on(hass, light_group):
if not group.is_on(light_group):
return
logger.info(
"Everyone has left but there are lights on. Turning them off")
light.async_turn_off(hass, light_ids)
light.async_turn_off(light_ids)
async_track_state_change(
hass, device_group, turn_off_lights_when_all_leave,

View File

@@ -15,6 +15,7 @@ from homeassistant.setup import async_prepare_setup_platform
from homeassistant.core import callback
from homeassistant.loader import bind_hass
from homeassistant.components import group, zone
from homeassistant.components.zone.zone import async_active_zone
from homeassistant.config import load_yaml_config_file, async_log_exception
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_per_platform, discovery
@@ -23,7 +24,6 @@ from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.restore_state import async_get_last_state
from homeassistant.helpers.typing import GPSType, ConfigType, HomeAssistantType
import homeassistant.helpers.config_validation as cv
from homeassistant.loader import get_component
import homeassistant.util as util
from homeassistant.util.async_ import run_coroutine_threadsafe
import homeassistant.util.dt as dt_util
@@ -33,7 +33,7 @@ from homeassistant.helpers.event import async_track_utc_time_change
from homeassistant.const import (
ATTR_GPS_ACCURACY, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_NAME, CONF_MAC,
DEVICE_DEFAULT_NAME, STATE_HOME, STATE_NOT_HOME, ATTR_ENTITY_ID,
CONF_ICON, ATTR_ICON)
CONF_ICON, ATTR_ICON, ATTR_NAME)
_LOGGER = logging.getLogger(__name__)
@@ -71,7 +71,6 @@ ATTR_GPS = 'gps'
ATTR_HOST_NAME = 'host_name'
ATTR_LOCATION_NAME = 'location_name'
ATTR_MAC = 'mac'
ATTR_NAME = 'name'
ATTR_SOURCE_TYPE = 'source_type'
ATTR_CONSIDER_HOME = 'consider_home'
@@ -321,7 +320,7 @@ class DeviceTracker(object):
# During init, we ignore the group
if self.group and self.track_new:
self.group.async_set_group(
self.hass, util.slugify(GROUP_NAME_ALL_DEVICES), visible=False,
util.slugify(GROUP_NAME_ALL_DEVICES), visible=False,
name=GROUP_NAME_ALL_DEVICES, add=[device.entity_id])
self.hass.bus.async_fire(EVENT_NEW_DEVICE, {
@@ -356,9 +355,9 @@ class DeviceTracker(object):
entity_ids = [dev.entity_id for dev in self.devices.values()
if dev.track]
self.group = get_component('group')
self.group = self.hass.components.group
self.group.async_set_group(
self.hass, util.slugify(GROUP_NAME_ALL_DEVICES), visible=False,
util.slugify(GROUP_NAME_ALL_DEVICES), visible=False,
name=GROUP_NAME_ALL_DEVICES, entity_ids=entity_ids)
@callback
@@ -541,7 +540,7 @@ class Device(Entity):
elif self.location_name:
self._state = self.location_name
elif self.gps is not None and self.source_type == SOURCE_TYPE_GPS:
zone_state = zone.async_active_zone(
zone_state = async_active_zone(
self.hass, self.gps[0], self.gps[1], self.gps_accuracy)
if zone_state is None:
self._state = STATE_NOT_HOME

View File

@@ -12,14 +12,18 @@ import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.device_tracker import (
PLATFORM_SCHEMA, SOURCE_TYPE_GPS)
from homeassistant.const import CONF_USERNAME, CONF_PASSWORD
from homeassistant.const import CONF_USERNAME, CONF_PASSWORD, ATTR_ID
from homeassistant.helpers.event import track_time_interval
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import slugify
REQUIREMENTS = ['locationsharinglib==2.0.2']
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['locationsharinglib==1.2.1']
ATTR_ADDRESS = 'address'
ATTR_FULL_NAME = 'full_name'
ATTR_LAST_SEEN = 'last_seen'
ATTR_NICKNAME = 'nickname'
CREDENTIALS_FILE = '.google_maps_location_sharing.cookies'
@@ -60,24 +64,29 @@ class GoogleMapsScanner(object):
self.success_init = True
except InvalidUser:
_LOGGER.error('You have specified invalid login credentials')
_LOGGER.error("You have specified invalid login credentials")
self.success_init = False
def _update_info(self, now=None):
for person in self.service.get_all_people():
dev_id = 'google_maps_{0}'.format(slugify(person.id))
try:
dev_id = 'google_maps_{0}'.format(person.id)
except TypeError:
_LOGGER.warning("No location(s) shared with this account")
return
attrs = {
'id': person.id,
'nickname': person.nickname,
'full_name': person.full_name,
'last_seen': person.datetime,
'address': person.address
ATTR_ADDRESS: person.address,
ATTR_FULL_NAME: person.full_name,
ATTR_ID: person.id,
ATTR_LAST_SEEN: person.datetime,
ATTR_NICKNAME: person.nickname,
}
self.see(
dev_id=dev_id,
gps=(person.latitude, person.longitude),
picture=person.picture_url,
source_type=SOURCE_TYPE_GPS,
attributes=attrs
gps_accuracy=person.accuracy,
attributes=attrs,
)

View File

@@ -4,7 +4,6 @@ Support for the GPSLogger platform.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.gpslogger/
"""
import asyncio
import logging
from hmac import compare_digest
@@ -22,6 +21,7 @@ from homeassistant.components.http import (
from homeassistant.components.device_tracker import ( # NOQA
DOMAIN, PLATFORM_SCHEMA
)
from homeassistant.helpers.typing import HomeAssistantType, ConfigType
_LOGGER = logging.getLogger(__name__)
@@ -32,8 +32,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
@asyncio.coroutine
def async_setup_scanner(hass, config, async_see, discovery_info=None):
async def async_setup_scanner(hass: HomeAssistantType, config: ConfigType,
async_see, discovery_info=None):
"""Set up an endpoint for the GPSLogger application."""
hass.http.register_view(GPSLoggerView(async_see, config))
@@ -54,8 +54,7 @@ class GPSLoggerView(HomeAssistantView):
# password is set
self.requires_auth = self._password is None
@asyncio.coroutine
def get(self, request: Request):
async def get(self, request: Request):
"""Handle for GPSLogger message received as GET."""
hass = request.app['hass']
data = request.query

View File

@@ -14,15 +14,18 @@ import homeassistant.helpers.config_validation as cv
from homeassistant.components.device_tracker import (
DOMAIN, PLATFORM_SCHEMA, DeviceScanner)
from homeassistant.const import (
CONF_HOST, CONF_PASSWORD, CONF_USERNAME
CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_TYPE
)
_LOGGER = logging.getLogger(__name__)
DEFAULT_TYPE = "rogers"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_TYPE, default=DEFAULT_TYPE): cv.string,
})
@@ -49,6 +52,11 @@ class HitronCODADeviceScanner(DeviceScanner):
self._username = config.get(CONF_USERNAME)
self._password = config.get(CONF_PASSWORD)
if config.get(CONF_TYPE) == "shaw":
self._type = 'pwd'
else:
self._type = 'pws'
self._userid = None
self.success_init = self._update_info()
@@ -74,7 +82,7 @@ class HitronCODADeviceScanner(DeviceScanner):
try:
data = [
('user', self._username),
('pws', self._password),
(self._type, self._password),
]
res = requests.post(self._loginurl, data=data, timeout=10)
except requests.exceptions.Timeout:

View File

@@ -13,7 +13,7 @@ import voluptuous as vol
from homeassistant.const import CONF_USERNAME, CONF_PASSWORD
from homeassistant.components.device_tracker import (
PLATFORM_SCHEMA, DOMAIN, ATTR_ATTRIBUTES, ENTITY_ID_FORMAT, DeviceScanner)
from homeassistant.components.zone import active_zone
from homeassistant.components.zone.zone import active_zone
from homeassistant.helpers.event import track_utc_time_change
import homeassistant.helpers.config_validation as cv
from homeassistant.util import slugify
@@ -24,8 +24,9 @@ _LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['pyicloud==0.9.1']
CONF_IGNORED_DEVICES = 'ignored_devices'
CONF_ACCOUNTNAME = 'account_name'
CONF_MAX_INTERVAL = 'max_interval'
CONF_GPS_ACCURACY_THRESHOLD = 'gps_accuracy_threshold'
# entity attributes
ATTR_ACCOUNTNAME = 'account_name'
@@ -64,13 +65,15 @@ DEVICESTATUSCODES = {
SERVICE_SCHEMA = vol.Schema({
vol.Optional(ATTR_ACCOUNTNAME): vol.All(cv.ensure_list, [cv.slugify]),
vol.Optional(ATTR_DEVICENAME): cv.slugify,
vol.Optional(ATTR_INTERVAL): cv.positive_int,
vol.Optional(ATTR_INTERVAL): cv.positive_int
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(ATTR_ACCOUNTNAME): cv.slugify,
vol.Optional(CONF_MAX_INTERVAL, default=30): cv.positive_int,
vol.Optional(CONF_GPS_ACCURACY_THRESHOLD, default=1000): cv.positive_int
})
@@ -79,8 +82,11 @@ def setup_scanner(hass, config: dict, see, discovery_info=None):
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
account = config.get(CONF_ACCOUNTNAME, slugify(username.partition('@')[0]))
max_interval = config.get(CONF_MAX_INTERVAL)
gps_accuracy_threshold = config.get(CONF_GPS_ACCURACY_THRESHOLD)
icloudaccount = Icloud(hass, username, password, account, see)
icloudaccount = Icloud(hass, username, password, account, max_interval,
gps_accuracy_threshold, see)
if icloudaccount.api is not None:
ICLOUDTRACKERS[account] = icloudaccount
@@ -96,6 +102,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None):
for account in accounts:
if account in ICLOUDTRACKERS:
ICLOUDTRACKERS[account].lost_iphone(devicename)
hass.services.register(DOMAIN, 'icloud_lost_iphone', lost_iphone,
schema=SERVICE_SCHEMA)
@@ -106,6 +113,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None):
for account in accounts:
if account in ICLOUDTRACKERS:
ICLOUDTRACKERS[account].update_icloud(devicename)
hass.services.register(DOMAIN, 'icloud_update', update_icloud,
schema=SERVICE_SCHEMA)
@@ -115,6 +123,7 @@ def setup_scanner(hass, config: dict, see, discovery_info=None):
for account in accounts:
if account in ICLOUDTRACKERS:
ICLOUDTRACKERS[account].reset_account_icloud()
hass.services.register(DOMAIN, 'icloud_reset_account',
reset_account_icloud, schema=SERVICE_SCHEMA)
@@ -137,7 +146,8 @@ def setup_scanner(hass, config: dict, see, discovery_info=None):
class Icloud(DeviceScanner):
"""Representation of an iCloud account."""
def __init__(self, hass, username, password, name, see):
def __init__(self, hass, username, password, name, max_interval,
gps_accuracy_threshold, see):
"""Initialize an iCloud account."""
self.hass = hass
self.username = username
@@ -148,6 +158,8 @@ class Icloud(DeviceScanner):
self.seen_devices = {}
self._overridestates = {}
self._intervals = {}
self._max_interval = max_interval
self._gps_accuracy_threshold = gps_accuracy_threshold
self.see = see
self._trusted_device = None
@@ -348,7 +360,7 @@ class Icloud(DeviceScanner):
self._overridestates[devicename] = None
if currentzone is not None:
self._intervals[devicename] = 30
self._intervals[devicename] = self._max_interval
return
if mindistance is None:
@@ -363,7 +375,6 @@ class Icloud(DeviceScanner):
if interval > 180:
# Three hour drive? This is far enough that they might be flying
# home - check every half hour
interval = 30
if battery is not None and battery <= 33 and mindistance > 3:
@@ -403,22 +414,24 @@ class Icloud(DeviceScanner):
status = device.status(DEVICESTATUSSET)
battery = status.get('batteryLevel', 0) * 100
location = status['location']
if location:
self.determine_interval(
devicename, location['latitude'],
location['longitude'], battery)
interval = self._intervals.get(devicename, 1)
attrs[ATTR_INTERVAL] = interval
accuracy = location['horizontalAccuracy']
kwargs['dev_id'] = dev_id
kwargs['host_name'] = status['name']
kwargs['gps'] = (location['latitude'],
location['longitude'])
kwargs['battery'] = battery
kwargs['gps_accuracy'] = accuracy
kwargs[ATTR_ATTRIBUTES] = attrs
self.see(**kwargs)
self.seen_devices[devicename] = True
if location and location['horizontalAccuracy']:
horizontal_accuracy = int(location['horizontalAccuracy'])
if horizontal_accuracy < self._gps_accuracy_threshold:
self.determine_interval(
devicename, location['latitude'],
location['longitude'], battery)
interval = self._intervals.get(devicename, 1)
attrs[ATTR_INTERVAL] = interval
accuracy = location['horizontalAccuracy']
kwargs['dev_id'] = dev_id
kwargs['host_name'] = status['name']
kwargs['gps'] = (location['latitude'],
location['longitude'])
kwargs['battery'] = battery
kwargs['gps_accuracy'] = accuracy
kwargs[ATTR_ATTRIBUTES] = attrs
self.see(**kwargs)
self.seen_devices[devicename] = True
except PyiCloudNoDevicesException:
_LOGGER.error("No iCloud Devices found")
@@ -434,7 +447,7 @@ class Icloud(DeviceScanner):
device.play_sound()
def update_icloud(self, devicename=None):
"""Authenticate against iCloud and scan for devices."""
"""Request device information from iCloud and update device_tracker."""
from pyicloud.exceptions import PyiCloudNoDevicesException
if self.api is None:
@@ -443,13 +456,13 @@ class Icloud(DeviceScanner):
try:
if devicename is not None:
if devicename in self.devices:
self.devices[devicename].location()
self.update_device(devicename)
else:
_LOGGER.error("devicename %s unknown for account %s",
devicename, self._attrs[ATTR_ACCOUNTNAME])
else:
for device in self.devices:
self.devices[device].location()
self.update_device(device)
except PyiCloudNoDevicesException:
_LOGGER.error("No iCloud Devices found")

View File

@@ -12,21 +12,27 @@ import homeassistant.helpers.config_validation as cv
from homeassistant.components.device_tracker import (
DOMAIN, PLATFORM_SCHEMA, DeviceScanner)
from homeassistant.const import (
CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_PORT)
CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_PORT, CONF_SSL,
CONF_DEVICES, CONF_EXCLUDE)
REQUIREMENTS = ['pynetgear==0.3.3']
REQUIREMENTS = ['pynetgear==0.4.0']
_LOGGER = logging.getLogger(__name__)
DEFAULT_HOST = 'routerlogin.net'
DEFAULT_USER = 'admin'
DEFAULT_PORT = 5000
CONF_APS = 'accesspoints'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_USERNAME, default=DEFAULT_USER): cv.string,
vol.Optional(CONF_HOST, default=''): cv.string,
vol.Optional(CONF_SSL, default=False): cv.boolean,
vol.Optional(CONF_USERNAME, default=''): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port
vol.Optional(CONF_PORT, default=None): vol.Any(None, cv.port),
vol.Optional(CONF_DEVICES, default=[]):
vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_EXCLUDE, default=[]):
vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_APS, default=[]):
vol.All(cv.ensure_list, [cv.string]),
})
@@ -34,11 +40,16 @@ def get_scanner(hass, config):
"""Validate the configuration and returns a Netgear scanner."""
info = config[DOMAIN]
host = info.get(CONF_HOST)
ssl = info.get(CONF_SSL)
username = info.get(CONF_USERNAME)
password = info.get(CONF_PASSWORD)
port = info.get(CONF_PORT)
devices = info.get(CONF_DEVICES)
excluded_devices = info.get(CONF_EXCLUDE)
accesspoints = info.get(CONF_APS)
scanner = NetgearDeviceScanner(host, username, password, port)
scanner = NetgearDeviceScanner(host, ssl, username, password, port,
devices, excluded_devices, accesspoints)
return scanner if scanner.success_init else None
@@ -46,16 +57,21 @@ def get_scanner(hass, config):
class NetgearDeviceScanner(DeviceScanner):
"""Queries a Netgear wireless router using the SOAP-API."""
def __init__(self, host, username, password, port):
def __init__(self, host, ssl, username, password, port, devices,
excluded_devices, accesspoints):
"""Initialize the scanner."""
import pynetgear
self.tracked_devices = devices
self.excluded_devices = excluded_devices
self.tracked_accesspoints = accesspoints
self.last_results = []
self._api = pynetgear.Netgear(password, host, username, port)
self._api = pynetgear.Netgear(password, host, username, port, ssl)
_LOGGER.info("Logging in")
results = self._api.get_attached_devices()
results = self.get_attached_devices()
self.success_init = results is not None
@@ -68,15 +84,50 @@ class NetgearDeviceScanner(DeviceScanner):
"""Scan for new devices and return a list with found device IDs."""
self._update_info()
return (device.mac for device in self.last_results)
devices = []
for dev in self.last_results:
tracked = (not self.tracked_devices or
dev.mac in self.tracked_devices or
dev.name in self.tracked_devices)
tracked = tracked and (not self.excluded_devices or not(
dev.mac in self.excluded_devices or
dev.name in self.excluded_devices))
if tracked:
devices.append(dev.mac)
if (self.tracked_accesspoints and
dev.conn_ap_mac in self.tracked_accesspoints):
devices.append(dev.mac + "_" + dev.conn_ap_mac)
return devices
def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
try:
return next(result.name for result in self.last_results
if result.mac == device)
except StopIteration:
return None
"""Return the name of the given device or the MAC if we don't know."""
parts = device.split("_")
mac = parts[0]
ap_mac = None
if len(parts) > 1:
ap_mac = parts[1]
name = None
for dev in self.last_results:
if dev.mac == mac:
name = dev.name
break
if not name or name == "--":
name = mac
if ap_mac:
ap_name = "Router"
for dev in self.last_results:
if dev.mac == ap_mac:
ap_name = dev.name
break
return name + " on " + ap_name
return name
def _update_info(self):
"""Retrieve latest information from the Netgear router.
@@ -88,9 +139,21 @@ class NetgearDeviceScanner(DeviceScanner):
_LOGGER.info("Scanning")
results = self._api.get_attached_devices()
results = self.get_attached_devices()
if results is None:
_LOGGER.warning("Error scanning devices")
self.last_results = results or []
def get_attached_devices(self):
"""
List attached devices with pynetgear.
The v2 method takes more time and is more heavy on the router
so we only use it if we need connected AP info.
"""
if self.tracked_accesspoints:
return self._api.get_attached_devices_2()
return self._api.get_attached_devices()

View File

@@ -207,7 +207,7 @@ def _req_json_rpc(url, session_id, rpcmethod, subsystem, method, **params):
try:
res = requests.post(url, data=data, timeout=5)
except requests.exceptions.Timeout:
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
return
if res.status_code == 200:

View File

@@ -4,7 +4,6 @@ Support for Dialogflow webhook.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/dialogflow/
"""
import asyncio
import logging
import voluptuous as vol
@@ -37,8 +36,7 @@ class DialogFlowError(HomeAssistantError):
"""Raised when a DialogFlow error happens."""
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up Dialogflow component."""
hass.http.register_view(DialogflowIntentsView)
@@ -51,16 +49,15 @@ class DialogflowIntentsView(HomeAssistantView):
url = INTENTS_API_ENDPOINT
name = 'api:dialogflow'
@asyncio.coroutine
def post(self, request):
async def post(self, request):
"""Handle Dialogflow."""
hass = request.app['hass']
message = yield from request.json()
message = await request.json()
_LOGGER.debug("Received Dialogflow request: %s", message)
try:
response = yield from async_handle_message(hass, message)
response = await async_handle_message(hass, message)
return b'' if response is None else self.json(response)
except DialogFlowError as err:
@@ -93,8 +90,7 @@ def dialogflow_error_response(hass, message, error):
return dialogflow_response.as_dict()
@asyncio.coroutine
def async_handle_message(hass, message):
async def async_handle_message(hass, message):
"""Handle a DialogFlow message."""
req = message.get('result')
action_incomplete = req['actionIncomplete']
@@ -110,7 +106,7 @@ def async_handle_message(hass, message):
raise DialogFlowError(
"You have not defined an action in your Dialogflow intent.")
intent_response = yield from intent.async_handle(
intent_response = await intent.async_handle(
hass, DOMAIN, action,
{key: {'value': value} for key, value
in parameters.items()})

View File

@@ -21,7 +21,7 @@ from homeassistant.helpers.event import async_track_point_in_utc_time
from homeassistant.helpers.discovery import async_load_platform, async_discover
import homeassistant.util.dt as dt_util
REQUIREMENTS = ['netdisco==1.3.1']
REQUIREMENTS = ['netdisco==1.4.1']
DOMAIN = 'discovery'
@@ -37,8 +37,10 @@ SERVICE_WINK = 'wink'
SERVICE_XIAOMI_GW = 'xiaomi_gw'
SERVICE_TELLDUSLIVE = 'tellstick'
SERVICE_HUE = 'philips_hue'
SERVICE_KONNECTED = 'konnected'
SERVICE_DECONZ = 'deconz'
SERVICE_DAIKIN = 'daikin'
SERVICE_SABNZBD = 'sabnzbd'
SERVICE_SAMSUNG_PRINTER = 'samsung_printer'
SERVICE_HOMEKIT = 'homekit'
@@ -59,7 +61,9 @@ SERVICE_HANDLERS = {
SERVICE_XIAOMI_GW: ('xiaomi_aqara', None),
SERVICE_TELLDUSLIVE: ('tellduslive', None),
SERVICE_DAIKIN: ('daikin', None),
SERVICE_SABNZBD: ('sabnzbd', None),
SERVICE_SAMSUNG_PRINTER: ('sensor', 'syncthru'),
SERVICE_KONNECTED: ('konnected', None),
'google_cast': ('media_player', 'cast'),
'panasonic_viera': ('media_player', 'panasonic_viera'),
'plex_mediaserver': ('media_player', 'plex'),
@@ -74,11 +78,11 @@ SERVICE_HANDLERS = {
'frontier_silicon': ('media_player', 'frontier_silicon'),
'openhome': ('media_player', 'openhome'),
'harmony': ('remote', 'harmony'),
'sabnzbd': ('sensor', 'sabnzbd'),
'bose_soundtouch': ('media_player', 'soundtouch'),
'bluesound': ('media_player', 'bluesound'),
'songpal': ('media_player', 'songpal'),
'kodi': ('media_player', 'kodi'),
'volumio': ('media_player', 'volumio'),
}
OPTIONAL_SERVICE_HANDLERS = {
@@ -189,6 +193,7 @@ def _discover(netdisco):
for disc in netdisco.discover():
for service in netdisco.get_info(disc):
results.append((disc, service))
finally:
netdisco.stop()

View File

@@ -22,7 +22,7 @@ from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_point_in_utc_time
from homeassistant.util.dt import utcnow
REQUIREMENTS = ['pyeight==0.0.7']
REQUIREMENTS = ['pyeight==0.0.8']
_LOGGER = logging.getLogger(__name__)

View File

@@ -20,7 +20,7 @@ import homeassistant.helpers.config_validation as cv
from homeassistant.util.json import load_json, save_json
from .hue_api import (
HueUsernameView, HueAllLightsStateView, HueOneLightStateView,
HueOneLightChangeView)
HueOneLightChangeView, HueGroupView)
from .upnp import DescriptionXmlView, UPNPResponderThread
DOMAIN = 'emulated_hue'
@@ -104,6 +104,7 @@ def setup(hass, yaml_config):
server.register_view(HueAllLightsStateView(config))
server.register_view(HueOneLightStateView(config))
server.register_view(HueOneLightChangeView(config))
server.register_view(HueGroupView(config))
upnp_listener = UPNPResponderThread(
config.host_ip_addr, config.listen_port,

View File

@@ -51,6 +51,29 @@ class HueUsernameView(HomeAssistantView):
return self.json([{'success': {'username': '12345678901234567890'}}])
class HueGroupView(HomeAssistantView):
"""Group handler to get Logitech Pop working."""
url = '/api/{username}/groups/0/action'
name = 'emulated_hue:groups:state'
requires_auth = False
def __init__(self, config):
"""Initialize the instance of the view."""
self.config = config
@core.callback
def put(self, request, username):
"""Process a request to make the Logitech Pop working."""
return self.json([{
'error': {
'address': '/groups/0/action/scene',
'type': 7,
'description': 'invalid value, dummy for parameter, scene'
}
}])
class HueAllLightsStateView(HomeAssistantView):
"""Handle requests for getting and setting info about entities."""

View File

@@ -15,7 +15,7 @@ from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['lakeside==0.5']
REQUIREMENTS = ['lakeside==0.6']
_LOGGER = logging.getLogger(__name__)

View File

@@ -31,7 +31,7 @@ _LOGGER = logging.getLogger(__name__)
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up the INSTEON PLM device class for the hass platform."""
plm = hass.data['insteon_plm']
plm = hass.data['insteon_plm'].get('plm')
address = discovery_info['address']
device = plm.devices[address]

View File

@@ -4,7 +4,6 @@ Support for MQTT fans.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/fan.mqtt/
"""
import asyncio
import logging
import voluptuous as vol
@@ -19,6 +18,7 @@ from homeassistant.components.mqtt import (
CONF_PAYLOAD_AVAILABLE, CONF_PAYLOAD_NOT_AVAILABLE, CONF_QOS, CONF_RETAIN,
MqttAvailability)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import HomeAssistantType, ConfigType
from homeassistant.components.fan import (SPEED_LOW, SPEED_MEDIUM,
SPEED_HIGH, FanEntity,
SUPPORT_SET_SPEED, SUPPORT_OSCILLATE,
@@ -77,8 +77,8 @@ PLATFORM_SCHEMA = mqtt.MQTT_RW_PLATFORM_SCHEMA.extend({
}).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema)
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
async def async_setup_platform(hass: HomeAssistantType, config: ConfigType,
async_add_devices, discovery_info=None):
"""Set up the MQTT fan platform."""
if discovery_info is not None:
config = PLATFORM_SCHEMA(discovery_info)
@@ -149,10 +149,9 @@ class MqttFan(MqttAvailability, FanEntity):
self._supported_features |= (topic[CONF_SPEED_STATE_TOPIC]
is not None and SUPPORT_SET_SPEED)
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Subscribe to MQTT events."""
yield from super().async_added_to_hass()
await super().async_added_to_hass()
templates = {}
for key, tpl in list(self._templates.items()):
@@ -173,7 +172,7 @@ class MqttFan(MqttAvailability, FanEntity):
self.async_schedule_update_ha_state()
if self._topic[CONF_STATE_TOPIC] is not None:
yield from mqtt.async_subscribe(
await mqtt.async_subscribe(
self.hass, self._topic[CONF_STATE_TOPIC], state_received,
self._qos)
@@ -190,7 +189,7 @@ class MqttFan(MqttAvailability, FanEntity):
self.async_schedule_update_ha_state()
if self._topic[CONF_SPEED_STATE_TOPIC] is not None:
yield from mqtt.async_subscribe(
await mqtt.async_subscribe(
self.hass, self._topic[CONF_SPEED_STATE_TOPIC], speed_received,
self._qos)
self._speed = SPEED_OFF
@@ -206,7 +205,7 @@ class MqttFan(MqttAvailability, FanEntity):
self.async_schedule_update_ha_state()
if self._topic[CONF_OSCILLATION_STATE_TOPIC] is not None:
yield from mqtt.async_subscribe(
await mqtt.async_subscribe(
self.hass, self._topic[CONF_OSCILLATION_STATE_TOPIC],
oscillation_received, self._qos)
self._oscillation = False
@@ -251,8 +250,7 @@ class MqttFan(MqttAvailability, FanEntity):
"""Return the oscillation state."""
return self._oscillation
@asyncio.coroutine
def async_turn_on(self, speed: str = None, **kwargs) -> None:
async def async_turn_on(self, speed: str = None, **kwargs) -> None:
"""Turn on the entity.
This method is a coroutine.
@@ -261,10 +259,9 @@ class MqttFan(MqttAvailability, FanEntity):
self.hass, self._topic[CONF_COMMAND_TOPIC],
self._payload[STATE_ON], self._qos, self._retain)
if speed:
yield from self.async_set_speed(speed)
await self.async_set_speed(speed)
@asyncio.coroutine
def async_turn_off(self, **kwargs) -> None:
async def async_turn_off(self, **kwargs) -> None:
"""Turn off the entity.
This method is a coroutine.
@@ -273,8 +270,7 @@ class MqttFan(MqttAvailability, FanEntity):
self.hass, self._topic[CONF_COMMAND_TOPIC],
self._payload[STATE_OFF], self._qos, self._retain)
@asyncio.coroutine
def async_set_speed(self, speed: str) -> None:
async def async_set_speed(self, speed: str) -> None:
"""Set the speed of the fan.
This method is a coroutine.
@@ -299,8 +295,7 @@ class MqttFan(MqttAvailability, FanEntity):
self._speed = speed
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_oscillate(self, oscillating: bool) -> None:
async def async_oscillate(self, oscillating: bool) -> None:
"""Set oscillation.
This method is a coroutine.

View File

@@ -51,8 +51,8 @@ set_direction:
description: Name(s) of the entities to toggle
example: 'fan.living_room'
direction:
description: The direction to rotate
example: 'left'
description: The direction to rotate. Either 'forward' or 'reverse'
example: 'forward'
dyson_set_night_mode:
description: Set the fan in night mode.

View File

@@ -0,0 +1,389 @@
"""
Support for Template fans.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/fan.template/
"""
import logging
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.const import (
CONF_FRIENDLY_NAME, CONF_VALUE_TEMPLATE, CONF_ENTITY_ID,
STATE_ON, STATE_OFF, MATCH_ALL, EVENT_HOMEASSISTANT_START,
STATE_UNKNOWN)
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.components.fan import (
SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH, SUPPORT_SET_SPEED, SUPPORT_OSCILLATE,
FanEntity, ATTR_SPEED, ATTR_OSCILLATING, ENTITY_ID_FORMAT,
SUPPORT_DIRECTION, DIRECTION_FORWARD, DIRECTION_REVERSE, ATTR_DIRECTION)
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.script import Script
_LOGGER = logging.getLogger(__name__)
CONF_FANS = 'fans'
CONF_SPEED_LIST = 'speeds'
CONF_SPEED_TEMPLATE = 'speed_template'
CONF_OSCILLATING_TEMPLATE = 'oscillating_template'
CONF_DIRECTION_TEMPLATE = 'direction_template'
CONF_ON_ACTION = 'turn_on'
CONF_OFF_ACTION = 'turn_off'
CONF_SET_SPEED_ACTION = 'set_speed'
CONF_SET_OSCILLATING_ACTION = 'set_oscillating'
CONF_SET_DIRECTION_ACTION = 'set_direction'
_VALID_STATES = [STATE_ON, STATE_OFF]
_VALID_OSC = [True, False]
_VALID_DIRECTIONS = [DIRECTION_FORWARD, DIRECTION_REVERSE]
FAN_SCHEMA = vol.Schema({
vol.Optional(CONF_FRIENDLY_NAME): cv.string,
vol.Required(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_SPEED_TEMPLATE): cv.template,
vol.Optional(CONF_OSCILLATING_TEMPLATE): cv.template,
vol.Optional(CONF_DIRECTION_TEMPLATE): cv.template,
vol.Required(CONF_ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(CONF_OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_SET_SPEED_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_SET_OSCILLATING_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_SET_DIRECTION_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(
CONF_SPEED_LIST,
default=[SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH]
): cv.ensure_list,
vol.Optional(CONF_ENTITY_ID): cv.entity_ids
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_FANS): vol.Schema({cv.slug: FAN_SCHEMA}),
})
async def async_setup_platform(
hass, config, async_add_devices, discovery_info=None
):
"""Set up the Template Fans."""
fans = []
for device, device_config in config[CONF_FANS].items():
friendly_name = device_config.get(CONF_FRIENDLY_NAME, device)
state_template = device_config[CONF_VALUE_TEMPLATE]
speed_template = device_config.get(CONF_SPEED_TEMPLATE)
oscillating_template = device_config.get(
CONF_OSCILLATING_TEMPLATE
)
direction_template = device_config.get(CONF_DIRECTION_TEMPLATE)
on_action = device_config[CONF_ON_ACTION]
off_action = device_config[CONF_OFF_ACTION]
set_speed_action = device_config.get(CONF_SET_SPEED_ACTION)
set_oscillating_action = device_config.get(CONF_SET_OSCILLATING_ACTION)
set_direction_action = device_config.get(CONF_SET_DIRECTION_ACTION)
speed_list = device_config[CONF_SPEED_LIST]
entity_ids = set()
manual_entity_ids = device_config.get(CONF_ENTITY_ID)
for template in (state_template, speed_template, oscillating_template,
direction_template):
if template is None:
continue
template.hass = hass
if entity_ids == MATCH_ALL or manual_entity_ids is not None:
continue
template_entity_ids = template.extract_entities()
if template_entity_ids == MATCH_ALL:
entity_ids = MATCH_ALL
else:
entity_ids |= set(template_entity_ids)
if manual_entity_ids is not None:
entity_ids = manual_entity_ids
elif entity_ids != MATCH_ALL:
entity_ids = list(entity_ids)
fans.append(
TemplateFan(
hass, device, friendly_name,
state_template, speed_template, oscillating_template,
direction_template, on_action, off_action, set_speed_action,
set_oscillating_action, set_direction_action, speed_list,
entity_ids
)
)
async_add_devices(fans)
class TemplateFan(FanEntity):
"""A template fan component."""
def __init__(self, hass, device_id, friendly_name,
state_template, speed_template, oscillating_template,
direction_template, on_action, off_action, set_speed_action,
set_oscillating_action, set_direction_action, speed_list,
entity_ids):
"""Initialize the fan."""
self.hass = hass
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass)
self._name = friendly_name
self._template = state_template
self._speed_template = speed_template
self._oscillating_template = oscillating_template
self._direction_template = direction_template
self._supported_features = 0
self._on_script = Script(hass, on_action)
self._off_script = Script(hass, off_action)
self._set_speed_script = None
if set_speed_action:
self._set_speed_script = Script(hass, set_speed_action)
self._set_oscillating_script = None
if set_oscillating_action:
self._set_oscillating_script = Script(hass, set_oscillating_action)
self._set_direction_script = None
if set_direction_action:
self._set_direction_script = Script(hass, set_direction_action)
self._state = STATE_OFF
self._speed = None
self._oscillating = None
self._direction = None
self._template.hass = self.hass
if self._speed_template:
self._speed_template.hass = self.hass
self._supported_features |= SUPPORT_SET_SPEED
if self._oscillating_template:
self._oscillating_template.hass = self.hass
self._supported_features |= SUPPORT_OSCILLATE
if self._direction_template:
self._direction_template.hass = self.hass
self._supported_features |= SUPPORT_DIRECTION
self._entities = entity_ids
# List of valid speeds
self._speed_list = speed_list
@property
def name(self):
"""Return the display name of this fan."""
return self._name
@property
def supported_features(self) -> int:
"""Flag supported features."""
return self._supported_features
@property
def speed_list(self: ToggleEntity) -> list:
"""Get the list of available speeds."""
return self._speed_list
@property
def is_on(self):
"""Return true if device is on."""
return self._state == STATE_ON
@property
def speed(self):
"""Return the current speed."""
return self._speed
@property
def oscillating(self):
"""Return the oscillation state."""
return self._oscillating
@property
def direction(self):
"""Return the oscillation state."""
return self._direction
@property
def should_poll(self):
"""Return the polling state."""
return False
# pylint: disable=arguments-differ
async def async_turn_on(self, speed: str = None) -> None:
"""Turn on the fan."""
await self._on_script.async_run()
self._state = STATE_ON
if speed is not None:
await self.async_set_speed(speed)
# pylint: disable=arguments-differ
async def async_turn_off(self) -> None:
"""Turn off the fan."""
await self._off_script.async_run()
self._state = STATE_OFF
async def async_set_speed(self, speed: str) -> None:
"""Set the speed of the fan."""
if self._set_speed_script is None:
return
if speed in self._speed_list:
self._speed = speed
await self._set_speed_script.async_run({ATTR_SPEED: speed})
else:
_LOGGER.error(
'Received invalid speed: %s. ' +
'Expected: %s.',
speed, self._speed_list)
async def async_oscillate(self, oscillating: bool) -> None:
"""Set oscillation of the fan."""
if self._set_oscillating_script is None:
return
if oscillating in _VALID_OSC:
self._oscillating = oscillating
await self._set_oscillating_script.async_run(
{ATTR_OSCILLATING: oscillating})
else:
_LOGGER.error(
'Received invalid oscillating value: %s. ' +
'Expected: %s.',
oscillating, ', '.join(_VALID_OSC))
async def async_set_direction(self, direction: str) -> None:
"""Set the direction of the fan."""
if self._set_direction_script is None:
return
if direction in _VALID_DIRECTIONS:
self._direction = direction
await self._set_direction_script.async_run(
{ATTR_DIRECTION: direction})
else:
_LOGGER.error(
'Received invalid direction: %s. ' +
'Expected: %s.',
direction, ', '.join(_VALID_DIRECTIONS))
async def async_added_to_hass(self):
"""Register callbacks."""
@callback
def template_fan_state_listener(entity, old_state, new_state):
"""Handle target device state changes."""
self.async_schedule_update_ha_state(True)
@callback
def template_fan_startup(event):
"""Update template on startup."""
self.hass.helpers.event.async_track_state_change(
self._entities, template_fan_state_listener)
self.async_schedule_update_ha_state(True)
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, template_fan_startup)
async def async_update(self):
"""Update the state from the template."""
# Update state
try:
state = self._template.async_render()
except TemplateError as ex:
_LOGGER.error(ex)
state = None
self._state = None
# Validate state
if state in _VALID_STATES:
self._state = state
elif state == STATE_UNKNOWN:
self._state = None
else:
_LOGGER.error(
'Received invalid fan is_on state: %s. ' +
'Expected: %s.',
state, ', '.join(_VALID_STATES))
self._state = None
# Update speed if 'speed_template' is configured
if self._speed_template is not None:
try:
speed = self._speed_template.async_render()
except TemplateError as ex:
_LOGGER.error(ex)
speed = None
self._state = None
# Validate speed
if speed in self._speed_list:
self._speed = speed
elif speed == STATE_UNKNOWN:
self._speed = None
else:
_LOGGER.error(
'Received invalid speed: %s. ' +
'Expected: %s.',
speed, self._speed_list)
self._speed = None
# Update oscillating if 'oscillating_template' is configured
if self._oscillating_template is not None:
try:
oscillating = self._oscillating_template.async_render()
except TemplateError as ex:
_LOGGER.error(ex)
oscillating = None
self._state = None
# Validate osc
if oscillating == 'True' or oscillating is True:
self._oscillating = True
elif oscillating == 'False' or oscillating is False:
self._oscillating = False
elif oscillating == STATE_UNKNOWN:
self._oscillating = None
else:
_LOGGER.error(
'Received invalid oscillating: %s. ' +
'Expected: True/False.', oscillating)
self._oscillating = None
# Update direction if 'direction_template' is configured
if self._direction_template is not None:
try:
direction = self._direction_template.async_render()
except TemplateError as ex:
_LOGGER.error(ex)
direction = None
self._state = None
# Validate speed
if direction in _VALID_DIRECTIONS:
self._direction = direction
elif direction == STATE_UNKNOWN:
self._direction = None
else:
_LOGGER.error(
'Received invalid direction: %s. ' +
'Expected: %s.',
direction, ', '.join(_VALID_DIRECTIONS))
self._direction = None

View File

@@ -10,7 +10,6 @@ from homeassistant.components import zha
from homeassistant.components.fan import (
DOMAIN, FanEntity, SPEED_OFF, SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH,
SUPPORT_SET_SPEED)
from homeassistant.const import STATE_UNKNOWN
DEPENDENCIES = ['zha']
@@ -72,7 +71,7 @@ class ZhaFan(zha.Entity, FanEntity):
@property
def is_on(self) -> bool:
"""Return true if entity is on."""
if self._state == STATE_UNKNOWN:
if self._state is None:
return False
return self._state != SPEED_OFF
@@ -103,7 +102,7 @@ class ZhaFan(zha.Entity, FanEntity):
"""Retrieve latest state."""
result = yield from zha.safe_read(self._endpoint.fan, ['fan_mode'])
new_value = result.get('fan_mode', None)
self._state = VALUE_TO_SPEED.get(new_value, STATE_UNKNOWN)
self._state = VALUE_TO_SPEED.get(new_value, None)
@property
def should_poll(self) -> bool:

View File

@@ -4,7 +4,7 @@ Support for RSS/Atom feeds.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/feedreader/
"""
from datetime import datetime
from datetime import datetime, timedelta
from logging import getLogger
from os.path import exists
from threading import Lock
@@ -12,8 +12,8 @@ import pickle
import voluptuous as vol
from homeassistant.const import EVENT_HOMEASSISTANT_START
from homeassistant.helpers.event import track_utc_time_change
from homeassistant.const import EVENT_HOMEASSISTANT_START, CONF_SCAN_INTERVAL
from homeassistant.helpers.event import track_time_interval
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['feedparser==5.2.1']
@@ -21,16 +21,22 @@ REQUIREMENTS = ['feedparser==5.2.1']
_LOGGER = getLogger(__name__)
CONF_URLS = 'urls'
CONF_MAX_ENTRIES = 'max_entries'
DEFAULT_MAX_ENTRIES = 20
DEFAULT_SCAN_INTERVAL = timedelta(hours=1)
DOMAIN = 'feedreader'
EVENT_FEEDREADER = 'feedreader'
MAX_ENTRIES = 20
CONFIG_SCHEMA = vol.Schema({
DOMAIN: {
vol.Required(CONF_URLS): vol.All(cv.ensure_list, [cv.url]),
vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL):
cv.time_period,
vol.Optional(CONF_MAX_ENTRIES, default=DEFAULT_MAX_ENTRIES):
cv.positive_int
}
}, extra=vol.ALLOW_EXTRA)
@@ -38,33 +44,50 @@ CONFIG_SCHEMA = vol.Schema({
def setup(hass, config):
"""Set up the Feedreader component."""
urls = config.get(DOMAIN)[CONF_URLS]
scan_interval = config.get(DOMAIN).get(CONF_SCAN_INTERVAL)
max_entries = config.get(DOMAIN).get(CONF_MAX_ENTRIES)
data_file = hass.config.path("{}.pickle".format(DOMAIN))
storage = StoredData(data_file)
feeds = [FeedManager(url, hass, storage) for url in urls]
feeds = [FeedManager(url, scan_interval, max_entries, hass, storage) for
url in urls]
return len(feeds) > 0
class FeedManager(object):
"""Abstraction over Feedparser module."""
def __init__(self, url, hass, storage):
"""Initialize the FeedManager object, poll every hour."""
def __init__(self, url, scan_interval, max_entries, hass, storage):
"""Initialize the FeedManager object, poll as per scan interval."""
self._url = url
self._scan_interval = scan_interval
self._max_entries = max_entries
self._feed = None
self._hass = hass
self._firstrun = True
self._storage = storage
self._last_entry_timestamp = None
self._last_update_successful = False
self._has_published_parsed = False
self._event_type = EVENT_FEEDREADER
self._feed_id = url
hass.bus.listen_once(
EVENT_HOMEASSISTANT_START, lambda _: self._update())
track_utc_time_change(
hass, lambda now: self._update(), minute=0, second=0)
self._init_regular_updates(hass)
def _log_no_entries(self):
"""Send no entries log at debug level."""
_LOGGER.debug("No new entries to be published in feed %s", self._url)
def _init_regular_updates(self, hass):
"""Schedule regular updates at the top of the clock."""
track_time_interval(hass, lambda now: self._update(),
self._scan_interval)
@property
def last_update_successful(self):
"""Return True if the last feed update was successful."""
return self._last_update_successful
def _update(self):
"""Update the feed and publish new entries to the event bus."""
import feedparser
@@ -76,26 +99,39 @@ class FeedManager(object):
else self._feed.get('modified'))
if not self._feed:
_LOGGER.error("Error fetching feed data from %s", self._url)
self._last_update_successful = False
else:
# The 'bozo' flag really only indicates that there was an issue
# during the initial parsing of the XML, but it doesn't indicate
# whether this is an unrecoverable error. In this case the
# feedparser lib is trying a less strict parsing approach.
# If an error is detected here, log error message but continue
# processing the feed entries if present.
if self._feed.bozo != 0:
_LOGGER.error("Error parsing feed %s", self._url)
_LOGGER.error("Error parsing feed %s: %s", self._url,
self._feed.bozo_exception)
# Using etag and modified, if there's no new data available,
# the entries list will be empty
elif self._feed.entries:
if self._feed.entries:
_LOGGER.debug("%s entri(es) available in feed %s",
len(self._feed.entries), self._url)
if len(self._feed.entries) > MAX_ENTRIES:
_LOGGER.debug("Processing only the first %s entries "
"in feed %s", MAX_ENTRIES, self._url)
self._feed.entries = self._feed.entries[0:MAX_ENTRIES]
self._filter_entries()
self._publish_new_entries()
if self._has_published_parsed:
self._storage.put_timestamp(
self._url, self._last_entry_timestamp)
self._feed_id, self._last_entry_timestamp)
else:
self._log_no_entries()
self._last_update_successful = True
_LOGGER.info("Fetch from feed %s completed", self._url)
def _filter_entries(self):
"""Filter the entries provided and return the ones to keep."""
if len(self._feed.entries) > self._max_entries:
_LOGGER.debug("Processing only the first %s entries "
"in feed %s", self._max_entries, self._url)
self._feed.entries = self._feed.entries[0:self._max_entries]
def _update_and_fire_entry(self, entry):
"""Update last_entry_timestamp and fire entry."""
# We are lucky, `published_parsed` data available, let's make use of
@@ -109,12 +145,12 @@ class FeedManager(object):
_LOGGER.debug("No published_parsed info available for entry %s",
entry.title)
entry.update({'feed_url': self._url})
self._hass.bus.fire(EVENT_FEEDREADER, entry)
self._hass.bus.fire(self._event_type, entry)
def _publish_new_entries(self):
"""Publish new entries to the event bus."""
new_entries = False
self._last_entry_timestamp = self._storage.get_timestamp(self._url)
self._last_entry_timestamp = self._storage.get_timestamp(self._feed_id)
if self._last_entry_timestamp:
self._firstrun = False
else:
@@ -157,18 +193,18 @@ class StoredData(object):
_LOGGER.error("Error loading data from pickled file %s",
self._data_file)
def get_timestamp(self, url):
"""Return stored timestamp for given url."""
def get_timestamp(self, feed_id):
"""Return stored timestamp for given feed id (usually the url)."""
self._fetch_data()
return self._data.get(url)
return self._data.get(feed_id)
def put_timestamp(self, url, timestamp):
"""Update timestamp for given URL."""
def put_timestamp(self, feed_id, timestamp):
"""Update timestamp for given feed id (usually the url)."""
self._fetch_data()
with self._lock, open(self._data_file, 'wb') as myfile:
self._data.update({url: timestamp})
self._data.update({feed_id: timestamp})
_LOGGER.debug("Overwriting feed %s timestamp in storage file %s",
url, self._data_file)
feed_id, self._data_file)
try:
pickle.dump(self._data, myfile)
except: # noqa: E722 # pylint: disable=bare-except

View File

@@ -43,7 +43,7 @@ def setup(hass, config):
def create_event_handler(patterns, hass):
""""Return the Watchdog EventHandler object."""
"""Return the Watchdog EventHandler object."""
from watchdog.events import PatternMatchingEventHandler
class EventHandler(PatternMatchingEventHandler):

View File

@@ -16,15 +16,16 @@ import voluptuous as vol
import jinja2
import homeassistant.helpers.config_validation as cv
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.http.view import HomeAssistantView
from homeassistant.components.http.const import KEY_AUTHENTICATED
from homeassistant.components import websocket_api
from homeassistant.config import find_config_file, load_yaml_config_file
from homeassistant.const import CONF_NAME, EVENT_THEMES_UPDATED
from homeassistant.core import callback
from homeassistant.helpers.translation import async_get_translations
from homeassistant.loader import bind_hass
REQUIREMENTS = ['home-assistant-frontend==20180426.0']
REQUIREMENTS = ['home-assistant-frontend==20180526.1']
DOMAIN = 'frontend'
DEPENDENCIES = ['api', 'websocket_api', 'http', 'system_log']
@@ -94,6 +95,10 @@ SERVICE_RELOAD_THEMES = 'reload_themes'
SERVICE_SET_THEME_SCHEMA = vol.Schema({
vol.Required(CONF_NAME): cv.string,
})
WS_TYPE_GET_PANELS = 'get_panels'
SCHEMA_GET_PANELS = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
vol.Required('type'): WS_TYPE_GET_PANELS,
})
class AbstractPanel:
@@ -142,21 +147,6 @@ class AbstractPanel:
'get', '/{}/{{extra:.+}}'.format(self.frontend_url_path),
index_view.get)
def to_response(self, hass, request):
"""Panel as dictionary."""
result = {
'component_name': self.component_name,
'icon': self.sidebar_icon,
'title': self.sidebar_title,
'url_path': self.frontend_url_path,
'config': self.config,
}
if _is_latest(hass.data[DATA_JS_VERSION], request):
result['url'] = self.webcomponent_url_latest
else:
result['url'] = self.webcomponent_url_es5
return result
class BuiltInPanel(AbstractPanel):
"""Panel that is part of hass_frontend."""
@@ -170,30 +160,15 @@ class BuiltInPanel(AbstractPanel):
self.frontend_url_path = frontend_url_path or component_name
self.config = config
@asyncio.coroutine
def async_finalize(self, hass, frontend_repository_path):
"""Finalize this panel for usage.
If frontend_repository_path is set, will be prepended to path of
built-in components.
"""
if frontend_repository_path is None:
import hass_frontend
import hass_frontend_es5
self.webcomponent_url_latest = \
'/frontend_latest/panels/ha-panel-{}-{}.html'.format(
self.component_name,
hass_frontend.FINGERPRINTS[self.component_name])
self.webcomponent_url_es5 = \
'/frontend_es5/panels/ha-panel-{}-{}.html'.format(
self.component_name,
hass_frontend_es5.FINGERPRINTS[self.component_name])
else:
# Dev mode
self.webcomponent_url_es5 = self.webcomponent_url_latest = \
'/home-assistant-polymer/panels/{}/ha-panel-{}.html'.format(
self.component_name, self.component_name)
def to_response(self, hass, request):
"""Panel as dictionary."""
return {
'component_name': self.component_name,
'icon': self.sidebar_icon,
'title': self.sidebar_title,
'config': self.config,
'url_path': self.frontend_url_path,
}
class ExternalPanel(AbstractPanel):
@@ -239,6 +214,21 @@ class ExternalPanel(AbstractPanel):
frontend_repository_path is None)
self.REGISTERED_COMPONENTS.add(self.component_name)
def to_response(self, hass, request):
"""Panel as dictionary."""
result = {
'component_name': self.component_name,
'icon': self.sidebar_icon,
'title': self.sidebar_title,
'url_path': self.frontend_url_path,
'config': self.config,
}
if _is_latest(hass.data[DATA_JS_VERSION], request):
result['url'] = self.webcomponent_url_latest
else:
result['url'] = self.webcomponent_url_es5
return result
@bind_hass
@asyncio.coroutine
@@ -291,6 +281,17 @@ def add_manifest_json_key(key, val):
@asyncio.coroutine
def async_setup(hass, config):
"""Set up the serving of the frontend."""
if list(hass.auth.async_auth_providers):
client = yield from hass.auth.async_create_client(
'Home Assistant Frontend',
redirect_uris=['/'],
no_secret=True,
)
else:
client = None
hass.components.websocket_api.async_register_command(
WS_TYPE_GET_PANELS, websocket_handle_get_panels, SCHEMA_GET_PANELS)
hass.http.register_view(ManifestJSONView)
conf = config.get(DOMAIN, {})
@@ -300,59 +301,40 @@ def async_setup(hass, config):
hass.data[DATA_JS_VERSION] = js_version = conf.get(CONF_JS_VERSION)
if is_dev:
for subpath in ["src", "build-translations", "build-temp", "build",
"hass_frontend", "bower_components", "panels",
"hassio"]:
hass.http.register_static_path(
"/home-assistant-polymer/{}".format(subpath),
os.path.join(repo_path, subpath),
False)
hass.http.register_static_path(
"/static/translations",
os.path.join(repo_path, "build-translations/output"), False)
sw_path_es5 = os.path.join(repo_path, "build-es5/service_worker.js")
sw_path_latest = os.path.join(repo_path, "build/service_worker.js")
static_path = os.path.join(repo_path, 'hass_frontend')
frontend_es5_path = os.path.join(repo_path, 'build-es5')
frontend_latest_path = os.path.join(repo_path, 'build')
hass_frontend_path = os.path.join(repo_path, 'hass_frontend')
hass_frontend_es5_path = os.path.join(repo_path, 'hass_frontend_es5')
else:
import hass_frontend
import hass_frontend_es5
sw_path_es5 = os.path.join(hass_frontend_es5.where(),
"service_worker.js")
sw_path_latest = os.path.join(hass_frontend.where(),
"service_worker.js")
# /static points to dir with files that are JS-type agnostic.
# ES5 files are served from /frontend_es5.
# ES6 files are served from /frontend_latest.
static_path = hass_frontend.where()
frontend_es5_path = hass_frontend_es5.where()
frontend_latest_path = static_path
hass_frontend_path = hass_frontend.where()
hass_frontend_es5_path = hass_frontend_es5.where()
hass.http.register_static_path(
"/service_worker_es5.js", sw_path_es5, False)
"/service_worker_es5.js",
os.path.join(hass_frontend_es5_path, "service_worker.js"), False)
hass.http.register_static_path(
"/service_worker.js", sw_path_latest, False)
"/service_worker.js",
os.path.join(hass_frontend_path, "service_worker.js"), False)
hass.http.register_static_path(
"/robots.txt", os.path.join(static_path, "robots.txt"), not is_dev)
hass.http.register_static_path("/static", static_path, not is_dev)
"/robots.txt",
os.path.join(hass_frontend_path, "robots.txt"), False)
hass.http.register_static_path("/static", hass_frontend_path, not is_dev)
hass.http.register_static_path(
"/frontend_latest", frontend_latest_path, not is_dev)
"/frontend_latest", hass_frontend_path, not is_dev)
hass.http.register_static_path(
"/frontend_es5", frontend_es5_path, not is_dev)
"/frontend_es5", hass_frontend_es5_path, not is_dev)
local = hass.config.path('www')
if os.path.isdir(local):
hass.http.register_static_path("/local", local, not is_dev)
index_view = IndexView(repo_path, js_version)
index_view = IndexView(repo_path, js_version, client)
hass.http.register_view(index_view)
@asyncio.coroutine
def finalize_panel(panel):
async def finalize_panel(panel):
"""Finalize setup of a panel."""
yield from panel.async_finalize(hass, repo_path)
if hasattr(panel, 'async_finalize'):
await panel.async_finalize(hass, repo_path)
panel.async_register_index_routes(hass.http.app.router, index_view)
yield from asyncio.wait([
@@ -444,10 +426,11 @@ class IndexView(HomeAssistantView):
requires_auth = False
extra_urls = ['/states', '/states/{extra}']
def __init__(self, repo_path, js_option):
def __init__(self, repo_path, js_option, client):
"""Initialize the frontend view."""
self.repo_path = repo_path
self.js_option = js_option
self.client = client
self._template_cache = {}
def get_template(self, latest):
@@ -501,7 +484,7 @@ class IndexView(HomeAssistantView):
extra_key = DATA_EXTRA_HTML_URL if latest else DATA_EXTRA_HTML_URL_ES5
resp = template.render(
template_params = dict(
no_auth=no_auth,
panel_url=panel_url,
panels=hass.data[DATA_PANELS],
@@ -509,7 +492,11 @@ class IndexView(HomeAssistantView):
extra_urls=hass.data[extra_key],
)
return web.Response(text=resp, content_type='text/html')
if self.client is not None:
template_params['client_id'] = self.client.id
return web.Response(text=template.render(**template_params),
content_type='text/html')
class ManifestJSONView(HomeAssistantView):
@@ -597,3 +584,19 @@ def _is_latest(js_option, request):
useragent = request.headers.get('User-Agent')
return useragent and hass_frontend.version(useragent)
@callback
def websocket_handle_get_panels(hass, connection, msg):
"""Handle get panels command.
Async friendly.
"""
panels = {
panel:
connection.hass.data[DATA_PANELS][panel].to_response(
connection.hass, connection.request)
for panel in connection.hass.data[DATA_PANELS]}
connection.to_write.put_nowait(websocket_api.result_message(
msg['id'], panels))

View File

@@ -70,8 +70,7 @@ def request_sync(hass):
hass.services.call(DOMAIN, SERVICE_REQUEST_SYNC)
@asyncio.coroutine
def async_setup(hass: HomeAssistant, yaml_config: Dict[str, Any]):
async def async_setup(hass: HomeAssistant, yaml_config: Dict[str, Any]):
"""Activate Google Actions component."""
config = yaml_config.get(DOMAIN, {})
agent_user_id = config.get(CONF_AGENT_USER_ID)
@@ -79,20 +78,19 @@ def async_setup(hass: HomeAssistant, yaml_config: Dict[str, Any]):
hass.http.register_view(GoogleAssistantAuthView(hass, config))
async_register_http(hass, config)
@asyncio.coroutine
def request_sync_service_handler(call):
async def request_sync_service_handler(call):
"""Handle request sync service calls."""
websession = async_get_clientsession(hass)
try:
with async_timeout.timeout(5, loop=hass.loop):
res = yield from websession.post(
res = await websession.post(
REQUEST_SYNC_BASE_URL,
params={'key': api_key},
json={'agent_user_id': agent_user_id})
_LOGGER.info("Submitted request_sync request to Google")
res.raise_for_status()
except aiohttp.ClientResponseError:
body = yield from res.read()
body = await res.read()
_LOGGER.error(
'request_sync request failed: %d %s', res.status, body)
except (asyncio.TimeoutError, aiohttp.ClientError):

View File

@@ -1,6 +1,5 @@
"""Google Assistant OAuth View."""
import asyncio
import logging
# Typing imports
@@ -44,8 +43,7 @@ class GoogleAssistantAuthView(HomeAssistantView):
self.client_id = cfg.get(CONF_CLIENT_ID)
self.access_token = cfg.get(CONF_ACCESS_TOKEN)
@asyncio.coroutine
def get(self, request: Request) -> Response:
async def get(self, request: Request) -> Response:
"""Handle oauth token request."""
query = request.query
redirect_uri = query.get('redirect_uri')

View File

@@ -4,7 +4,6 @@ Support for Google Actions Smart Home Control.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/google_assistant/
"""
import asyncio
import logging
from aiohttp.hdrs import AUTHORIZATION
@@ -77,14 +76,13 @@ class GoogleAssistantView(HomeAssistantView):
self.access_token = access_token
self.gass_config = gass_config
@asyncio.coroutine
def post(self, request: Request) -> Response:
async def post(self, request: Request) -> Response:
"""Handle Google Assistant requests."""
auth = request.headers.get(AUTHORIZATION, None)
if 'Bearer {}'.format(self.access_token) != auth:
return self.json_message("missing authorization", status_code=401)
message = yield from request.json() # type: dict
result = yield from async_handle_message(
message = await request.json() # type: dict
result = await async_handle_message(
request.app['hass'], self.gass_config, message)
return self.json(result)

View File

@@ -102,18 +102,23 @@ class _GoogleEntity:
if state.state == STATE_UNAVAILABLE:
return None
entity_config = self.config.entity_config.get(state.entity_id, {})
name = (entity_config.get(CONF_NAME) or state.name).strip()
# If an empty string
if not name:
return None
traits = self.traits()
# Found no supported traits for this entity
if not traits:
return None
entity_config = self.config.entity_config.get(state.entity_id, {})
device = {
'id': state.entity_id,
'name': {
'name': entity_config.get(CONF_NAME) or state.name
'name': name
},
'attributes': {},
'traits': [trait.name for trait in traits],

View File

@@ -14,7 +14,7 @@ from homeassistant.const import (
ATTR_ENTITY_ID, CONF_ICON, CONF_NAME, STATE_CLOSED, STATE_HOME,
STATE_NOT_HOME, STATE_OFF, STATE_ON, STATE_OPEN, STATE_LOCKED,
STATE_UNLOCKED, STATE_OK, STATE_PROBLEM, STATE_UNKNOWN,
ATTR_ASSUMED_STATE, SERVICE_RELOAD)
ATTR_ASSUMED_STATE, SERVICE_RELOAD, ATTR_NAME, ATTR_ICON)
from homeassistant.core import callback
from homeassistant.loader import bind_hass
from homeassistant.helpers.entity import Entity, async_generate_entity_id
@@ -35,8 +35,6 @@ ATTR_ADD_ENTITIES = 'add_entities'
ATTR_AUTO = 'auto'
ATTR_CONTROL = 'control'
ATTR_ENTITIES = 'entities'
ATTR_ICON = 'icon'
ATTR_NAME = 'name'
ATTR_OBJECT_ID = 'object_id'
ATTR_ORDER = 'order'
ATTR_VIEW = 'view'
@@ -245,34 +243,31 @@ def get_entity_ids(hass, entity_id, domain_filter=None):
if ent_id.startswith(domain_filter)]
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up all groups found defined in the configuration."""
component = hass.data.get(DOMAIN)
if component is None:
component = hass.data[DOMAIN] = EntityComponent(_LOGGER, DOMAIN, hass)
yield from _async_process_config(hass, config, component)
await _async_process_config(hass, config, component)
@asyncio.coroutine
def reload_service_handler(service):
async def reload_service_handler(service):
"""Remove all user-defined groups and load new ones from config."""
auto = list(filter(lambda e: not e.user_defined, component.entities))
conf = yield from component.async_prepare_reload()
conf = await component.async_prepare_reload()
if conf is None:
return
yield from _async_process_config(hass, conf, component)
await _async_process_config(hass, conf, component)
yield from component.async_add_entities(auto)
await component.async_add_entities(auto)
hass.services.async_register(
DOMAIN, SERVICE_RELOAD, reload_service_handler,
schema=RELOAD_SERVICE_SCHEMA)
@asyncio.coroutine
def groups_service_handler(service):
async def groups_service_handler(service):
"""Handle dynamic group service functions."""
object_id = service.data[ATTR_OBJECT_ID]
entity_id = ENTITY_ID_FORMAT.format(object_id)
@@ -287,7 +282,7 @@ def async_setup(hass, config):
ATTR_VISIBLE, ATTR_ICON, ATTR_VIEW, ATTR_CONTROL
) if service.data.get(attr) is not None}
yield from Group.async_create_group(
await Group.async_create_group(
hass, service.data.get(ATTR_NAME, object_id),
object_id=object_id,
entity_ids=entity_ids,
@@ -308,11 +303,11 @@ def async_setup(hass, config):
if ATTR_ADD_ENTITIES in service.data:
delta = service.data[ATTR_ADD_ENTITIES]
entity_ids = set(group.tracking) | set(delta)
yield from group.async_update_tracked_entity_ids(entity_ids)
await group.async_update_tracked_entity_ids(entity_ids)
if ATTR_ENTITIES in service.data:
entity_ids = service.data[ATTR_ENTITIES]
yield from group.async_update_tracked_entity_ids(entity_ids)
await group.async_update_tracked_entity_ids(entity_ids)
if ATTR_NAME in service.data:
group.name = service.data[ATTR_NAME]
@@ -335,13 +330,13 @@ def async_setup(hass, config):
need_update = True
if need_update:
yield from group.async_update_ha_state()
await group.async_update_ha_state()
return
# remove group
if service.service == SERVICE_REMOVE:
yield from component.async_remove_entity(entity_id)
await component.async_remove_entity(entity_id)
hass.services.async_register(
DOMAIN, SERVICE_SET, groups_service_handler,
@@ -351,8 +346,7 @@ def async_setup(hass, config):
DOMAIN, SERVICE_REMOVE, groups_service_handler,
schema=REMOVE_SERVICE_SCHEMA)
@asyncio.coroutine
def visibility_service_handler(service):
async def visibility_service_handler(service):
"""Change visibility of a group."""
visible = service.data.get(ATTR_VISIBLE)
@@ -363,7 +357,7 @@ def async_setup(hass, config):
tasks.append(group.async_update_ha_state())
if tasks:
yield from asyncio.wait(tasks, loop=hass.loop)
await asyncio.wait(tasks, loop=hass.loop)
hass.services.async_register(
DOMAIN, SERVICE_SET_VISIBILITY, visibility_service_handler,
@@ -372,8 +366,7 @@ def async_setup(hass, config):
return True
@asyncio.coroutine
def _async_process_config(hass, config, component):
async def _async_process_config(hass, config, component):
"""Process group configuration."""
for object_id, conf in config.get(DOMAIN, {}).items():
name = conf.get(CONF_NAME, object_id)
@@ -384,7 +377,7 @@ def _async_process_config(hass, config, component):
# Don't create tasks and await them all. The order is important as
# groups get a number based on creation order.
yield from Group.async_create_group(
await Group.async_create_group(
hass, name, entity_ids, icon=icon, view=view,
control=control, object_id=object_id)
@@ -428,10 +421,9 @@ class Group(Entity):
hass.loop).result()
@staticmethod
@asyncio.coroutine
def async_create_group(hass, name, entity_ids=None, user_defined=True,
visible=True, icon=None, view=False, control=None,
object_id=None):
async def async_create_group(hass, name, entity_ids=None,
user_defined=True, visible=True, icon=None,
view=False, control=None, object_id=None):
"""Initialize a group.
This method must be run in the event loop.
@@ -453,7 +445,7 @@ class Group(Entity):
component = hass.data[DOMAIN] = \
EntityComponent(_LOGGER, DOMAIN, hass)
yield from component.async_add_entities([group], True)
await component.async_add_entities([group], True)
return group
@@ -520,17 +512,16 @@ class Group(Entity):
self.async_update_tracked_entity_ids(entity_ids), self.hass.loop
).result()
@asyncio.coroutine
def async_update_tracked_entity_ids(self, entity_ids):
async def async_update_tracked_entity_ids(self, entity_ids):
"""Update the member entity IDs.
This method must be run in the event loop.
"""
yield from self.async_stop()
await self.async_stop()
self.tracking = tuple(ent_id.lower() for ent_id in entity_ids)
self.group_on, self.group_off = None, None
yield from self.async_update_ha_state(True)
await self.async_update_ha_state(True)
self.async_start()
@callback
@@ -544,8 +535,7 @@ class Group(Entity):
self.hass, self.tracking, self._async_state_changed_listener
)
@asyncio.coroutine
def async_stop(self):
async def async_stop(self):
"""Unregister the group from Home Assistant.
This method must be run in the event loop.
@@ -554,27 +544,24 @@ class Group(Entity):
self._async_unsub_state_changed()
self._async_unsub_state_changed = None
@asyncio.coroutine
def async_update(self):
async def async_update(self):
"""Query all members and determine current group state."""
self._state = STATE_UNKNOWN
self._async_update_group_state()
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Callback when added to HASS."""
if self.tracking:
self.async_start()
@asyncio.coroutine
def async_will_remove_from_hass(self):
async def async_will_remove_from_hass(self):
"""Callback when removed from HASS."""
if self._async_unsub_state_changed:
self._async_unsub_state_changed()
self._async_unsub_state_changed = None
@asyncio.coroutine
def _async_state_changed_listener(self, entity_id, old_state, new_state):
async def _async_state_changed_listener(self, entity_id, old_state,
new_state):
"""Respond to a member state changing.
This method must be run in the event loop.
@@ -584,7 +571,7 @@ class Group(Entity):
return
self._async_update_group_state(new_state)
yield from self.async_update_ha_state()
await self.async_update_ha_state()
@property
def _tracking_states(self):

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