Compare commits

...

207 Commits

Author SHA1 Message Date
Paulus Schoutsen
3639a4470c Use twine for release 2018-03-26 16:16:42 -07:00
Paulus Schoutsen
94d9aa0c5f Bump version to 0.66.0.b2 2018-03-26 16:10:03 -07:00
Paulus Schoutsen
a06eea444a version should contain just 'b' not 'beta' (#13476) 2018-03-26 16:09:18 -07:00
Paulus Schoutsen
ce3a5972c7 Upgrade aiohue and fix race condition (#13475)
* Bump aiohue to 1.3

* Store bridge in hass.data before setting up platform

* Fix tests
2018-03-26 16:09:18 -07:00
Fabian Affolter
f48ce3d437 Fix ID (fixes #13444) (#13471) 2018-03-26 16:09:17 -07:00
Paulus Schoutsen
dfe3219f3f Hue: Convert XY to HS color if HS not present (#13465)
* Hue: Convert XY to HS color if HS not present

* Revert change to test

* Address comments

* Lint
2018-03-26 16:09:17 -07:00
Paulus Schoutsen
a507ed0af8 Version bump to 0.66.0.beta1 2018-03-25 18:24:16 -07:00
Beat
068b037944 Fix encoding errors in mikrotik device tracker (#13464) 2018-03-25 18:23:32 -07:00
Cedric Van Goethem
38d2702e3c Add extra check for ESSID field in case there's a wired connection (#13459) 2018-03-25 18:23:32 -07:00
Paulus Schoutsen
93b9ec0b0f Add version bump script (#13447)
* Add version bump script

* Lint
2018-03-25 18:23:31 -07:00
Anders Melchiorsen
22cefc7e64 Improve detection of entity names in templates (#13432)
* Improve detection of entity names in templates

* Only test variables
2018-03-25 18:23:31 -07:00
cdce8p
60f6109cbf HomeKit: Bugfix & improved logging (#13431)
* Bugfix & improved logging

* Removed logging statements

* Removed logging test
2018-03-25 18:23:30 -07:00
a-andre
24d299e266 Hyperion: fix typo (#13429) 2018-03-25 18:23:30 -07:00
Anders Melchiorsen
444805df10 LimitlessLED hs_color fixes (#13425) 2018-03-25 18:23:30 -07:00
Anders Melchiorsen
a08293cff7 Log invalid templates in script delays (#13423)
* Log invalid templates in script delays

* Abort on error

* Remove unused import
2018-03-25 18:23:29 -07:00
Patrick Hofmann
0d48a8eec6 Security fix & lock for HomeMatic (#11980)
* HomeMatic KeyMatic device become a real lock component

* Adds supported features to lock component.

Locks may are capable to open the door latch.
If component is support it, the SUPPORT_OPENING bitmask can be supplied in the supported_features property.

* hound improvements.

* Travis improvements.

* Improvements from review process

* Simplifies is_locked method

* Adds an openable lock in the lock demo component

* removes blank line

* Adds test for openable demo lock and lint and reviewer improvements.

* adds new line...

* Comment end with a period.

* Additional blank line.

* Mock service based testing, lint fixes

* Update description
2018-03-25 18:23:29 -07:00
Paulus Schoutsen
8a204fd15b Bump frontend to 20180326.0 2018-03-25 18:10:59 -07:00
Paulus Schoutsen
8e14e803cb Fix release script 2018-03-23 14:27:21 -07:00
Paulus Schoutsen
101b39300b Version bump to 0.66.0.beta0 2018-03-23 14:17:36 -07:00
Paulus Schoutsen
725e1ddfc1 Update translations 2018-03-23 14:15:44 -07:00
Otto Winter
6a625bdb37 Cast Integration Cleanup (#13275)
* Cast Integration Cleanup

* Fix long line

* Fixes and logging

* Fix tests

* Lint

* Report unknown state with None

* Lint

* Switch to async_add_job

Gets rid of those pesky "Setup of platform cast is taking over 10 seconds." messages.

* Re-introduce PlatformNotReady

* Add tests

* Remove unnecessary checks

* Test PlatformNotReady

* Fix async in sync context

* Blocking update

It's not using async anyway

* Upgrade pychromecast to 2.1.0

* Make reviewing easier

I like "protected" access, but I like reviewing more :)

* Make reviewing even easier :)

* Comment tests
2018-03-23 14:02:52 -07:00
Matt Hamrick
630734ca15 Switched values to downcase. (#13406) 2018-03-23 13:54:36 -07:00
cdce8p
7fd687f59c Fix current_cover_position (#13135) 2018-03-23 13:54:19 -07:00
Paulus Schoutsen
4bd6776443 Google assistant sync (#13392)
* Add Google Assistant Sync API

* Update const.py

* Async/await
2018-03-23 12:13:52 -07:00
Sebastian Muszynski
2532d67b9a Add send sticker service to telegram bot (#13387)
* Add send sticker service to telegram bot

* A caption is not supported
2018-03-23 19:16:57 +01:00
Mattias Welponer
df8596e896 Cleanup homematicip_cloud (#13356)
* Cleanup and proposed changes from MartinHjelmare

* Removed coroutine decorator from async_added_to_hass

* Added blank line

* Fix of component url

* Fix of component url

* Fix url of the sensor component
2018-03-23 11:05:02 -07:00
Adam Mills
2497dd5e33 Hue: Use the currently active color mode (#13376)
* Hue: Use the currently active color mode

* Round hue/sat colors before reporting to API

* .gitignore cache fix
2018-03-23 11:01:40 -07:00
cdce8p
553920780f Added default return value for HS_Color (#13395) 2018-03-23 10:22:48 -07:00
Jerad Meisner
8852e52601 Switched to async/await. Bumped pyxeoma version (#13404) 2018-03-23 10:22:01 -07:00
Martin Hjelmare
23165cbd1a Enhance mysensors binary sensor device classes (#13367) 2018-03-23 18:11:53 +01:00
Philip Rosenberg-Watt
23f06b0040 Cache LaMetric devices for offline use (#13379)
If the connection to the LaMetric server fails, we should still be able
to send notifications to known and reachable devices.
2018-03-23 18:10:52 +01:00
Anders Melchiorsen
5ec6f25d4e Fix Sonos playing Sveriges Radio (#13401) 2018-03-23 18:09:17 +01:00
cgtobi
79c9d3ba10 Fix incorrect unit of measurement for precip_intensity. (#13415) 2018-03-23 18:08:16 +01:00
Martin Hjelmare
ba7178dc0c Enhance mysensors sensor units and icons (#13365) 2018-03-23 18:06:07 +01:00
Erik Eriksson
2c7bc6eaf8 Support setting icon when configuring MQTT entity (#13304) 2018-03-23 11:30:44 +01:00
Gerard
c50b00226c Avoid breaking change for BMW ConnectedDrive sensors in #12591 (#13380) 2018-03-23 07:32:33 +01:00
Paulus Schoutsen
fb1fafefab Include all config flow translations with backend translations (#13394) 2018-03-22 12:21:33 -07:00
Jeroen ter Heerdt
98620d8ce8 Fixing Egardia 'home armed' state not shown correctly. (#13335)
* Fixing Egardia 'home armed' state not shown correctly.

* Updating requirements_all.

* Adding DEPEDENCY list to Egardia components.

* updating requirements_all
2018-03-22 10:53:52 -07:00
Paulus Schoutsen
d385e9645d Merge remote-tracking branch 'origin/master' into dev 2018-03-22 10:20:35 -07:00
cgtobi
e9cdbe5d8c Add language parameter to darksky sensor (#13297) 2018-03-22 13:34:02 +01:00
Paulus Schoutsen
6e75c5427c Update frontend to 20180322.0 2018-03-21 21:22:16 -07:00
Diogo Gomes
1676df6a5f Mediaroom async (#13321)
* Initial commit on new asyncio based version

* Async version

* Lint

* updated to lasted pymediaroom version

* bump version

* optimistic state updates

* bump version

* Moved class import to method import

* async schedule and name correction

* Addresses @balloob comments

* missed fixes

* no unique_id for configuration based STB

* hound

* handle 2 mediaroom platforms
2018-03-21 18:06:41 -07:00
Martin Hjelmare
17cbd0f3c9 Add watt to mysensors switch attributes (#13370) 2018-03-21 23:55:49 +01:00
Martin Hjelmare
2d7d8848cb Fix mysensors RGBW (#13364)
Tuple doesn't have append method.
2018-03-21 23:48:50 +01:00
Thomas Svedberg
3939460814 Add the possibility to filter on line(s) in Västtrafik Public Transport sensor (#13317)
* Add the possibility to filter on line(s) in Västtrafik Public Transport sensor

Add a config entry "lines" to be able to filter departures on line(s) for the
vasttrafik sensor.

* Change log level to debug if no departures found.

* Remove extra None argument from dict().get() calls as it is already the default.

* Ensure "lines" is a list of strings. Also fix an indentation error.

* Correct to long line
2018-03-21 15:21:51 -07:00
maxclaey
36bc7f8175 Configuration options for IFTTT alarm control panel (#13352)
* Improvements

* Use optimistic instead of await callback

* Fix default value for optimistic
2018-03-21 12:29:58 -07:00
maxclaey
0396725fe9 Homekit Bugfix: Use get instead of indexing (#13353)
Fixes bug for alarm_control_panel if not code is required.
2018-03-21 19:06:46 +01:00
Scott Reston
74c249e57d Fix retrieval of track URL into medi_content_id (#13333)
'current.item' was returning blank.
2018-03-21 10:44:53 -07:00
Anders Melchiorsen
f8127a3902 Add a polling fallback for Sonos (#13310)
* Prepare for poll

* Add a polling fallback for Sonos
2018-03-20 19:27:07 -07:00
Martin Hjelmare
3426487277 Fix mysensors light turn on hs color (#13349) 2018-03-20 18:26:56 -07:00
Paulus Schoutsen
cfb0b00c0c Do not include unavailable entities in Google Assistant SYNC (#13358) 2018-03-20 18:09:34 -07:00
Anders Melchiorsen
852eef8046 Fix Sonos radio stations with ampersand (#13293) 2018-03-20 18:05:03 -07:00
Daniel Perna
05c9c57500 Update pyhomematic to 0.1.40 (#13354)
* Update __init__.py

* Update requirements_all.txt
2018-03-20 20:32:59 +01:00
John Arild Berentsen
5c4529d044 Bugfix: Zwave set_config_parameter failed when config list contained int (#13301)
* Cast list and bool options to STR

* Add button options to STR

* Add TYPE_BUTTON to value types

* Adjust comparison

* Remove Logging

* Remove Empty line

* Update tests

* Update tests

* Mistake
2018-03-20 14:04:24 +01:00
Daniel Høyer Iversen
3fa080a795 Add min and max price as attribute for Tibber sensor (#13313) 2018-03-20 08:46:10 +01:00
Sergio Viudes
0977be1842 Added switch for DoorBird second relay (#13339) 2018-03-20 08:43:31 +01:00
Johann Kellerman
4270bc7abb Perform check_config service in current process (#13017)
* Perform check_config service in current process

* feedback
2018-03-19 14:20:04 -07:00
Ryan McLean
a04c6d5830 Plex unavailable client cleanup (#13156)
* Added timestamp for when device was marked unavailable

* protect time 1st marked

* client removal, no errors

* Optional removal interval added

* Linting error fix

* Implemented guard to prevent indentation
Removed vars in favour of inline calcs

* Using hass.add_job() for cleanup

* Lint

* Revert removal interval to 600sec

* Changed datetime to hass implementation

* Forgot to include one of the references to dt
2018-03-19 14:15:21 -07:00
Per Osbäck
f287955422 zha: catch the exception from bellows if a device isn't available. (#13314)
* catch the exception from bellows if a device isn't available.

* fix import of zigpy exception

* fix lint import
2018-03-19 14:12:53 -07:00
Qxlkdr
2bc7e58780 Add trafikverket_weatherstation sensor platform (#12115)
* Create trafikverket_weatherstation.py

Created PR 12111 but due to permission issue I'm creating a new fork and PR.

* Added dot

Added dot to the first (second) row of the file, after the description.

* Corrections based on feedback

Done:
- Run flake8 before this commit
- Fixed invalid variables
- Shortened the xml variable/query via if statement (air_vs_road)
- Moved imports if update() to top of the file
- Imported CONF_API_KEY and CONF_TYPE
- Updated documentation (api_key): home-assistant/home-assistant.github.io#4562

Actions left:
- Error handling
- Request timeout
- Add sensor (file) to .coveragerc

* Multiple corrections

Done:
- Executed pylint and flake8 tests before commit
- Fixed import order
- Implemented request timeout
- Used variable air_vs_road in the return as well

Actions left:
- Error handling
- Add sensor (file) to .coveragerc

* Error handling

Done:
- Error handling for network
- Error handling for JSON response

* Added trafikverket_weatherstation.py

Added trafikverket_weatherstation.py in correct order.

* Road as default

Changed if statement to check for 'road' which means it will always defaulting to 'air' in other cases. Even if it will only accept 'air' and 'road' from the PLATFORM_SCHEMA.

* Updated variable names

Updated variable names to be more understandable as requested by @MartinHjelmare

* Standard Libraries

Grouped Standard Libraries

* Return None

Changed return None to only return as suggested.
2018-03-19 21:38:07 +01:00
Otto Winter
947218d51c pytest 3.4.0 cache gitignore (#13308) 2018-03-19 10:47:10 +01:00
Diogo Gomes
49683181d1 Superfluous None (#13326) 2018-03-18 20:42:23 -07:00
Adam Mills
89c7c80e42 Use hue/sat as internal light color interface (#11288)
* Accept and report both xy and RGB color for lights

* Fix demo light supported_features

* Add new XY color util functions

* Always make color changes available as xy and RGB

* Always expose color as RGB and XY

* Consolidate color supported_features

* Test fixes

* Additional test fix

* Use hue/sat as the hass core color interface

* Tests updates

* Assume MQTT RGB devices need full RGB brightness

* Convert new platforms

* More migration

* Use float for HS API

* Fix backwards conversion for KNX lights

* Adjust limitless min saturation for new scale
2018-03-18 15:00:29 -07:00
nielstron
6b059489a6 Adding a discoverable Samsung Syncthru Printer sensor platform (#13134)
* Added a simple component to support the BLNET

Adds a component based on pyblnet, that hooks up the blnet to home assistant

* Adds support for custimzation of blnet sensor devices

* Setting up blnet as a platfrom

* Updated use of state_attributes

Now the friendly_name (and for digital values the mode) is set in the state_attributes whereas the name is defined as "blnet_(analog|digital)_{sensornumber}" so you can reliably add them to groups.

* Added support for the SyncThru printer web service

* Added pysyncthru to the requirements

* Changed to Dependencis, import inside setup_platform

* Switch back to REQUIREMENTS

Looks like DEPENDENCIES is not meant for python packages but for other HA components

* Fixed access to _attributes

* Final fix

* Several Bugfixes

When the printer goes offline, the last state will be kept.
Also now checks if the printer is reachable upon setup

* Register syncthru as discoverable

* Included possible conditions to monitor

* Split the printer sensor in several seperate sensor entities

* Fixed bug at sensor creation, pep8 conform

* Bugfix

* Bugfix

* Removed Blnet components

* Fixed unused import

* Renamed discoverable to samsung_printer

* Removed unused Attribute _friendly_name

* Inserted missing space

* Pinned requirements and added to coveragerc

* Reduced redundancy by condensing into multiple sub-classes

* Fixed indentation

* Fixed super constructor calls

* Fixed super constructor calls

* Fixed format

* Resolving style issues and using name instead of friendly_name

* Pinned pysyncthru in requirements_all, having trouble with friendly_name

* Iterating over dictionary instead of dict.keys()

* ran gen_reqirements_all.py

* Fixed flake 8 issues

* Added a simple component to support the BLNET

Adds a component based on pyblnet, that hooks up the blnet to home assistant

* Implemented requested changes

* raised dependecies to pysyncthru version that has timeouts

* Raised required version for full timeout support

* Adds support for custimzation of blnet sensor devices

* Setting up blnet as a platfrom

* Updated use of state_attributes

Now the friendly_name (and for digital values the mode) is set in the state_attributes whereas the name is defined as "blnet_(analog|digital)_{sensornumber}" so you can reliably add them to groups.

* Added support for the SyncThru printer web service

* Added pysyncthru to the requirements

* Removed Blnet components

* Pinned requirements and added to coveragerc

* Fixed indentation

* Fixed format

* Pinned pysyncthru in requirements_all, having trouble with friendly_name

* ran gen_reqirements_all.py

* Updated requirements_all

* Renamed sensor objects, removed passing of hass entity

* Removed merge artifacts

* Reset syncthru to newest state

* Updated requirements_all

* switched to using the newest version of pysyncthru

* Sorted coveragerc
2018-03-18 09:26:33 -07:00
Erik Eriksson
1cbf9792d7 Support MQTT Lock discovery (#13303) 2018-03-18 09:26:07 -07:00
Kevin Raddatz
437ffc8337 Update plex.py (#12157)
* Update plex.py

show information about media depending if it is a movie or an episode
set time_between_scans to 10 s to match with plex media_player component

* Update plex.py

lint

* Update plex.py

linting

* Update plex.py

linting

* Update plex.py

linting

* Update plex.py

added catch  for tracks and everything else
if no release year is given, instead of () it now show nothing

* Update plex.py

Remove the album year to match with the Plex UI

* Update README.rst

* Update README.rst

* Update plex.py

reformat code to make it more readable
recorded tv shows might not have episode numbers assigned -> check before adding to title

* Update plex.py

cleanup excessive whitespace

* Update plex.py

cleanup excessive whitespace
2018-03-18 09:25:25 -07:00
Igor Bernstein
9cb3c9034f Zigbee fan (#12289)
* wip: initial control

* fix initial state

* cosmetic cleanup

* doc typo

* lint

* fixes

* fix unknown bug

* Lint
2018-03-18 09:17:56 -07:00
uchagani
1dcc51cbdf Add ecobee fan mode (#12732)
* add ability to set fan on

* add tests and change "not on" status to "auto"

* hound fix

* more hounds

* I don't understand new lines

* fix linting errors

* more linting fixes

* change method signature

* lint fixes

* hopefully last lint fix

* correct temp ranges according to ecobee API docs

* update dependency to latest version

* update tests with values from new temp logic

* fix linting issue

* more linting fixes

* add SUPPORT_FAN_MODE to capabilities

* add fan_list to attributes.
restore current fan state to OFF if fan is not running.
change target high/low temps from null to target temp when not in auto mode.
change target temp from null to high/low temp when in auto mode
change mode attribute to climate_mode for consistency with other lists.

* remove unused import

* simplify logic

* lint fixes

* revert change for target temps
2018-03-18 09:02:07 -07:00
maxclaey
022d8fb816 Support for security systems controlled by IFTTT (#12975)
* Add IFTTT alarm control panel

* Update .coveragerc

* Add support for code

* Bugfix

* Fix logging problem

* Pin requirements

* Update requirements_all.txt

* Fix lint errors

* Use ifttt component as a dependency instead of interacting with ifttt manually
Take into account review comments

* No default value for code

* Take into account review comments

* Provide a "push_alarm_state" service to change the state from IFTTT

* Add service description

* Fix @balloob review comments. Thanks!

* Fix service description name
2018-03-18 09:00:08 -07:00
Diogo Gomes
1e17b2fd63 Added Time based SMA to Filter Sensor (#13104)
* Added Time based SMA

* move "now" to _filter_state()

* Addressed comments

* fix long line

* type and name

* # pylint: disable=redefined-builtin

* added test
2018-03-18 08:58:52 -07:00
Mattias Welponer
b45dad507a Add initial support fo HomematicIP components (#12761)
* Add initial support fo HomematicIP components

* Fix module import

* Update reqirments file as well

* Added HomematicIP files

* Update to homematicip

* Code cleanup based on highligted issues

* Update of reqiremnets file as well

* Fix dispatcher usage

* Rename homematicip to homematicip_cloud
2018-03-18 08:57:53 -07:00
Fabian Affolter
8ed3024026 Upgrade async_timeout to 2.0.1 (#13290) 2018-03-17 17:37:31 -07:00
cburgess
d042b3d7d1 Update to latest python-nest (#12590)
Due to an upstream bug some devices will be assigned a where_id that is not
visible in the nest API. As a result we can't get a friendly name for the
where_id.

A workaround has been released for python-nest in version 3.7.0. Update the
home assistant requirements to python-nest==3.7.0 to work around this issue.

References:
https://nestdevelopers.io/t/missing-where-name-from-some-devices/1202
https://github.com/jkoelker/python-nest/issues/127
https://github.com/jkoelker/python-nest/pull/128

Fixes #12589
Fixes #12950
Fixes #13074
2018-03-17 17:35:16 -07:00
Pascal Vizeli
4d3743f3f7 Delete .gitmodules (#13295) 2018-03-17 19:08:52 +01:00
cgtobi
181eca4b45 Upgrade python-forecastio to 1.4.0 (#13282)
* Upgrade python-forecastio to 1.4.0

* Upgrade python-forecastio to 1.4.0 for sensor as well.
2018-03-17 17:43:07 +01:00
Fabian Affolter
dbc59ad1a7 Upgrade python-telegram-bot to 10.0.1 (#13294) 2018-03-17 17:41:10 +01:00
Fabian Affolter
82f59ba984 Upgrade numpy to 1.14.2 (#13291) 2018-03-17 17:40:31 +01:00
Fabian Affolter
d35077271d Upgrade TwitterAPI to 2.5.0 (#13287) 2018-03-17 17:40:03 +01:00
Fabian Affolter
aec61b7c86 Upgrade sqlalchemy to 1.2.5 (#13292) 2018-03-17 17:39:24 +01:00
Fabian Affolter
e01a0f91d6 Upgrade aiohttp_cors to 0.7.0 (#13289) 2018-03-17 17:37:53 +01:00
Fabian Affolter
8fed405da7 Upgrade aiohttp to 3.0.9 (#13288) 2018-03-17 17:37:09 +01:00
Otto Winter
3442b6741d Fix WUnderground duplicate entity ids (#13285)
* Fix WUnderground duplicate entity ids

* Entity Namespace
2018-03-17 13:14:53 +01:00
Otto Winter
f5093b474a Python 3.5 async with (#13283) 2018-03-17 12:27:21 +01:00
thrawnarn
05676ba18b Changed to async/await (#13246)
* Changed to async/await

* Hound fixes

* Lint fixes

* Changed sleep
2018-03-17 12:14:01 +01:00
Sebastian Muszynski
66c6f9cdd6 Unused xiaomi miio sensor method removed (#13281)
* Unused method removed.

* remove unused import
2018-03-17 11:51:40 +01:00
Paulus Schoutsen
5a9013cda5 Refactor Hue: phue -> aiohue (#13043)
* phue -> aiohue

* Clean up

* Fix config

* Address comments

* Typo

* Fix rebase error

* Mark light as unavailable when bridge is disconnected

* Tests

* Make Throttle work with double delay and async

* Rework update logic

* Don't resolve host to IP

* Clarify comment

* No longer do unnecessary updates

* Add more doc

* Another comment update

* Wrap up tests

* Lint

* Fix tests

* PyLint does not like mix 'n match async and coroutine

* Lint

* Update aiohue to 1.2

* Lint

* Fix await MagicMock
2018-03-16 20:27:05 -07:00
Paulus Schoutsen
d78e75db66 Bump frontend to 20180316.0 2018-03-16 15:39:30 -07:00
Sebastian Muszynski
d04ba3f86d Xiaomi MiIO Sensor: Xiaomi Air Quality Monitor (PM2.5) integration (#13264)
* Xiaomi MiIO Sensor: Xiaomi Air Quality Monitor (PM2.5) integration.

* Missing newline added.

* Use a unique data key per domain.

* turn_{on,off} service moved to __init__.py.

* All sensors group added.

* Sensor is a ToggleEntity now.

* is_on property added.

* Use Async / await syntax.

* Make hound happy.

* Unique id added.

* Turn on/off service removed from abstract sensor.

* Turn on/off methods removed.
Device unavailable handling improved.

* Unused import removed.

* Sensor migrated back to an entity.

* Rebased and requirements updated.
2018-03-16 22:13:04 +01:00
Sebastian Muszynski
ed6cd0ccfa Xiaomi MiIO Remote: Unique id added (#13266)
* Unique id added.

* Provide the exception as "ex"
2018-03-16 21:15:23 +01:00
Jens Timmerman
88d2a6ab80 Fix guide link in CONTRIBUTING.md (#13272) 2018-03-16 21:13:32 +01:00
Sebastian Muszynski
fe7012549e Xiaomi MiIO light: Philips Eyecare Smart Lamp 2 integration (#12883)
* Xiaomi Philips Eyecare Smart Lamp 2 support added.

* Blank lines removed.

* Pylint errors fixed.

* Abstract light introduced.

* Smart night light mode renamed.

* Use the conventional power on/off methods again.

* Eyecare mode service added.

* Eyecare mode attribute added.

* Name of the ambient light entity fixed.

* Reuse of the same local variable name within the same scope fixed.

* Use Async / await syntax.

* Missed method fixed.

* Make hound happy.

* Don't abuse the system property supported_features anymore.

* Make hound happy.

* Wrong hanging indentation fixed.
Unnecessary parens after 'return' keyword fixed.

* Refactoring.

* Additional supported features bit mask removed as long as the differences of the supported devices are simple.

* Support for Xiaomi Philips Zhirui Smart LED Bulb E14 Candle Lamp added.

* Docstrings updated.
Refactoring.

* Unique id added.

* Filter service calls. Dummy methods removed.

* Device available handling improved.

* super() used for calling the parent class

* Self removed from super().
2018-03-16 20:59:18 +01:00
Sebastian Muszynski
f013619e69 Xiaomi MiIO Switch: Power Strip support improved (#12917)
* Xiaomi MiIO Switch: Power Strip support improved.

* New service descriptions added.

* Make hound happy.

* Pylint fixed.

* Use Async / await syntax.

* Missed method fixed.

* Make hound happy.

* Don't abuse the system property supported_features anymore.

* Check the correct method.

* Refactoring.

* Make hound happy.

* pythion-miio version bumped.

* Clean-up.

* Unique id added.

* Filter service calls.
Device unavailable handling improved.
2018-03-16 19:58:03 +01:00
Teemu R
78144bc6de Use the first, not the last volume controller when multiple are available on songpal (#13222)
* use the first, not the last volume controller

* Do not mutate the list but simply pick the first by index
2018-03-16 12:14:21 +01:00
cdce8p
f6ae2d338d Homekit: Use util functions for unit conversion (#13253)
* Updated to util/color for conversion
* Updated temperature sensor to use util/temperature conversion
2018-03-16 11:38:44 +01:00
BioSehnsucht
99f7e2bd97 Added Stride notification component (#13221)
* Added Stride notification component

* Fix trailing whitespace in Stride notify

* More whitespace fixes and rogue comment for Stride notify

* More whitespace fixing for Stride notify

* Correcting hanging indents for Stride notify
2018-03-15 20:36:03 -07:00
karlkar
b1079cb493 Fix for not setting up the camera if it is offline during setup phase (#13082)
* Fix for not setting up the camera if it is offline during setup phase

* async/await and modified service creation

* Properly handle not supported PTZ

* setup platform made synchronous as ONVIFService constructors do I/O

* Fix intendation issue
2018-03-15 20:30:41 -07:00
Fabien Piuzzi
0deef34881 Adding Foobot device sensor (#12417)
* Added Foobot device sensor

* Added error handling tests

* Corrections after PR review.

* Migrated to async/await syntax

 * lint fixes
 * stop raising HomeAssistantError
 * debug log for number of requests

* Moved shared data between sensors from a class attribute to a separate class

* Made test more async-aware

disabled setup error test for now as it's not working

* Working failure scenarios tests
2018-03-15 19:50:58 -07:00
cdce8p
2350ce96a6 Homekit: New supported devices (#13244)
* Fixed log message
* Added support for scripts
* Added support for lights
* Small refactoring
* Added support for humidity sensor
* Added tests
2018-03-16 01:05:28 +01:00
Anders Melchiorsen
de1ff1e952 Fix Sonos join/unjoin in scripts (#13248) 2018-03-15 16:12:43 -07:00
Gerard
d13bcf8412 Add extra sensors for BMW ConnectedDrive (#12591)
* Added extra sensors for BMW ConnectedDrive

* Updates based on review of @MartinHjelmare

* Updates based on 2nd review of @MartinHjelmare

* Changed control flow for updates to support updates triggered by remote services.

* updated library version number

* Changed order of commands so that the UI looks consistent.

State of lock is now set optimisitcally before getting proper update
from the server. So that the state does not toggle in the UI.

* Added comment on optimistic state

* Updated requirements_all.txt

* Revert access permission changes

* Fix for Travis

* Changes based on review by @MartinHjelmare
2018-03-15 22:56:35 +01:00
Paulus Schoutsen
456ff4e84b Tado: don't reference unset hass var (#13237)
Tado: don't reference unset hass var
2018-03-15 13:53:59 -07:00
Paulus Schoutsen
89a19c89a7 Fix aiohttp deprecation warnings (#13240)
* Fix aiohttp deprecation warnings

* Fix Ring deprecation warning

* Lint
2018-03-15 21:49:49 +01:00
Juggels
a86bf81768 Fix 'dict' object has no attribute 'strftime' (#13215)
* Fix 'dict' object has no attribute 'strftime'

* Clear existing list instead of new object
2018-03-15 21:43:20 +01:00
Anders Melchiorsen
5e675677ad Cleanup Sonos platform setup (#13225)
* Cleanup Sonos platform setup

* Remove unneeded lists
2018-03-15 20:43:28 +01:00
maxlaverse
ff416c0e7a Try to fix caldav (#13236)
* Fix device attribute type for event end

* Fix is_over and add tests
2018-03-15 10:58:11 -07:00
Paulus Schoutsen
170b8671b9 Fix logbook JSON serialize issue (#13229)
* Fix logbook JSON serialize issue

* Address flakiness

* Lint

* deflake ?

* Deflake 2
2018-03-15 10:54:22 -07:00
Maximilien Cuony
ee6d6a8859 myStrom: Add RGB support to Wifi bulbs (#13194) 2018-03-15 16:45:27 +01:00
Andrei Pop
1d2fd8a2e9 Edimax component reports wrong power values (#13011)
* Fixed Edimax switch authentication error for newer firmware.

* pyedimax moved to pypi

* Added pyedimax to gen_requirements_all.py

* Cleanup

* Fixed https://github.com/home-assistant/home-assistant/issues/13008

* Only ValueError now

* Trivial error.
2018-03-15 16:27:42 +01:00
Eugene Kuzin
92f13ff60d media_content_type attribute display fix (#13204)
* media_content_type fix

Kodi media_content_type attribute display fix

* media_content_type fix (#6989)

fixes attribute display for unknown media

* code cleanup

* trailing whitespaces

* comments correction

* redundant "else:" removed
2018-03-15 08:43:29 -04:00
Clement Wong
5c434f143e Tibber use appNickname as name (#13231) 2018-03-15 13:16:52 +01:00
cdce8p
646ed5de52 Added cover.group platform (replaces #12303) (#12692)
* Added cover.group platform
* Added async/await, smaller changes
* Made (async_update) methods regular methods
* Small improvements
* Changed classname
* Changes based on feedback
* Service calls
* update_supported_features is now a callback method
* combined all 'update_attr_*' methods in 'async_update'
* Small changes
* Fixes
   * is_closed
   * current_position
   * current_tilt_position
* Updated tests
* Small changes 2
2018-03-15 12:31:31 +01:00
Otto Winter
27c1806897 Python 3.5 adjustments (#13173) 2018-03-15 13:10:54 +02:00
Fabian Affolter
6909be1cc7 Add docstring (#13232) 2018-03-15 11:45:54 +01:00
PhracturedBlue
223bc187dc More robust MJPEG parser. Fixes #13138. (#13226)
* More robust MJPEG parser. Fixes ##13138.

* Reimplement image extraction from mjpeg without ascy generator to support python 3.5
2018-03-14 21:44:13 -07:00
c727
c971d61422 Change Hass.io icon to home-assistant (#13230) 2018-03-14 20:56:56 -07:00
Kane610
e122692b46 deCONZ - Add support for consumption and power sensors (#13218)
* Add support for consumption and power sensors

* Keep attr_current inside component
2018-03-14 20:07:37 -07:00
Paulus Schoutsen
76874e1cbc Update translations 2018-03-14 19:47:31 -07:00
cdce8p
d348f09d3d HomeKit Restructure (new config options) (#12997)
* Restructure
* Pincode will now be autogenerated and display using a persistence notification
* Added 'homekit.start' service
* Added config options
* Renamed files for types
* Improved tests
* Changes (based on feedback)
* Removed CONF_PIN_CODE
* Added services.yaml
* Service will only be registered if auto_start=False
* Bugfix names, changed default port
* Generate aids with zlib.adler32
* Added entity filter, minor changes
* Small changes
2018-03-15 02:48:21 +01:00
Paulus Schoutsen
64f18c62f4 Update frontend 2018-03-14 16:39:15 -07:00
Paulus Schoutsen
be2e202618 Bump frontend to 20180315.0 2018-03-14 16:13:46 -07:00
engrbm87
07f20676cb Add notifications to downloader.py (#12961)
* Update downloader.py

Add persistent notification to alert when download is finished or in case of download failure.

* Update downloader.py

* Update downloader.py

* Update downloader.py

* Fire and event when download is requested

Added 2 events to represent download completed and download failed. This will allow the user to trigger an automation based on the status of the download.

* Update downloader.py

* Update downloader.py

replaced . with _

* Update downloader.py

fixed linting errors
2018-03-14 16:03:40 -07:00
Paulus Schoutsen
a30ca4307b Merge branch 'master' into dev 2018-03-14 15:58:55 -07:00
Paulus Schoutsen
e1a5e5a8ba Fix input_boolean Google Assistant serialize error (#13220) 2018-03-14 15:07:37 -07:00
Paulus Schoutsen
a9917e7a56 Fix history API (#13214) 2018-03-14 22:29:51 +01:00
Anders Melchiorsen
ef7ce5eb1b Ignore unsupported Sonos favorites (#13195) 2018-03-14 12:08:41 -07:00
Anders Melchiorsen
7fc9ac0931 Avoid Sonos error when joining with self (#13196) 2018-03-14 12:07:50 -07:00
Paulus Schoutsen
e2029e3970 Add vesync to coveragerc 2018-03-14 12:05:17 -07:00
Paulus Schoutsen
7e2fc19f5a Sort coveragerc 2018-03-14 11:39:38 -07:00
cdce8p
c48c8710b7 Bugfix HomeKit: Error string values for temperature (#13162) 2018-03-14 13:22:38 +01:00
Dan Nixon
b6bed1dfab Report swap in MiB (#13148)
It makes sense to report swap and memory in the same unit and MiB is
more useful considering Home Assistant may be running on lower end
hardware (Raspberry Pi for example) where 100MiB resolution is not
adequate.
2018-03-14 08:47:45 +01:00
Vincent Van Den Berghe
948f29544a Fixed SI units for current consumption (#13190) 2018-03-14 08:14:35 +01:00
Mark Perdue
6310deb5c2 Add new platform for VeSync switches (#13000)
* Added vesync platform
Support for power toggling, current power, and daily energy kWh

* Adds vesync to requirements file.

* Reorder vesync item in requirements_all.txt from gen_requirements_all

* Removes unnecessary global values that are not used in this component

* Removes try/catch from setup_platform -no throws. Guard check login()

* Remove unnecessary boolean convert

* Fix indentation of log messages
2018-03-14 00:10:47 -07:00
JC Connell
cfded7eab9 Python Spotcrime sensor requires API key, fixes include/exclude (#12926)
* Add spotcrime.py to dev

* Modify sensor to accept user API key

* Update Spotcrime to 1.0.3 in requirements_all.txt

* Fix line 76 (97 > 79 characters)

* Fix lint errors
2018-03-14 08:01:10 +01:00
Pascal Vizeli
0ef4340099 Fix freegeoip (#13193) 2018-03-13 20:50:08 -07:00
Jon Maddox
24a9da85c0 Channels clean ups (#12967)
* already in the default schema

* these are already globally disabled

* require a single entity id

* remove unused import

* w h i t e s p a c e

* actually keep it

* it is a string

* use a generator expression

* 💄

* Revert "💄"

This reverts commit 81c08bb732.

* Revert "actually keep it"

This reverts commit 0d92d3afb2.

* Revert "remove unused import"

This reverts commit 8a166208e4.

* Revert "already in the default schema"

This reverts commit 9173de4fd3.

* we're already ensuring defaults with the platform schema
2018-03-13 14:14:02 -07:00
Alok Saboo
71baa6532e Revert throttle Arlo api calls (#13174) 2018-03-13 14:12:28 -07:00
Otto Winter
4c9e7c2da4 Upgrade pytest to 3.4.2 (#13169)
* Upgrade pytest to 3.4.2

* Upgrade pytest-sugar to 0.9.1
2018-03-13 13:57:04 -07:00
Otto Winter
5958e6a60f Improve MQTT failed connection error message (#13184) 2018-03-13 13:56:16 -07:00
Andreas Wolter
3e7a737bff Added IPAreaThermostat and an exception-list for HM_IGNORE_DISCOVERY_NODE (#13171) 2018-03-13 21:54:09 +01:00
Ville Skyttä
dd48fb04a3 upcloud: Provide unique ID for server entities (#13181) 2018-03-13 13:51:10 -07:00
Otto Winter
d5612b5ccc Upgrade holidays to 0.9.4 (#13167) 2018-03-13 17:30:31 +01:00
Kane610
8a1687accb deConz rewrite to use async await syntax (#13151)
* Rewrite to use async await syntax

* Fix hound comment
2018-03-13 08:47:45 +01:00
Jesse Hills
53351423dd Change iglo port to cv.port validator (#13163) 2018-03-13 08:29:20 +01:00
Daniel Høyer Iversen
75fb8ef98b upgrade tibber libary to 0.4.0 to use aiohttp 3.0 (#13164) 2018-03-13 07:04:27 +01:00
Fabian Affolter
989638b266 Upgrade Sphinx to 1.7.1 (#13127) 2018-03-12 18:22:48 -07:00
Otto Winter
d028c33e7f Disable Monkey Patch for 3.6.3+ (#13150) 2018-03-12 16:12:21 -07:00
Paulus Schoutsen
0a2e949e0a Remove crazy JSON encoding things that are no longer used (#13029)
Catch JSON encoding errors in HTTP view
2018-03-12 23:22:08 +01:00
Jeroen ter Heerdt
ae286a550b Adding check for empty discovery info in alarm control panel Egardia. (#13114) 2018-03-12 14:03:05 -07:00
Fabian Affolter
c5330a13b6 Upgrade schiene to 0.22 (#13121) 2018-03-12 14:02:36 -07:00
Fabian Affolter
6ab4a408d2 Upgrade zeroconf to 0.20.0 (#13123) 2018-03-12 14:02:03 -07:00
Fabian Affolter
1202134964 Upgrade youtube_dl to 2018.03.10 (#13124) 2018-03-12 14:01:32 -07:00
Fabian Affolter
bbbb44b999 Upgrade TwitterAPI to 2.4.10 (#13126) 2018-03-12 14:01:05 -07:00
Fabian Affolter
54e0cc1304 Upgrade mypy to 0.570 (#13128) 2018-03-12 14:00:10 -07:00
Per Osbäck
f9e07e617c update to async/await (#13137) 2018-03-12 13:57:13 -07:00
Alok Saboo
95a528a75f Throttle Arlo api calls (#13143) 2018-03-12 13:56:33 -07:00
Paulus Schoutsen
51b0cbefe3 Catch if bridge goes unavailable (#13109) 2018-03-12 13:55:22 -07:00
Paulus Schoutsen
8d8b07abd5 Fix unavailable property for wemo switch (#13106)
* Fix unavailable property for wemo switch

* Have subscriptions respect the lock

* Move subscription callback to added to hass section
2018-03-12 13:54:56 -07:00
Federico Zivolo
15d345c4ef fix: Support different JointSpace API versions (#13084) 2018-03-12 12:33:04 -07:00
Fabian Affolter
676c94561b Upgrade astral to 1.6 (#13120) 2018-03-12 12:28:27 -07:00
Fabian Affolter
02ad9c3574 Upgrade aiohttp to 3.0.7 (#13119) 2018-03-12 12:26:51 -07:00
Otto Winter
890197e407 asyncio.ensure_future Python 3.5 (#13141) 2018-03-12 19:42:08 +01:00
Paulus Schoutsen
9ee123f5ce Version bump to 0.66.0.dev0 2018-03-11 13:20:47 -07:00
Adam Mills
14aa4e7694 Lint script tweaks (#13093)
* Also lint working tree files

When performing a git diff of upstream/dev..., git is diffing against
the current HEAD, but does not include working tree files. By manually
calculating a merge-base SHA to diff against, git will still diff those
files.

* Don't pylint tests files, since we don't in CI

* Use merge base for lazytox

* Simplify files changed header
2018-03-11 16:15:09 -04:00
tadly
991c457430 Updated jsonrpc-websocket to 0.6 (#13096)
Fix Kodi by updating jsonrpc-websocket to 0.6
2018-03-11 12:46:16 -07:00
Greg Dowling
401e92f84e Bump pyvera to 0.2.42. Improve event loop robustness. (#13095) 2018-03-11 12:43:28 -07:00
Otto Winter
1dc5fa145f Revert "Cast automatically drop connection (#12635)" (#13094)
This reverts commit e14893416f.
2018-03-11 12:42:58 -07:00
Joe Lu
dff4f6ce48 Integrated with py-synology:0.2.0 which has fix to auto-renew session when it's expired (#13079) 2018-03-11 12:33:36 -07:00
Paulus Schoutsen
56b3cb0583 Fix Tado doing async wrong (#13078)
* Fix Tado doing async wrong

* Remove last coroutine decorator
2018-03-11 12:33:07 -07:00
Paulus Schoutsen
d0f089975d Run asyncio event loop in debug mode during tests (#13058)
* Run asyncio event loop in debug mode during tests

* Remove debug mode again
2018-03-11 12:32:12 -07:00
Adam Mills
26960283a0 Config flow translations (#13066)
* Development script for testing translation strings

* Localize backend of config flow

* Fix hue tests

* Update hue.en.json

* Move components to individual directories

* Bridge -> bridge
2018-03-11 12:04:34 -07:00
Matthias Urlichs
f5cc40024d Rename homeassistant.util.async to .async_ (#13088)
"async" is (going to be) a reserved word.
2018-03-11 10:01:12 -07:00
Paulus Schoutsen
d42b5a93dd Implement Hue available property (#12939) 2018-03-11 09:49:28 -07:00
Andrey
3dfc49d311 Make Sensibo climate registry_entity compliant (#13086) 2018-03-11 17:19:25 +01:00
Adam Mills
dc8424032b Remove Z-Wave old/new entity_id attributes (#12652) 2018-03-11 10:30:03 -04:00
Johann Kellerman
f164a5a65f Better errors for unknown secrets (#13072) 2018-03-11 12:51:03 +02:00
Otto Winter
d74a2b68c1 Sensor template don't exit early on TemplateError (#13041)
* Sensor template don't exit early on TemplateError

* Add friendly name unknown state test

* Also track entites from attribute templates

* Use set instead of list
2018-03-10 20:45:32 -08:00
Jesse Hills
458598546d - Bump iGlo Version (#13063)
- Use effect list as a method
2018-03-10 20:31:57 -08:00
Julius Mittenzwei
3f6d30ed06 Fixes KNX fire event problem, issue https://github.com/home-assistant/home-assistant/issues/13049 (#13062) 2018-03-10 20:26:21 -08:00
Diogo Gomes
28ff1f7ac2 Convert decimals from SQL results 2018-03-11 00:27:58 +02:00
Paulus Schoutsen
0e00de8a33 Convert decimals from SQL results (#13059) 2018-03-10 10:40:28 -08:00
Paulus Schoutsen
ae47da7bce Update frontend to 20180310.0 2018-03-10 10:19:49 -08:00
Paulus Schoutsen
f01b5b0040 Don't call async from sync (#13057) 2018-03-10 10:02:16 -08:00
Johann Kellerman
40485a6e89 Ensure we have valid config AFTER merging packages #13015 (#13038)
* Ensure we have valid config AFTER merging packages #13015

* also fix packages
2018-03-10 10:02:04 -08:00
cdce8p
7ea7fc8d38 Script/lint, Lazytox: Fix issue to ignore delete files (#13051)
* Fix issue to ignore delete files

* Updated lazytox
2018-03-10 09:12:23 -08:00
Timmo
86baed4e52 Glances Docker Sensors (#13026)
* Added container count

* Added container count

* Change Name

* Fix if

* Added Docker cpu use and memory use
2018-03-10 18:11:53 +01:00
Sebastian Muszynski
b4b779c49d python-miio version bumped. (#13055) 2018-03-10 09:11:10 -08:00
Sebastian Muszynski
0143752d94 Yeelight version bumped. (#13056) 2018-03-10 09:10:50 -08:00
Anders Melchiorsen
e910ecfd5f Fix async lifx_set_state (#13045) 2018-03-10 11:07:02 +01:00
John Allen
4d74fc2d07 Fix sensibo's min/max_temp properties (#12996)
The super class has these as properties, not regular methods
2018-03-10 10:52:45 +02:00
Paul Tarjan
f9c1675c95 Use request.query (#13037)
Fixes #13036
2018-03-10 00:36:20 -08:00
Jerad Meisner
76fb2447a5 Bump pysabnzbd version (#13042) 2018-03-10 09:27:13 +01:00
Otto Winter
2fae86bbd3 Make lazytox script executable (#13040) 2018-03-10 08:39:49 +01:00
cdce8p
3ca139e21e HomeKit Bugfix: names (#13031)
* Fix display_names, changed default port (+1)

* Revert port change
2018-03-09 19:41:59 -08:00
Paulus Schoutsen
a8a895a61b allow ios device tracker see calls to go through (#13020) 2018-03-09 19:39:50 -08:00
Paulus Schoutsen
36361d623d Make Throttle async aware (#13027)
* Make Throttle async aware

* Lint
2018-03-09 19:38:51 -08:00
Paulus Schoutsen
652e0d45a9 Add support for input boolean to Google Assistant (#13030) 2018-03-09 19:38:33 -08:00
Heiko Thiery
556901ea48 remove rounding of temperature reading (#13018)
With homeassistant 0.65.0 the filter sensor is introduced. Now there
is a common way to filter the peaks comming from the readings.

Signed-off-by: Heiko Thiery <heiko.thiery@gmail.com>
2018-03-09 15:53:28 -08:00
Johann Kellerman
05255b9c3f Safe fix for #13015 (#13024) 2018-03-09 15:52:21 -08:00
Paulus Schoutsen
11e1b8a19d Update netdisco to 1.3.0 (#13007) 2018-03-09 13:04:23 -08:00
Johann Kellerman
37d8cd7b75 New lazytox.py script (#12862) 2018-03-09 22:27:39 +02:00
Ryan McLean
d8a7c547df Updated to plexapi 3.0.6 (#13005) 2018-03-09 08:50:39 -08:00
Ryan McLean
ecaf0189cc Plex mark devices unavailable if they 'vanish' and clear media (#12811)
* Marks Devices unavailable if they 'vanish' and clears media

* Fixed PEP8 complaint

* Fixed Linting

* Lint Fix

* Fix redine of id

* More lint fixes

* Removed redundant loop for setting availability of client
Renamed '_is_device_available' to '_available'
Renamed 'available_ids' to 'available_client_ids'

* removed whitespace per houndCI
2018-03-09 08:50:21 -08:00
Otto Winter
ca5f470956 Clean up Light Groups (#12962)
* Clean up Light Groups

* Fix tests

* Remove light group from .coveragerc

* async_schedule_update_ha_state called anyway
2018-03-09 06:15:39 -08:00
mueslo
3ba19c52d5 Add consider_home and source_type to device_tracker.see service (#12849)
* Add consider_home and source_type to device_tracker.see service

* Use schema instead of manual validation

* Extend schema to validate all keys

* Fix style

* Set battery level to int
2018-03-08 23:57:21 -08:00
Johann Kellerman
6734c966b3 check_config script evolution (#12792)
* Initial async_check_ha_config_file

* check_ha_config_file

* Various fixes

* feedback - return the config

* move_to_check_config
2018-03-08 19:34:24 -08:00
Steve Easley
5e2296f2a4 Get zha switch and binary_sensor state on startup (#11672)
* Get zha switch and binary_sensor state on startup

* Removed unused var

* Make zha switch report status

* Use right method name

* Formatting fix

* Updates to match latest dev

* PR feedback updates

* Use async for cluster commands
2018-03-08 19:31:52 -08:00
PhracturedBlue
c5228cbc64 Add camera proxy (#12006)
* Add camera proxy

* Fix additional tox linting issues

* Trivial cleanup

* update to new async/await methods rather than decorators.  Other minor fixes from code review
2018-03-08 18:23:52 -08:00
387 changed files with 11105 additions and 5275 deletions

View File

@@ -109,6 +109,9 @@ omit =
homeassistant/components/homematic/__init__.py
homeassistant/components/*/homematic.py
homeassistant/components/homematicip_cloud.py
homeassistant/components/*/homematicip_cloud.py
homeassistant/components/ihc/*
homeassistant/components/*/ihc.py
@@ -309,6 +312,7 @@ omit =
homeassistant/components/alarm_control_panel/canary.py
homeassistant/components/alarm_control_panel/concord232.py
homeassistant/components/alarm_control_panel/ialarm.py
homeassistant/components/alarm_control_panel/ifttt.py
homeassistant/components/alarm_control_panel/manual_mqtt.py
homeassistant/components/alarm_control_panel/nx584.py
homeassistant/components/alarm_control_panel/simplisafe.py
@@ -332,6 +336,7 @@ omit =
homeassistant/components/camera/foscam.py
homeassistant/components/camera/mjpeg.py
homeassistant/components/camera/onvif.py
homeassistant/components/camera/proxy.py
homeassistant/components/camera/ring.py
homeassistant/components/camera/rpi_camera.py
homeassistant/components/camera/synology.py
@@ -403,20 +408,20 @@ omit =
homeassistant/components/image_processing/dlib_face_detect.py
homeassistant/components/image_processing/dlib_face_identify.py
homeassistant/components/image_processing/seven_segments.py
homeassistant/components/keyboard.py
homeassistant/components/keyboard_remote.py
homeassistant/components/keyboard.py
homeassistant/components/light/avion.py
homeassistant/components/light/blinksticklight.py
homeassistant/components/light/blinkt.py
homeassistant/components/light/decora.py
homeassistant/components/light/decora_wifi.py
homeassistant/components/light/decora.py
homeassistant/components/light/flux_led.py
homeassistant/components/light/greenwave.py
homeassistant/components/light/hue.py
homeassistant/components/light/hyperion.py
homeassistant/components/light/iglo.py
homeassistant/components/light/lifx.py
homeassistant/components/light/lifx_legacy.py
homeassistant/components/light/lifx.py
homeassistant/components/light/limitlessled.py
homeassistant/components/light/mystrom.py
homeassistant/components/light/osramlightify.py
@@ -442,6 +447,7 @@ omit =
homeassistant/components/media_player/bluesound.py
homeassistant/components/media_player/braviatv.py
homeassistant/components/media_player/cast.py
homeassistant/components/media_player/channels.py
homeassistant/components/media_player/clementine.py
homeassistant/components/media_player/cmus.py
homeassistant/components/media_player/denon.py
@@ -482,8 +488,8 @@ omit =
homeassistant/components/media_player/vlc.py
homeassistant/components/media_player/volumio.py
homeassistant/components/media_player/xiaomi_tv.py
homeassistant/components/media_player/yamaha.py
homeassistant/components/media_player/yamaha_musiccast.py
homeassistant/components/media_player/yamaha.py
homeassistant/components/media_player/ziggo_mediabox_xl.py
homeassistant/components/mycroft.py
homeassistant/components/notify/aws_lambda.py
@@ -491,8 +497,8 @@ omit =
homeassistant/components/notify/aws_sqs.py
homeassistant/components/notify/ciscospark.py
homeassistant/components/notify/clickatell.py
homeassistant/components/notify/clicksend.py
homeassistant/components/notify/clicksend_tts.py
homeassistant/components/notify/clicksend.py
homeassistant/components/notify/discord.py
homeassistant/components/notify/free_mobile.py
homeassistant/components/notify/gntp.py
@@ -517,6 +523,7 @@ omit =
homeassistant/components/notify/sendgrid.py
homeassistant/components/notify/simplepush.py
homeassistant/components/notify/slack.py
homeassistant/components/notify/stride.py
homeassistant/components/notify/smtp.py
homeassistant/components/notify/synology_chat.py
homeassistant/components/notify/syslog.py
@@ -554,7 +561,6 @@ omit =
homeassistant/components/sensor/crimereports.py
homeassistant/components/sensor/cups.py
homeassistant/components/sensor/currencylayer.py
homeassistant/components/sensor/darksky.py
homeassistant/components/sensor/deluge.py
homeassistant/components/sensor/deutsche_bahn.py
homeassistant/components/sensor/dht.py
@@ -576,6 +582,7 @@ omit =
homeassistant/components/sensor/fitbit.py
homeassistant/components/sensor/fixer.py
homeassistant/components/sensor/folder.py
homeassistant/components/sensor/foobot.py
homeassistant/components/sensor/fritzbox_callmonitor.py
homeassistant/components/sensor/fritzbox_netmonitor.py
homeassistant/components/sensor/gearbest.py
@@ -588,8 +595,8 @@ omit =
homeassistant/components/sensor/haveibeenpwned.py
homeassistant/components/sensor/hp_ilo.py
homeassistant/components/sensor/htu21d.py
homeassistant/components/sensor/imap.py
homeassistant/components/sensor/imap_email_content.py
homeassistant/components/sensor/imap.py
homeassistant/components/sensor/influxdb.py
homeassistant/components/sensor/irish_rail_transport.py
homeassistant/components/sensor/kwb.py
@@ -632,8 +639,8 @@ omit =
homeassistant/components/sensor/scrape.py
homeassistant/components/sensor/sense.py
homeassistant/components/sensor/sensehat.py
homeassistant/components/sensor/serial.py
homeassistant/components/sensor/serial_pm.py
homeassistant/components/sensor/serial.py
homeassistant/components/sensor/shodan.py
homeassistant/components/sensor/simulated.py
homeassistant/components/sensor/skybeacon.py
@@ -647,6 +654,7 @@ omit =
homeassistant/components/sensor/supervisord.py
homeassistant/components/sensor/swiss_hydrological_data.py
homeassistant/components/sensor/swiss_public_transport.py
homeassistant/components/sensor/syncthru.py
homeassistant/components/sensor/synologydsm.py
homeassistant/components/sensor/systemmonitor.py
homeassistant/components/sensor/sytadin.py
@@ -656,6 +664,7 @@ omit =
homeassistant/components/sensor/tibber.py
homeassistant/components/sensor/time_date.py
homeassistant/components/sensor/torque.py
homeassistant/components/sensor/trafikverket_weatherstation.py
homeassistant/components/sensor/transmission.py
homeassistant/components/sensor/travisci.py
homeassistant/components/sensor/twitch.py
@@ -697,6 +706,7 @@ omit =
homeassistant/components/switch/telnet.py
homeassistant/components/switch/tplink.py
homeassistant/components/switch/transmission.py
homeassistant/components/switch/vesync.py
homeassistant/components/switch/xiaomi_miio.py
homeassistant/components/telegram_bot/*
homeassistant/components/thingspeak.py

View File

@@ -12,19 +12,18 @@
## Checklist:
- [ ] The code change is tested and works locally.
- [ ] Local tests pass with `tox`. **Your PR cannot be merged unless tests pass**
If user exposed functionality or configuration variables are added/changed:
- [ ] Documentation added/updated in [home-assistant.github.io](https://github.com/home-assistant/home-assistant.github.io)
If the code communicates with devices, web services, or third-party tools:
- [ ] Local tests with `tox` run successfully. **Your PR cannot be merged unless tests pass**
- [ ] New dependencies have been added to the `REQUIREMENTS` variable ([example][ex-requir]).
- [ ] New dependencies are only imported inside functions that use them ([example][ex-import]).
- [ ] New dependencies have been added to `requirements_all.txt` by running `script/gen_requirements_all.py`.
- [ ] New files were added to `.coveragerc`.
If the code does not interact with devices:
- [ ] Local tests with `tox` run successfully. **Your PR cannot be merged unless tests pass**
- [ ] Tests have been added to verify that the new code works.
[ex-requir]: https://github.com/home-assistant/home-assistant/blob/dev/homeassistant/components/keyboard.py#L14

1
.gitignore vendored
View File

@@ -21,6 +21,7 @@ Icon
*.iml
# pytest
.pytest_cache
.cache
# GITHUB Proposed Python stuff:

0
.gitmodules vendored
View File

View File

@@ -49,6 +49,7 @@ homeassistant/components/camera/yi.py @bachya
homeassistant/components/climate/ephember.py @ttroy50
homeassistant/components/climate/eq3btsmart.py @rytilahti
homeassistant/components/climate/sensibo.py @andrey-git
homeassistant/components/cover/group.py @cdce8p
homeassistant/components/cover/template.py @PhracturedBlue
homeassistant/components/device_tracker/automatic.py @armills
homeassistant/components/device_tracker/tile.py @bachya

View File

@@ -4,7 +4,7 @@ Everybody is invited and welcome to contribute to Home Assistant. There is a lot
The process is straight-forward.
- Read [How to get faster PR reviews](https://github.com/kubernetes/community/blob/master/contributors/devel/pull-requests.md#best-practices-for-faster-reviews) by Kubernetes (but skip step 0)
- Read [How to get faster PR reviews](https://github.com/kubernetes/community/blob/master/contributors/guide/pull-requests.md#best-practices-for-faster-reviews) by Kubernetes (but skip step 0)
- Fork the Home Assistant [git repository](https://github.com/home-assistant/home-assistant).
- Write the code for your device, notification service, sensor, or IoT thing.
- Ensure tests work.

View File

@@ -4,10 +4,10 @@ homeassistant.util package
Submodules
----------
homeassistant.util.async module
homeassistant.util.async_ module
-------------------------------
.. automodule:: homeassistant.util.async
.. automodule:: homeassistant.util.async_
:members:
:undoc-members:
:show-inheritance:

View File

@@ -272,7 +272,7 @@ def setup_and_run_hass(config_dir: str,
if args.open_ui:
# Imported here to avoid importing asyncio before monkey patch
from homeassistant.util.async import run_callback_threadsafe
from homeassistant.util.async_ import run_callback_threadsafe
def open_browser(event):
"""Open the webinterface in a browser."""
@@ -335,7 +335,8 @@ def main() -> int:
"""Start Home Assistant."""
validate_python()
if os.environ.get('HASS_NO_MONKEY') != '1':
monkey_patch_needed = sys.version_info[:3] < (3, 6, 3)
if monkey_patch_needed and os.environ.get('HASS_NO_MONKEY') != '1':
if sys.version_info[:2] >= (3, 6):
monkey_patch.disable_c_asyncio()
monkey_patch.patch_weakref_tasks()

View File

@@ -86,14 +86,6 @@ def async_from_config_dict(config: Dict[str, Any],
if enable_log:
async_enable_logging(hass, verbose, log_rotate_days, log_file)
if sys.version_info[:2] < (3, 5):
_LOGGER.warning(
'Python 3.4 support has been deprecated and will be removed in '
'the beginning of 2018. Please upgrade Python or your operating '
'system. More info: https://home-assistant.io/blog/2017/10/06/'
'deprecating-python-3.4-support/'
)
core_config = config.get(core.DOMAIN, {})
try:

View File

@@ -12,13 +12,14 @@ import requests
import homeassistant.components.alarm_control_panel as alarm
from homeassistant.const import (
STATE_ALARM_DISARMED, STATE_ALARM_ARMED_HOME,
STATE_ALARM_ARMED_AWAY, STATE_ALARM_TRIGGERED)
STATE_ALARM_ARMED_AWAY, STATE_ALARM_TRIGGERED,
STATE_ALARM_ARMED_NIGHT)
from homeassistant.components.egardia import (
EGARDIA_DEVICE, EGARDIA_SERVER,
REPORT_SERVER_CODES_IGNORE, CONF_REPORT_SERVER_CODES,
CONF_REPORT_SERVER_ENABLED, CONF_REPORT_SERVER_PORT
)
REQUIREMENTS = ['pythonegardia==1.0.38']
DEPENDENCIES = ['egardia']
_LOGGER = logging.getLogger(__name__)
@@ -27,6 +28,8 @@ STATES = {
'DAY HOME': STATE_ALARM_ARMED_HOME,
'DISARM': STATE_ALARM_DISARMED,
'ARMHOME': STATE_ALARM_ARMED_HOME,
'HOME': STATE_ALARM_ARMED_HOME,
'NIGHT HOME': STATE_ALARM_ARMED_NIGHT,
'TRIGGERED': STATE_ALARM_TRIGGERED
}

View File

@@ -0,0 +1,170 @@
"""
Interfaces with alarm control panels that have to be controlled through IFTTT.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/alarm_control_panel.ifttt/
"""
import logging
import voluptuous as vol
import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel import (
DOMAIN, PLATFORM_SCHEMA)
from homeassistant.components.ifttt import (
ATTR_EVENT, DOMAIN as IFTTT_DOMAIN, SERVICE_TRIGGER)
from homeassistant.const import (
ATTR_ENTITY_ID, ATTR_STATE, CONF_NAME, CONF_CODE,
CONF_OPTIMISTIC, STATE_ALARM_DISARMED, STATE_ALARM_ARMED_NIGHT,
STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_AWAY)
import homeassistant.helpers.config_validation as cv
DEPENDENCIES = ['ifttt']
_LOGGER = logging.getLogger(__name__)
ALLOWED_STATES = [
STATE_ALARM_DISARMED, STATE_ALARM_ARMED_NIGHT,
STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME]
DATA_IFTTT_ALARM = 'ifttt_alarm'
DEFAULT_NAME = "Home"
CONF_EVENT_AWAY = "event_arm_away"
CONF_EVENT_HOME = "event_arm_home"
CONF_EVENT_NIGHT = "event_arm_night"
CONF_EVENT_DISARM = "event_disarm"
DEFAULT_EVENT_AWAY = "alarm_arm_away"
DEFAULT_EVENT_HOME = "alarm_arm_home"
DEFAULT_EVENT_NIGHT = "alarm_arm_night"
DEFAULT_EVENT_DISARM = "alarm_disarm"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_CODE): cv.string,
vol.Optional(CONF_EVENT_AWAY, default=DEFAULT_EVENT_AWAY): cv.string,
vol.Optional(CONF_EVENT_HOME, default=DEFAULT_EVENT_HOME): cv.string,
vol.Optional(CONF_EVENT_NIGHT, default=DEFAULT_EVENT_NIGHT): cv.string,
vol.Optional(CONF_EVENT_DISARM, default=DEFAULT_EVENT_DISARM): cv.string,
vol.Optional(CONF_OPTIMISTIC, default=False): cv.boolean,
})
SERVICE_PUSH_ALARM_STATE = "ifttt_push_alarm_state"
PUSH_ALARM_STATE_SERVICE_SCHEMA = vol.Schema({
vol.Required(ATTR_ENTITY_ID): cv.entity_ids,
vol.Required(ATTR_STATE): cv.string,
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up a control panel managed through IFTTT."""
if DATA_IFTTT_ALARM not in hass.data:
hass.data[DATA_IFTTT_ALARM] = []
name = config.get(CONF_NAME)
code = config.get(CONF_CODE)
event_away = config.get(CONF_EVENT_AWAY)
event_home = config.get(CONF_EVENT_HOME)
event_night = config.get(CONF_EVENT_NIGHT)
event_disarm = config.get(CONF_EVENT_DISARM)
optimistic = config.get(CONF_OPTIMISTIC)
alarmpanel = IFTTTAlarmPanel(name, code, event_away, event_home,
event_night, event_disarm, optimistic)
hass.data[DATA_IFTTT_ALARM].append(alarmpanel)
add_devices([alarmpanel])
async def push_state_update(service):
"""Set the service state as device state attribute."""
entity_ids = service.data.get(ATTR_ENTITY_ID)
state = service.data.get(ATTR_STATE)
devices = hass.data[DATA_IFTTT_ALARM]
if entity_ids:
devices = [d for d in devices if d.entity_id in entity_ids]
for device in devices:
device.push_alarm_state(state)
device.async_schedule_update_ha_state()
hass.services.register(DOMAIN, SERVICE_PUSH_ALARM_STATE, push_state_update,
schema=PUSH_ALARM_STATE_SERVICE_SCHEMA)
class IFTTTAlarmPanel(alarm.AlarmControlPanel):
"""Representation of an alarm control panel controlled throught IFTTT."""
def __init__(self, name, code, event_away, event_home, event_night,
event_disarm, optimistic):
"""Initialize the alarm control panel."""
self._name = name
self._code = code
self._event_away = event_away
self._event_home = event_home
self._event_night = event_night
self._event_disarm = event_disarm
self._optimistic = optimistic
self._state = None
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def assumed_state(self):
"""Notify that this platform return an assumed state."""
return True
@property
def code_format(self):
"""Return one or more characters."""
return None if self._code is None else '.+'
def alarm_disarm(self, code=None):
"""Send disarm command."""
if not self._check_code(code):
return
self.set_alarm_state(self._event_disarm, STATE_ALARM_DISARMED)
def alarm_arm_away(self, code=None):
"""Send arm away command."""
if not self._check_code(code):
return
self.set_alarm_state(self._event_away, STATE_ALARM_ARMED_AWAY)
def alarm_arm_home(self, code=None):
"""Send arm home command."""
if not self._check_code(code):
return
self.set_alarm_state(self._event_home, STATE_ALARM_ARMED_HOME)
def alarm_arm_night(self, code=None):
"""Send arm night command."""
if not self._check_code(code):
return
self.set_alarm_state(self._event_night, STATE_ALARM_ARMED_NIGHT)
def set_alarm_state(self, event, state):
"""Call the IFTTT trigger service to change the alarm state."""
data = {ATTR_EVENT: event}
self.hass.services.call(IFTTT_DOMAIN, SERVICE_TRIGGER, data)
_LOGGER.debug("Called IFTTT component to trigger event %s", event)
if self._optimistic:
self._state = state
def push_alarm_state(self, value):
"""Push the alarm state to the given value."""
if value in ALLOWED_STATES:
_LOGGER.debug("Pushed the alarm state to %s", value)
self._state = value
def _check_code(self, code):
return self._code is None or self._code == code

View File

@@ -69,3 +69,13 @@ alarmdecoder_alarm_toggle_chime:
code:
description: A required code to toggle the alarm control panel chime with.
example: 1234
ifttt_push_alarm_state:
description: Update the alarm state to the specified value.
fields:
entity_id:
description: Name of the alarm control panel which state has to be updated.
example: 'alarm_control_panel.downstairs'
state:
description: The state to which the alarm control panel has to be set.
example: 'armed_night'

View File

@@ -438,9 +438,7 @@ class _LightCapabilities(_AlexaEntity):
supported = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
if supported & light.SUPPORT_BRIGHTNESS:
yield _AlexaBrightnessController(self.entity)
if supported & light.SUPPORT_RGB_COLOR:
yield _AlexaColorController(self.entity)
if supported & light.SUPPORT_XY_COLOR:
if supported & light.SUPPORT_COLOR:
yield _AlexaColorController(self.entity)
if supported & light.SUPPORT_COLOR_TEMP:
yield _AlexaColorTemperatureController(self.entity)
@@ -842,25 +840,16 @@ def async_api_adjust_brightness(hass, config, request, entity):
@asyncio.coroutine
def async_api_set_color(hass, config, request, entity):
"""Process a set color request."""
supported = entity.attributes.get(ATTR_SUPPORTED_FEATURES)
rgb = color_util.color_hsb_to_RGB(
float(request[API_PAYLOAD]['color']['hue']),
float(request[API_PAYLOAD]['color']['saturation']),
float(request[API_PAYLOAD]['color']['brightness'])
)
if supported & light.SUPPORT_RGB_COLOR > 0:
yield from hass.services.async_call(entity.domain, SERVICE_TURN_ON, {
ATTR_ENTITY_ID: entity.entity_id,
light.ATTR_RGB_COLOR: rgb,
}, blocking=False)
else:
xyz = color_util.color_RGB_to_xy(*rgb)
yield from hass.services.async_call(entity.domain, SERVICE_TURN_ON, {
ATTR_ENTITY_ID: entity.entity_id,
light.ATTR_XY_COLOR: (xyz[0], xyz[1]),
light.ATTR_BRIGHTNESS: xyz[2],
}, blocking=False)
yield from hass.services.async_call(entity.domain, SERVICE_TURN_ON, {
ATTR_ENTITY_ID: entity.entity_id,
light.ATTR_RGB_COLOR: rgb,
}, blocking=False)
return api_message(request)

View File

@@ -0,0 +1,118 @@
"""
Reads vehicle status from BMW connected drive portal.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.bmw_connected_drive/
"""
import asyncio
import logging
from homeassistant.components.bmw_connected_drive import DOMAIN as BMW_DOMAIN
from homeassistant.components.binary_sensor import BinarySensorDevice
DEPENDENCIES = ['bmw_connected_drive']
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPES = {
'lids': ['Doors', 'opening'],
'windows': ['Windows', 'opening'],
'door_lock_state': ['Door lock state', 'safety']
}
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the BMW sensors."""
accounts = hass.data[BMW_DOMAIN]
_LOGGER.debug('Found BMW accounts: %s',
', '.join([a.name for a in accounts]))
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)
add_devices(devices, True)
class BMWConnectedDriveSensor(BinarySensorDevice):
"""Representation of a BMW vehicle binary sensor."""
def __init__(self, account, vehicle, attribute: str, sensor_name,
device_class):
"""Constructor."""
self._account = account
self._vehicle = vehicle
self._attribute = attribute
self._name = '{} {}'.format(self._vehicle.modelName, self._attribute)
self._sensor_name = sensor_name
self._device_class = device_class
self._state = None
@property
def should_poll(self) -> bool:
"""Data update is triggered from BMWConnectedDriveEntity."""
return False
@property
def name(self):
"""Return the name of the binary sensor."""
return self._name
@property
def device_class(self):
"""Return the class of the binary sensor."""
return self._device_class
@property
def is_on(self):
"""Return the state of the binary sensor."""
return self._state
@property
def device_state_attributes(self):
"""Return the state attributes of the binary sensor."""
vehicle_state = self._vehicle.state
result = {
'car': self._vehicle.modelName
}
if self._attribute == 'lids':
for lid in vehicle_state.lids:
result[lid.name] = lid.state.value
elif self._attribute == 'windows':
for window in vehicle_state.windows:
result[window.name] = window.state.value
elif self._attribute == 'door_lock_state':
result['door_lock_state'] = vehicle_state.door_lock_state.value
return result
def update(self):
"""Read new state data from the library."""
vehicle_state = self._vehicle.state
# device class opening: On means open, Off means closed
if self._attribute == 'lids':
_LOGGER.debug("Status of lid: %s", vehicle_state.all_lids_closed)
self._state = not vehicle_state.all_lids_closed
if self._attribute == 'windows':
self._state = not vehicle_state.all_windows_closed
# device class safety: On means unsafe, Off means safe
if self._attribute == 'door_lock_state':
# Possible values: LOCKED, SECURED, SELECTIVELOCKED, UNLOCKED
self._state = bool(vehicle_state.door_lock_state.value
in ('SELECTIVELOCKED', 'UNLOCKED'))
def update_callback(self):
"""Schedule a state update."""
self.schedule_update_ha_state(True)
@asyncio.coroutine
def async_added_to_hass(self):
"""Add callback after being added to hass.
Show latest data after startup.
"""
self._account.add_update_listener(self.update_callback)

View File

@@ -4,8 +4,6 @@ Support for deCONZ binary sensor.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.deconz/
"""
import asyncio
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.deconz import (
DOMAIN as DATA_DECONZ, DATA_DECONZ_ID)
@@ -15,8 +13,8 @@ from homeassistant.core import callback
DEPENDENCIES = ['deconz']
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Set up the deCONZ binary sensor."""
if discovery_info is None:
return
@@ -25,8 +23,7 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
sensors = hass.data[DATA_DECONZ].sensors
entities = []
for key in sorted(sensors.keys(), key=int):
sensor = sensors[key]
for sensor in sensors.values():
if sensor and sensor.type in DECONZ_BINARY_SENSOR:
entities.append(DeconzBinarySensor(sensor))
async_add_devices(entities, True)
@@ -39,8 +36,7 @@ class DeconzBinarySensor(BinarySensorDevice):
"""Set up sensor and add update callback to get data from websocket."""
self._sensor = sensor
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Subscribe sensors events."""
self._sensor.register_async_callback(self.async_update_callback)
self.hass.data[DATA_DECONZ_ID][self.entity_id] = self._sensor.deconz_id
@@ -96,9 +92,9 @@ class DeconzBinarySensor(BinarySensorDevice):
def device_state_attributes(self):
"""Return the state attributes of the sensor."""
from pydeconz.sensor import PRESENCE
attr = {
ATTR_BATTERY_LEVEL: self._sensor.battery,
}
if self._sensor.type in PRESENCE:
attr = {}
if self._sensor.battery:
attr[ATTR_BATTERY_LEVEL] = self._sensor.battery
if self._sensor.type in PRESENCE and self._sensor.dark:
attr['dark'] = self._sensor.dark
return attr

View File

@@ -12,7 +12,7 @@ from homeassistant.const import STATE_ON, STATE_OFF
from homeassistant.components.egardia import (
EGARDIA_DEVICE, ATTR_DISCOVER_DEVICES)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['egardia']
EGARDIA_TYPE_TO_DEVICE_CLASS = {'IR Sensor': 'motion',
'Door Contact': 'opening',
'IR': 'motion'}

View File

@@ -9,6 +9,17 @@ from homeassistant.components.binary_sensor import (
DEVICE_CLASSES, DOMAIN, BinarySensorDevice)
from homeassistant.const import STATE_ON
SENSORS = {
'S_DOOR': 'door',
'S_MOTION': 'motion',
'S_SMOKE': 'smoke',
'S_SPRINKLER': 'safety',
'S_WATER_LEAK': 'safety',
'S_SOUND': 'sound',
'S_VIBRATION': 'vibration',
'S_MOISTURE': 'moisture',
}
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the MySensors platform for binary sensors."""
@@ -29,18 +40,7 @@ class MySensorsBinarySensor(mysensors.MySensorsEntity, BinarySensorDevice):
def device_class(self):
"""Return the class of this sensor, from DEVICE_CLASSES."""
pres = self.gateway.const.Presentation
class_map = {
pres.S_DOOR: 'opening',
pres.S_MOTION: 'motion',
pres.S_SMOKE: 'smoke',
}
if float(self.gateway.protocol_version) >= 1.5:
class_map.update({
pres.S_SPRINKLER: 'sprinkler',
pres.S_WATER_LEAK: 'leak',
pres.S_SOUND: 'sound',
pres.S_VIBRATION: 'vibration',
pres.S_MOISTURE: 'moisture',
})
if class_map.get(self.child_type) in DEVICE_CLASSES:
return class_map.get(self.child_type)
device_class = SENSORS.get(pres(self.child_type).name)
if device_class in DEVICE_CLASSES:
return device_class
return None

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.0']
REQUIREMENTS = ['numpy==1.14.2']
_LOGGER = logging.getLogger(__name__)

View File

@@ -17,7 +17,7 @@ import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['holidays==0.9.3']
REQUIREMENTS = ['holidays==0.9.4']
# List of all countries currently supported by holidays
# There seems to be no way to get the list out at runtime

View File

@@ -37,7 +37,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
BMW_COMPONENTS = ['device_tracker', 'sensor']
BMW_COMPONENTS = ['binary_sensor', 'device_tracker', 'lock', 'sensor']
UPDATE_INTERVAL = 5 # in minutes

View File

@@ -194,7 +194,9 @@ class WebDavCalendarData(object):
@staticmethod
def is_over(vevent):
"""Return if the event is over."""
return dt.now() > WebDavCalendarData.get_end_date(vevent)
return dt.now() >= WebDavCalendarData.to_datetime(
WebDavCalendarData.get_end_date(vevent)
)
@staticmethod
def get_hass_date(obj):
@@ -230,4 +232,4 @@ class WebDavCalendarData(object):
else:
enddate = obj.dtstart.value + timedelta(days=1)
return WebDavCalendarData.to_datetime(enddate)
return enddate

View File

@@ -496,6 +496,10 @@ class TodoistProjectData(object):
# We had no valid tasks
return True
# Make sure the task collection is reset to prevent an
# infinite collection repeating the same tasks
self.all_project_tasks.clear()
# Organize the best tasks (so users can see all the tasks
# they have, organized)
while project_tasks:

View File

@@ -21,7 +21,7 @@ from homeassistant.components.camera import (
PLATFORM_SCHEMA, DEFAULT_CONTENT_TYPE, Camera)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers import config_validation as cv
from homeassistant.util.async import run_coroutine_threadsafe
from homeassistant.util.async_ import run_coroutine_threadsafe
_LOGGER = logging.getLogger(__name__)

View File

@@ -6,6 +6,7 @@ https://home-assistant.io/components/camera.onvif/
"""
import asyncio
import logging
import os
import voluptuous as vol
@@ -103,92 +104,128 @@ class ONVIFHassCamera(Camera):
def __init__(self, hass, config):
"""Initialize a ONVIF camera."""
from onvif import ONVIFCamera, exceptions
super().__init__()
import onvif
self._username = config.get(CONF_USERNAME)
self._password = config.get(CONF_PASSWORD)
self._host = config.get(CONF_HOST)
self._port = config.get(CONF_PORT)
self._name = config.get(CONF_NAME)
self._ffmpeg_arguments = config.get(CONF_EXTRA_ARGUMENTS)
self._profile_index = config.get(CONF_PROFILE)
self._input = None
camera = None
self._media_service = \
onvif.ONVIFService('http://{}:{}/onvif/device_service'.format(
self._host, self._port),
self._username, self._password,
'{}/wsdl/media.wsdl'.format(os.path.dirname(
onvif.__file__)))
self._ptz_service = \
onvif.ONVIFService('http://{}:{}/onvif/device_service'.format(
self._host, self._port),
self._username, self._password,
'{}/wsdl/ptz.wsdl'.format(os.path.dirname(
onvif.__file__)))
def obtain_input_uri(self):
"""Set the input uri for the camera."""
from onvif import exceptions
_LOGGER.debug("Connecting with ONVIF Camera: %s on port %s",
self._host, self._port)
try:
_LOGGER.debug("Connecting with ONVIF Camera: %s on port %s",
config.get(CONF_HOST), config.get(CONF_PORT))
camera = ONVIFCamera(
config.get(CONF_HOST), config.get(CONF_PORT),
config.get(CONF_USERNAME), config.get(CONF_PASSWORD)
)
media_service = camera.create_media_service()
self._profiles = media_service.GetProfiles()
self._profile_index = config.get(CONF_PROFILE)
if self._profile_index >= len(self._profiles):
profiles = self._media_service.GetProfiles()
if self._profile_index >= len(profiles):
_LOGGER.warning("ONVIF Camera '%s' doesn't provide profile %d."
" Using the last profile.",
self._name, self._profile_index)
self._profile_index = -1
req = media_service.create_type('GetStreamUri')
req = self._media_service.create_type('GetStreamUri')
# pylint: disable=protected-access
req.ProfileToken = self._profiles[self._profile_index]._token
self._input = media_service.GetStreamUri(req).Uri.replace(
'rtsp://', 'rtsp://{}:{}@'.format(
config.get(CONF_USERNAME),
config.get(CONF_PASSWORD)), 1)
req.ProfileToken = profiles[self._profile_index]._token
uri_no_auth = self._media_service.GetStreamUri(req).Uri
uri_for_log = uri_no_auth.replace(
'rtsp://', 'rtsp://<user>:<password>@', 1)
self._input = uri_no_auth.replace(
'rtsp://', 'rtsp://{}:{}@'.format(self._username,
self._password), 1)
_LOGGER.debug(
"ONVIF Camera Using the following URL for %s: %s",
self._name, self._input)
except Exception as err:
_LOGGER.error("Unable to communicate with ONVIF Camera: %s", err)
raise
try:
self._ptz = camera.create_ptz_service()
self._name, uri_for_log)
# we won't need the media service anymore
self._media_service = None
except exceptions.ONVIFError as err:
self._ptz = None
_LOGGER.warning("Unable to setup PTZ for ONVIF Camera: %s", err)
_LOGGER.debug("Couldn't setup camera '%s'. Error: %s",
self._name, err)
return
def perform_ptz(self, pan, tilt, zoom):
"""Perform a PTZ action on the camera."""
if self._ptz:
from onvif import exceptions
if self._ptz_service:
pan_val = 1 if pan == DIR_RIGHT else -1 if pan == DIR_LEFT else 0
tilt_val = 1 if tilt == DIR_UP else -1 if tilt == DIR_DOWN else 0
zoom_val = 1 if zoom == ZOOM_IN else -1 if zoom == ZOOM_OUT else 0
req = {"Velocity": {
"PanTilt": {"_x": pan_val, "_y": tilt_val},
"Zoom": {"_x": zoom_val}}}
self._ptz.ContinuousMove(req)
try:
self._ptz_service.ContinuousMove(req)
except exceptions.ONVIFError as err:
if "Bad Request" in err.reason:
self._ptz_service = None
_LOGGER.debug("Camera '%s' doesn't support PTZ.",
self._name)
else:
_LOGGER.debug("Camera '%s' doesn't support PTZ.", self._name)
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Callback when entity is added to hass."""
if ONVIF_DATA not in self.hass.data:
self.hass.data[ONVIF_DATA] = {}
self.hass.data[ONVIF_DATA][ENTITIES] = []
self.hass.data[ONVIF_DATA][ENTITIES].append(self)
@asyncio.coroutine
def async_camera_image(self):
async def async_camera_image(self):
"""Return a still image response from the camera."""
from haffmpeg import ImageFrame, IMAGE_JPEG
if not self._input:
await self.hass.async_add_job(self.obtain_input_uri)
if not self._input:
return None
ffmpeg = ImageFrame(
self.hass.data[DATA_FFMPEG].binary, loop=self.hass.loop)
image = yield from asyncio.shield(ffmpeg.get_image(
image = await asyncio.shield(ffmpeg.get_image(
self._input, output_format=IMAGE_JPEG,
extra_cmd=self._ffmpeg_arguments), loop=self.hass.loop)
return image
@asyncio.coroutine
def handle_async_mjpeg_stream(self, request):
async def handle_async_mjpeg_stream(self, request):
"""Generate an HTTP MJPEG stream from the camera."""
from haffmpeg import CameraMjpeg
if not self._input:
await self.hass.async_add_job(self.obtain_input_uri)
if not self._input:
return None
stream = CameraMjpeg(self.hass.data[DATA_FFMPEG].binary,
loop=self.hass.loop)
yield from stream.open_camera(
await stream.open_camera(
self._input, extra_cmd=self._ffmpeg_arguments)
yield from async_aiohttp_proxy_stream(
await async_aiohttp_proxy_stream(
self.hass, request, stream,
'multipart/x-mixed-replace;boundary=ffserver')
yield from stream.close()
await stream.close()
@property
def name(self):

View File

@@ -11,7 +11,7 @@ import async_timeout
import voluptuous as vol
from homeassistant.util.async import run_coroutine_threadsafe
from homeassistant.util.async_ import run_coroutine_threadsafe
from homeassistant.helpers import config_validation as cv
import homeassistant.util.dt as dt_util

View File

@@ -4,7 +4,6 @@ Support for Xeoma Cameras.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.xeoma/
"""
import asyncio
import logging
import voluptuous as vol
@@ -14,7 +13,7 @@ from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME)
from homeassistant.helpers import config_validation as cv
REQUIREMENTS = ['pyxeoma==1.3']
REQUIREMENTS = ['pyxeoma==1.4.0']
_LOGGER = logging.getLogger(__name__)
@@ -41,8 +40,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Discover and setup Xeoma Cameras."""
from pyxeoma.xeoma import Xeoma, XeomaError
@@ -53,8 +52,8 @@ def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
xeoma = Xeoma(host, login, password)
try:
yield from xeoma.async_test_connection()
discovered_image_names = yield from xeoma.async_get_image_names()
await xeoma.async_test_connection()
discovered_image_names = await xeoma.async_get_image_names()
discovered_cameras = [
{
CONF_IMAGE_NAME: image_name,
@@ -103,12 +102,11 @@ class XeomaCamera(Camera):
self._password = password
self._last_image = None
@asyncio.coroutine
def async_camera_image(self):
async def async_camera_image(self):
"""Return a still image response from the camera."""
from pyxeoma.xeoma import XeomaError
try:
image = yield from self._xeoma.async_get_camera_image(
image = await self._xeoma.async_get_camera_image(
self._image, self._username, self._password)
self._last_image = image
except XeomaError as err:

View File

@@ -14,10 +14,10 @@ from homeassistant.components.climate import (
ATTR_TARGET_TEMP_LOW, ATTR_TARGET_TEMP_HIGH, SUPPORT_TARGET_TEMPERATURE,
SUPPORT_AWAY_MODE, SUPPORT_HOLD_MODE, SUPPORT_OPERATION_MODE,
SUPPORT_TARGET_HUMIDITY_LOW, SUPPORT_TARGET_HUMIDITY_HIGH,
SUPPORT_AUX_HEAT, SUPPORT_TARGET_TEMPERATURE_HIGH,
SUPPORT_TARGET_TEMPERATURE_LOW)
SUPPORT_AUX_HEAT, SUPPORT_TARGET_TEMPERATURE_HIGH, SUPPORT_FAN_MODE,
SUPPORT_TARGET_TEMPERATURE_LOW, STATE_OFF)
from homeassistant.const import (
ATTR_ENTITY_ID, STATE_OFF, STATE_ON, ATTR_TEMPERATURE, TEMP_FAHRENHEIT)
ATTR_ENTITY_ID, STATE_ON, ATTR_TEMPERATURE, TEMP_FAHRENHEIT)
import homeassistant.helpers.config_validation as cv
_CONFIGURING = {}
@@ -50,7 +50,7 @@ SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE | SUPPORT_AWAY_MODE |
SUPPORT_HOLD_MODE | SUPPORT_OPERATION_MODE |
SUPPORT_TARGET_HUMIDITY_LOW | SUPPORT_TARGET_HUMIDITY_HIGH |
SUPPORT_AUX_HEAT | SUPPORT_TARGET_TEMPERATURE_HIGH |
SUPPORT_TARGET_TEMPERATURE_LOW)
SUPPORT_TARGET_TEMPERATURE_LOW | SUPPORT_FAN_MODE)
def setup_platform(hass, config, add_devices, discovery_info=None):
@@ -122,6 +122,7 @@ class Thermostat(ClimateDevice):
self._climate_list = self.climate_list
self._operation_list = ['auto', 'auxHeatOnly', 'cool',
'heat', 'off']
self._fan_list = ['auto', 'on']
self.update_without_throttle = False
def update(self):
@@ -180,24 +181,29 @@ class Thermostat(ClimateDevice):
return self.thermostat['runtime']['desiredCool'] / 10.0
return None
@property
def desired_fan_mode(self):
"""Return the desired fan mode of operation."""
return self.thermostat['runtime']['desiredFanMode']
@property
def fan(self):
"""Return the current fan state."""
"""Return the current fan status."""
if 'fan' in self.thermostat['equipmentStatus']:
return STATE_ON
return STATE_OFF
@property
def current_fan_mode(self):
"""Return the fan setting."""
return self.thermostat['runtime']['desiredFanMode']
@property
def current_hold_mode(self):
"""Return current hold mode."""
mode = self._current_hold_mode
return None if mode == AWAY_MODE else mode
@property
def fan_list(self):
"""Return the available fan modes."""
return self._fan_list
@property
def _current_hold_mode(self):
events = self.thermostat['events']
@@ -206,7 +212,7 @@ class Thermostat(ClimateDevice):
if event['type'] == 'hold':
if event['holdClimateRef'] == 'away':
if int(event['endDate'][0:4]) - \
int(event['startDate'][0:4]) <= 1:
int(event['startDate'][0:4]) <= 1:
# A temporary hold from away climate is a hold
return 'away'
# A permanent hold from away climate
@@ -228,7 +234,7 @@ class Thermostat(ClimateDevice):
def current_operation(self):
"""Return current operation."""
if self.operation_mode == 'auxHeatOnly' or \
self.operation_mode == 'heatPump':
self.operation_mode == 'heatPump':
return STATE_HEAT
return self.operation_mode
@@ -271,10 +277,11 @@ class Thermostat(ClimateDevice):
operation = STATE_HEAT
else:
operation = status
return {
"actual_humidity": self.thermostat['runtime']['actualHumidity'],
"fan": self.fan,
"mode": self.mode,
"climate_mode": self.mode,
"operation": operation,
"climate_list": self.climate_list,
"fan_min_on_time": self.fan_min_on_time
@@ -342,25 +349,46 @@ class Thermostat(ClimateDevice):
cool_temp_setpoint, heat_temp_setpoint,
self.hold_preference())
_LOGGER.debug("Setting ecobee hold_temp to: heat=%s, is=%s, "
"cool=%s, is=%s", heat_temp, isinstance(
heat_temp, (int, float)), cool_temp,
"cool=%s, is=%s", heat_temp,
isinstance(heat_temp, (int, float)), cool_temp,
isinstance(cool_temp, (int, float)))
self.update_without_throttle = True
def set_fan_mode(self, fan_mode):
"""Set the fan mode. Valid values are "on" or "auto"."""
if (fan_mode.lower() != STATE_ON) and (fan_mode.lower() != STATE_AUTO):
error = "Invalid fan_mode value: Valid values are 'on' or 'auto'"
_LOGGER.error(error)
return
cool_temp = self.thermostat['runtime']['desiredCool'] / 10.0
heat_temp = self.thermostat['runtime']['desiredHeat'] / 10.0
self.data.ecobee.set_fan_mode(self.thermostat_index, fan_mode,
cool_temp, heat_temp,
self.hold_preference())
_LOGGER.info("Setting fan mode to: %s", fan_mode)
def set_temp_hold(self, temp):
"""Set temperature hold in modes other than auto."""
# Set arbitrary range when not in auto mode
if self.current_operation == STATE_HEAT:
"""Set temperature hold in modes other than auto.
Ecobee API: It is good practice to set the heat and cool hold
temperatures to be the same, if the thermostat is in either heat, cool,
auxHeatOnly, or off mode. If the thermostat is in auto mode, an
additional rule is required. The cool hold temperature must be greater
than the heat hold temperature by at least the amount in the
heatCoolMinDelta property.
https://www.ecobee.com/home/developer/api/examples/ex5.shtml
"""
if self.current_operation == STATE_HEAT or self.current_operation == \
STATE_COOL:
heat_temp = temp
cool_temp = temp + 20
elif self.current_operation == STATE_COOL:
heat_temp = temp - 20
cool_temp = temp
else:
# In auto mode set temperature between
heat_temp = temp - 10
cool_temp = temp + 10
delta = self.thermostat['settings']['heatCoolMinDelta'] / 10
heat_temp = temp - delta
cool_temp = temp + delta
self.set_auto_temp_hold(heat_temp, cool_temp)
def set_temperature(self, **kwargs):
@@ -369,8 +397,8 @@ class Thermostat(ClimateDevice):
high_temp = kwargs.get(ATTR_TARGET_TEMP_HIGH)
temp = kwargs.get(ATTR_TEMPERATURE)
if self.current_operation == STATE_AUTO and (low_temp is not None or
high_temp is not None):
if self.current_operation == STATE_AUTO and \
(low_temp is not None or high_temp is not None):
self.set_auto_temp_hold(low_temp, high_temp)
elif temp is not None:
self.set_temp_hold(temp)

View File

@@ -248,6 +248,11 @@ class SensiboClimate(ClimateDevice):
return self._temperatures_list[-1] \
if self._temperatures_list else super().max_temp
@property
def unique_id(self):
"""Return unique ID based on Sensibo ID."""
return self._id
@asyncio.coroutine
def async_set_temperature(self, **kwargs):
"""Set new target temperature."""

View File

@@ -37,6 +37,7 @@ CONF_FILTER = 'filter'
CONF_GOOGLE_ACTIONS = 'google_actions'
CONF_RELAYER = 'relayer'
CONF_USER_POOL_ID = 'user_pool_id'
CONF_GOOGLE_ACTIONS_SYNC_URL = 'google_actions_sync_url'
DEFAULT_MODE = 'production'
DEPENDENCIES = ['http']
@@ -75,6 +76,7 @@ CONFIG_SCHEMA = vol.Schema({
vol.Optional(CONF_USER_POOL_ID): str,
vol.Optional(CONF_REGION): str,
vol.Optional(CONF_RELAYER): str,
vol.Optional(CONF_GOOGLE_ACTIONS_SYNC_URL): str,
vol.Optional(CONF_ALEXA): ALEXA_SCHEMA,
vol.Optional(CONF_GOOGLE_ACTIONS): GACTIONS_SCHEMA,
}),
@@ -110,7 +112,7 @@ class Cloud:
def __init__(self, hass, mode, alexa, google_actions,
cognito_client_id=None, user_pool_id=None, region=None,
relayer=None):
relayer=None, google_actions_sync_url=None):
"""Create an instance of Cloud."""
self.hass = hass
self.mode = mode
@@ -128,6 +130,7 @@ class Cloud:
self.user_pool_id = user_pool_id
self.region = region
self.relayer = relayer
self.google_actions_sync_url = google_actions_sync_url
else:
info = SERVERS[mode]
@@ -136,6 +139,7 @@ class Cloud:
self.user_pool_id = info['user_pool_id']
self.region = info['region']
self.relayer = info['relayer']
self.google_actions_sync_url = info['google_actions_sync_url']
@property
def is_logged_in(self):

View File

@@ -8,7 +8,9 @@ SERVERS = {
'cognito_client_id': '60i2uvhvbiref2mftj7rgcrt9u',
'user_pool_id': 'us-east-1_87ll5WOP8',
'region': 'us-east-1',
'relayer': 'wss://cloud.hass.io:8000/websocket'
'relayer': 'wss://cloud.hass.io:8000/websocket',
'google_actions_sync_url': ('https://24ab3v80xd.execute-api.us-east-1.'
'amazonaws.com/prod/smart_home_sync'),
}
}

View File

@@ -16,9 +16,9 @@ from .const import DOMAIN, REQUEST_TIMEOUT
_LOGGER = logging.getLogger(__name__)
@asyncio.coroutine
def async_setup(hass):
async def async_setup(hass):
"""Initialize the HTTP API."""
hass.http.register_view(GoogleActionsSyncView)
hass.http.register_view(CloudLoginView)
hass.http.register_view(CloudLogoutView)
hass.http.register_view(CloudAccountView)
@@ -38,12 +38,11 @@ _CLOUD_ERRORS = {
def _handle_cloud_errors(handler):
"""Handle auth errors."""
@asyncio.coroutine
@wraps(handler)
def error_handler(view, request, *args, **kwargs):
async def error_handler(view, request, *args, **kwargs):
"""Handle exceptions that raise from the wrapped request handler."""
try:
result = yield from handler(view, request, *args, **kwargs)
result = await handler(view, request, *args, **kwargs)
return result
except (auth_api.CloudError, asyncio.TimeoutError) as err:
@@ -57,6 +56,31 @@ def _handle_cloud_errors(handler):
return error_handler
class GoogleActionsSyncView(HomeAssistantView):
"""Trigger a Google Actions Smart Home Sync."""
url = '/api/cloud/google_actions/sync'
name = 'api:cloud:google_actions/sync'
@_handle_cloud_errors
async def post(self, request):
"""Trigger a Google Actions sync."""
hass = request.app['hass']
cloud = hass.data[DOMAIN]
websession = hass.helpers.aiohttp_client.async_get_clientsession()
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop):
await hass.async_add_job(auth_api.check_token, cloud)
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop):
req = await websession.post(
cloud.google_actions_sync_url, headers={
'authorization': cloud.id_token
})
return self.json({}, status_code=req.status)
class CloudLoginView(HomeAssistantView):
"""Login to Home Assistant cloud."""
@@ -68,19 +92,18 @@ class CloudLoginView(HomeAssistantView):
vol.Required('email'): str,
vol.Required('password'): str,
}))
@asyncio.coroutine
def post(self, request, data):
async def post(self, request, data):
"""Handle login request."""
hass = request.app['hass']
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop):
yield from hass.async_add_job(auth_api.login, cloud, data['email'],
data['password'])
await hass.async_add_job(auth_api.login, cloud, data['email'],
data['password'])
hass.async_add_job(cloud.iot.connect)
# Allow cloud to start connecting.
yield from asyncio.sleep(0, loop=hass.loop)
await asyncio.sleep(0, loop=hass.loop)
return self.json(_account_data(cloud))
@@ -91,14 +114,13 @@ class CloudLogoutView(HomeAssistantView):
name = 'api:cloud:logout'
@_handle_cloud_errors
@asyncio.coroutine
def post(self, request):
async def post(self, request):
"""Handle logout request."""
hass = request.app['hass']
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop):
yield from cloud.logout()
await cloud.logout()
return self.json_message('ok')
@@ -109,8 +131,7 @@ class CloudAccountView(HomeAssistantView):
url = '/api/cloud/account'
name = 'api:cloud:account'
@asyncio.coroutine
def get(self, request):
async def get(self, request):
"""Get account info."""
hass = request.app['hass']
cloud = hass.data[DOMAIN]
@@ -132,14 +153,13 @@ class CloudRegisterView(HomeAssistantView):
vol.Required('email'): str,
vol.Required('password'): vol.All(str, vol.Length(min=6)),
}))
@asyncio.coroutine
def post(self, request, data):
async def post(self, request, data):
"""Handle registration request."""
hass = request.app['hass']
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop):
yield from hass.async_add_job(
await hass.async_add_job(
auth_api.register, cloud, data['email'], data['password'])
return self.json_message('ok')
@@ -155,14 +175,13 @@ class CloudResendConfirmView(HomeAssistantView):
@RequestDataValidator(vol.Schema({
vol.Required('email'): str,
}))
@asyncio.coroutine
def post(self, request, data):
async def post(self, request, data):
"""Handle resending confirm email code request."""
hass = request.app['hass']
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop):
yield from hass.async_add_job(
await hass.async_add_job(
auth_api.resend_email_confirm, cloud, data['email'])
return self.json_message('ok')
@@ -178,14 +197,13 @@ class CloudForgotPasswordView(HomeAssistantView):
@RequestDataValidator(vol.Schema({
vol.Required('email'): str,
}))
@asyncio.coroutine
def post(self, request, data):
async def post(self, request, data):
"""Handle forgot password request."""
hass = request.app['hass']
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop):
yield from hass.async_add_job(
await hass.async_add_job(
auth_api.forgot_password, cloud, data['email'])
return self.json_message('ok')

View File

@@ -0,0 +1,24 @@
{
"config": {
"error": {
"invalid_object_id": "Ung\u00fcltige Objekt-ID"
},
"step": {
"init": {
"data": {
"object_id": "Objekt-ID"
},
"description": "Bitte gib eine Objekt_ID f\u00fcr das Test-Entity ein.",
"title": "W\u00e4hle eine Objekt-ID"
},
"name": {
"data": {
"name": "Name"
},
"description": "Bitte gib einen Namen f\u00fcr das Test-Entity ein",
"title": "Name des Test-Entity"
}
},
"title": "Beispiel Konfig-Eintrag"
}
}

View File

@@ -0,0 +1,24 @@
{
"config": {
"error": {
"invalid_object_id": "Invalid object ID"
},
"step": {
"init": {
"data": {
"object_id": "Object ID"
},
"description": "Please enter an object_id for the test entity.",
"title": "Pick object id"
},
"name": {
"data": {
"name": "Name"
},
"description": "Please enter a name for the test entity.",
"title": "Name of the entity"
}
},
"title": "Config Entry Example"
}
}

View File

@@ -0,0 +1,11 @@
{
"config": {
"step": {
"name": {
"data": {
"name": "Nimi"
}
}
}
}
}

View File

@@ -0,0 +1,24 @@
{
"config": {
"error": {
"invalid_object_id": "\uc624\ube0c\uc81d\ud2b8 ID\uac00 \uc798\ubabb\ub418\uc5c8\uc2b5\ub2c8\ub2e4"
},
"step": {
"init": {
"data": {
"object_id": "\uc624\ube0c\uc81d\ud2b8 ID"
},
"description": "\ud14c\uc2a4\ud2b8 \uad6c\uc131\uc694\uc18c\uc758 \uc624\ube0c\uc81d\ud2b8 ID \ub97c \uc785\ub825\ud558\uc138\uc694",
"title": "\uc624\ube0c\uc81d\ud2b8 ID \uc120\ud0dd"
},
"name": {
"data": {
"name": "\uc774\ub984"
},
"description": "\ud14c\uc2a4\ud2b8 \uad6c\uc131\uc694\uc18c\uc758 \uc774\ub984\uc744 \uc785\ub825\ud558\uc138\uc694.",
"title": "\uad6c\uc131\uc694\uc18c \uc774\ub984"
}
},
"title": "\uc785\ub825 \uc608\uc81c \uad6c\uc131"
}
}

View File

@@ -0,0 +1,24 @@
{
"config": {
"error": {
"invalid_object_id": "Ongeldig object ID"
},
"step": {
"init": {
"data": {
"object_id": "Object ID"
},
"description": "Voer een object_id in voor het testen van de entiteit.",
"title": "Kies object id"
},
"name": {
"data": {
"name": "Naam"
},
"description": "Voer een naam in voor het testen van de entiteit.",
"title": "Naam van de entiteit"
}
},
"title": "Voorbeeld van de config vermelding"
}
}

View File

@@ -0,0 +1,24 @@
{
"config": {
"error": {
"invalid_object_id": "Ugyldig objekt ID"
},
"step": {
"init": {
"data": {
"object_id": "Objekt ID"
},
"description": "Vennligst skriv inn en object_id for testenheten.",
"title": "Velg objekt ID"
},
"name": {
"data": {
"name": "Navn"
},
"description": "Vennligst skriv inn et navn for testenheten.",
"title": "Navn p\u00e5 enheten"
}
},
"title": "Konfigureringseksempel"
}
}

View File

@@ -0,0 +1,24 @@
{
"config": {
"error": {
"invalid_object_id": "Nieprawid\u0142owy identyfikator obiektu"
},
"step": {
"init": {
"data": {
"object_id": "Identyfikator obiektu"
},
"description": "Prosz\u0119 wprowadzi\u0107 identyfikator obiektu (object_id) dla jednostki testowej.",
"title": "Wybierz identyfikator obiektu"
},
"name": {
"data": {
"name": "Nazwa"
},
"description": "Prosz\u0119 wprowadzi\u0107 nazw\u0119 dla jednostki testowej.",
"title": "Nazwa jednostki"
}
},
"title": "Przyk\u0142ad wpisu do konfiguracji"
}
}

View File

@@ -0,0 +1,15 @@
{
"config": {
"step": {
"init": {
"description": "Introduce\u021bi un obiect_id pentru entitatea testat\u0103.",
"title": "Alege\u021bi id-ul obiectului"
},
"name": {
"data": {
"name": "Nume"
}
}
}
}
}

View File

@@ -0,0 +1,24 @@
{
"config": {
"error": {
"invalid_object_id": "Neveljaven ID objekta"
},
"step": {
"init": {
"data": {
"object_id": "ID objekta"
},
"description": "Prosimo, vnesite Id_objekta za testni subjekt.",
"title": "Izberite ID objekta"
},
"name": {
"data": {
"name": "Ime"
},
"description": "Vnesite ime za testni subjekt.",
"title": "Ime subjekta"
}
},
"title": "Primer nastavitve"
}
}

View File

@@ -0,0 +1,24 @@
{
"config": {
"error": {
"invalid_object_id": "ID \u0111\u1ed1i t\u01b0\u1ee3ng kh\u00f4ng h\u1ee3p l\u1ec7"
},
"step": {
"init": {
"data": {
"object_id": "ID \u0111\u1ed1i t\u01b0\u1ee3ng"
},
"description": "Xin vui l\u00f2ng nh\u1eadp m\u1ed9t object_id cho th\u1eed nghi\u1ec7m th\u1ef1c th\u1ec3.",
"title": "Ch\u1ecdn id \u0111\u1ed1i t\u01b0\u1ee3ng"
},
"name": {
"data": {
"name": "T\u00ean"
},
"description": "Xin vui l\u00f2ng nh\u1eadp t\u00ean cho th\u1eed nghi\u1ec7m th\u1ef1c th\u1ec3.",
"title": "T\u00ean c\u1ee7a th\u1ef1c th\u1ec3"
}
},
"title": "V\u00ed d\u1ee5 v\u1ec1 c\u1ea5u h\u00ecnh th\u1ef1c th\u1ec3"
}
}

View File

@@ -0,0 +1,24 @@
{
"config": {
"error": {
"invalid_object_id": "\u65e0\u6548\u7684\u5bf9\u8c61 ID"
},
"step": {
"init": {
"data": {
"object_id": "\u5bf9\u8c61 ID"
},
"description": "\u8bf7\u4e3a\u6d4b\u8bd5\u8bbe\u5907\u8f93\u5165\u5bf9\u8c61 ID",
"title": "\u8bf7\u9009\u62e9\u5bf9\u8c61 ID"
},
"name": {
"data": {
"name": "\u540d\u79f0"
},
"description": "\u8bf7\u4e3a\u6d4b\u8bd5\u8bbe\u5907\u8f93\u5165\u540d\u79f0",
"title": "\u8bbe\u5907\u540d\u79f0"
}
},
"title": "\u6837\u4f8b\u914d\u7f6e\u6761\u76ee"
}
}

View File

@@ -62,13 +62,11 @@ class ExampleConfigFlow(config_entries.ConfigFlowHandler):
return (yield from self.async_step_name())
errors = {
'object_id': 'Invalid object id.'
'object_id': 'invalid_object_id'
}
return self.async_show_form(
title='Pick object id',
step_id='init',
description="Please enter an object_id for the test entity.",
data_schema=vol.Schema({
'object_id': str
}),
@@ -92,9 +90,7 @@ class ExampleConfigFlow(config_entries.ConfigFlowHandler):
)
return self.async_show_form(
title='Name of the entity',
step_id='name',
description="Please enter a name for the test entity.",
data_schema=vol.Schema({
'name': str
}),

View File

@@ -0,0 +1,24 @@
{
"config": {
"title": "Config Entry Example",
"step": {
"init": {
"title": "Pick object id",
"description": "Please enter an object_id for the test entity.",
"data": {
"object_id": "Object ID"
}
},
"name": {
"title": "Name of the entity",
"description": "Please enter a name for the test entity.",
"data": {
"name": "Name"
}
}
},
"error": {
"invalid_object_id": "Invalid object ID"
}
}
}

View File

@@ -15,7 +15,7 @@ from homeassistant.const import EVENT_TIME_CHANGED, ATTR_FRIENDLY_NAME, \
ATTR_ENTITY_PICTURE
from homeassistant.loader import bind_hass
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.util.async import run_callback_threadsafe
from homeassistant.util.async_ import run_callback_threadsafe
_LOGGER = logging.getLogger(__name__)
_KEY_INSTANCE = 'configurator'

View File

@@ -0,0 +1,271 @@
"""
This platform allows several cover to be grouped into one cover.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/cover.group/
"""
import logging
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.components.cover import (
DOMAIN, PLATFORM_SCHEMA, CoverDevice, ATTR_POSITION,
ATTR_CURRENT_POSITION, ATTR_TILT_POSITION, ATTR_CURRENT_TILT_POSITION,
SUPPORT_OPEN, SUPPORT_CLOSE, SUPPORT_STOP, SUPPORT_SET_POSITION,
SUPPORT_OPEN_TILT, SUPPORT_CLOSE_TILT,
SUPPORT_STOP_TILT, SUPPORT_SET_TILT_POSITION,
SERVICE_OPEN_COVER, SERVICE_CLOSE_COVER, SERVICE_SET_COVER_POSITION,
SERVICE_STOP_COVER, SERVICE_OPEN_COVER_TILT, SERVICE_CLOSE_COVER_TILT,
SERVICE_STOP_COVER_TILT, SERVICE_SET_COVER_TILT_POSITION)
from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES,
CONF_ENTITIES, CONF_NAME, STATE_CLOSED)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_state_change
_LOGGER = logging.getLogger(__name__)
KEY_OPEN_CLOSE = 'open_close'
KEY_STOP = 'stop'
KEY_POSITION = 'position'
DEFAULT_NAME = 'Cover Group'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Required(CONF_ENTITIES): cv.entities_domain(DOMAIN),
})
async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Set up the Group Cover platform."""
async_add_devices(
[CoverGroup(config[CONF_NAME], config[CONF_ENTITIES])])
class CoverGroup(CoverDevice):
"""Representation of a CoverGroup."""
def __init__(self, name, entities):
"""Initialize a CoverGroup entity."""
self._name = name
self._is_closed = False
self._cover_position = 100
self._tilt_position = None
self._supported_features = 0
self._assumed_state = True
self._entities = entities
self._covers = {KEY_OPEN_CLOSE: set(), KEY_STOP: set(),
KEY_POSITION: set()}
self._tilts = {KEY_OPEN_CLOSE: set(), KEY_STOP: set(),
KEY_POSITION: set()}
@callback
def update_supported_features(self, entity_id, old_state, new_state,
update_state=True):
"""Update dictionaries with supported features."""
if not new_state:
for values in self._covers.values():
values.discard(entity_id)
for values in self._tilts.values():
values.discard(entity_id)
if update_state:
self.async_schedule_update_ha_state(True)
return
features = new_state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
if features & (SUPPORT_OPEN | SUPPORT_CLOSE):
self._covers[KEY_OPEN_CLOSE].add(entity_id)
else:
self._covers[KEY_OPEN_CLOSE].discard(entity_id)
if features & (SUPPORT_STOP):
self._covers[KEY_STOP].add(entity_id)
else:
self._covers[KEY_STOP].discard(entity_id)
if features & (SUPPORT_SET_POSITION):
self._covers[KEY_POSITION].add(entity_id)
else:
self._covers[KEY_POSITION].discard(entity_id)
if features & (SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT):
self._tilts[KEY_OPEN_CLOSE].add(entity_id)
else:
self._tilts[KEY_OPEN_CLOSE].discard(entity_id)
if features & (SUPPORT_STOP_TILT):
self._tilts[KEY_STOP].add(entity_id)
else:
self._tilts[KEY_STOP].discard(entity_id)
if features & (SUPPORT_SET_TILT_POSITION):
self._tilts[KEY_POSITION].add(entity_id)
else:
self._tilts[KEY_POSITION].discard(entity_id)
if update_state:
self.async_schedule_update_ha_state(True)
async def async_added_to_hass(self):
"""Register listeners."""
for entity_id in self._entities:
new_state = self.hass.states.get(entity_id)
self.update_supported_features(entity_id, None, new_state,
update_state=False)
async_track_state_change(self.hass, self._entities,
self.update_supported_features)
await self.async_update()
@property
def name(self):
"""Return the name of the cover."""
return self._name
@property
def assumed_state(self):
"""Enable buttons even if at end position."""
return self._assumed_state
@property
def should_poll(self):
"""Disable polling for cover group."""
return False
@property
def supported_features(self):
"""Flag supported features for the cover."""
return self._supported_features
@property
def is_closed(self):
"""Return if all covers in group are closed."""
return self._is_closed
@property
def current_cover_position(self):
"""Return current position for all covers."""
return self._cover_position
@property
def current_cover_tilt_position(self):
"""Return current tilt position for all covers."""
return self._tilt_position
async def async_open_cover(self, **kwargs):
"""Move the covers up."""
data = {ATTR_ENTITY_ID: self._covers[KEY_OPEN_CLOSE]}
await self.hass.services.async_call(
DOMAIN, SERVICE_OPEN_COVER, data, blocking=True)
async def async_close_cover(self, **kwargs):
"""Move the covers down."""
data = {ATTR_ENTITY_ID: self._covers[KEY_OPEN_CLOSE]}
await self.hass.services.async_call(
DOMAIN, SERVICE_CLOSE_COVER, data, blocking=True)
async def async_stop_cover(self, **kwargs):
"""Fire the stop action."""
data = {ATTR_ENTITY_ID: self._covers[KEY_STOP]}
await self.hass.services.async_call(
DOMAIN, SERVICE_STOP_COVER, data, blocking=True)
async def async_set_cover_position(self, **kwargs):
"""Set covers position."""
data = {ATTR_ENTITY_ID: self._covers[KEY_POSITION],
ATTR_POSITION: kwargs[ATTR_POSITION]}
await self.hass.services.async_call(
DOMAIN, SERVICE_SET_COVER_POSITION, data, blocking=True)
async def async_open_cover_tilt(self, **kwargs):
"""Tilt covers open."""
data = {ATTR_ENTITY_ID: self._tilts[KEY_OPEN_CLOSE]}
await self.hass.services.async_call(
DOMAIN, SERVICE_OPEN_COVER_TILT, data, blocking=True)
async def async_close_cover_tilt(self, **kwargs):
"""Tilt covers closed."""
data = {ATTR_ENTITY_ID: self._tilts[KEY_OPEN_CLOSE]}
await self.hass.services.async_call(
DOMAIN, SERVICE_CLOSE_COVER_TILT, data, blocking=True)
async def async_stop_cover_tilt(self, **kwargs):
"""Stop cover tilt."""
data = {ATTR_ENTITY_ID: self._tilts[KEY_STOP]}
await self.hass.services.async_call(
DOMAIN, SERVICE_STOP_COVER_TILT, data, blocking=True)
async def async_set_cover_tilt_position(self, **kwargs):
"""Set tilt position."""
data = {ATTR_ENTITY_ID: self._tilts[KEY_POSITION],
ATTR_TILT_POSITION: kwargs[ATTR_TILT_POSITION]}
await self.hass.services.async_call(
DOMAIN, SERVICE_SET_COVER_TILT_POSITION, data, blocking=True)
async def async_update(self):
"""Update state and attributes."""
self._assumed_state = False
self._is_closed = True
for entity_id in self._entities:
state = self.hass.states.get(entity_id)
if not state:
continue
if state.state != STATE_CLOSED:
self._is_closed = False
break
self._cover_position = None
if self._covers[KEY_POSITION]:
position = -1
self._cover_position = 0 if self.is_closed else 100
for entity_id in self._covers[KEY_POSITION]:
state = self.hass.states.get(entity_id)
pos = state.attributes.get(ATTR_CURRENT_POSITION)
if position == -1:
position = pos
elif position != pos:
self._assumed_state = True
break
else:
if position != -1:
self._cover_position = position
self._tilt_position = None
if self._tilts[KEY_POSITION]:
position = -1
self._tilt_position = 100
for entity_id in self._tilts[KEY_POSITION]:
state = self.hass.states.get(entity_id)
pos = state.attributes.get(ATTR_CURRENT_TILT_POSITION)
if position == -1:
position = pos
elif position != pos:
self._assumed_state = True
break
else:
if position != -1:
self._tilt_position = position
supported_features = 0
supported_features |= SUPPORT_OPEN | SUPPORT_CLOSE \
if self._covers[KEY_OPEN_CLOSE] else 0
supported_features |= SUPPORT_STOP \
if self._covers[KEY_STOP] else 0
supported_features |= SUPPORT_SET_POSITION \
if self._covers[KEY_POSITION] else 0
supported_features |= SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT \
if self._tilts[KEY_OPEN_CLOSE] else 0
supported_features |= SUPPORT_STOP_TILT \
if self._tilts[KEY_STOP] else 0
supported_features |= SUPPORT_SET_TILT_POSITION \
if self._tilts[KEY_POSITION] else 0
self._supported_features = supported_features
if not self._assumed_state:
for entity_id in self._entities:
state = self.hass.states.get(entity_id)
if state and state.attributes.get(ATTR_ASSUMED_STATE):
self._assumed_state = True
break

View File

@@ -234,7 +234,9 @@ class CoverTemplate(CoverDevice):
None is unknown, 0 is closed, 100 is fully open.
"""
return self._position
if self._position_template or self._position_script:
return self._position
return None
@property
def current_cover_tilt_position(self):

View File

@@ -4,8 +4,6 @@ Support for deCONZ devices.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/deconz/
"""
import asyncio
import logging
import voluptuous as vol
@@ -19,7 +17,7 @@ from homeassistant.helpers import discovery
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.util.json import load_json, save_json
REQUIREMENTS = ['pydeconz==30']
REQUIREMENTS = ['pydeconz==32']
_LOGGER = logging.getLogger(__name__)
@@ -57,30 +55,28 @@ Unlock your deCONZ gateway to register with Home Assistant.
"""
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up services and configuration for deCONZ component."""
result = False
config_file = yield from hass.async_add_job(
config_file = await hass.async_add_job(
load_json, hass.config.path(CONFIG_FILE))
@asyncio.coroutine
def async_deconz_discovered(service, discovery_info):
async def async_deconz_discovered(service, discovery_info):
"""Call when deCONZ gateway has been found."""
deconz_config = {}
deconz_config[CONF_HOST] = discovery_info.get(CONF_HOST)
deconz_config[CONF_PORT] = discovery_info.get(CONF_PORT)
yield from async_request_configuration(hass, config, deconz_config)
await async_request_configuration(hass, config, deconz_config)
if config_file:
result = yield from async_setup_deconz(hass, config, config_file)
result = await async_setup_deconz(hass, config, config_file)
if not result and DOMAIN in config and CONF_HOST in config[DOMAIN]:
deconz_config = config[DOMAIN]
if CONF_API_KEY in deconz_config:
result = yield from async_setup_deconz(hass, config, deconz_config)
result = await async_setup_deconz(hass, config, deconz_config)
else:
yield from async_request_configuration(hass, config, deconz_config)
await async_request_configuration(hass, config, deconz_config)
return True
if not result:
@@ -89,8 +85,7 @@ def async_setup(hass, config):
return True
@asyncio.coroutine
def async_setup_deconz(hass, config, deconz_config):
async def async_setup_deconz(hass, config, deconz_config):
"""Set up a deCONZ session.
Load config, group, light and sensor data for server information.
@@ -100,7 +95,7 @@ def async_setup_deconz(hass, config, deconz_config):
from pydeconz import DeconzSession
websession = async_get_clientsession(hass)
deconz = DeconzSession(hass.loop, websession, **deconz_config)
result = yield from deconz.async_load_parameters()
result = await deconz.async_load_parameters()
if result is False:
_LOGGER.error("Failed to communicate with deCONZ")
return False
@@ -113,8 +108,7 @@ def async_setup_deconz(hass, config, deconz_config):
hass, component, DOMAIN, {}, config))
deconz.start()
@asyncio.coroutine
def async_configure(call):
async def async_configure(call):
"""Set attribute of device in deCONZ.
Field is a string representing a specific device in deCONZ
@@ -140,7 +134,7 @@ def async_setup_deconz(hass, config, deconz_config):
if field is None:
_LOGGER.error('Could not find the entity %s', entity_id)
return
yield from deconz.async_put_state(field, data)
await deconz.async_put_state(field, data)
hass.services.async_register(
DOMAIN, 'configure', async_configure, schema=SERVICE_SCHEMA)
@@ -159,21 +153,19 @@ def async_setup_deconz(hass, config, deconz_config):
return True
@asyncio.coroutine
def async_request_configuration(hass, config, deconz_config):
async def async_request_configuration(hass, config, deconz_config):
"""Request configuration steps from the user."""
configurator = hass.components.configurator
@asyncio.coroutine
def async_configuration_callback(data):
async def async_configuration_callback(data):
"""Set up actions to do when our configuration callback is called."""
from pydeconz.utils import async_get_api_key
api_key = yield from async_get_api_key(hass.loop, **deconz_config)
api_key = await async_get_api_key(hass.loop, **deconz_config)
if api_key:
deconz_config[CONF_API_KEY] = api_key
result = yield from async_setup_deconz(hass, config, deconz_config)
result = await async_setup_deconz(hass, config, deconz_config)
if result:
yield from hass.async_add_job(
await hass.async_add_job(
save_json, hass.config.path(CONFIG_FILE), deconz_config)
configurator.async_request_done(request_id)
return

View File

@@ -28,7 +28,7 @@ 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
from homeassistant.util.async_ import run_coroutine_threadsafe
import homeassistant.util.dt as dt_util
from homeassistant.util.yaml import dump

View File

@@ -73,7 +73,8 @@ class MikrotikScanner(DeviceScanner):
self.host,
self.username,
self.password,
port=int(self.port)
port=int(self.port),
encoding='utf-8'
)
try:

View File

@@ -98,7 +98,8 @@ class UnifiScanner(DeviceScanner):
# Filter clients to provided SSID list
if self._ssid_filter:
clients = [client for client in clients
if client['essid'] in self._ssid_filter]
if 'essid' in client and
client['essid'] in self._ssid_filter]
self._clients = {
client['mac']: client

View File

@@ -6,7 +6,6 @@ Will emit EVENT_PLATFORM_DISCOVERED whenever a new service has been discovered.
Knows which components handle certain types, will make sure they are
loaded before the EVENT_PLATFORM_DISCOVERED is fired.
"""
import asyncio
import json
from datetime import timedelta
import logging
@@ -21,7 +20,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.2.4']
REQUIREMENTS = ['netdisco==1.3.0']
DOMAIN = 'discovery'
@@ -39,6 +38,7 @@ SERVICE_TELLDUSLIVE = 'tellstick'
SERVICE_HUE = 'philips_hue'
SERVICE_DECONZ = 'deconz'
SERVICE_DAIKIN = 'daikin'
SERVICE_SAMSUNG_PRINTER = 'samsung_printer'
SERVICE_HANDLERS = {
SERVICE_HASS_IOS_APP: ('ios', None),
@@ -54,6 +54,7 @@ SERVICE_HANDLERS = {
SERVICE_HUE: ('hue', None),
SERVICE_DECONZ: ('deconz', None),
SERVICE_DAIKIN: ('daikin', None),
SERVICE_SAMSUNG_PRINTER: ('sensor', 'syncthru'),
'google_cast': ('media_player', 'cast'),
'panasonic_viera': ('media_player', 'panasonic_viera'),
'plex_mediaserver': ('media_player', 'plex'),
@@ -84,8 +85,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Start a discovery service."""
from netdisco.discovery import NetworkDiscovery
@@ -99,8 +99,7 @@ def async_setup(hass, config):
# Platforms ignore by config
ignored_platforms = config[DOMAIN][CONF_IGNORE]
@asyncio.coroutine
def new_service_found(service, info):
async def new_service_found(service, info):
"""Handle a new service if one is found."""
if service in ignored_platforms:
logger.info("Ignoring service: %s %s", service, info)
@@ -124,15 +123,14 @@ def async_setup(hass, config):
component, platform = comp_plat
if platform is None:
yield from async_discover(hass, service, info, component, config)
await async_discover(hass, service, info, component, config)
else:
yield from async_load_platform(
await async_load_platform(
hass, component, platform, info, config)
@asyncio.coroutine
def scan_devices(now):
async def scan_devices(now):
"""Scan for devices."""
results = yield from hass.async_add_job(_discover, netdisco)
results = await hass.async_add_job(_discover, netdisco)
for result in results:
hass.async_add_job(new_service_found(*result))

View File

@@ -13,7 +13,7 @@ from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD
from homeassistant.components.http import HomeAssistantView
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['DoorBirdPy==0.1.2']
REQUIREMENTS = ['DoorBirdPy==0.1.3']
_LOGGER = logging.getLogger(__name__)

View File

@@ -25,6 +25,8 @@ ATTR_OVERWRITE = 'overwrite'
CONF_DOWNLOAD_DIR = 'download_dir'
DOMAIN = 'downloader'
DOWNLOAD_FAILED_EVENT = 'download_failed'
DOWNLOAD_COMPLETED_EVENT = 'download_completed'
SERVICE_DOWNLOAD_FILE = 'download_file'
@@ -133,9 +135,19 @@ def setup(hass, config):
fil.write(chunk)
_LOGGER.debug("Downloading of %s done", url)
hass.bus.fire(
"{}_{}".format(DOMAIN, DOWNLOAD_COMPLETED_EVENT), {
'url': url,
'filename': filename
})
except requests.exceptions.ConnectionError:
_LOGGER.exception("ConnectionError occurred for %s", url)
hass.bus.fire(
"{}_{}".format(DOMAIN, DOWNLOAD_FAILED_EVENT), {
'url': url,
'filename': filename
})
# Remove file if we started downloading but failed
if final_path and os.path.isfile(final_path):

View File

@@ -16,7 +16,7 @@ from homeassistant.const import CONF_API_KEY
from homeassistant.util import Throttle
from homeassistant.util.json import save_json
REQUIREMENTS = ['python-ecobee-api==0.0.15']
REQUIREMENTS = ['python-ecobee-api==0.0.17']
_CONFIGURING = {}
_LOGGER = logging.getLogger(__name__)

View File

@@ -15,7 +15,7 @@ from homeassistant.const import (
CONF_PORT, CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_NAME,
EVENT_HOMEASSISTANT_STOP)
REQUIREMENTS = ['pythonegardia==1.0.38']
REQUIREMENTS = ['pythonegardia==1.0.39']
_LOGGER = logging.getLogger(__name__)

View File

@@ -29,7 +29,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
REQUIREMENTS = ['python-miio==0.3.7']
REQUIREMENTS = ['python-miio==0.3.8']
ATTR_TEMPERATURE = 'temperature'
ATTR_HUMIDITY = 'humidity'

View File

@@ -0,0 +1,114 @@
"""
Fans on Zigbee Home Automation networks.
For more details on this platform, please refer to the documentation
at https://home-assistant.io/components/fan.zha/
"""
import asyncio
import logging
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']
_LOGGER = logging.getLogger(__name__)
# Additional speeds in zigbee's ZCL
# Spec is unclear as to what this value means. On King Of Fans HBUniversal
# receiver, this means Very High.
SPEED_ON = 'on'
# The fan speed is self-regulated
SPEED_AUTO = 'auto'
# When the heated/cooled space is occupied, the fan is always on
SPEED_SMART = 'smart'
SPEED_LIST = [
SPEED_OFF,
SPEED_LOW,
SPEED_MEDIUM,
SPEED_HIGH,
SPEED_ON,
SPEED_AUTO,
SPEED_SMART
]
VALUE_TO_SPEED = {i: speed for i, speed in enumerate(SPEED_LIST)}
SPEED_TO_VALUE = {speed: i for i, speed in enumerate(SPEED_LIST)}
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up the Zigbee Home Automation fans."""
discovery_info = zha.get_discovery_info(hass, discovery_info)
if discovery_info is None:
return
async_add_devices([ZhaFan(**discovery_info)], update_before_add=True)
class ZhaFan(zha.Entity, FanEntity):
"""Representation of a ZHA fan."""
_domain = DOMAIN
@property
def supported_features(self) -> int:
"""Flag supported features."""
return SUPPORT_SET_SPEED
@property
def speed_list(self) -> list:
"""Get the list of available speeds."""
return SPEED_LIST
@property
def speed(self) -> str:
"""Return the current speed."""
return self._state
@property
def is_on(self) -> bool:
"""Return true if entity is on."""
if self._state == STATE_UNKNOWN:
return False
return self._state != SPEED_OFF
@asyncio.coroutine
def async_turn_on(self, speed: str = None, **kwargs) -> None:
"""Turn the entity on."""
if speed is None:
speed = SPEED_MEDIUM
yield from self.async_set_speed(speed)
@asyncio.coroutine
def async_turn_off(self, **kwargs) -> None:
"""Turn the entity off."""
yield from self.async_set_speed(SPEED_OFF)
@asyncio.coroutine
def async_set_speed(self: FanEntity, speed: str) -> None:
"""Set the speed of the fan."""
yield from self._endpoint.fan.write_attributes({
'fan_mode': SPEED_TO_VALUE[speed]})
self._state = speed
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_update(self):
"""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)
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
False if entity pushes its state to HA.
"""
return False

View File

@@ -24,7 +24,7 @@ from homeassistant.core import callback
from homeassistant.helpers.translation import async_get_translations
from homeassistant.loader import bind_hass
REQUIREMENTS = ['home-assistant-frontend==20180310.0']
REQUIREMENTS = ['home-assistant-frontend==20180326.0']
DOMAIN = 'frontend'
DEPENDENCIES = ['api', 'websocket_api', 'http', 'system_log']

View File

@@ -243,7 +243,7 @@ class ColorSpectrumTrait(_Trait):
if domain != light.DOMAIN:
return False
return features & (light.SUPPORT_RGB_COLOR | light.SUPPORT_XY_COLOR)
return features & light.SUPPORT_COLOR
def sync_attributes(self):
"""Return color spectrum attributes for a sync request."""
@@ -254,13 +254,11 @@ class ColorSpectrumTrait(_Trait):
"""Return color spectrum query attributes."""
response = {}
# No need to handle XY color because light component will always
# convert XY to RGB if possible (which is when brightness is available)
color_rgb = self.state.attributes.get(light.ATTR_RGB_COLOR)
if color_rgb is not None:
color_hs = self.state.attributes.get(light.ATTR_HS_COLOR)
if color_hs is not None:
response['color'] = {
'spectrumRGB': int(color_util.color_rgb_to_hex(
color_rgb[0], color_rgb[1], color_rgb[2]), 16),
*color_util.color_hs_to_RGB(*color_hs)), 16),
}
return response
@@ -274,11 +272,12 @@ class ColorSpectrumTrait(_Trait):
"""Execute a color spectrum command."""
# Convert integer to hex format and left pad with 0's till length 6
hex_value = "{0:06x}".format(params['color']['spectrumRGB'])
color = color_util.rgb_hex_to_rgb_list(hex_value)
color = color_util.color_RGB_to_hs(
*color_util.rgb_hex_to_rgb_list(hex_value))
await hass.services.async_call(light.DOMAIN, SERVICE_TURN_ON, {
ATTR_ENTITY_ID: self.state.entity_id,
light.ATTR_RGB_COLOR: color
light.ATTR_HS_COLOR: color
}, blocking=True)

View File

@@ -21,7 +21,7 @@ from homeassistant.helpers.entity import Entity, async_generate_entity_id
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.event import async_track_state_change
import homeassistant.helpers.config_validation as cv
from homeassistant.util.async import run_coroutine_threadsafe
from homeassistant.util.async_ import run_coroutine_threadsafe
DOMAIN = 'group'

View File

@@ -156,7 +156,7 @@ def async_setup(hass, config):
if 'frontend' in hass.config.components:
yield from hass.components.frontend.async_register_built_in_panel(
'hassio', 'Hass.io', 'mdi:access-point-network')
'hassio', 'Hass.io', 'mdi:home-assistant')
if 'http' in config:
yield from hassio.update_hass_api(config['http'])

View File

@@ -239,15 +239,16 @@ def get_state(hass, utc_point_in_time, entity_id, run=None):
def async_setup(hass, config):
"""Set up the history hooks."""
filters = Filters()
exclude = config[DOMAIN].get(CONF_EXCLUDE)
conf = config.get(DOMAIN, {})
exclude = conf.get(CONF_EXCLUDE)
if exclude:
filters.excluded_entities = exclude.get(CONF_ENTITIES, [])
filters.excluded_domains = exclude.get(CONF_DOMAINS, [])
include = config[DOMAIN].get(CONF_INCLUDE)
include = conf.get(CONF_INCLUDE)
if include:
filters.included_entities = include.get(CONF_ENTITIES, [])
filters.included_domains = include.get(CONF_DOMAINS, [])
use_include_order = config[DOMAIN].get(CONF_ORDER)
use_include_order = conf.get(CONF_ORDER)
hass.http.register_view(HistoryPeriodView(filters, use_include_order))
yield from hass.components.frontend.async_register_built_in_panel(
@@ -308,7 +309,7 @@ class HistoryPeriodView(HomeAssistantView):
result = yield from hass.async_add_job(
get_significant_states, hass, start_time, end_time,
entity_ids, self.filters, include_start_time_state)
result = result.values()
result = list(result.values())
if _LOGGER.isEnabledFor(logging.DEBUG):
elapsed = time.perf_counter() - timer_start
_LOGGER.debug(
@@ -318,7 +319,6 @@ class HistoryPeriodView(HomeAssistantView):
# by any entities explicitly included in the configuration.
if self.use_include_order:
result = list(result)
sorted_result = []
for order_entity in self.filters.included_entities:
for state_list in result:

View File

@@ -3,154 +3,205 @@
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/homekit/
"""
import asyncio
import logging
import re
from zlib import adler32
import voluptuous as vol
from homeassistant.const import (
ATTR_SUPPORTED_FEATURES, ATTR_UNIT_OF_MEASUREMENT, CONF_PORT,
TEMP_CELSIUS, TEMP_FAHRENHEIT,
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP)
from homeassistant.components.climate import (
SUPPORT_TARGET_TEMPERATURE_HIGH, SUPPORT_TARGET_TEMPERATURE_LOW)
from homeassistant.components.cover import SUPPORT_SET_POSITION
from homeassistant.const import (
ATTR_CODE, ATTR_SUPPORTED_FEATURES, ATTR_UNIT_OF_MEASUREMENT,
CONF_PORT, TEMP_CELSIUS, TEMP_FAHRENHEIT,
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entityfilter import FILTER_SCHEMA
from homeassistant.util import get_local_ip
from homeassistant.util.decorator import Registry
from .const import (
DOMAIN, HOMEKIT_FILE, CONF_AUTO_START, CONF_ENTITY_CONFIG, CONF_FILTER,
DEFAULT_PORT, DEFAULT_AUTO_START, SERVICE_HOMEKIT_START)
from .util import (
validate_entity_config, show_setup_message)
TYPES = Registry()
_LOGGER = logging.getLogger(__name__)
_RE_VALID_PINCODE = r"^(\d{3}-\d{2}-\d{3})$"
DOMAIN = 'homekit'
REQUIREMENTS = ['HAP-python==1.1.7']
BRIDGE_NAME = 'Home Assistant'
CONF_PIN_CODE = 'pincode'
HOMEKIT_FILE = '.homekit.state'
def valid_pin(value):
"""Validate pin code value."""
match = re.match(_RE_VALID_PINCODE, str(value).strip())
if not match:
raise vol.Invalid("Pin must be in the format: '123-45-678'")
return match.group(0)
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.All({
vol.Optional(CONF_PORT, default=51826): vol.Coerce(int),
vol.Optional(CONF_PIN_CODE, default='123-45-678'): valid_pin,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_AUTO_START, default=DEFAULT_AUTO_START): cv.boolean,
vol.Optional(CONF_FILTER, default={}): FILTER_SCHEMA,
vol.Optional(CONF_ENTITY_CONFIG, default={}): validate_entity_config,
})
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Setup the HomeKit component."""
_LOGGER.debug("Begin setup HomeKit")
_LOGGER.debug('Begin setup HomeKit')
conf = config[DOMAIN]
port = conf.get(CONF_PORT)
pin = str.encode(conf.get(CONF_PIN_CODE))
port = conf[CONF_PORT]
auto_start = conf[CONF_AUTO_START]
entity_filter = conf[CONF_FILTER]
entity_config = conf[CONF_ENTITY_CONFIG]
homekit = HomeKit(hass, port)
homekit.setup_bridge(pin)
homekit = HomeKit(hass, port, entity_filter, entity_config)
homekit.setup()
if auto_start:
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, homekit.start)
return True
def handle_homekit_service_start(service):
"""Handle start HomeKit service call."""
if homekit.started:
_LOGGER.warning('HomeKit is already running')
return
homekit.start()
hass.services.async_register(DOMAIN, SERVICE_HOMEKIT_START,
handle_homekit_service_start)
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, homekit.start_driver)
return True
def import_types():
"""Import all types from files in the HomeKit directory."""
_LOGGER.debug("Import type files.")
# pylint: disable=unused-variable
from . import ( # noqa F401
covers, security_systems, sensors, switches, thermostats)
def get_accessory(hass, state):
def get_accessory(hass, state, aid, config):
"""Take state and return an accessory object if supported."""
if not aid:
_LOGGER.warning('The entitiy "%s" is not supported, since it '
'generates an invalid aid, please change it.',
state.entity_id)
return None
if state.domain == 'sensor':
unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
if unit == TEMP_CELSIUS or unit == TEMP_FAHRENHEIT:
_LOGGER.debug("Add \"%s\" as \"%s\"",
_LOGGER.debug('Add "%s" as "%s"',
state.entity_id, 'TemperatureSensor')
return TYPES['TemperatureSensor'](hass, state.entity_id,
state.name)
state.name, aid=aid)
elif unit == '%':
_LOGGER.debug('Add "%s" as %s"',
state.entity_id, 'HumiditySensor')
return TYPES['HumiditySensor'](hass, state.entity_id, state.name,
aid=aid)
elif state.domain == 'cover':
# Only add covers that support set_cover_position
if state.attributes.get(ATTR_SUPPORTED_FEATURES) & 4:
_LOGGER.debug("Add \"%s\" as \"%s\"",
state.entity_id, 'Window')
return TYPES['Window'](hass, state.entity_id, state.name)
features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
if features & SUPPORT_SET_POSITION:
_LOGGER.debug('Add "%s" as "%s"',
state.entity_id, 'WindowCovering')
return TYPES['WindowCovering'](hass, state.entity_id, state.name,
aid=aid)
elif state.domain == 'alarm_control_panel':
_LOGGER.debug("Add \"%s\" as \"%s\"", state.entity_id,
_LOGGER.debug('Add "%s" as "%s"', state.entity_id,
'SecuritySystem')
return TYPES['SecuritySystem'](hass, state.entity_id, state.name)
return TYPES['SecuritySystem'](hass, state.entity_id, state.name,
alarm_code=config.get(ATTR_CODE),
aid=aid)
elif state.domain == 'climate':
support_auto = False
features = state.attributes.get(ATTR_SUPPORTED_FEATURES)
features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
support_temp_range = SUPPORT_TARGET_TEMPERATURE_LOW | \
SUPPORT_TARGET_TEMPERATURE_HIGH
# Check if climate device supports auto mode
if (features & SUPPORT_TARGET_TEMPERATURE_HIGH) \
and (features & SUPPORT_TARGET_TEMPERATURE_LOW):
support_auto = True
_LOGGER.debug("Add \"%s\" as \"%s\"", state.entity_id, 'Thermostat')
support_auto = bool(features & support_temp_range)
_LOGGER.debug('Add "%s" as "%s"', state.entity_id, 'Thermostat')
return TYPES['Thermostat'](hass, state.entity_id,
state.name, support_auto)
state.name, support_auto, aid=aid)
elif state.domain == 'light':
return TYPES['Light'](hass, state.entity_id, state.name, aid=aid)
elif state.domain == 'switch' or state.domain == 'remote' \
or state.domain == 'input_boolean':
_LOGGER.debug("Add \"%s\" as \"%s\"", state.entity_id, 'Switch')
return TYPES['Switch'](hass, state.entity_id, state.name)
or state.domain == 'input_boolean' or state.domain == 'script':
_LOGGER.debug('Add "%s" as "%s"', state.entity_id, 'Switch')
return TYPES['Switch'](hass, state.entity_id, state.name, aid=aid)
return None
def generate_aid(entity_id):
"""Generate accessory aid with zlib adler32."""
aid = adler32(entity_id.encode('utf-8'))
if aid == 0 or aid == 1:
return None
return aid
class HomeKit():
"""Class to handle all actions between HomeKit and Home Assistant."""
def __init__(self, hass, port):
def __init__(self, hass, port, entity_filter, entity_config):
"""Initialize a HomeKit object."""
self._hass = hass
self._port = port
self._filter = entity_filter
self._config = entity_config
self.started = False
self.bridge = None
self.driver = None
def setup_bridge(self, pin):
"""Setup the bridge component to track all accessories."""
from .accessories import HomeBridge
self.bridge = HomeBridge(BRIDGE_NAME, 'homekit.bridge', pin)
def setup(self):
"""Setup bridge and accessory driver."""
from .accessories import HomeBridge, HomeDriver
def start_driver(self, event):
"""Start the accessory driver."""
from pyhap.accessory_driver import AccessoryDriver
self._hass.bus.listen_once(
EVENT_HOMEASSISTANT_STOP, self.stop_driver)
self._hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, self.stop)
import_types()
_LOGGER.debug("Start adding accessories.")
for state in self._hass.states.all():
acc = get_accessory(self._hass, state)
if acc is not None:
self.bridge.add_accessory(acc)
ip_address = get_local_ip()
path = self._hass.config.path(HOMEKIT_FILE)
self.driver = AccessoryDriver(self.bridge, self._port,
ip_address, path)
_LOGGER.debug("Driver started")
self.bridge = HomeBridge(self._hass)
self.driver = HomeDriver(self.bridge, self._port, get_local_ip(), path)
def add_bridge_accessory(self, state):
"""Try adding accessory to bridge if configured beforehand."""
if not state or not self._filter(state.entity_id):
return
aid = generate_aid(state.entity_id)
conf = self._config.pop(state.entity_id, {})
acc = get_accessory(self._hass, state, aid, conf)
if acc is not None:
self.bridge.add_accessory(acc)
def start(self, *args):
"""Start the accessory driver."""
if self.started:
return
self.started = True
# pylint: disable=unused-variable
from . import ( # noqa F401
type_covers, type_lights, type_security_systems, type_sensors,
type_switches, type_thermostats)
for state in self._hass.states.all():
self.add_bridge_accessory(state)
for entity_id in self._config:
_LOGGER.warning('The entity "%s" was not setup when HomeKit '
'was started', entity_id)
self.bridge.set_broker(self.driver)
if not self.bridge.paired:
show_setup_message(self.bridge, self._hass)
_LOGGER.debug('Driver start')
self.driver.start()
def stop_driver(self, event):
def stop(self, *args):
"""Stop the accessory driver."""
_LOGGER.debug("Driver stop")
if self.driver is not None:
if not self.started:
return
_LOGGER.debug('Driver stop')
if self.driver and self.driver.run_sentinel:
self.driver.stop()

View File

@@ -2,15 +2,33 @@
import logging
from pyhap.accessory import Accessory, Bridge, Category
from pyhap.accessory_driver import AccessoryDriver
from homeassistant.helpers.event import async_track_state_change
from .const import (
SERV_ACCESSORY_INFO, SERV_BRIDGING_STATE, MANUFACTURER,
CHAR_MODEL, CHAR_MANUFACTURER, CHAR_NAME, CHAR_SERIAL_NUMBER)
ACCESSORY_MODEL, ACCESSORY_NAME, BRIDGE_MODEL, BRIDGE_NAME,
MANUFACTURER, SERV_ACCESSORY_INFO, SERV_BRIDGING_STATE,
CHAR_MANUFACTURER, CHAR_MODEL, CHAR_NAME, CHAR_SERIAL_NUMBER)
from .util import (
show_setup_message, dismiss_setup_message)
_LOGGER = logging.getLogger(__name__)
def add_preload_service(acc, service, chars=None):
"""Define and return a service to be available for the accessory."""
from pyhap.loader import get_serv_loader, get_char_loader
service = get_serv_loader().get(service)
if chars:
chars = chars if isinstance(chars, list) else [chars]
for char_name in chars:
char = get_char_loader().get(char_name)
service.add_characteristic(char)
acc.add_service(service)
return service
def set_accessory_info(acc, name, model, manufacturer=MANUFACTURER,
serial_number='0000'):
"""Set the default accessory information."""
@@ -21,50 +39,70 @@ def set_accessory_info(acc, name, model, manufacturer=MANUFACTURER,
service.get_characteristic(CHAR_SERIAL_NUMBER).set_value(serial_number)
def add_preload_service(acc, service, chars=None, opt_chars=None):
"""Define and return a service to be available for the accessory."""
from pyhap.loader import get_serv_loader, get_char_loader
service = get_serv_loader().get(service)
if chars:
chars = chars if isinstance(chars, list) else [chars]
for char_name in chars:
char = get_char_loader().get(char_name)
service.add_characteristic(char)
if opt_chars:
opt_chars = opt_chars if isinstance(opt_chars, list) else [opt_chars]
for opt_char_name in opt_chars:
opt_char = get_char_loader().get(opt_char_name)
service.add_opt_characteristic(opt_char)
acc.add_service(service)
return service
def override_properties(char, properties=None, valid_values=None):
"""Override characteristic property values and valid values."""
if properties:
char.properties.update(properties)
def override_properties(char, new_properties):
"""Override characteristic property values."""
char.properties.update(new_properties)
if valid_values:
char.properties['ValidValues'].update(valid_values)
class HomeAccessory(Accessory):
"""Class to extend the Accessory class."""
"""Adapter class for Accessory."""
def __init__(self, display_name, model, category='OTHER', **kwargs):
# pylint: disable=no-member
def __init__(self, name=ACCESSORY_NAME, model=ACCESSORY_MODEL,
category='OTHER', **kwargs):
"""Initialize a Accessory object."""
super().__init__(display_name, **kwargs)
set_accessory_info(self, display_name, model)
super().__init__(name, **kwargs)
set_accessory_info(self, name, model)
self.category = getattr(Category, category, Category.OTHER)
def _set_services(self):
add_preload_service(self, SERV_ACCESSORY_INFO)
def run(self):
"""Method called by accessory after driver is started."""
state = self._hass.states.get(self._entity_id)
self.update_state(new_state=state)
async_track_state_change(
self._hass, self._entity_id, self.update_state)
class HomeBridge(Bridge):
"""Class to extend the Bridge class."""
"""Adapter class for Bridge."""
def __init__(self, display_name, model, pincode, **kwargs):
def __init__(self, hass, name=BRIDGE_NAME,
model=BRIDGE_MODEL, **kwargs):
"""Initialize a Bridge object."""
super().__init__(display_name, pincode=pincode, **kwargs)
set_accessory_info(self, display_name, model)
super().__init__(name, **kwargs)
set_accessory_info(self, name, model)
self._hass = hass
def _set_services(self):
add_preload_service(self, SERV_ACCESSORY_INFO)
add_preload_service(self, SERV_BRIDGING_STATE)
def setup_message(self):
"""Prevent print of pyhap setup message to terminal."""
pass
def add_paired_client(self, client_uuid, client_public):
"""Override super function to dismiss setup message if paired."""
super().add_paired_client(client_uuid, client_public)
dismiss_setup_message(self._hass)
def remove_paired_client(self, client_uuid):
"""Override super function to show setup message if unpaired."""
super().remove_paired_client(client_uuid)
show_setup_message(self, self._hass)
class HomeDriver(AccessoryDriver):
"""Adapter class for AccessoryDriver."""
def __init__(self, *args, **kwargs):
"""Initialize a AccessoryDriver object."""
super().__init__(*args, **kwargs)

View File

@@ -1,31 +1,67 @@
"""Constants used be the HomeKit component."""
# #### MISC ####
DOMAIN = 'homekit'
HOMEKIT_FILE = '.homekit.state'
HOMEKIT_NOTIFY_ID = 4663548
# #### CONFIG ####
CONF_AUTO_START = 'auto_start'
CONF_ENTITY_CONFIG = 'entity_config'
CONF_FILTER = 'filter'
# #### CONFIG DEFAULTS ####
DEFAULT_AUTO_START = True
DEFAULT_PORT = 51827
# #### HOMEKIT COMPONENT SERVICES ####
SERVICE_HOMEKIT_START = 'start'
# #### STRING CONSTANTS ####
ACCESSORY_MODEL = 'homekit.accessory'
ACCESSORY_NAME = 'Home Accessory'
BRIDGE_MODEL = 'homekit.bridge'
BRIDGE_NAME = 'Home Assistant'
MANUFACTURER = 'HomeAssistant'
# Services
# #### Categories ####
CATEGORY_LIGHT = 'LIGHTBULB'
CATEGORY_SENSOR = 'SENSOR'
# #### Services ####
SERV_ACCESSORY_INFO = 'AccessoryInformation'
SERV_BRIDGING_STATE = 'BridgingState'
SERV_HUMIDITY_SENSOR = 'HumiditySensor'
# CurrentRelativeHumidity | StatusActive, StatusFault, StatusTampered,
# StatusLowBattery, Name
SERV_LIGHTBULB = 'Lightbulb' # On | Brightness, Hue, Saturation, Name
SERV_SECURITY_SYSTEM = 'SecuritySystem'
SERV_SWITCH = 'Switch'
SERV_TEMPERATURE_SENSOR = 'TemperatureSensor'
SERV_THERMOSTAT = 'Thermostat'
SERV_WINDOW_COVERING = 'WindowCovering'
# Characteristics
# #### Characteristics ####
CHAR_ACC_IDENTIFIER = 'AccessoryIdentifier'
CHAR_BRIGHTNESS = 'Brightness' # Int | [0, 100]
CHAR_CATEGORY = 'Category'
CHAR_COOLING_THRESHOLD_TEMPERATURE = 'CoolingThresholdTemperature'
CHAR_CURRENT_HEATING_COOLING = 'CurrentHeatingCoolingState'
CHAR_CURRENT_POSITION = 'CurrentPosition'
CHAR_CURRENT_HUMIDITY = 'CurrentRelativeHumidity' # percent
CHAR_CURRENT_SECURITY_STATE = 'SecuritySystemCurrentState'
CHAR_CURRENT_TEMPERATURE = 'CurrentTemperature'
CHAR_HEATING_THRESHOLD_TEMPERATURE = 'HeatingThresholdTemperature'
CHAR_HUE = 'Hue' # arcdegress | [0, 360]
CHAR_LINK_QUALITY = 'LinkQuality'
CHAR_MANUFACTURER = 'Manufacturer'
CHAR_MODEL = 'Model'
CHAR_NAME = 'Name'
CHAR_ON = 'On'
CHAR_ON = 'On' # boolean
CHAR_POSITION_STATE = 'PositionState'
CHAR_REACHABLE = 'Reachable'
CHAR_SATURATION = 'Saturation' # percent
CHAR_SERIAL_NUMBER = 'SerialNumber'
CHAR_TARGET_HEATING_COOLING = 'TargetHeatingCoolingState'
CHAR_TARGET_POSITION = 'TargetPosition'
@@ -33,5 +69,5 @@ CHAR_TARGET_SECURITY_STATE = 'SecuritySystemTargetState'
CHAR_TARGET_TEMPERATURE = 'TargetTemperature'
CHAR_TEMP_DISPLAY_UNITS = 'TemperatureDisplayUnits'
# Properties
# #### Properties ####
PROP_CELSIUS = {'minValue': -273, 'maxValue': 999}

View File

@@ -1,72 +0,0 @@
"""Class to hold all sensor accessories."""
import logging
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT, TEMP_FAHRENHEIT, TEMP_CELSIUS)
from homeassistant.helpers.event import async_track_state_change
from . import TYPES
from .accessories import (
HomeAccessory, add_preload_service, override_properties)
from .const import (
SERV_TEMPERATURE_SENSOR, CHAR_CURRENT_TEMPERATURE, PROP_CELSIUS)
_LOGGER = logging.getLogger(__name__)
def calc_temperature(state, unit=TEMP_CELSIUS):
"""Calculate temperature from state and unit.
Always return temperature as Celsius value.
Conversion is handled on the device.
"""
try:
value = float(state)
except ValueError:
return None
return round((value - 32) / 1.8, 2) if unit == TEMP_FAHRENHEIT else value
@TYPES.register('TemperatureSensor')
class TemperatureSensor(HomeAccessory):
"""Generate a TemperatureSensor accessory for a temperature sensor.
Sensor entity must return temperature in °C, °F.
"""
def __init__(self, hass, entity_id, display_name):
"""Initialize a TemperatureSensor accessory object."""
super().__init__(display_name, entity_id, 'SENSOR')
self._hass = hass
self._entity_id = entity_id
self.serv_temp = add_preload_service(self, SERV_TEMPERATURE_SENSOR)
self.char_temp = self.serv_temp. \
get_characteristic(CHAR_CURRENT_TEMPERATURE)
override_properties(self.char_temp, PROP_CELSIUS)
self.char_temp.value = 0
self.unit = None
def run(self):
"""Method called be object after driver is started."""
state = self._hass.states.get(self._entity_id)
self.update_temperature(new_state=state)
async_track_state_change(
self._hass, self._entity_id, self.update_temperature)
def update_temperature(self, entity_id=None, old_state=None,
new_state=None):
"""Update temperature after state changed."""
if new_state is None:
return
unit = new_state.attributes[ATTR_UNIT_OF_MEASUREMENT]
temperature = calc_temperature(new_state.state, unit)
if temperature is not None:
self.char_temp.set_value(temperature)
_LOGGER.debug("%s: Current temperature set to %d°C",
self._entity_id, temperature)

View File

@@ -0,0 +1,4 @@
# Describes the format for available HomeKit services
start:
description: Starts the HomeKit component driver.

View File

@@ -2,7 +2,6 @@
import logging
from homeassistant.components.cover import ATTR_CURRENT_POSITION
from homeassistant.helpers.event import async_track_state_change
from . import TYPES
from .accessories import HomeAccessory, add_preload_service
@@ -14,16 +13,17 @@ from .const import (
_LOGGER = logging.getLogger(__name__)
@TYPES.register('Window')
class Window(HomeAccessory):
@TYPES.register('WindowCovering')
class WindowCovering(HomeAccessory):
"""Generate a Window accessory for a cover entity.
The cover entity must support: set_cover_position.
"""
def __init__(self, hass, entity_id, display_name):
"""Initialize a Window accessory object."""
super().__init__(display_name, entity_id, 'WINDOW')
def __init__(self, hass, entity_id, display_name, *args, **kwargs):
"""Initialize a WindowCovering accessory object."""
super().__init__(display_name, entity_id, 'WINDOW_COVERING',
*args, **kwargs)
self._hass = hass
self._entity_id = entity_id
@@ -31,12 +31,12 @@ class Window(HomeAccessory):
self.current_position = None
self.homekit_target = None
self.serv_cover = add_preload_service(self, SERV_WINDOW_COVERING)
self.char_current_position = self.serv_cover. \
serv_cover = add_preload_service(self, SERV_WINDOW_COVERING)
self.char_current_position = serv_cover. \
get_characteristic(CHAR_CURRENT_POSITION)
self.char_target_position = self.serv_cover. \
self.char_target_position = serv_cover. \
get_characteristic(CHAR_TARGET_POSITION)
self.char_position_state = self.serv_cover. \
self.char_position_state = serv_cover. \
get_characteristic(CHAR_POSITION_STATE)
self.char_current_position.value = 0
self.char_target_position.value = 0
@@ -44,36 +44,28 @@ class Window(HomeAccessory):
self.char_target_position.setter_callback = self.move_cover
def run(self):
"""Method called be object after driver is started."""
state = self._hass.states.get(self._entity_id)
self.update_cover_position(new_state=state)
async_track_state_change(
self._hass, self._entity_id, self.update_cover_position)
def move_cover(self, value):
"""Move cover to value if call came from HomeKit."""
self.char_target_position.set_value(value, should_callback=False)
if value != self.current_position:
_LOGGER.debug("%s: Set position to %d", self._entity_id, value)
_LOGGER.debug('%s: Set position to %d', self._entity_id, value)
self.homekit_target = value
if value > self.current_position:
self.char_position_state.set_value(1)
elif value < self.current_position:
self.char_position_state.set_value(0)
self._hass.services.call(
'cover', 'set_cover_position',
{'entity_id': self._entity_id, 'position': value})
self._hass.components.cover.set_cover_position(
value, self._entity_id)
def update_cover_position(self, entity_id=None, old_state=None,
new_state=None):
def update_state(self, entity_id=None, old_state=None, new_state=None):
"""Update cover position after state changed."""
if new_state is None:
return
current_position = new_state.attributes[ATTR_CURRENT_POSITION]
current_position = new_state.attributes.get(ATTR_CURRENT_POSITION)
if current_position is None:
return
self.current_position = int(current_position)
self.char_current_position.set_value(self.current_position)

View File

@@ -0,0 +1,148 @@
"""Class to hold all light accessories."""
import logging
from homeassistant.components.light import (
ATTR_HS_COLOR, ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, SUPPORT_COLOR)
from homeassistant.const import ATTR_SUPPORTED_FEATURES, STATE_ON, STATE_OFF
from . import TYPES
from .accessories import HomeAccessory, add_preload_service
from .const import (
CATEGORY_LIGHT, SERV_LIGHTBULB,
CHAR_BRIGHTNESS, CHAR_HUE, CHAR_ON, CHAR_SATURATION)
_LOGGER = logging.getLogger(__name__)
RGB_COLOR = 'rgb_color'
@TYPES.register('Light')
class Light(HomeAccessory):
"""Generate a Light accessory for a light entity.
Currently supports: state, brightness, rgb_color.
"""
def __init__(self, hass, entity_id, name, *args, **kwargs):
"""Initialize a new Light accessory object."""
super().__init__(name, entity_id, CATEGORY_LIGHT, *args, **kwargs)
self._hass = hass
self._entity_id = entity_id
self._flag = {CHAR_ON: False, CHAR_BRIGHTNESS: False,
CHAR_HUE: False, CHAR_SATURATION: False,
RGB_COLOR: False}
self.chars = []
self._features = self._hass.states.get(self._entity_id) \
.attributes.get(ATTR_SUPPORTED_FEATURES)
if self._features & SUPPORT_BRIGHTNESS:
self.chars.append(CHAR_BRIGHTNESS)
if self._features & SUPPORT_COLOR:
self.chars.append(CHAR_HUE)
self.chars.append(CHAR_SATURATION)
self._hue = None
self._saturation = None
serv_light = add_preload_service(self, SERV_LIGHTBULB, self.chars)
self.char_on = serv_light.get_characteristic(CHAR_ON)
self.char_on.setter_callback = self.set_state
self.char_on.value = 0
if CHAR_BRIGHTNESS in self.chars:
self.char_brightness = serv_light \
.get_characteristic(CHAR_BRIGHTNESS)
self.char_brightness.setter_callback = self.set_brightness
self.char_brightness.value = 0
if CHAR_HUE in self.chars:
self.char_hue = serv_light.get_characteristic(CHAR_HUE)
self.char_hue.setter_callback = self.set_hue
self.char_hue.value = 0
if CHAR_SATURATION in self.chars:
self.char_saturation = serv_light \
.get_characteristic(CHAR_SATURATION)
self.char_saturation.setter_callback = self.set_saturation
self.char_saturation.value = 75
def set_state(self, value):
"""Set state if call came from HomeKit."""
if self._flag[CHAR_BRIGHTNESS]:
return
_LOGGER.debug('%s: Set state to %d', self._entity_id, value)
self._flag[CHAR_ON] = True
self.char_on.set_value(value, should_callback=False)
if value == 1:
self._hass.components.light.turn_on(self._entity_id)
elif value == 0:
self._hass.components.light.turn_off(self._entity_id)
def set_brightness(self, value):
"""Set brightness if call came from HomeKit."""
_LOGGER.debug('%s: Set brightness to %d', self._entity_id, value)
self._flag[CHAR_BRIGHTNESS] = True
self.char_brightness.set_value(value, should_callback=False)
self._hass.components.light.turn_on(
self._entity_id, brightness_pct=value)
def set_saturation(self, value):
"""Set saturation if call came from HomeKit."""
_LOGGER.debug('%s: Set saturation to %d', self._entity_id, value)
self._flag[CHAR_SATURATION] = True
self.char_saturation.set_value(value, should_callback=False)
self._saturation = value
self.set_color()
def set_hue(self, value):
"""Set hue if call came from HomeKit."""
_LOGGER.debug('%s: Set hue to %d', self._entity_id, value)
self._flag[CHAR_HUE] = True
self.char_hue.set_value(value, should_callback=False)
self._hue = value
self.set_color()
def set_color(self):
"""Set color if call came from HomeKit."""
# Handle Color
if self._features & SUPPORT_COLOR and self._flag[CHAR_HUE] and \
self._flag[CHAR_SATURATION]:
color = (self._hue, self._saturation)
_LOGGER.debug('%s: Set hs_color to %s', self._entity_id, color)
self._flag.update({
CHAR_HUE: False, CHAR_SATURATION: False, RGB_COLOR: True})
self._hass.components.light.turn_on(
self._entity_id, hs_color=color)
def update_state(self, entity_id=None, old_state=None, new_state=None):
"""Update light after state change."""
if not new_state:
return
# Handle State
state = new_state.state
if not self._flag[CHAR_ON] and state in [STATE_ON, STATE_OFF] and \
self.char_on.value != (state == STATE_ON):
self.char_on.set_value(state == STATE_ON, should_callback=False)
self._flag[CHAR_ON] = False
# Handle Brightness
if CHAR_BRIGHTNESS in self.chars:
brightness = new_state.attributes.get(ATTR_BRIGHTNESS)
if not self._flag[CHAR_BRIGHTNESS] and isinstance(brightness, int):
brightness = round(brightness / 255 * 100, 0)
if self.char_brightness.value != brightness:
self.char_brightness.set_value(brightness,
should_callback=False)
self._flag[CHAR_BRIGHTNESS] = False
# Handle Color
if CHAR_SATURATION in self.chars and CHAR_HUE in self.chars:
hue, saturation = new_state.attributes.get(
ATTR_HS_COLOR, (None, None))
if not self._flag[RGB_COLOR] and (
hue != self._hue or saturation != self._saturation):
self.char_hue.set_value(hue, should_callback=False)
self.char_saturation.set_value(saturation,
should_callback=False)
self._flag[RGB_COLOR] = False

View File

@@ -5,7 +5,6 @@ from homeassistant.const import (
STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME,
STATE_ALARM_ARMED_NIGHT, STATE_ALARM_DISARMED,
ATTR_ENTITY_ID, ATTR_CODE)
from homeassistant.helpers.event import async_track_state_change
from . import TYPES
from .accessories import HomeAccessory, add_preload_service
@@ -28,9 +27,11 @@ STATE_TO_SERVICE = {STATE_ALARM_DISARMED: 'alarm_disarm',
class SecuritySystem(HomeAccessory):
"""Generate an SecuritySystem accessory for an alarm control panel."""
def __init__(self, hass, entity_id, display_name, alarm_code=None):
def __init__(self, hass, entity_id, display_name,
alarm_code, *args, **kwargs):
"""Initialize a SecuritySystem accessory object."""
super().__init__(display_name, entity_id, 'ALARM_SYSTEM')
super().__init__(display_name, entity_id, 'ALARM_SYSTEM',
*args, **kwargs)
self._hass = hass
self._entity_id = entity_id
@@ -38,39 +39,29 @@ class SecuritySystem(HomeAccessory):
self.flag_target_state = False
self.service_alarm = add_preload_service(self, SERV_SECURITY_SYSTEM)
self.char_current_state = self.service_alarm. \
serv_alarm = add_preload_service(self, SERV_SECURITY_SYSTEM)
self.char_current_state = serv_alarm. \
get_characteristic(CHAR_CURRENT_SECURITY_STATE)
self.char_current_state.value = 3
self.char_target_state = self.service_alarm. \
self.char_target_state = serv_alarm. \
get_characteristic(CHAR_TARGET_SECURITY_STATE)
self.char_target_state.value = 3
self.char_target_state.setter_callback = self.set_security_state
def run(self):
"""Method called be object after driver is started."""
state = self._hass.states.get(self._entity_id)
self.update_security_state(new_state=state)
async_track_state_change(self._hass, self._entity_id,
self.update_security_state)
def set_security_state(self, value):
"""Move security state to value if call came from HomeKit."""
_LOGGER.debug("%s: Set security state to %d",
_LOGGER.debug('%s: Set security state to %d',
self._entity_id, value)
self.flag_target_state = True
self.char_target_state.set_value(value, should_callback=False)
hass_value = HOMEKIT_TO_HASS[value]
service = STATE_TO_SERVICE[hass_value]
params = {ATTR_ENTITY_ID: self._entity_id}
if self._alarm_code is not None:
params[ATTR_CODE] = self._alarm_code
params = {ATTR_ENTITY_ID: self._entity_id, ATTR_CODE: self._alarm_code}
self._hass.services.call('alarm_control_panel', service, params)
def update_security_state(self, entity_id=None,
old_state=None, new_state=None):
def update_state(self, entity_id=None, old_state=None, new_state=None):
"""Update security state after state changed."""
if new_state is None:
return
@@ -78,15 +69,15 @@ class SecuritySystem(HomeAccessory):
hass_state = new_state.state
if hass_state not in HASS_TO_HOMEKIT:
return
current_security_state = HASS_TO_HOMEKIT[hass_state]
self.char_current_state.set_value(current_security_state)
_LOGGER.debug("%s: Updated current state to %s (%d)",
self._entity_id, hass_state,
current_security_state)
self.char_current_state.set_value(current_security_state,
should_callback=False)
_LOGGER.debug('%s: Updated current state to %s (%d)',
self._entity_id, hass_state, current_security_state)
if not self.flag_target_state:
self.char_target_state.set_value(current_security_state,
should_callback=False)
elif self.char_target_state.get_value() \
== self.char_current_state.get_value():
if self.char_target_state.value == self.char_current_state.value:
self.flag_target_state = False

View File

@@ -0,0 +1,99 @@
"""Class to hold all sensor accessories."""
import logging
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT, TEMP_FAHRENHEIT, TEMP_CELSIUS)
from homeassistant.util.temperature import fahrenheit_to_celsius
from . import TYPES
from .accessories import (
HomeAccessory, add_preload_service, override_properties)
from .const import (
CATEGORY_SENSOR, SERV_HUMIDITY_SENSOR, SERV_TEMPERATURE_SENSOR,
CHAR_CURRENT_HUMIDITY, CHAR_CURRENT_TEMPERATURE, PROP_CELSIUS)
_LOGGER = logging.getLogger(__name__)
def calc_temperature(state, unit=TEMP_CELSIUS):
"""Calculate temperature from state and unit.
Always return temperature as Celsius value.
Conversion is handled on the device.
"""
try:
value = float(state)
except ValueError:
return None
return fahrenheit_to_celsius(value) if unit == TEMP_FAHRENHEIT else value
def calc_humidity(state):
"""Calculate humidity from state."""
try:
return float(state)
except ValueError:
return None
@TYPES.register('TemperatureSensor')
class TemperatureSensor(HomeAccessory):
"""Generate a TemperatureSensor accessory for a temperature sensor.
Sensor entity must return temperature in °C, °F.
"""
def __init__(self, hass, entity_id, name, *args, **kwargs):
"""Initialize a TemperatureSensor accessory object."""
super().__init__(name, entity_id, CATEGORY_SENSOR, *args, **kwargs)
self._hass = hass
self._entity_id = entity_id
serv_temp = add_preload_service(self, SERV_TEMPERATURE_SENSOR)
self.char_temp = serv_temp.get_characteristic(CHAR_CURRENT_TEMPERATURE)
override_properties(self.char_temp, PROP_CELSIUS)
self.char_temp.value = 0
self.unit = None
def update_state(self, entity_id=None, old_state=None, new_state=None):
"""Update temperature after state changed."""
if new_state is None:
return
unit = new_state.attributes[ATTR_UNIT_OF_MEASUREMENT]
temperature = calc_temperature(new_state.state, unit)
if temperature:
self.char_temp.set_value(temperature, should_callback=False)
_LOGGER.debug('%s: Current temperature set to %d°C',
self._entity_id, temperature)
@TYPES.register('HumiditySensor')
class HumiditySensor(HomeAccessory):
"""Generate a HumiditySensor accessory as humidity sensor."""
def __init__(self, hass, entity_id, name, *args, **kwargs):
"""Initialize a HumiditySensor accessory object."""
super().__init__(name, entity_id, CATEGORY_SENSOR, *args, **kwargs)
self._hass = hass
self._entity_id = entity_id
serv_humidity = add_preload_service(self, SERV_HUMIDITY_SENSOR)
self.char_humidity = serv_humidity \
.get_characteristic(CHAR_CURRENT_HUMIDITY)
self.char_humidity.value = 0
def update_state(self, entity_id=None, old_state=None, new_state=None):
"""Update accessory after state change."""
if new_state is None:
return
humidity = calc_humidity(new_state.state)
if humidity:
self.char_humidity.set_value(humidity, should_callback=False)
_LOGGER.debug('%s: Current humidity set to %d%%',
self._entity_id, humidity)

View File

@@ -1,9 +1,9 @@
"""Class to hold all switch accessories."""
import logging
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.const import (
ATTR_ENTITY_ID, SERVICE_TURN_ON, SERVICE_TURN_OFF, STATE_ON)
from homeassistant.core import split_entity_id
from homeassistant.helpers.event import async_track_state_change
from . import TYPES
from .accessories import HomeAccessory, add_preload_service
@@ -16,9 +16,9 @@ _LOGGER = logging.getLogger(__name__)
class Switch(HomeAccessory):
"""Generate a Switch accessory."""
def __init__(self, hass, entity_id, display_name):
def __init__(self, hass, entity_id, display_name, *args, **kwargs):
"""Initialize a Switch accessory object to represent a remote."""
super().__init__(display_name, entity_id, 'SWITCH')
super().__init__(display_name, entity_id, 'SWITCH', *args, **kwargs)
self._hass = hass
self._entity_id = entity_id
@@ -26,25 +26,18 @@ class Switch(HomeAccessory):
self.flag_target_state = False
self.service_switch = add_preload_service(self, SERV_SWITCH)
self.char_on = self.service_switch.get_characteristic(CHAR_ON)
serv_switch = add_preload_service(self, SERV_SWITCH)
self.char_on = serv_switch.get_characteristic(CHAR_ON)
self.char_on.value = False
self.char_on.setter_callback = self.set_state
def run(self):
"""Method called be object after driver is started."""
state = self._hass.states.get(self._entity_id)
self.update_state(new_state=state)
async_track_state_change(self._hass, self._entity_id,
self.update_state)
def set_state(self, value):
"""Move switch state to value if call came from HomeKit."""
_LOGGER.debug("%s: Set switch state to %s",
_LOGGER.debug('%s: Set switch state to %s',
self._entity_id, value)
self.flag_target_state = True
service = 'turn_on' if value else 'turn_off'
self.char_on.set_value(value, should_callback=False)
service = SERVICE_TURN_ON if value else SERVICE_TURN_OFF
self._hass.services.call(self._domain, service,
{ATTR_ENTITY_ID: self._entity_id})
@@ -53,10 +46,10 @@ class Switch(HomeAccessory):
if new_state is None:
return
current_state = (new_state.state == 'on')
current_state = (new_state.state == STATE_ON)
if not self.flag_target_state:
_LOGGER.debug("%s: Set current state to %s",
_LOGGER.debug('%s: Set current state to %s',
self._entity_id, current_state)
self.char_on.set_value(current_state, should_callback=False)
else:
self.flag_target_state = False
self.flag_target_state = False

View File

@@ -7,9 +7,7 @@ from homeassistant.components.climate import (
ATTR_OPERATION_MODE, ATTR_OPERATION_LIST,
STATE_HEAT, STATE_COOL, STATE_AUTO)
from homeassistant.const import (
ATTR_ENTITY_ID, ATTR_UNIT_OF_MEASUREMENT,
TEMP_CELSIUS, TEMP_FAHRENHEIT)
from homeassistant.helpers.event import async_track_state_change
ATTR_UNIT_OF_MEASUREMENT, TEMP_CELSIUS, TEMP_FAHRENHEIT)
from . import TYPES
from .accessories import HomeAccessory, add_preload_service
@@ -33,9 +31,11 @@ HC_HOMEKIT_TO_HASS = {c: s for s, c in HC_HASS_TO_HOMEKIT.items()}
class Thermostat(HomeAccessory):
"""Generate a Thermostat accessory for a climate."""
def __init__(self, hass, entity_id, display_name, support_auto=False):
def __init__(self, hass, entity_id, display_name,
support_auto, *args, **kwargs):
"""Initialize a Thermostat accessory object."""
super().__init__(display_name, entity_id, 'THERMOSTAT')
super().__init__(display_name, entity_id, 'THERMOSTAT',
*args, **kwargs)
self._hass = hass
self._entity_id = entity_id
@@ -46,48 +46,47 @@ class Thermostat(HomeAccessory):
self.coolingthresh_flag_target_state = False
self.heatingthresh_flag_target_state = False
extra_chars = None
# Add additional characteristics if auto mode is supported
if support_auto:
extra_chars = [CHAR_COOLING_THRESHOLD_TEMPERATURE,
CHAR_HEATING_THRESHOLD_TEMPERATURE]
extra_chars = [
CHAR_COOLING_THRESHOLD_TEMPERATURE,
CHAR_HEATING_THRESHOLD_TEMPERATURE] if support_auto else None
# Preload the thermostat service
self.service_thermostat = add_preload_service(self, SERV_THERMOSTAT,
extra_chars)
serv_thermostat = add_preload_service(self, SERV_THERMOSTAT,
extra_chars)
# Current and target mode characteristics
self.char_current_heat_cool = self.service_thermostat. \
self.char_current_heat_cool = serv_thermostat. \
get_characteristic(CHAR_CURRENT_HEATING_COOLING)
self.char_current_heat_cool.value = 0
self.char_target_heat_cool = self.service_thermostat. \
self.char_target_heat_cool = serv_thermostat. \
get_characteristic(CHAR_TARGET_HEATING_COOLING)
self.char_target_heat_cool.value = 0
self.char_target_heat_cool.setter_callback = self.set_heat_cool
# Current and target temperature characteristics
self.char_current_temp = self.service_thermostat. \
self.char_current_temp = serv_thermostat. \
get_characteristic(CHAR_CURRENT_TEMPERATURE)
self.char_current_temp.value = 21.0
self.char_target_temp = self.service_thermostat. \
self.char_target_temp = serv_thermostat. \
get_characteristic(CHAR_TARGET_TEMPERATURE)
self.char_target_temp.value = 21.0
self.char_target_temp.setter_callback = self.set_target_temperature
# Display units characteristic
self.char_display_units = self.service_thermostat. \
self.char_display_units = serv_thermostat. \
get_characteristic(CHAR_TEMP_DISPLAY_UNITS)
self.char_display_units.value = 0
# If the device supports it: high and low temperature characteristics
if support_auto:
self.char_cooling_thresh_temp = self.service_thermostat. \
self.char_cooling_thresh_temp = serv_thermostat. \
get_characteristic(CHAR_COOLING_THRESHOLD_TEMPERATURE)
self.char_cooling_thresh_temp.value = 23.0
self.char_cooling_thresh_temp.setter_callback = \
self.set_cooling_threshold
self.char_heating_thresh_temp = self.service_thermostat. \
self.char_heating_thresh_temp = serv_thermostat. \
get_characteristic(CHAR_HEATING_THRESHOLD_TEMPERATURE)
self.char_heating_thresh_temp.value = 19.0
self.char_heating_thresh_temp.setter_callback = \
@@ -96,61 +95,49 @@ class Thermostat(HomeAccessory):
self.char_cooling_thresh_temp = None
self.char_heating_thresh_temp = None
def run(self):
"""Method called be object after driver is started."""
state = self._hass.states.get(self._entity_id)
self.update_thermostat(new_state=state)
async_track_state_change(self._hass, self._entity_id,
self.update_thermostat)
def set_heat_cool(self, value):
"""Move operation mode to value if call came from HomeKit."""
self.char_target_heat_cool.set_value(value, should_callback=False)
if value in HC_HOMEKIT_TO_HASS:
_LOGGER.debug("%s: Set heat-cool to %d", self._entity_id, value)
_LOGGER.debug('%s: Set heat-cool to %d', self._entity_id, value)
self.heat_cool_flag_target_state = True
hass_value = HC_HOMEKIT_TO_HASS[value]
self._hass.services.call('climate', 'set_operation_mode',
{ATTR_ENTITY_ID: self._entity_id,
ATTR_OPERATION_MODE: hass_value})
self._hass.components.climate.set_operation_mode(
operation_mode=hass_value, entity_id=self._entity_id)
def set_cooling_threshold(self, value):
"""Set cooling threshold temp to value if call came from HomeKit."""
_LOGGER.debug("%s: Set cooling threshold temperature to %.2f",
_LOGGER.debug('%s: Set cooling threshold temperature to %.2f',
self._entity_id, value)
self.coolingthresh_flag_target_state = True
low = self.char_heating_thresh_temp.get_value()
self._hass.services.call(
'climate', 'set_temperature',
{ATTR_ENTITY_ID: self._entity_id,
ATTR_TARGET_TEMP_HIGH: value,
ATTR_TARGET_TEMP_LOW: low})
self.char_cooling_thresh_temp.set_value(value, should_callback=False)
low = self.char_heating_thresh_temp.value
self._hass.components.climate.set_temperature(
entity_id=self._entity_id, target_temp_high=value,
target_temp_low=low)
def set_heating_threshold(self, value):
"""Set heating threshold temp to value if call came from HomeKit."""
_LOGGER.debug("%s: Set heating threshold temperature to %.2f",
_LOGGER.debug('%s: Set heating threshold temperature to %.2f',
self._entity_id, value)
self.heatingthresh_flag_target_state = True
self.char_heating_thresh_temp.set_value(value, should_callback=False)
# Home assistant always wants to set low and high at the same time
high = self.char_cooling_thresh_temp.get_value()
self._hass.services.call(
'climate', 'set_temperature',
{ATTR_ENTITY_ID: self._entity_id,
ATTR_TARGET_TEMP_LOW: value,
ATTR_TARGET_TEMP_HIGH: high})
high = self.char_cooling_thresh_temp.value
self._hass.components.climate.set_temperature(
entity_id=self._entity_id, target_temp_high=high,
target_temp_low=value)
def set_target_temperature(self, value):
"""Set target temperature to value if call came from HomeKit."""
_LOGGER.debug("%s: Set target temperature to %.2f",
_LOGGER.debug('%s: Set target temperature to %.2f',
self._entity_id, value)
self.temperature_flag_target_state = True
self._hass.services.call(
'climate', 'set_temperature',
{ATTR_ENTITY_ID: self._entity_id,
ATTR_TEMPERATURE: value})
self.char_target_temp.set_value(value, should_callback=False)
self._hass.components.climate.set_temperature(
temperature=value, entity_id=self._entity_id)
def update_thermostat(self, entity_id=None,
old_state=None, new_state=None):
def update_state(self, entity_id=None, old_state=None, new_state=None):
"""Update security state after state changed."""
if new_state is None:
return
@@ -166,62 +153,58 @@ class Thermostat(HomeAccessory):
if not self.temperature_flag_target_state:
self.char_target_temp.set_value(target_temp,
should_callback=False)
else:
self.temperature_flag_target_state = False
self.temperature_flag_target_state = False
# Update cooling threshold temperature if characteristic exists
if self.char_cooling_thresh_temp is not None:
if self.char_cooling_thresh_temp:
cooling_thresh = new_state.attributes.get(ATTR_TARGET_TEMP_HIGH)
if cooling_thresh is not None:
if cooling_thresh:
if not self.coolingthresh_flag_target_state:
self.char_cooling_thresh_temp.set_value(
cooling_thresh, should_callback=False)
else:
self.coolingthresh_flag_target_state = False
self.coolingthresh_flag_target_state = False
# Update heating threshold temperature if characteristic exists
if self.char_heating_thresh_temp is not None:
if self.char_heating_thresh_temp:
heating_thresh = new_state.attributes.get(ATTR_TARGET_TEMP_LOW)
if heating_thresh is not None:
if heating_thresh:
if not self.heatingthresh_flag_target_state:
self.char_heating_thresh_temp.set_value(
heating_thresh, should_callback=False)
else:
self.heatingthresh_flag_target_state = False
self.heatingthresh_flag_target_state = False
# Update display units
display_units = new_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
if display_units is not None \
if display_units \
and display_units in UNIT_HASS_TO_HOMEKIT:
self.char_display_units.set_value(
UNIT_HASS_TO_HOMEKIT[display_units])
# Update target operation mode
operation_mode = new_state.attributes.get(ATTR_OPERATION_MODE)
if operation_mode is not None \
if operation_mode \
and operation_mode in HC_HASS_TO_HOMEKIT:
if not self.heat_cool_flag_target_state:
self.char_target_heat_cool.set_value(
HC_HASS_TO_HOMEKIT[operation_mode], should_callback=False)
else:
self.heat_cool_flag_target_state = False
self.heat_cool_flag_target_state = False
# Set current operation mode based on temperatures and target mode
if operation_mode == STATE_HEAT:
if current_temp < target_temp:
if isinstance(target_temp, float) and current_temp < target_temp:
current_operation_mode = STATE_HEAT
else:
current_operation_mode = STATE_OFF
elif operation_mode == STATE_COOL:
if current_temp > target_temp:
if isinstance(target_temp, float) and current_temp > target_temp:
current_operation_mode = STATE_COOL
else:
current_operation_mode = STATE_OFF
elif operation_mode == STATE_AUTO:
# Check if auto is supported
if self.char_cooling_thresh_temp is not None:
lower_temp = self.char_heating_thresh_temp.get_value()
upper_temp = self.char_cooling_thresh_temp.get_value()
if self.char_cooling_thresh_temp:
lower_temp = self.char_heating_thresh_temp.value
upper_temp = self.char_cooling_thresh_temp.value
if current_temp < lower_temp:
current_operation_mode = STATE_HEAT
elif current_temp > upper_temp:
@@ -232,9 +215,11 @@ class Thermostat(HomeAccessory):
# Check if heating or cooling are supported
heat = STATE_HEAT in new_state.attributes[ATTR_OPERATION_LIST]
cool = STATE_COOL in new_state.attributes[ATTR_OPERATION_LIST]
if current_temp < target_temp and heat:
if isinstance(target_temp, float) and \
current_temp < target_temp and heat:
current_operation_mode = STATE_HEAT
elif current_temp > target_temp and cool:
elif isinstance(target_temp, float) and \
current_temp > target_temp and cool:
current_operation_mode = STATE_COOL
else:
current_operation_mode = STATE_OFF

View File

@@ -0,0 +1,46 @@
"""Collection of useful functions for the HomeKit component."""
import logging
import voluptuous as vol
from homeassistant.core import split_entity_id
from homeassistant.const import (
ATTR_CODE)
import homeassistant.helpers.config_validation as cv
from .const import HOMEKIT_NOTIFY_ID
_LOGGER = logging.getLogger(__name__)
def validate_entity_config(values):
"""Validate config entry for CONF_ENTITY."""
entities = {}
for key, config in values.items():
entity = cv.entity_id(key)
params = {}
if not isinstance(config, dict):
raise vol.Invalid('The configuration for "{}" must be '
' an dictionary.'.format(entity))
domain, _ = split_entity_id(entity)
if domain == 'alarm_control_panel':
code = config.get(ATTR_CODE)
params[ATTR_CODE] = cv.string(code) if code else None
entities[entity] = params
return entities
def show_setup_message(bridge, hass):
"""Display persistent notification with setup information."""
pin = bridge.pincode.decode()
message = 'To setup Home Assistant in the Home App, enter the ' \
'following code:\n### {}'.format(pin)
hass.components.persistent_notification.create(
message, 'HomeKit Setup', HOMEKIT_NOTIFY_ID)
def dismiss_setup_message(hass):
"""Dismiss persistent notification and remove QR code."""
hass.components.persistent_notification.dismiss(HOMEKIT_NOTIFY_ID)

View File

@@ -20,7 +20,7 @@ from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
from homeassistant.loader import bind_hass
REQUIREMENTS = ['pyhomematic==0.1.39']
REQUIREMENTS = ['pyhomematic==0.1.40']
DOMAIN = 'homematic'
_LOGGER = logging.getLogger(__name__)
@@ -33,6 +33,7 @@ DISCOVER_SENSORS = 'homematic.sensor'
DISCOVER_BINARY_SENSORS = 'homematic.binary_sensor'
DISCOVER_COVER = 'homematic.cover'
DISCOVER_CLIMATE = 'homematic.climate'
DISCOVER_LOCKS = 'homematic.locks'
ATTR_DISCOVER_DEVICES = 'devices'
ATTR_PARAM = 'param'
@@ -59,7 +60,7 @@ SERVICE_SET_INSTALL_MODE = 'set_install_mode'
HM_DEVICE_TYPES = {
DISCOVER_SWITCHES: [
'Switch', 'SwitchPowermeter', 'IOSwitch', 'IPSwitch', 'RFSiren',
'IPSwitchPowermeter', 'KeyMatic', 'HMWIOSwitch', 'Rain', 'EcoLogic'],
'IPSwitchPowermeter', 'HMWIOSwitch', 'Rain', 'EcoLogic'],
DISCOVER_LIGHTS: ['Dimmer', 'KeyDimmer', 'IPKeyDimmer'],
DISCOVER_SENSORS: [
'SwitchPowermeter', 'Motion', 'MotionV2', 'RemoteMotion', 'MotionIP',
@@ -68,7 +69,7 @@ HM_DEVICE_TYPES = {
'WeatherStation', 'ThermostatWall2', 'TemperatureDiffSensor',
'TemperatureSensor', 'CO2Sensor', 'IPSwitchPowermeter', 'HMWIOSwitch',
'FillingLevel', 'ValveDrive', 'EcoLogic', 'IPThermostatWall',
'IPSmoke', 'RFSiren', 'PresenceIP'],
'IPSmoke', 'RFSiren', 'PresenceIP', 'IPAreaThermostat'],
DISCOVER_CLIMATE: [
'Thermostat', 'ThermostatWall', 'MAXThermostat', 'ThermostatWall2',
'MAXWallThermostat', 'IPThermostat', 'IPThermostatWall',
@@ -78,7 +79,8 @@ HM_DEVICE_TYPES = {
'MotionIP', 'RemoteMotion', 'WeatherSensor', 'TiltSensor',
'IPShutterContact', 'HMWIOSwitch', 'MaxShutterContact', 'Rain',
'WiredSensor', 'PresenceIP'],
DISCOVER_COVER: ['Blind', 'KeyBlind', 'IPKeyBlind', 'IPKeyBlindTilt']
DISCOVER_COVER: ['Blind', 'KeyBlind', 'IPKeyBlind', 'IPKeyBlindTilt'],
DISCOVER_LOCKS: ['KeyMatic']
}
HM_IGNORE_DISCOVERY_NODE = [
@@ -86,6 +88,10 @@ HM_IGNORE_DISCOVERY_NODE = [
'ACTUAL_HUMIDITY'
]
HM_IGNORE_DISCOVERY_NODE_EXCEPTIONS = {
'ACTUAL_TEMPERATURE': ['IPAreaThermostat'],
}
HM_ATTRIBUTE_SUPPORT = {
'LOWBAT': ['battery', {0: 'High', 1: 'Low'}],
'LOW_BAT': ['battery', {0: 'High', 1: 'Low'}],
@@ -460,7 +466,8 @@ def _system_callback_handler(hass, config, src, *args):
('cover', DISCOVER_COVER),
('binary_sensor', DISCOVER_BINARY_SENSORS),
('sensor', DISCOVER_SENSORS),
('climate', DISCOVER_CLIMATE)):
('climate', DISCOVER_CLIMATE),
('lock', DISCOVER_LOCKS)):
# Get all devices of a specific type
found_devices = _get_devices(
hass, discovery_type, addresses, interface)
@@ -505,7 +512,8 @@ def _get_devices(hass, discovery_type, keys, interface):
# Generate options for 1...n elements with 1...n parameters
for param, channels in metadata.items():
if param in HM_IGNORE_DISCOVERY_NODE:
if param in HM_IGNORE_DISCOVERY_NODE and class_name not in \
HM_IGNORE_DISCOVERY_NODE_EXCEPTIONS.get(param, []):
continue
# Add devices

View File

@@ -0,0 +1,176 @@
"""
Support for HomematicIP components.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/homematicip_cloud/
"""
import logging
from socket import timeout
import voluptuous as vol
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import (dispatcher_send,
async_dispatcher_connect)
from homeassistant.helpers.discovery import load_platform
from homeassistant.helpers.entity import Entity
REQUIREMENTS = ['homematicip==0.8']
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'homematicip_cloud'
CONF_NAME = 'name'
CONF_ACCESSPOINT = 'accesspoint'
CONF_AUTHTOKEN = 'authtoken'
CONFIG_SCHEMA = vol.Schema({
vol.Optional(DOMAIN): [vol.Schema({
vol.Optional(CONF_NAME, default=''): cv.string,
vol.Required(CONF_ACCESSPOINT): cv.string,
vol.Required(CONF_AUTHTOKEN): cv.string,
})],
}, extra=vol.ALLOW_EXTRA)
EVENT_HOME_CHANGED = 'homematicip_home_changed'
EVENT_DEVICE_CHANGED = 'homematicip_device_changed'
EVENT_GROUP_CHANGED = 'homematicip_group_changed'
EVENT_SECURITY_CHANGED = 'homematicip_security_changed'
EVENT_JOURNAL_CHANGED = 'homematicip_journal_changed'
ATTR_HOME_ID = 'home_id'
ATTR_HOME_LABEL = 'home_label'
ATTR_DEVICE_ID = 'device_id'
ATTR_DEVICE_LABEL = 'device_label'
ATTR_STATUS_UPDATE = 'status_update'
ATTR_FIRMWARE_STATE = 'firmware_state'
ATTR_LOW_BATTERY = 'low_battery'
ATTR_SABOTAGE = 'sabotage'
ATTR_RSSI = 'rssi'
ATTR_TYPE = 'type'
def setup(hass, config):
"""Set up the HomematicIP component."""
# pylint: disable=import-error, no-name-in-module
from homematicip.home import Home
hass.data.setdefault(DOMAIN, {})
homes = hass.data[DOMAIN]
accesspoints = config.get(DOMAIN, [])
def _update_event(events):
"""Handle incoming HomeMaticIP events."""
for event in events:
etype = event['eventType']
edata = event['data']
if etype == 'DEVICE_CHANGED':
dispatcher_send(hass, EVENT_DEVICE_CHANGED, edata.id)
elif etype == 'GROUP_CHANGED':
dispatcher_send(hass, EVENT_GROUP_CHANGED, edata.id)
elif etype == 'HOME_CHANGED':
dispatcher_send(hass, EVENT_HOME_CHANGED, edata.id)
elif etype == 'JOURNAL_CHANGED':
dispatcher_send(hass, EVENT_SECURITY_CHANGED, edata.id)
return True
for device in accesspoints:
name = device.get(CONF_NAME)
accesspoint = device.get(CONF_ACCESSPOINT)
authtoken = device.get(CONF_AUTHTOKEN)
home = Home()
if name.lower() == 'none':
name = ''
home.label = name
try:
home.set_auth_token(authtoken)
home.init(accesspoint)
if home.get_current_state():
_LOGGER.info("Connection to HMIP established")
else:
_LOGGER.warning("Connection to HMIP could not be established")
return False
except timeout:
_LOGGER.warning("Connection to HMIP could not be established")
return False
homes[home.id] = home
home.onEvent += _update_event
home.enable_events()
_LOGGER.info('HUB name: %s, id: %s', home.label, home.id)
for component in ['sensor']:
load_platform(hass, component, DOMAIN, {'homeid': home.id}, config)
return True
class HomematicipGenericDevice(Entity):
"""Representation of an HomematicIP generic device."""
def __init__(self, home, device):
"""Initialize the generic device."""
self._home = home
self._device = device
async def async_added_to_hass(self):
"""Register callbacks."""
async_dispatcher_connect(
self.hass, EVENT_DEVICE_CHANGED, self._device_changed)
@callback
def _device_changed(self, deviceid):
"""Handle device state changes."""
if deviceid is None or deviceid == self._device.id:
_LOGGER.debug('Event device %s', self._device.label)
self.async_schedule_update_ha_state()
def _name(self, addon=''):
"""Return the name of the device."""
name = ''
if self._home.label != '':
name += self._home.label + ' '
name += self._device.label
if addon != '':
name += ' ' + addon
return name
@property
def name(self):
"""Return the name of the generic device."""
return self._name()
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def available(self):
"""Device available."""
return not self._device.unreach
def _generic_state_attributes(self):
"""Return the state attributes of the generic device."""
laststatus = ''
if self._device.lastStatusUpdate is not None:
laststatus = self._device.lastStatusUpdate.isoformat()
return {
ATTR_HOME_LABEL: self._home.label,
ATTR_DEVICE_LABEL: self._device.label,
ATTR_HOME_ID: self._device.homeId,
ATTR_DEVICE_ID: self._device.id.lower(),
ATTR_STATUS_UPDATE: laststatus,
ATTR_FIRMWARE_STATE: self._device.updateState.lower(),
ATTR_LOW_BATTERY: self._device.lowBat,
ATTR_RSSI: self._device.rssiDeviceValue,
ATTR_TYPE: self._device.modelType
}
@property
def device_state_attributes(self):
"""Return the state attributes of the generic device."""
return self._generic_state_attributes()

View File

@@ -4,7 +4,6 @@ This module provides WSGI application to serve the Home Assistant API.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/http/
"""
from ipaddress import ip_network
import logging
import os
@@ -32,7 +31,7 @@ from .static import (
from .const import KEY_AUTHENTICATED, KEY_REAL_IP # noqa
from .view import HomeAssistantView # noqa
REQUIREMENTS = ['aiohttp_cors==0.6.0']
REQUIREMENTS = ['aiohttp_cors==0.7.0']
DOMAIN = 'http'

View File

@@ -9,7 +9,7 @@ import json
import logging
from aiohttp import web
from aiohttp.web_exceptions import HTTPUnauthorized
from aiohttp.web_exceptions import HTTPUnauthorized, HTTPInternalServerError
import homeassistant.remote as rem
from homeassistant.core import is_callback
@@ -31,8 +31,12 @@ class HomeAssistantView(object):
# pylint: disable=no-self-use
def json(self, result, status_code=200, headers=None):
"""Return a JSON response."""
msg = json.dumps(
result, sort_keys=True, cls=rem.JSONEncoder).encode('UTF-8')
try:
msg = json.dumps(
result, sort_keys=True, cls=rem.JSONEncoder).encode('UTF-8')
except TypeError as err:
_LOGGER.error('Unable to serialize to JSON: %s\n%s', err, result)
raise HTTPInternalServerError
response = web.Response(
body=msg, content_type=CONTENT_TYPE_JSON, status=status_code,
headers=headers)

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"all_configured": "Alle Philips Hue Bridges sind bereits konfiguriert",
"discover_timeout": "Nicht in der Lage Hue Bridges zu entdecken",
"no_bridges": "Philips Hue Bridges entdeckt"
},
"error": {
"linking": "Unbekannter Link-Fehler aufgetreten.",
"register_failed": "Registrieren fehlgeschlagen, bitte versuche es erneut"
},
"step": {
"init": {
"data": {
"host": "Host"
},
"title": "W\u00e4hle eine Hue Bridge"
},
"link": {
"description": "Dr\u00fccke den Knopf auf der Bridge, um Philips Hue mit Home Assistant zu registrieren.\n\n![Position des Buttons auf der Bridge](/static/images/config_philips_hue.jpg)",
"title": "Hub verbinden"
}
},
"title": "Philips Hue Bridge"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"all_configured": "All Philips Hue bridges are already configured",
"discover_timeout": "Unable to discover Hue bridges",
"no_bridges": "No Philips Hue bridges discovered"
},
"error": {
"linking": "Unknown linking error occurred.",
"register_failed": "Failed to register, please try again"
},
"step": {
"init": {
"data": {
"host": "Host"
},
"title": "Pick Hue bridge"
},
"link": {
"description": "Press the button on the bridge to register Philips Hue with Home Assistant.\n\n![Location of button on bridge](/static/images/config_philips_hue.jpg)",
"title": "Link Hub"
}
},
"title": "Philips Hue Bridge"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"all_configured": "\ubaa8\ub4e0 \ud544\ub9bd\uc2a4 Hue \ube0c\ub9bf\uc9c0\uac00 \uc774\ubbf8 \uc124\uc815\ub41c \uc0c1\ud0dc\uc785\ub2c8\ub2e4",
"discover_timeout": "Hue \ube0c\ub9bf\uc9c0\ub97c \ucc3e\uc744 \uc218 \uc5c6\uc2b5\ub2c8\ub2e4",
"no_bridges": "\ubc1c\uacac\ub41c \ud544\ub9bd\uc2a4 Hue \ube0c\ub9bf\uc9c0\uac00 \uc5c6\uc2b5\ub2c8\ub2e4"
},
"error": {
"linking": "\uc54c \uc218\uc5c6\ub294 \uc5f0\uacb0 \uc624\ub958\uac00 \ubc1c\uc0dd\ud588\uc2b5\ub2c8\ub2e4.",
"register_failed": "\ub4f1\ub85d\ud558\uc9c0 \ubabb\ud588\uc2b5\ub2c8\ub2e4. \ub2e4\uc2dc \uc2dc\ub3c4\ud574\ubcf4\uc138\uc694"
},
"step": {
"init": {
"data": {
"host": "\ud638\uc2a4\ud2b8"
},
"title": "Hue \ube0c\ub9bf\uc9c0 \uc120\ud0dd"
},
"link": {
"description": "\ube0c\ub9bf\uc9c0\uc758 \ubc84\ud2bc\uc744 \ub20c\ub7ec \ud544\ub9bd\uc2a4 Hue\ub97c Home Assistant\uc5d0 \ub4f1\ub85d\ud558\uc138\uc694.\n\n![\ube0c\ub9bf\uc9c0 \ubc84\ud2bc \uc704\uce58](/static/images/config_philips_hue.jpg)",
"title": "\ud5c8\ube0c \uc5f0\uacb0"
}
},
"title": "\ud544\ub9bd\uc2a4 Hue \ube0c\ub9bf\uc9c0"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"all_configured": "Alle Philips Hue bridges zijn al geconfigureerd",
"discover_timeout": "Hue bridges kunnen niet worden gevonden",
"no_bridges": "Geen Philips Hue bridges ontdekt"
},
"error": {
"linking": "Er is een onbekende verbindingsfout opgetreden.",
"register_failed": "Registratie is mislukt, probeer het opnieuw"
},
"step": {
"init": {
"data": {
"host": "Host"
},
"title": "Kies Hue bridge"
},
"link": {
"description": "Druk op de knop van de bridge om Philips Hue te registreren met de Home Assistant. ![Locatie van de knop op bridge] (/static/images/config_philips_hue.jpg)",
"title": "Link Hub"
}
},
"title": "Philips Hue Bridge"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"all_configured": "Alle Philips Hue Bridger er allerede konfigurert",
"discover_timeout": "Kunne ikke oppdage Hue Bridger",
"no_bridges": "Ingen Philips Hue Bridger oppdaget"
},
"error": {
"linking": "Ukjent koblingsfeil oppstod.",
"register_failed": "Registrering feilet, vennligst pr\u00f8v igjen"
},
"step": {
"init": {
"data": {
"host": "Vert"
},
"title": "Velg Hue Bridge"
},
"link": {
"description": "Trykk p\u00e5 knappen p\u00e5 Bridgen for \u00e5 registrere Philips Hue med Home Assistant. \n\n ![Knappens plassering p\u00e5 Bridgen](/static/images/config_philips_hue.jpg)",
"title": "Link Hub"
}
},
"title": "Philips Hue Bridge"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"all_configured": "Wszystkie mostki Hue s\u0105 ju\u017c skonfigurowane",
"discover_timeout": "Nie mo\u017cna wykry\u0107 \u017cadnych mostk\u00f3w Hue",
"no_bridges": "Nie wykryto \u017cadnych mostk\u00f3w Hue"
},
"error": {
"linking": "Wyst\u0105pi\u0142 nieznany b\u0142\u0105d w trakcie \u0142\u0105czenia.",
"register_failed": "Nie uda\u0142o si\u0119 zarejestrowa\u0107. Prosz\u0119 spr\u00f3bowa\u0107 ponownie."
},
"step": {
"init": {
"data": {
"host": "Host"
},
"title": "Wybierz mostek Hue"
},
"link": {
"description": "Naci\u015bnij przycisk na mostku, aby zarejestrowa\u0107 Philips Hue z Home Assistant.",
"title": "Hub Link"
}
},
"title": "Mostek Philips Hue"
}
}

View File

@@ -0,0 +1,18 @@
{
"config": {
"error": {
"linking": "A ap\u0103rut o eroare de leg\u0103tur\u0103 necunoscut\u0103.",
"register_failed": "Nu a reu\u0219it \u00eenregistrarea, \u00eencerca\u021bi din nou"
},
"step": {
"init": {
"data": {
"host": "Gazd\u0103"
}
},
"link": {
"description": "Ap\u0103sa\u021bi butonul de pe pod pentru a \u00eenregistra Philips Hue cu Home Assistant. \n\n ! [Loca\u021bia butonului pe pod] (/ static / images / config_philips_hue.jpg)"
}
}
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"all_configured": "Vsi mostovi Philips Hue so \u017ee konfigurirani",
"discover_timeout": "Ni bilo mogo\u010de odkriti Hue mostov",
"no_bridges": "Ni odkritih mostov Philips Hue"
},
"error": {
"linking": "Pri\u0161lo je do neznane napake pri povezavi.",
"register_failed": "Registracija ni uspela, poskusite znova"
},
"step": {
"init": {
"data": {
"host": "Host"
},
"title": "Izberite Hue most"
},
"link": {
"description": "Pritisnite gumb na mostu, da registrirate Philips Hue s Home Assistentom. \n\n ! [Polo\u017eaj gumba na mostu] (/static/images/config_philips_hue.jpg)",
"title": "Link Hub"
}
},
"title": "Philips Hue Bridge"
}
}

View File

@@ -0,0 +1,26 @@
{
"config": {
"abort": {
"all_configured": "\u5168\u90e8\u98de\u5229\u6d66 Hue \u6865\u63a5\u5668\u5df2\u914d\u7f6e",
"discover_timeout": "\u65e0\u6cd5\u55c5\u63a2 Hue \u6865\u63a5\u5668",
"no_bridges": "\u672a\u53d1\u73b0\u98de\u5229\u6d66 Hue Bridge"
},
"error": {
"linking": "\u53d1\u751f\u672a\u77e5\u7684\u8fde\u63a5\u9519\u8bef\u3002",
"register_failed": "\u6ce8\u518c\u5931\u8d25\uff0c\u8bf7\u91cd\u8bd5"
},
"step": {
"init": {
"data": {
"host": "\u4e3b\u673a"
},
"title": "\u9009\u62e9 Hue Bridge"
},
"link": {
"description": "\u8bf7\u6309\u4e0b\u6865\u63a5\u5668\u4e0a\u7684\u6309\u94ae\uff0c\u5728 Home Assistant \u4e0a\u6ce8\u518c\u98de\u5229\u6d66 Hue ![\u6865\u63a5\u5668\u6309\u94ae\u4f4d\u7f6e](/static/images/config_philips_hue.jpg)",
"title": "\u8fde\u63a5\u4e2d\u67a2"
}
},
"title": "\u98de\u5229\u6d66 Hue Bridge"
}
}

View File

@@ -6,22 +6,22 @@ https://home-assistant.io/components/hue/
"""
import asyncio
import json
from functools import partial
import ipaddress
import logging
import os
import socket
import async_timeout
import requests
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.components.discovery import SERVICE_HUE
from homeassistant.const import CONF_FILENAME, CONF_HOST
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import discovery, aiohttp_client
from homeassistant import config_entries
from homeassistant.util.json import save_json
REQUIREMENTS = ['phue==1.0', 'aiohue==0.3.0']
REQUIREMENTS = ['aiohue==1.3.0']
_LOGGER = logging.getLogger(__name__)
@@ -36,26 +36,23 @@ DEFAULT_ALLOW_UNREACHABLE = False
PHUE_CONFIG_FILE = 'phue.conf'
CONF_ALLOW_IN_EMULATED_HUE = "allow_in_emulated_hue"
DEFAULT_ALLOW_IN_EMULATED_HUE = True
CONF_ALLOW_HUE_GROUPS = "allow_hue_groups"
DEFAULT_ALLOW_HUE_GROUPS = True
BRIDGE_CONFIG_SCHEMA = vol.Schema([{
vol.Optional(CONF_HOST): cv.string,
BRIDGE_CONFIG_SCHEMA = vol.Schema({
# Validate as IP address and then convert back to a string.
vol.Required(CONF_HOST): vol.All(ipaddress.ip_address, cv.string),
vol.Optional(CONF_FILENAME, default=PHUE_CONFIG_FILE): cv.string,
vol.Optional(CONF_ALLOW_UNREACHABLE,
default=DEFAULT_ALLOW_UNREACHABLE): cv.boolean,
vol.Optional(CONF_ALLOW_IN_EMULATED_HUE,
default=DEFAULT_ALLOW_IN_EMULATED_HUE): cv.boolean,
vol.Optional(CONF_ALLOW_HUE_GROUPS,
default=DEFAULT_ALLOW_HUE_GROUPS): cv.boolean,
}])
})
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Optional(CONF_BRIDGES): BRIDGE_CONFIG_SCHEMA,
vol.Optional(CONF_BRIDGES):
vol.All(cv.ensure_list, [BRIDGE_CONFIG_SCHEMA]),
}),
}, extra=vol.ALLOW_EXTRA)
@@ -73,7 +70,7 @@ Press the button on the bridge to register Philips Hue with Home Assistant.
"""
def setup(hass, config):
async def async_setup(hass, config):
"""Set up the Hue platform."""
conf = config.get(DOMAIN)
if conf is None:
@@ -82,196 +79,212 @@ def setup(hass, config):
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
discovery.listen(
hass,
SERVICE_HUE,
lambda service, discovery_info:
bridge_discovered(hass, service, discovery_info))
async def async_bridge_discovered(service, discovery_info):
"""Dispatcher for Hue discovery events."""
# Ignore emulated hue
if "HASS Bridge" in discovery_info.get('name', ''):
return
await async_setup_bridge(
hass, discovery_info['host'],
'phue-{}.conf'.format(discovery_info['serial']))
discovery.async_listen(hass, SERVICE_HUE, async_bridge_discovered)
# User has configured bridges
if CONF_BRIDGES in conf:
bridges = conf[CONF_BRIDGES]
# Component is part of config but no bridges specified, discover.
elif DOMAIN in config:
# discover from nupnp
hosts = requests.get(API_NUPNP).json()
bridges = [{
websession = aiohttp_client.async_get_clientsession(hass)
async with websession.get(API_NUPNP) as req:
hosts = await req.json()
# Run through config schema to populate defaults
bridges = [BRIDGE_CONFIG_SCHEMA({
CONF_HOST: entry['internalipaddress'],
CONF_FILENAME: '.hue_{}.conf'.format(entry['id']),
} for entry in hosts]
}) for entry in hosts]
else:
# Component not specified in config, we're loaded via discovery
bridges = []
for bridge in bridges:
filename = bridge.get(CONF_FILENAME)
allow_unreachable = bridge.get(CONF_ALLOW_UNREACHABLE)
allow_in_emulated_hue = bridge.get(CONF_ALLOW_IN_EMULATED_HUE)
allow_hue_groups = bridge.get(CONF_ALLOW_HUE_GROUPS)
if not bridges:
return True
host = bridge.get(CONF_HOST)
if host is None:
host = _find_host_from_config(hass, filename)
if host is None:
_LOGGER.error("No host found in configuration")
return False
setup_bridge(host, hass, filename, allow_unreachable,
allow_in_emulated_hue, allow_hue_groups)
await asyncio.wait([
async_setup_bridge(
hass, bridge[CONF_HOST], bridge[CONF_FILENAME],
bridge[CONF_ALLOW_UNREACHABLE], bridge[CONF_ALLOW_HUE_GROUPS]
) for bridge in bridges
])
return True
def bridge_discovered(hass, service, discovery_info):
"""Dispatcher for Hue discovery events."""
if "HASS Bridge" in discovery_info.get('name', ''):
return
host = discovery_info.get('host')
serial = discovery_info.get('serial')
filename = 'phue-{}.conf'.format(serial)
setup_bridge(host, hass, filename)
def setup_bridge(host, hass, filename=None, allow_unreachable=False,
allow_in_emulated_hue=True, allow_hue_groups=True,
username=None):
async def async_setup_bridge(
hass, host, filename=None,
allow_unreachable=DEFAULT_ALLOW_UNREACHABLE,
allow_hue_groups=DEFAULT_ALLOW_HUE_GROUPS,
username=None):
"""Set up a given Hue bridge."""
assert filename or username, 'Need to pass at least a username or filename'
# Only register a device once
if socket.gethostbyname(host) in hass.data[DOMAIN]:
if host in hass.data[DOMAIN]:
return
if username is None:
username = await hass.async_add_job(
_find_username_from_config, hass, filename)
bridge = HueBridge(host, hass, filename, username, allow_unreachable,
allow_in_emulated_hue, allow_hue_groups)
bridge.setup()
allow_hue_groups)
await bridge.async_setup()
def _find_host_from_config(hass, filename=PHUE_CONFIG_FILE):
"""Attempt to detect host based on existing configuration."""
def _find_username_from_config(hass, filename):
"""Load username from config."""
path = hass.config.path(filename)
if not os.path.isfile(path):
return None
try:
with open(path) as inp:
return next(iter(json.load(inp).keys()))
except (ValueError, AttributeError, StopIteration):
# ValueError if can't parse as JSON
# AttributeError if JSON value is not a dict
# StopIteration if no keys
return None
with open(path) as inp:
return list(json.load(inp).values())[0]['username']
class HueBridge(object):
"""Manages a single Hue bridge."""
def __init__(self, host, hass, filename, username, allow_unreachable=False,
allow_in_emulated_hue=True, allow_hue_groups=True):
def __init__(self, host, hass, filename, username,
allow_unreachable=False, allow_groups=True):
"""Initialize the system."""
self.host = host
self.bridge_id = socket.gethostbyname(host)
self.hass = hass
self.filename = filename
self.username = username
self.allow_unreachable = allow_unreachable
self.allow_in_emulated_hue = allow_in_emulated_hue
self.allow_hue_groups = allow_hue_groups
self.allow_groups = allow_groups
self.available = True
self.bridge = None
self.lights = {}
self.lightgroups = {}
self.configured = False
self.config_request_id = None
self.api = None
hass.data[DOMAIN][self.bridge_id] = self
def setup(self):
async def async_setup(self):
"""Set up a phue bridge based on host parameter."""
import phue
import aiohue
api = aiohue.Bridge(
self.host,
username=self.username,
websession=aiohttp_client.async_get_clientsession(self.hass)
)
try:
kwargs = {}
if self.username is not None:
kwargs['username'] = self.username
if self.filename is not None:
kwargs['config_file_path'] = \
self.hass.config.path(self.filename)
self.bridge = phue.Bridge(self.host, **kwargs)
except OSError: # Wrong host was given
with async_timeout.timeout(5):
# Initialize bridge and validate our username
if not self.username:
await api.create_user('home-assistant')
await api.initialize()
except (aiohue.LinkButtonNotPressed, aiohue.Unauthorized):
_LOGGER.warning("Connected to Hue at %s but not registered.",
self.host)
self.async_request_configuration()
return
except (asyncio.TimeoutError, aiohue.RequestError):
_LOGGER.error("Error connecting to the Hue bridge at %s",
self.host)
return
except phue.PhueRegistrationException:
_LOGGER.warning("Connected to Hue at %s but not registered.",
self.host)
self.request_configuration()
except aiohue.AiohueException:
_LOGGER.exception('Unknown Hue linking error occurred')
self.async_request_configuration()
return
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unknown error connecting with Hue bridge at %s",
self.host)
return
self.hass.data[DOMAIN][self.host] = self
# If we came here and configuring this host, mark as done
if self.config_request_id:
request_id = self.config_request_id
self.config_request_id = None
configurator = self.hass.components.configurator
configurator.request_done(request_id)
self.hass.components.configurator.async_request_done(request_id)
self.configured = True
self.username = api.username
discovery.load_platform(
# Save config file
await self.hass.async_add_job(
save_json, self.hass.config.path(self.filename),
{self.host: {'username': api.username}})
self.api = api
self.hass.async_add_job(discovery.async_load_platform(
self.hass, 'light', DOMAIN,
{'bridge_id': self.bridge_id})
{'host': self.host}))
# create a service for calling run_scene directly on the bridge,
# used to simplify automation rules.
def hue_activate_scene(call):
"""Service to call directly into bridge to set scenes."""
group_name = call.data[ATTR_GROUP_NAME]
scene_name = call.data[ATTR_SCENE_NAME]
self.bridge.run_scene(group_name, scene_name)
self.hass.services.register(
DOMAIN, SERVICE_HUE_SCENE, hue_activate_scene,
self.hass.services.async_register(
DOMAIN, SERVICE_HUE_SCENE, self.hue_activate_scene,
schema=SCENE_SCHEMA)
def request_configuration(self):
@callback
def async_request_configuration(self):
"""Request configuration steps from the user."""
configurator = self.hass.components.configurator
# We got an error if this method is called while we are configuring
if self.config_request_id:
configurator.notify_errors(
configurator.async_notify_errors(
self.config_request_id,
"Failed to register, please try again.")
return
self.config_request_id = configurator.request_config(
"Philips Hue",
lambda data: self.setup(),
async def config_callback(data):
"""Callback for configurator data."""
await self.async_setup()
self.config_request_id = configurator.async_request_config(
"Philips Hue", config_callback,
description=CONFIG_INSTRUCTIONS,
entity_picture="/static/images/logo_philips_hue.png",
submit_caption="I have pressed the button"
)
def get_api(self):
"""Return the full api dictionary from phue."""
return self.bridge.get_api()
async def hue_activate_scene(self, call, updated=False):
"""Service to call directly into bridge to set scenes."""
group_name = call.data[ATTR_GROUP_NAME]
scene_name = call.data[ATTR_SCENE_NAME]
def set_light(self, light_id, command):
"""Adjust properties of one or more lights. See phue for details."""
return self.bridge.set_light(light_id, command)
group = next(
(group for group in self.api.groups.values()
if group.name == group_name), None)
def set_group(self, light_id, command):
"""Change light settings for a group. See phue for detail."""
return self.bridge.set_group(light_id, command)
scene_id = next(
(scene.id for scene in self.api.scenes.values()
if scene.name == scene_name), None)
# If we can't find it, fetch latest info.
if not updated and (group is None or scene_id is None):
await self.api.groups.update()
await self.api.scenes.update()
await self.hue_activate_scene(call, updated=True)
return
if group is None:
_LOGGER.warning('Unable to find group %s', group_name)
return
if scene_id is None:
_LOGGER.warning('Unable to find scene %s', scene_name)
return
await group.set_action(scene=scene_id)
@config_entries.HANDLERS.register(DOMAIN)
@@ -305,12 +318,12 @@ class HueFlowHandler(config_entries.ConfigFlowHandler):
bridges = await discover_nupnp(websession=self._websession)
except asyncio.TimeoutError:
return self.async_abort(
reason='Unable to discover Hue bridges.'
reason='discover_timeout'
)
if not bridges:
return self.async_abort(
reason='No Philips Hue bridges discovered.'
reason='no_bridges'
)
# Find already configured hosts
@@ -323,7 +336,7 @@ class HueFlowHandler(config_entries.ConfigFlowHandler):
if not hosts:
return self.async_abort(
reason='All Philips Hue bridges are already configured.'
reason='all_configured'
)
elif len(hosts) == 1:
@@ -332,7 +345,6 @@ class HueFlowHandler(config_entries.ConfigFlowHandler):
return self.async_show_form(
step_id='init',
title='Pick Hue Bridge',
data_schema=vol.Schema({
vol.Required('host'): vol.In(hosts)
})
@@ -353,10 +365,10 @@ class HueFlowHandler(config_entries.ConfigFlowHandler):
await bridge.initialize()
except (asyncio.TimeoutError, aiohue.RequestError,
aiohue.LinkButtonNotPressed):
errors['base'] = 'Failed to register, please try again.'
errors['base'] = 'register_failed'
except aiohue.AiohueException:
errors['base'] = 'Unknown linking error occurred.'
_LOGGER.exception('Uknown Hue linking error occurred')
errors['base'] = 'linking'
_LOGGER.exception('Unknown Hue linking error occurred')
else:
return self.async_create_entry(
title=bridge.config.name,
@@ -369,15 +381,12 @@ class HueFlowHandler(config_entries.ConfigFlowHandler):
return self.async_show_form(
step_id='link',
title='Link Hub',
description=CONFIG_INSTRUCTIONS,
errors=errors,
)
async def async_setup_entry(hass, entry):
"""Set up a bridge for a config entry."""
await hass.async_add_job(partial(
setup_bridge, entry.data['host'], hass,
username=entry.data['username']))
await async_setup_bridge(hass, entry.data['host'],
username=entry.data['username'])
return True

View File

@@ -0,0 +1,26 @@
{
"config": {
"title": "Philips Hue Bridge",
"step": {
"init": {
"title": "Pick Hue bridge",
"data": {
"host": "Host"
}
},
"link": {
"title": "Link Hub",
"description": "Press the button on the bridge to register Philips Hue with Home Assistant.\n\n![Location of button on bridge](/static/images/config_philips_hue.jpg)"
}
},
"error": {
"register_failed": "Failed to register, please try again",
"linking": "Unknown linking error occurred."
},
"abort": {
"discover_timeout": "Unable to discover Hue bridges",
"no_bridges": "No Philips Hue bridges discovered",
"all_configured": "All Philips Hue bridges are already configured"
}
}
}

View File

@@ -17,7 +17,7 @@ from homeassistant.components.image_processing import (
PLATFORM_SCHEMA, ImageProcessingEntity, CONF_CONFIDENCE, CONF_SOURCE,
CONF_ENTITY_ID, CONF_NAME, ATTR_ENTITY_ID, ATTR_CONFIDENCE)
import homeassistant.helpers.config_validation as cv
from homeassistant.util.async import run_callback_threadsafe
from homeassistant.util.async_ import run_callback_threadsafe
DEPENDENCIES = ['microsoft_face']

View File

@@ -17,7 +17,7 @@ from homeassistant.const import STATE_UNKNOWN, CONF_REGION
from homeassistant.components.image_processing import (
PLATFORM_SCHEMA, ImageProcessingEntity, CONF_CONFIDENCE, CONF_SOURCE,
CONF_ENTITY_ID, CONF_NAME, ATTR_ENTITY_ID, ATTR_CONFIDENCE)
from homeassistant.util.async import run_callback_threadsafe
from homeassistant.util.async_ import run_callback_threadsafe
_LOGGER = logging.getLogger(__name__)

View File

@@ -16,7 +16,7 @@ from homeassistant.components.image_processing import (
from homeassistant.core import split_entity_id
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['numpy==1.14.0']
REQUIREMENTS = ['numpy==1.14.2']
_LOGGER = logging.getLogger(__name__)

View File

@@ -40,9 +40,8 @@ SUPPORT_BRIGHTNESS = 1
SUPPORT_COLOR_TEMP = 2
SUPPORT_EFFECT = 4
SUPPORT_FLASH = 8
SUPPORT_RGB_COLOR = 16
SUPPORT_COLOR = 16
SUPPORT_TRANSITION = 32
SUPPORT_XY_COLOR = 64
SUPPORT_WHITE_VALUE = 128
# Integer that represents transition time in seconds to make change.
@@ -51,6 +50,7 @@ ATTR_TRANSITION = "transition"
# Lists holding color values
ATTR_RGB_COLOR = "rgb_color"
ATTR_XY_COLOR = "xy_color"
ATTR_HS_COLOR = "hs_color"
ATTR_COLOR_TEMP = "color_temp"
ATTR_KELVIN = "kelvin"
ATTR_MIN_MIREDS = "min_mireds"
@@ -86,8 +86,9 @@ LIGHT_PROFILES_FILE = "light_profiles.csv"
PROP_TO_ATTR = {
'brightness': ATTR_BRIGHTNESS,
'color_temp': ATTR_COLOR_TEMP,
'rgb_color': ATTR_RGB_COLOR,
'xy_color': ATTR_XY_COLOR,
'min_mireds': ATTR_MIN_MIREDS,
'max_mireds': ATTR_MAX_MIREDS,
'hs_color': ATTR_HS_COLOR,
'white_value': ATTR_WHITE_VALUE,
'effect_list': ATTR_EFFECT_LIST,
'effect': ATTR_EFFECT,
@@ -111,6 +112,11 @@ LIGHT_TURN_ON_SCHEMA = vol.Schema({
vol.Exclusive(ATTR_XY_COLOR, COLOR_GROUP):
vol.All(vol.ExactSequence((cv.small_float, cv.small_float)),
vol.Coerce(tuple)),
vol.Exclusive(ATTR_HS_COLOR, COLOR_GROUP):
vol.All(vol.ExactSequence(
(vol.All(vol.Coerce(float), vol.Range(min=0, max=360)),
vol.All(vol.Coerce(float), vol.Range(min=0, max=100)))),
vol.Coerce(tuple)),
vol.Exclusive(ATTR_COLOR_TEMP, COLOR_GROUP):
vol.All(vol.Coerce(int), vol.Range(min=1)),
vol.Exclusive(ATTR_KELVIN, COLOR_GROUP):
@@ -149,13 +155,13 @@ def is_on(hass, entity_id=None):
@bind_hass
def turn_on(hass, entity_id=None, transition=None, brightness=None,
brightness_pct=None, rgb_color=None, xy_color=None,
brightness_pct=None, rgb_color=None, xy_color=None, hs_color=None,
color_temp=None, kelvin=None, white_value=None,
profile=None, flash=None, effect=None, color_name=None):
"""Turn all or specified light on."""
hass.add_job(
async_turn_on, hass, entity_id, transition, brightness, brightness_pct,
rgb_color, xy_color, color_temp, kelvin, white_value,
rgb_color, xy_color, hs_color, color_temp, kelvin, white_value,
profile, flash, effect, color_name)
@@ -163,8 +169,9 @@ def turn_on(hass, entity_id=None, transition=None, brightness=None,
@bind_hass
def async_turn_on(hass, entity_id=None, transition=None, brightness=None,
brightness_pct=None, rgb_color=None, xy_color=None,
color_temp=None, kelvin=None, white_value=None,
profile=None, flash=None, effect=None, color_name=None):
hs_color=None, color_temp=None, kelvin=None,
white_value=None, profile=None, flash=None, effect=None,
color_name=None):
"""Turn all or specified light on."""
data = {
key: value for key, value in [
@@ -175,6 +182,7 @@ def async_turn_on(hass, entity_id=None, transition=None, brightness=None,
(ATTR_BRIGHTNESS_PCT, brightness_pct),
(ATTR_RGB_COLOR, rgb_color),
(ATTR_XY_COLOR, xy_color),
(ATTR_HS_COLOR, hs_color),
(ATTR_COLOR_TEMP, color_temp),
(ATTR_KELVIN, kelvin),
(ATTR_WHITE_VALUE, white_value),
@@ -254,6 +262,14 @@ def preprocess_turn_on_alternatives(params):
if brightness_pct is not None:
params[ATTR_BRIGHTNESS] = int(255 * brightness_pct/100)
xy_color = params.pop(ATTR_XY_COLOR, None)
if xy_color is not None:
params[ATTR_HS_COLOR] = color_util.color_xy_to_hs(*xy_color)
rgb_color = params.pop(ATTR_RGB_COLOR, None)
if rgb_color is not None:
params[ATTR_HS_COLOR] = color_util.color_RGB_to_hs(*rgb_color)
class SetIntentHandler(intent.IntentHandler):
"""Handle set color intents."""
@@ -281,7 +297,7 @@ class SetIntentHandler(intent.IntentHandler):
if 'color' in slots:
intent.async_test_feature(
state, SUPPORT_RGB_COLOR, 'changing colors')
state, SUPPORT_COLOR, 'changing colors')
service_data[ATTR_RGB_COLOR] = slots['color']['value']
# Use original passed in value of the color because we don't have
# human readable names for that internally.
@@ -428,13 +444,8 @@ class Light(ToggleEntity):
return None
@property
def xy_color(self):
"""Return the XY color value [float, float]."""
return None
@property
def rgb_color(self):
"""Return the RGB color value [int, int, int]."""
def hs_color(self):
"""Return the hue and saturation color value [float, float]."""
return None
@property
@@ -484,11 +495,16 @@ class Light(ToggleEntity):
if value is not None:
data[attr] = value
if ATTR_RGB_COLOR not in data and ATTR_XY_COLOR in data and \
ATTR_BRIGHTNESS in data:
data[ATTR_RGB_COLOR] = color_util.color_xy_brightness_to_RGB(
data[ATTR_XY_COLOR][0], data[ATTR_XY_COLOR][1],
data[ATTR_BRIGHTNESS])
# Expose current color also as RGB and XY
if ATTR_HS_COLOR in data:
data[ATTR_RGB_COLOR] = color_util.color_hs_to_RGB(
*data[ATTR_HS_COLOR])
data[ATTR_XY_COLOR] = color_util.color_hs_to_xy(
*data[ATTR_HS_COLOR])
data[ATTR_HS_COLOR] = (
round(data[ATTR_HS_COLOR][0], 3),
round(data[ATTR_HS_COLOR][1], 3),
)
return data

View File

@@ -8,8 +8,9 @@ import logging
from homeassistant.components.abode import AbodeDevice, DOMAIN as ABODE_DOMAIN
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_RGB_COLOR,
SUPPORT_BRIGHTNESS, SUPPORT_RGB_COLOR, Light)
ATTR_BRIGHTNESS, ATTR_HS_COLOR,
SUPPORT_BRIGHTNESS, SUPPORT_COLOR, Light)
import homeassistant.util.color as color_util
DEPENDENCIES = ['abode']
@@ -44,10 +45,12 @@ class AbodeLight(AbodeDevice, Light):
def turn_on(self, **kwargs):
"""Turn on the light."""
if (ATTR_RGB_COLOR in kwargs and
if (ATTR_HS_COLOR in kwargs and
self._device.is_dimmable and self._device.has_color):
self._device.set_color(kwargs[ATTR_RGB_COLOR])
elif ATTR_BRIGHTNESS in kwargs and self._device.is_dimmable:
self._device.set_color(color_util.color_hs_to_RGB(
*kwargs[ATTR_HS_COLOR]))
if ATTR_BRIGHTNESS in kwargs and self._device.is_dimmable:
self._device.set_level(kwargs[ATTR_BRIGHTNESS])
else:
self._device.switch_on()
@@ -68,16 +71,16 @@ class AbodeLight(AbodeDevice, Light):
return self._device.brightness
@property
def rgb_color(self):
def hs_color(self):
"""Return the color of the light."""
if self._device.is_dimmable and self._device.has_color:
return self._device.color
return color_util.color_RGB_to_hs(*self._device.color)
@property
def supported_features(self):
"""Flag supported features."""
if self._device.is_dimmable and self._device.has_color:
return SUPPORT_BRIGHTNESS | SUPPORT_RGB_COLOR
return SUPPORT_BRIGHTNESS | SUPPORT_COLOR
elif self._device.is_dimmable:
return SUPPORT_BRIGHTNESS

View File

@@ -9,9 +9,11 @@ import logging
import voluptuous as vol
from homeassistant.components.light import (
ATTR_RGB_COLOR, SUPPORT_RGB_COLOR, Light, PLATFORM_SCHEMA)
ATTR_BRIGHTNESS, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, Light,
PLATFORM_SCHEMA)
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
import homeassistant.util.color as color_util
REQUIREMENTS = ['blinkstick==1.1.8']
@@ -21,7 +23,7 @@ CONF_SERIAL = 'serial'
DEFAULT_NAME = 'Blinkstick'
SUPPORT_BLINKSTICK = SUPPORT_RGB_COLOR
SUPPORT_BLINKSTICK = SUPPORT_BRIGHTNESS | SUPPORT_COLOR
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_SERIAL): cv.string,
@@ -39,7 +41,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
stick = blinkstick.find_by_serial(serial)
add_devices([BlinkStickLight(stick, name)])
add_devices([BlinkStickLight(stick, name)], True)
class BlinkStickLight(Light):
@@ -50,7 +52,8 @@ class BlinkStickLight(Light):
self._stick = stick
self._name = name
self._serial = stick.get_serial()
self._rgb_color = stick.get_color()
self._hs_color = None
self._brightness = None
@property
def should_poll(self):
@@ -63,14 +66,19 @@ class BlinkStickLight(Light):
return self._name
@property
def rgb_color(self):
def brightness(self):
"""Read back the brightness of the light."""
return self._brightness
@property
def hs_color(self):
"""Read back the color of the light."""
return self._rgb_color
return self._hs_color
@property
def is_on(self):
"""Check whether any of the LEDs colors are non-zero."""
return sum(self._rgb_color) > 0
"""Return True if entity is on."""
return self._brightness > 0
@property
def supported_features(self):
@@ -79,18 +87,24 @@ class BlinkStickLight(Light):
def update(self):
"""Read back the device state."""
self._rgb_color = self._stick.get_color()
rgb_color = self._stick.get_color()
hsv = color_util.color_RGB_to_hsv(*rgb_color)
self._hs_color = hsv[:2]
self._brightness = hsv[2]
def turn_on(self, **kwargs):
"""Turn the device on."""
if ATTR_RGB_COLOR in kwargs:
self._rgb_color = kwargs[ATTR_RGB_COLOR]
if ATTR_HS_COLOR in kwargs:
self._hs_color = kwargs[ATTR_HS_COLOR]
if ATTR_BRIGHTNESS in kwargs:
self._brightness = kwargs[ATTR_BRIGHTNESS]
else:
self._rgb_color = [255, 255, 255]
self._brightness = 255
self._stick.set_color(red=self._rgb_color[0],
green=self._rgb_color[1],
blue=self._rgb_color[2])
rgb_color = color_util.color_hsv_to_RGB(
self._hs_color[0], self._hs_color[1], self._brightness / 255 * 100)
self._stick.set_color(
red=rgb_color[0], green=rgb_color[1], blue=rgb_color[2])
def turn_off(self, **kwargs):
"""Turn the device off."""

View File

@@ -10,15 +10,16 @@ import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.light import (
ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, ATTR_RGB_COLOR, SUPPORT_RGB_COLOR,
ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, ATTR_HS_COLOR, SUPPORT_COLOR,
Light, PLATFORM_SCHEMA)
from homeassistant.const import CONF_NAME
import homeassistant.util.color as color_util
REQUIREMENTS = ['blinkt==0.1.0']
_LOGGER = logging.getLogger(__name__)
SUPPORT_BLINKT = (SUPPORT_BRIGHTNESS | SUPPORT_RGB_COLOR)
SUPPORT_BLINKT = (SUPPORT_BRIGHTNESS | SUPPORT_COLOR)
DEFAULT_NAME = 'blinkt'
@@ -55,7 +56,7 @@ class BlinktLight(Light):
self._index = index
self._is_on = False
self._brightness = 255
self._rgb_color = [255, 255, 255]
self._hs_color = [0, 0]
@property
def name(self):
@@ -71,12 +72,9 @@ class BlinktLight(Light):
return self._brightness
@property
def rgb_color(self):
"""Read back the color of the light.
Returns [r, g, b] list with values in range of 0-255.
"""
return self._rgb_color
def hs_color(self):
"""Read back the color of the light."""
return self._hs_color
@property
def supported_features(self):
@@ -100,16 +98,17 @@ class BlinktLight(Light):
def turn_on(self, **kwargs):
"""Instruct the light to turn on and set correct brightness & color."""
if ATTR_RGB_COLOR in kwargs:
self._rgb_color = kwargs[ATTR_RGB_COLOR]
if ATTR_HS_COLOR in kwargs:
self._hs_color = kwargs[ATTR_HS_COLOR]
if ATTR_BRIGHTNESS in kwargs:
self._brightness = kwargs[ATTR_BRIGHTNESS]
percent_bright = (self._brightness / 255)
rgb_color = color_util.color_hs_to_RGB(*self._hs_color)
self._blinkt.set_pixel(self._index,
self._rgb_color[0],
self._rgb_color[1],
self._rgb_color[2],
rgb_color[0],
rgb_color[1],
rgb_color[2],
percent_bright)
self._blinkt.show()

View File

@@ -4,23 +4,21 @@ Support for deCONZ light.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/light.deconz/
"""
import asyncio
from homeassistant.components.deconz import (
DOMAIN as DATA_DECONZ, DATA_DECONZ_ID)
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_RGB_COLOR,
ATTR_TRANSITION, ATTR_XY_COLOR, EFFECT_COLORLOOP, FLASH_LONG, FLASH_SHORT,
SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_FLASH,
SUPPORT_RGB_COLOR, SUPPORT_TRANSITION, SUPPORT_XY_COLOR, Light)
ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_HS_COLOR,
ATTR_TRANSITION, EFFECT_COLORLOOP, FLASH_LONG, FLASH_SHORT,
SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT,
SUPPORT_FLASH, SUPPORT_TRANSITION, Light)
from homeassistant.core import callback
from homeassistant.util.color import color_RGB_to_xy
import homeassistant.util.color as color_util
DEPENDENCIES = ['deconz']
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Set up the deCONZ light."""
if discovery_info is None:
return
@@ -53,14 +51,12 @@ class DeconzLight(Light):
self._features |= SUPPORT_COLOR_TEMP
if self._light.xy is not None:
self._features |= SUPPORT_RGB_COLOR
self._features |= SUPPORT_XY_COLOR
self._features |= SUPPORT_COLOR
if self._light.effect is not None:
self._features |= SUPPORT_EFFECT
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Subscribe to lights events."""
self._light.register_async_callback(self.async_update_callback)
self.hass.data[DATA_DECONZ_ID][self.entity_id] = self._light.deconz_id
@@ -120,22 +116,15 @@ class DeconzLight(Light):
"""No polling needed."""
return False
@asyncio.coroutine
def async_turn_on(self, **kwargs):
async def async_turn_on(self, **kwargs):
"""Turn on light."""
data = {'on': True}
if ATTR_COLOR_TEMP in kwargs:
data['ct'] = kwargs[ATTR_COLOR_TEMP]
if ATTR_RGB_COLOR in kwargs:
xyb = color_RGB_to_xy(
*(int(val) for val in kwargs[ATTR_RGB_COLOR]))
data['xy'] = xyb[0], xyb[1]
data['bri'] = xyb[2]
if ATTR_XY_COLOR in kwargs:
data['xy'] = kwargs[ATTR_XY_COLOR]
if ATTR_HS_COLOR in kwargs:
data['xy'] = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR])
if ATTR_BRIGHTNESS in kwargs:
data['bri'] = kwargs[ATTR_BRIGHTNESS]
@@ -157,10 +146,9 @@ class DeconzLight(Light):
else:
data['effect'] = 'none'
yield from self._light.async_set_state(data)
await self._light.async_set_state(data)
@asyncio.coroutine
def async_turn_off(self, **kwargs):
async def async_turn_off(self, **kwargs):
"""Turn off light."""
data = {'on': False}
@@ -176,4 +164,4 @@ class DeconzLight(Light):
data['alert'] = 'lselect'
del data['on']
yield from self._light.async_set_state(data)
await self._light.async_set_state(data)

View File

@@ -7,14 +7,13 @@ https://home-assistant.io/components/demo/
import random
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT,
ATTR_RGB_COLOR, ATTR_WHITE_VALUE, ATTR_XY_COLOR, SUPPORT_BRIGHTNESS,
SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_RGB_COLOR, SUPPORT_WHITE_VALUE,
Light)
ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_HS_COLOR,
ATTR_WHITE_VALUE, SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT,
SUPPORT_COLOR, SUPPORT_WHITE_VALUE, Light)
LIGHT_COLORS = [
[237, 224, 33],
[255, 63, 111],
(56, 86),
(345, 75),
]
LIGHT_EFFECT_LIST = ['rainbow', 'none']
@@ -22,7 +21,7 @@ LIGHT_EFFECT_LIST = ['rainbow', 'none']
LIGHT_TEMPS = [240, 380]
SUPPORT_DEMO = (SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_EFFECT |
SUPPORT_RGB_COLOR | SUPPORT_WHITE_VALUE)
SUPPORT_COLOR | SUPPORT_WHITE_VALUE)
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
@@ -40,17 +39,16 @@ def setup_platform(hass, config, add_devices_callback, discovery_info=None):
class DemoLight(Light):
"""Representation of a demo light."""
def __init__(self, unique_id, name, state, available=False, rgb=None,
ct=None, brightness=180, xy_color=(.5, .5), white=200,
effect_list=None, effect=None):
def __init__(self, unique_id, name, state, available=False, hs_color=None,
ct=None, brightness=180, white=200, effect_list=None,
effect=None):
"""Initialize the light."""
self._unique_id = unique_id
self._name = name
self._state = state
self._rgb = rgb
self._hs_color = hs_color
self._ct = ct or random.choice(LIGHT_TEMPS)
self._brightness = brightness
self._xy_color = xy_color
self._white = white
self._effect_list = effect_list
self._effect = effect
@@ -84,14 +82,9 @@ class DemoLight(Light):
return self._brightness
@property
def xy_color(self) -> tuple:
"""Return the XY color value [float, float]."""
return self._xy_color
@property
def rgb_color(self) -> tuple:
"""Return the RBG color value."""
return self._rgb
def hs_color(self) -> tuple:
"""Return the hs color value."""
return self._hs_color
@property
def color_temp(self) -> int:
@@ -127,8 +120,8 @@ class DemoLight(Light):
"""Turn the light on."""
self._state = True
if ATTR_RGB_COLOR in kwargs:
self._rgb = kwargs[ATTR_RGB_COLOR]
if ATTR_HS_COLOR in kwargs:
self._hs_color = kwargs[ATTR_HS_COLOR]
if ATTR_COLOR_TEMP in kwargs:
self._ct = kwargs[ATTR_COLOR_TEMP]
@@ -136,9 +129,6 @@ class DemoLight(Light):
if ATTR_BRIGHTNESS in kwargs:
self._brightness = kwargs[ATTR_BRIGHTNESS]
if ATTR_XY_COLOR in kwargs:
self._xy_color = kwargs[ATTR_XY_COLOR]
if ATTR_WHITE_VALUE in kwargs:
self._white = kwargs[ATTR_WHITE_VALUE]

View File

@@ -12,10 +12,11 @@ import voluptuous as vol
from homeassistant.const import CONF_DEVICES, CONF_NAME, CONF_PROTOCOL
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ATTR_EFFECT, EFFECT_COLORLOOP,
ATTR_BRIGHTNESS, ATTR_HS_COLOR, ATTR_EFFECT, EFFECT_COLORLOOP,
EFFECT_RANDOM, SUPPORT_BRIGHTNESS, SUPPORT_EFFECT,
SUPPORT_RGB_COLOR, Light, PLATFORM_SCHEMA)
SUPPORT_COLOR, Light, PLATFORM_SCHEMA)
import homeassistant.helpers.config_validation as cv
import homeassistant.util.color as color_util
REQUIREMENTS = ['flux_led==0.21']
@@ -27,7 +28,7 @@ ATTR_MODE = 'mode'
DOMAIN = 'flux_led'
SUPPORT_FLUX_LED = (SUPPORT_BRIGHTNESS | SUPPORT_EFFECT |
SUPPORT_RGB_COLOR)
SUPPORT_COLOR)
MODE_RGB = 'rgb'
MODE_RGBW = 'rgbw'
@@ -183,9 +184,9 @@ class FluxLight(Light):
return self._bulb.brightness
@property
def rgb_color(self):
def hs_color(self):
"""Return the color property."""
return self._bulb.getRgb()
return color_util.color_RGB_to_hs(*self._bulb.getRgb())
@property
def supported_features(self):
@@ -202,7 +203,8 @@ class FluxLight(Light):
if not self.is_on:
self._bulb.turnOn()
rgb = kwargs.get(ATTR_RGB_COLOR)
hs_color = kwargs.get(ATTR_HS_COLOR)
rgb = color_util.color_hs_to_RGB(*hs_color)
brightness = kwargs.get(ATTR_BRIGHTNESS)
effect = kwargs.get(ATTR_EFFECT)

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