Compare commits

...

119 Commits

Author SHA1 Message Date
Paulus Schoutsen b3454bfd9c 2023.1.2 (#85481) 2023-01-08 21:44:13 -05:00
Paulus Schoutsen 834847988d Bumped version to 2023.1.2 2023-01-08 20:24:25 -05:00
Allen Porter caf15534bb Bump gcal_sync to 4.1.1 (#85453) 2023-01-08 20:24:19 -05:00
Allen Porter 10cb2e31c4 Bump ical to 4.2.9 (#85401) 2023-01-08 20:24:18 -05:00
Lutz Lengemann 85c9f9facf Increase Hydrawise default scan interval (#85398)
Increasing default scan interval

Fixes #83540
2023-01-08 20:24:17 -05:00
J. Nick Koston 5ff7b3bb1a Bump pySwitchbot to 0.36.3 (#85360) 2023-01-08 20:24:16 -05:00
J. Nick Koston e5ba423d6d Add note to SwitchBot locks that usernames are case sensitive (#85359) 2023-01-08 20:24:15 -05:00
puddly b30d4ef7cf Bump ZHA dependencies (#85355)
* Bump ZHA dependencies

* Deprecated `foundation.Command` -> `foundation.GeneralCommand`
2023-01-08 20:24:15 -05:00
Joakim Plate 00e563f1b8 Switch play pause method in philips js (#85343)
fixes undefined
2023-01-08 20:24:14 -05:00
Phil Bruckner cf06f3b81d Bump life360 package to 5.5.0 (#85322)
Improve debug output & redact sensitive info from log.
Fix bug that was masking some HTTP errors.
Retry HTTP errors 502, 503 & 504, which have been observed to happen every once
in a while, resulting in fewer unnecessary unavailable states.
2023-01-08 20:24:13 -05:00
starkillerOG a781fcca86 Bump reolink-aio to 0.1.3 (#85309)
bump reolink-aio to 0.1.3
2023-01-08 20:24:12 -05:00
Tom Puttemans 764550f2e1 Fix dsmr_reader peak hour consumption unit of measurement (#85301) 2023-01-08 20:24:11 -05:00
puddly 7396bcc585 Retry ZHA config entry setup when ENETUNREACH is caught (#84615)
* The config entry is not ready on `ENETUNREACH`

* Use new `TransientConnectionError` from zigpy
2023-01-08 20:20:26 -05:00
epenet 7e6b087773 Allow SensorDeviceClass.POWER_FACTOR unit None (#85287)
Co-authored-by: Erik Montnemery <erik@montnemery.com>
2023-01-06 09:27:02 +01:00
Paulus Schoutsen 71ce7373a3 2023.1.1 (#85277) 2023-01-05 23:18:21 -05:00
Paulus Schoutsen 33bb9c230b Bumped version to 2023.1.1 2023-01-05 22:24:17 -05:00
Charles Garwood f0f2c12d91 Fix Fully Kiosk service call config entry handling (#85275)
* Make sure we're getting the fully_kiosk config entry

* Make sure we're getting the fully_kiosk config entry
2023-01-05 22:23:52 -05:00
J. Nick Koston 2840821594 Reject the WiFI AP when considering to update a shelly config entry from zeroconf (#85265)
Reject the WiFI AP IP when considering to update a shelly config entry from zeroconf

fixes #85180
2023-01-05 22:23:51 -05:00
rikroe edfd83c3a7 Bump bimmer_connected to 0.12.0 (#85255)
* Bump bimmer_connected to 0.12.0

* Fix mypy

* Remove not needed code

Co-authored-by: rikroe <rikroe@users.noreply.github.com>
2023-01-05 22:23:51 -05:00
starkillerOG ee88f34a91 bump reolink-aio to 0.1.2 (#85247) 2023-01-05 22:22:35 -05:00
J. Nick Koston fa4c250001 Improve error reporting when switchbot auth fails (#85244)
* Improve error reporting when switchbot auth fails

related issue #85243

* bump

* coverage
2023-01-05 22:21:55 -05:00
Franck Nijhof 59d6f827c3 Fix device class for DSMR gas sensors providing energy readings (#85202) 2023-01-05 22:18:30 -05:00
epenet 26ea02aa8f Remove invalid device class for RSSI sensors (#85191)
* Remove invalid device class for RRSI sensors

* Restore state class
2023-01-05 22:18:29 -05:00
epenet d73b86132b Adjust valid energy units (#85190) 2023-01-05 22:18:28 -05:00
Franck Nijhof 8034faadca Remove invalid AQI unit from Environment Canada (#85183) 2023-01-05 22:18:27 -05:00
Erik Montnemery 3c2b7c0d69 Bump hatasmota to 0.6.2 (#85182) 2023-01-05 22:18:26 -05:00
Ernst Klamer 563ad02c65 Bump bthome-ble to 2.4.1 (#85153)
fix https://github.com/home-assistant/core/issues/85142
fixes undefined
2023-01-05 22:15:13 -05:00
Michal Čihař fe89b663e7 Fix lacrosse_view fetching of latest data (#85117)
lacrosse_view: fixed fetching of latest data

When using datetime.utcnow(), it only replaces timezone information with
UTC making the actual time offset by the timezone. When you are in UTC-
timezones, it makes no issue as the offset is in the future, but when in
UTC+, the last hour(s) of data are missing.

This commits swtiches to time.time() as UTC timestamp is actually what
the API expects.

It also reduces the window to one hour what noticeably improves the API
performance.
2023-01-05 22:15:12 -05:00
William Scanlon dcd07d3135 Bump pyeconet to 0.1.18 to fix energy usage (#85094) 2023-01-05 22:15:11 -05:00
Robert Svensson 8bf2299407 Only subscribe to relevant IDs for state updates (#85252)
Make sure to only subscribe to the relevant ID
2023-01-05 21:49:22 -05:00
Robert Svensson 9c689d757c Limit calls in UniFi to write state (#85248)
Limit calls to write state to when relevant
2023-01-05 15:38:24 -05:00
Franck Nijhof 4e4fc1767f 2023.1.0 (#85120) 2023-01-04 20:47:22 +01:00
Martin Hjelmare cc3c5772c5 Fix Z-Wave JS sensor units and device classes (#85129)
fixes undefined
2023-01-04 19:47:59 +01:00
J. Nick Koston 6ba6991ecd Bump home-assistant-bluetooth to 1.9.2 (#85123) 2023-01-04 18:36:15 +01:00
Franck Nijhof d52d068469 Merge branch 'master' into rc 2023-01-04 17:09:15 +01:00
Franck Nijhof 09b3611a63 Bumped version to 2023.1.0 2023-01-04 17:05:21 +01:00
Joakim Sørensen ab2f05d3e9 Handle zone exception when setting up Cloudflare (#85110) 2023-01-04 17:04:43 +01:00
Guido Schmitz 90ac0c870f Remove illuminance device class for sensors in devolo Home Control (#85108) 2023-01-04 17:04:40 +01:00
Bram Kragten 0fd113db59 Update frontend to 20230104.0 (#85107) 2023-01-04 17:04:35 +01:00
Jan Bouwhuis 1b43323f5e Allow MQTT device_class or state_class to be set as None (#85106)
* Allow MQTT device_class to be set as `None`

* Add test

* Also allow sensor state_class to be `None`
2023-01-04 17:04:30 +01:00
Jan Bouwhuis 6108e581b1 Do not reset current selection on reconfig or MQTT select (#85099)
* Do not reset current selection on reconfig

* Add a test
2023-01-04 11:54:27 +01:00
Aaron Bach c8c68f05ec Remove workaround for reloading PurpleAir upon device removal (#85086) 2023-01-04 11:53:06 +01:00
Franck Nijhof b80467dc58 Update adguard to 0.6.1 (#85052)
* Update adguard to 0.6.0

* Update adguard to 0.6.1
2023-01-04 11:49:16 +01:00
Andre Lengwenus 6e9f0eca03 Fix integer only LCN variable values (#85035) 2023-01-04 11:49:10 +01:00
Paulus Schoutsen cc6a2f0338 2022.12.9 (#85030) 2023-01-02 22:06:36 -05:00
J. Nick Koston 6ebf2ec9ec Fix failing HomeKit Controller diagnostics tests (#84936) 2023-01-02 22:05:25 -05:00
Paulus Schoutsen 9ecee11af6 Bumped version to 2023.1.0b5 2023-01-02 21:30:16 -05:00
J. Nick Koston 9a1669103b Fix bluetooth not being loaded with esphome proxies when removed from default_config (#85032)
* Fix bluetooth not being loaded with esphome proxies when removed from default_config

fixes #84960

* actually commit the conftest change
2023-01-02 21:30:02 -05:00
Paulus Schoutsen 368ea0586d Bump slixmpp to 1.8.3 (#85031) 2023-01-02 21:30:01 -05:00
J. Nick Koston 4a7db6ee71 Bump httpx to 0.23.2 (#85023)
changelogs:
https://github.com/encode/httpcore/compare/0.16.2...0.16.3
https://github.com/encode/httpx/compare/0.23.1...0.23.2
2023-01-02 21:30:00 -05:00
Tobias Sauerwein a10b9572c7 Bump pyatmo to v7.5.0 (#85016) 2023-01-02 21:29:59 -05:00
starkillerOG 0b47bf1f0b Switch to reolink-aio (#85014)
* switch to reolink-aio

* fix imports
2023-01-02 21:29:58 -05:00
Bram Kragten 5f4d286556 Update frontend to 20230102.0 (#85010)
Co-authored-by: Franck Nijhof <git@frenck.dev>
2023-01-02 21:29:57 -05:00
Daniel Hjelseth Høyer b23ab3c65a Update Tibber lib to 0.26.7. Improve error handling of realtime data (#85008) 2023-01-02 21:29:56 -05:00
J. Nick Koston 7c199b36f8 Bump home-assistant-bluetooth to 1.9.1 (#85005)
fixes #83722
2023-01-02 21:29:55 -05:00
David F. Mulcahey d4e55ee030 Bump ZHA quirks (#85004) 2023-01-02 21:29:55 -05:00
starkillerOG f3ec82543e Bump motionblinds to 0.6.15 (#84994) 2023-01-02 21:29:54 -05:00
Erik Montnemery 4013d4c48d Revert "Add aliases to device registry items" (#84976) 2023-01-02 21:29:53 -05:00
Martin Hjelmare 93ac908776 Handle not available add-on in hassio add-on manager (#84943)
* Handle not available add-on in hassio add-on manager

* Fix zwave_js tests

* Fix sky connect tests

* Fix matter tests

* Fix yellow tests

* Update hardware tests
2023-01-02 21:29:52 -05:00
starkillerOG 2ad1a53038 Consider 95% as closed for Motion blinds venetian blinds (#84872) 2023-01-02 21:29:51 -05:00
Paulus Schoutsen 3ba59fbebe Bumped version to 2022.12.9 2023-01-02 20:30:09 -05:00
Martin Hjelmare f3fab5c1f5 Handle not available add-on in hassio add-on manager (#84943)
* Handle not available add-on in hassio add-on manager

* Fix zwave_js tests

* Fix sky connect tests

* Fix matter tests

* Fix yellow tests

* Update hardware tests
2023-01-02 20:30:03 -05:00
Paulus Schoutsen 2d120cb6ba Bumped version to 2023.1.0b4 2023-01-01 20:25:29 -05:00
Allen Porter ad782166c7 Fix caldav calendars with custom timezones (#84955)
* Fix caldav calendars with custom timezones

* Revert whitespace change
2023-01-01 20:23:33 -05:00
J. Nick Koston bc9202cf02 Bump pySwitchbot to 0.36.1 (#84937)
changelog: https://github.com/Danielhiversen/pySwitchbot/compare/0.36.0...0.36.1

small fix for the battery not updating with passive scanning
after lock operation
2023-01-01 20:23:32 -05:00
J. Nick Koston 0d385d3b67 Fix failing HomeKit Controller diagnostics tests (#84936) 2023-01-01 20:23:31 -05:00
Allen Porter 76fa24aba1 Fix Climate device HVAC mode trigger UI (#84930)
* Fix Climate device HVAC mode trigger UI

* Use updated order of test case results
2023-01-01 20:23:30 -05:00
ChopperRob 95ae37cd87 Fix haveibeenpwned user-agent string (#84919)
* Fixed user-agent string not being accepted as an valid header

* Update homeassistant/components/haveibeenpwned/sensor.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Removed the aiohttp import

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
2023-01-01 20:22:56 -05:00
Robert Svensson bc1d22f4ec Bump pydeconz to v106 (#84914)
fixes undefined
2023-01-01 20:20:15 -05:00
Allen Porter 67e1872ab6 Fix free/busy google calendars (#84907)
fixes undefined
2023-01-01 20:20:14 -05:00
tronikos 516c2b0cdb Google Assistant SDK: Log command and response (#84904)
Log command and response
2023-01-01 20:20:13 -05:00
Aaron Bach 60f067b68f Use serial number for AirVisal Pro config entry unique ID (#84902)
* Use serial number for AirVisal Pro config entry unique ID

* Code review
2023-01-01 20:20:13 -05:00
Aaron Bach ff76567061 Fix issues with PurpleAir sensor device class and unit (#84896) 2023-01-01 20:20:12 -05:00
Aaron Bach 93488cfa0f Don't include distance in PurpleAir sensor selector (#84893) 2023-01-01 20:20:11 -05:00
J. Nick Koston 9655619667 Small fixes for SwitchBot Locks (#84888)
Co-authored-by: Aaron Bach <bachya1208@gmail.com>
2023-01-01 20:20:10 -05:00
starkillerOG 32736b3336 Process late feedback for Reolink (#84884)
Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
2023-01-01 20:20:09 -05:00
starkillerOG c77b78928e Bump motionblinds to 0.6.14 (#84873) 2023-01-01 20:20:08 -05:00
William Scanlon a7ba242f1f Bump pyeconet to 0.1.17 (#84868) 2023-01-01 20:20:08 -05:00
Greg Dowling 043d58d697 Bump pyroon library to 0.1.2. (#84865) 2023-01-01 20:20:07 -05:00
Robert Svensson 6408890543 Bump aiounifi to v43 (#84864) 2023-01-01 20:20:06 -05:00
Franck Nijhof c5f7d7ae85 Only reflect unavailable state in DSMR when disconnected (#84862)
* Only reflect unavailable state in DSMR when disonnected

* Addressreview comment
2023-01-01 20:20:05 -05:00
Franck Nijhof 7ab27cd9bf Do not validate device classes when entity state is unknown (#84860) 2023-01-01 20:20:04 -05:00
Artem Draft 9932c0cb91 Bump pybravia to 0.2.5 (#84835) 2023-01-01 20:20:03 -05:00
Aaron Bach 565d4f85c1 Ensure AirVisual Pro migration includes device and entity customizations (#84798)
* Ensure AirVisual Pro migration includes device and entity customizations

* Update homeassistant/components/airvisual/__init__.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Code review

* Fix tests

* Fix tests FOR REAL

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
2023-01-01 20:20:02 -05:00
Franck Nijhof 7be60d4569 Bumped version to 2023.1.0b3 2022-12-30 16:50:35 +01:00
Franck Nijhof a50622cbfd Add availability property to DSMR sensors (#84848) 2022-12-30 16:49:35 +01:00
Bram Kragten fb41b024c0 Update frontend to 20221230.0 (#84842) 2022-12-30 16:49:31 +01:00
Artem Draft 80ac4c0269 Redesign and refactor Bravia TV config_flow (#84832)
fixes undefined
2022-12-30 16:49:27 +01:00
Damian Sypniewski 0e0677b690 Add option to retrieve SwitchBot Lock encryption key through config flow (#84830)
Co-authored-by: J. Nick Koston <nick@koston.org>
2022-12-30 16:48:39 +01:00
SukramJ 50d9e3efe6 Add mA to SensorDeviceClass.CURRENT units (#84492)
fixes undefined
2022-12-30 16:45:39 +01:00
Jan Bouwhuis ca28006d76 Add mV as a unit for voltage and enable conversions (#84805)
fixes undefined
2022-12-30 16:41:51 +01:00
Phil Cole ac3711e6ab Use pycarwings2 2.14 (#84792)
fixes undefined
2022-12-30 16:40:22 +01:00
epenet 5901964bf6 Enable unit conversion for DATA_SIZE (#84699) 2022-12-30 16:40:19 +01:00
epenet b24c40f2df Enable unit conversion for DATA_RATE (#84698) 2022-12-30 16:40:16 +01:00
Chris Straffon 2cb7a80f98 Fix growatt identification issue (#84628)
Fixes https://github.com/home-assistant/core/issues/84600
fixes undefined
2022-12-30 16:40:11 +01:00
Steven Looman f05de2b28c Actually try port when finding next available port for ssdp server (#84206)
fixes undefined
2022-12-30 16:29:17 +01:00
Paulus Schoutsen d9aff9d7b0 Bumped version to 2023.1.0b2 2022-12-29 20:55:27 -05:00
shbatm 46e11c2fa8 ISY994: Bump PyISY to 3.0.10 (#84821) 2022-12-29 20:54:48 -05:00
J. Nick Koston 522477d5a4 Fix thermobeacon WS08 models that identify with manufacturer_id 27 (#84812)
fixes #84706
2022-12-29 20:54:47 -05:00
Joakim Plate cc2b592221 Correct missing alarm reset button on nibe (#84809)
fixes undefined
2022-12-29 20:54:46 -05:00
Aaron Bach bd86111dd8 Fix AirVisual Pro sensors with incorrect units for their device classes (#84800) 2022-12-29 20:54:45 -05:00
Michael f0514008fa Deprecate YAML config in PI-Hole (#84797)
create an issue about deprecated yaml config
2022-12-29 20:54:44 -05:00
Aaron Bach 3c8a66abbe Don't attempt setup on migrated AirVisual Pro in the airvisual domain (#84796)
fixes undefined
2022-12-29 20:54:44 -05:00
Aaron Bach f1d509be03 Remove ozone device class from OpenUV sensor (#84791)
fixes undefined
2022-12-29 20:54:43 -05:00
Robert Svensson fbdc7d44bc Only subscribe to specific UniFi object ID (#84787) 2022-12-29 20:54:42 -05:00
Hans Oischinger cae386465e Catch vicare errors when deactivating preset fails (#84778)
vicare: catch errors when deactivating preset fails
2022-12-29 20:54:41 -05:00
Allen Porter 31847e3a69 Check google calendar API scope to determine if write access is enabled (#84749)
* Check google calendar API scope to determine if write access is enabled

* Add API scope for calendar service for creating events
2022-12-29 20:54:40 -05:00
Jc2k 5787e1506c Fix UUID normalisation for vendor extensions in homekit_controller thread transport (#84746) 2022-12-29 20:54:39 -05:00
starkillerOG 9a29f64128 Bump pynetgear to 0.10.9 (#84733) 2022-12-29 20:54:38 -05:00
Tomas Kislan 6c0e4a9e8f Fix and upgrade minio integration (#84545)
closes https://github.com/home-assistant/core/issues/79842
2022-12-29 20:54:37 -05:00
Franck Nijhof 9ce64f8990 Bumped version to 2023.1.0b1 2022-12-28 22:18:06 +01:00
Aaron Bach 6ef4086683 Fix incorrect values for AirVisual Pro sensors (#84725) 2022-12-28 22:16:22 +01:00
Aaron Bach b146f52317 Remove incorrect unit for AirVisual AQI sensor (#84723)
fixes undefined
2022-12-28 22:16:19 +01:00
Hans Oischinger 001bd78bcb water_heater: Add unsupported states (#84720) 2022-12-28 22:16:16 +01:00
Allen Porter ba4ec8f8c1 Gracefully handle caldav event with missing summary (#84719)
fixes undefined
2022-12-28 22:16:12 +01:00
Michael 8aa3a6cc15 Remove deprecated tankerkoenig YAML config (#84711)
remove yaml import
2022-12-28 22:16:09 +01:00
Hmmbob ed43e1d3a4 Update apprise to 1.2.1 (#84705) 2022-12-28 22:16:06 +01:00
Marcel van der Veldt b7654c0fce Bump python matter server to 1.0.8 (#84692)
Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
2022-12-28 22:16:02 +01:00
Franck Nijhof 99f3cfdf8a Bumped version to 2023.1.0b0 2022-12-28 16:51:38 +01:00
166 changed files with 2130 additions and 1180 deletions
+2 -2
View File
@@ -947,8 +947,8 @@ build.json @home-assistant/supervisor
/tests/components/remote/ @home-assistant/core
/homeassistant/components/renault/ @epenet
/tests/components/renault/ @epenet
/homeassistant/components/reolink/ @starkillerOG @JimStar
/tests/components/reolink/ @starkillerOG @JimStar
/homeassistant/components/reolink/ @starkillerOG
/tests/components/reolink/ @starkillerOG
/homeassistant/components/repairs/ @home-assistant/core
/tests/components/repairs/ @home-assistant/core
/homeassistant/components/repetier/ @MTrab @ShadowBr0ther
@@ -3,7 +3,7 @@
"name": "AdGuard Home",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/adguard",
"requirements": ["adguardhome==0.5.1"],
"requirements": ["adguardhome==0.6.1"],
"codeowners": ["@frenck"],
"iot_class": "local_polling",
"integration_type": "service",
+67 -40
View File
@@ -32,6 +32,7 @@ from homeassistant.helpers import (
aiohttp_client,
config_validation as cv,
device_registry as dr,
entity_registry as er,
)
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
@@ -117,36 +118,6 @@ def async_get_geography_id(geography_dict: Mapping[str, Any]) -> str:
)
@callback
def async_get_pro_config_entry_by_ip_address(
hass: HomeAssistant, ip_address: str
) -> ConfigEntry:
"""Get the Pro config entry related to an IP address."""
[config_entry] = [
entry
for entry in hass.config_entries.async_entries(DOMAIN_AIRVISUAL_PRO)
if entry.data[CONF_IP_ADDRESS] == ip_address
]
return config_entry
@callback
def async_get_pro_device_by_config_entry(
hass: HomeAssistant, config_entry: ConfigEntry
) -> dr.DeviceEntry:
"""Get the Pro device entry related to a config entry.
Note that a Pro config entry can only contain a single device.
"""
device_registry = dr.async_get(hass)
[device_entry] = [
device_entry
for device_entry in device_registry.devices.values()
if config_entry.entry_id in device_entry.config_entries
]
return device_entry
@callback
def async_sync_geo_coordinator_update_intervals(
hass: HomeAssistant, api_key: str
@@ -207,6 +178,11 @@ def _standardize_geography_config_entry(
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up AirVisual as config entry."""
if CONF_API_KEY not in entry.data:
# If this is a migrated AirVisual Pro entry, there's no actual setup to do;
# that will be handled by the `airvisual_pro` domain:
return False
_standardize_geography_config_entry(hass, entry)
websession = aiohttp_client.async_get_clientsession(hass)
@@ -301,14 +277,31 @@ async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
version = 3
if entry.data[CONF_INTEGRATION_TYPE] == INTEGRATION_TYPE_NODE_PRO:
device_registry = dr.async_get(hass)
entity_registry = er.async_get(hass)
ip_address = entry.data[CONF_IP_ADDRESS]
# Get the existing Pro device entry before it is removed by the migration:
old_device_entry = async_get_pro_device_by_config_entry(hass, entry)
# Store the existing Pro device before the migration removes it:
old_device_entry = next(
entry
for entry in dr.async_entries_for_config_entry(
device_registry, entry.entry_id
)
)
# Store the existing Pro entity entries (mapped by unique ID) before the
# migration removes it:
old_entity_entries: dict[str, er.RegistryEntry] = {
entry.unique_id: entry
for entry in er.async_entries_for_device(
entity_registry, old_device_entry.id, include_disabled_entities=True
)
}
# Remove this config entry and create a new one under the `airvisual_pro`
# domain:
new_entry_data = {**entry.data}
new_entry_data.pop(CONF_INTEGRATION_TYPE)
tasks = [
hass.config_entries.async_remove(entry.entry_id),
hass.config_entries.flow.async_init(
@@ -319,18 +312,52 @@ async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
]
await asyncio.gather(*tasks)
# After the migration has occurred, grab the new config and device entries
# (now under the `airvisual_pro` domain):
new_config_entry = next(
entry
for entry in hass.config_entries.async_entries(DOMAIN_AIRVISUAL_PRO)
if entry.data[CONF_IP_ADDRESS] == ip_address
)
new_device_entry = next(
entry
for entry in dr.async_entries_for_config_entry(
device_registry, new_config_entry.entry_id
)
)
# Update the new device entry with any customizations from the old one:
device_registry.async_update_device(
new_device_entry.id,
area_id=old_device_entry.area_id,
disabled_by=old_device_entry.disabled_by,
name_by_user=old_device_entry.name_by_user,
)
# Update the new entity entries with any customizations from the old ones:
for new_entity_entry in er.async_entries_for_device(
entity_registry, new_device_entry.id, include_disabled_entities=True
):
if old_entity_entry := old_entity_entries.get(
new_entity_entry.unique_id
):
entity_registry.async_update_entity(
new_entity_entry.entity_id,
area_id=old_entity_entry.area_id,
device_class=old_entity_entry.device_class,
disabled_by=old_entity_entry.disabled_by,
hidden_by=old_entity_entry.hidden_by,
icon=old_entity_entry.icon,
name=old_entity_entry.name,
new_entity_id=old_entity_entry.entity_id,
unit_of_measurement=old_entity_entry.unit_of_measurement,
)
# If any automations are using the old device ID, create a Repairs issues
# with instructions on how to update it:
if device_automations := automation.automations_with_device(
hass, old_device_entry.id
):
new_config_entry = async_get_pro_config_entry_by_ip_address(
hass, ip_address
)
new_device_entry = async_get_pro_device_by_config_entry(
hass, new_config_entry
)
async_create_issue(
hass,
DOMAIN,
@@ -69,7 +69,6 @@ GEOGRAPHY_SENSOR_DESCRIPTIONS = (
key=SENSOR_KIND_AQI,
name="Air quality index",
device_class=SensorDeviceClass.AQI,
native_unit_of_measurement="AQI",
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
@@ -2,6 +2,7 @@
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass, field
from typing import Any
from pyairvisual.node import (
@@ -33,13 +34,24 @@ STEP_USER_SCHEMA = vol.Schema(
)
async def async_validate_credentials(ip_address: str, password: str) -> dict[str, Any]:
"""Validate an IP address/password combo (and return any errors as appropriate)."""
@dataclass
class ValidationResult:
"""Define a validation result."""
serial_number: str | None = None
errors: dict[str, Any] = field(default_factory=dict)
async def async_validate_credentials(
ip_address: str, password: str
) -> ValidationResult:
"""Validate an IP address/password combo."""
node = NodeSamba(ip_address, password)
errors = {}
try:
await node.async_connect()
measurements = await node.async_get_latest_measurements()
except InvalidAuthenticationError as err:
LOGGER.error("Invalid password for Pro at IP address %s: %s", ip_address, err)
errors["base"] = "invalid_auth"
@@ -52,10 +64,12 @@ async def async_validate_credentials(ip_address: str, password: str) -> dict[str
except Exception as err: # pylint: disable=broad-except
LOGGER.exception("Unknown error while connecting to %s: %s", ip_address, err)
errors["base"] = "unknown"
else:
return ValidationResult(serial_number=measurements["serial_number"])
finally:
await node.async_disconnect()
return errors
return ValidationResult(errors=errors)
class AirVisualProFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
@@ -89,11 +103,15 @@ class AirVisualProFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
assert self._reauth_entry
if errors := await async_validate_credentials(
validation_result = await async_validate_credentials(
self._reauth_entry.data[CONF_IP_ADDRESS], user_input[CONF_PASSWORD]
):
)
if validation_result.errors:
return self.async_show_form(
step_id="reauth_confirm", data_schema=STEP_REAUTH_SCHEMA, errors=errors
step_id="reauth_confirm",
data_schema=STEP_REAUTH_SCHEMA,
errors=validation_result.errors,
)
self.hass.config_entries.async_update_entry(
@@ -113,14 +131,18 @@ class AirVisualProFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
ip_address = user_input[CONF_IP_ADDRESS]
await self.async_set_unique_id(ip_address)
self._abort_if_unique_id_configured()
if errors := await async_validate_credentials(
validation_result = await async_validate_credentials(
ip_address, user_input[CONF_PASSWORD]
):
)
if validation_result.errors:
return self.async_show_form(
step_id="user", data_schema=STEP_USER_SCHEMA, errors=errors
step_id="user",
data_schema=STEP_USER_SCHEMA,
errors=validation_result.errors,
)
await self.async_set_unique_id(validation_result.serial_number)
self._abort_if_unique_id_configured()
return self.async_create_entry(title=ip_address, data=user_input)
@@ -39,7 +39,6 @@ SENSOR_DESCRIPTIONS = (
key=SENSOR_KIND_AQI,
name="Air quality index",
device_class=SensorDeviceClass.AQI,
native_unit_of_measurement="AQI",
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
@@ -94,7 +93,7 @@ SENSOR_DESCRIPTIONS = (
key=SENSOR_KIND_VOC,
name="VOC",
device_class=SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS,
native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION,
native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
state_class=SensorStateClass.MEASUREMENT,
),
)
@@ -159,6 +158,6 @@ class AirVisualProSensor(AirVisualProEntity, SensorEntity):
elif self.entity_description.key == SENSOR_KIND_BATTERY_LEVEL:
self._attr_native_value = self.status["battery"]
else:
self._attr_native_value = self.MEASUREMENTS_KEY_TO_VALUE[
self.entity_description.key
self._attr_native_value = self.measurements[
self.MEASUREMENTS_KEY_TO_VALUE[self.entity_description.key]
]
@@ -2,7 +2,7 @@
"domain": "apprise",
"name": "Apprise",
"documentation": "https://www.home-assistant.io/integrations/apprise",
"requirements": ["apprise==1.2.0"],
"requirements": ["apprise==1.2.1"],
"codeowners": ["@caronc"],
"iot_class": "cloud_push",
"loggers": ["apprise"]
@@ -69,6 +69,7 @@ class BMWDeviceTracker(BMWBaseEntity, TrackerEntity):
return (
self.vehicle.vehicle_location.location[0]
if self.vehicle.is_vehicle_tracking_enabled
and self.vehicle.vehicle_location.location
else None
)
@@ -78,6 +79,7 @@ class BMWDeviceTracker(BMWBaseEntity, TrackerEntity):
return (
self.vehicle.vehicle_location.location[1]
if self.vehicle.is_vehicle_tracking_enabled
and self.vehicle.vehicle_location.location
else None
)
@@ -2,7 +2,7 @@
"domain": "bmw_connected_drive",
"name": "BMW Connected Drive",
"documentation": "https://www.home-assistant.io/integrations/bmw_connected_drive",
"requirements": ["bimmer_connected==0.10.4"],
"requirements": ["bimmer_connected==0.12.0"],
"codeowners": ["@gerard33", "@rikroe"],
"config_flow": true,
"iot_class": "cloud_polling",
@@ -44,8 +44,6 @@ class BraviaTVConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self.client: BraviaTV | None = None
self.device_config: dict[str, Any] = {}
self.entry: ConfigEntry | None = None
self.client_id: str = ""
self.nickname: str = ""
@staticmethod
@callback
@@ -62,8 +60,13 @@ class BraviaTVConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
)
self.client = BraviaTV(host=host, session=session)
async def async_create_device(self) -> FlowResult:
"""Initialize and create Bravia TV device from config."""
async def gen_instance_ids(self) -> tuple[str, str]:
"""Generate client_id and nickname."""
uuid = await instance_id.async_get(self.hass)
return uuid, f"{NICKNAME_PREFIX} {uuid[:6]}"
async def async_connect_device(self) -> None:
"""Connect to Bravia TV device from config."""
assert self.client
pin = self.device_config[CONF_PIN]
@@ -72,13 +75,16 @@ class BraviaTVConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
if use_psk:
await self.client.connect(psk=pin)
else:
self.device_config[CONF_CLIENT_ID] = self.client_id
self.device_config[CONF_NICKNAME] = self.nickname
await self.client.connect(
pin=pin, clientid=self.client_id, nickname=self.nickname
)
client_id = self.device_config[CONF_CLIENT_ID]
nickname = self.device_config[CONF_NICKNAME]
await self.client.connect(pin=pin, clientid=client_id, nickname=nickname)
await self.client.set_wol_mode(True)
async def async_create_device(self) -> FlowResult:
"""Create Bravia TV device from config."""
assert self.client
await self.async_connect_device()
system_info = await self.client.get_system_info()
cid = system_info[ATTR_CID].lower()
title = system_info[ATTR_MODEL]
@@ -90,6 +96,16 @@ class BraviaTVConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_create_entry(title=title, data=self.device_config)
async def async_reauth_device(self) -> FlowResult:
"""Reauthorize Bravia TV device from config."""
assert self.entry
assert self.client
await self.async_connect_device()
self.hass.config_entries.async_update_entry(self.entry, data=self.device_config)
await self.hass.config_entries.async_reload(self.entry.entry_id)
return self.async_abort(reason="reauth_successful")
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
@@ -100,28 +116,51 @@ class BraviaTVConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
host = user_input[CONF_HOST]
if is_host_valid(host):
self.device_config[CONF_HOST] = host
self.create_client()
return await self.async_step_authorize()
errors[CONF_HOST] = "invalid_host"
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({vol.Required(CONF_HOST, default=""): str}),
data_schema=vol.Schema({vol.Required(CONF_HOST): str}),
errors=errors,
)
async def async_step_authorize(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Authorize Bravia TV device."""
"""Handle authorize step."""
self.create_client()
if user_input is not None:
self.device_config[CONF_USE_PSK] = user_input[CONF_USE_PSK]
if user_input[CONF_USE_PSK]:
return await self.async_step_psk()
return await self.async_step_pin()
return self.async_show_form(
step_id="authorize",
data_schema=vol.Schema(
{
vol.Required(CONF_USE_PSK, default=False): bool,
}
),
)
async def async_step_pin(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle PIN authorize step."""
errors: dict[str, str] = {}
self.client_id, self.nickname = await self.gen_instance_ids()
client_id, nickname = await self.gen_instance_ids()
if user_input is not None:
self.device_config[CONF_PIN] = user_input[CONF_PIN]
self.device_config[CONF_USE_PSK] = user_input[CONF_USE_PSK]
self.device_config[CONF_CLIENT_ID] = client_id
self.device_config[CONF_NICKNAME] = nickname
try:
if self.entry:
return await self.async_reauth_device()
return await self.async_create_device()
except BraviaTVAuthError:
errors["base"] = "invalid_auth"
@@ -133,16 +172,44 @@ class BraviaTVConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
assert self.client
try:
await self.client.pair(self.client_id, self.nickname)
await self.client.pair(client_id, nickname)
except BraviaTVError:
return self.async_abort(reason="no_ip_control")
return self.async_show_form(
step_id="authorize",
step_id="pin",
data_schema=vol.Schema(
{
vol.Required(CONF_PIN, default=""): str,
vol.Required(CONF_USE_PSK, default=False): bool,
vol.Required(CONF_PIN): str,
}
),
errors=errors,
)
async def async_step_psk(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle PSK authorize step."""
errors: dict[str, str] = {}
if user_input is not None:
self.device_config[CONF_PIN] = user_input[CONF_PIN]
try:
if self.entry:
return await self.async_reauth_device()
return await self.async_create_device()
except BraviaTVAuthError:
errors["base"] = "invalid_auth"
except BraviaTVNotSupported:
errors["base"] = "unsupported_model"
except BraviaTVError:
errors["base"] = "cannot_connect"
return self.async_show_form(
step_id="psk",
data_schema=vol.Schema(
{
vol.Required(CONF_PIN): str,
}
),
errors=errors,
@@ -181,7 +248,6 @@ class BraviaTVConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
) -> FlowResult:
"""Allow the user to confirm adding the device."""
if user_input is not None:
self.create_client()
return await self.async_step_authorize()
return self.async_show_form(step_id="confirm")
@@ -190,59 +256,7 @@ class BraviaTVConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle configuration by re-auth."""
self.entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
self.device_config = {**entry_data}
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Dialog that informs the user that reauth is required."""
self.create_client()
client_id, nickname = await self.gen_instance_ids()
assert self.client is not None
assert self.entry is not None
if user_input is not None:
pin = user_input[CONF_PIN]
use_psk = user_input[CONF_USE_PSK]
try:
if use_psk:
await self.client.connect(psk=pin)
else:
self.device_config[CONF_CLIENT_ID] = client_id
self.device_config[CONF_NICKNAME] = nickname
await self.client.connect(
pin=pin, clientid=client_id, nickname=nickname
)
await self.client.set_wol_mode(True)
except BraviaTVError:
return self.async_abort(reason="reauth_unsuccessful")
else:
self.hass.config_entries.async_update_entry(
self.entry, data={**self.device_config, **user_input}
)
await self.hass.config_entries.async_reload(self.entry.entry_id)
return self.async_abort(reason="reauth_successful")
try:
await self.client.pair(client_id, nickname)
except BraviaTVError:
return self.async_abort(reason="reauth_unsuccessful")
return self.async_show_form(
step_id="reauth_confirm",
data_schema=vol.Schema(
{
vol.Required(CONF_PIN, default=""): str,
vol.Required(CONF_USE_PSK, default=False): bool,
}
),
)
async def gen_instance_ids(self) -> tuple[str, str]:
"""Generate client_id and nickname."""
uuid = await instance_id.async_get(self.hass)
return uuid, f"{NICKNAME_PREFIX} {uuid[:6]}"
return await self.async_step_authorize()
class BraviaTVOptionsFlowHandler(config_entries.OptionsFlowWithConfigEntry):
@@ -2,7 +2,7 @@
"domain": "braviatv",
"name": "Sony Bravia TV",
"documentation": "https://www.home-assistant.io/integrations/braviatv",
"requirements": ["pybravia==0.2.3"],
"requirements": ["pybravia==0.2.5"],
"codeowners": ["@bieniu", "@Drafteed"],
"ssdp": [
{
+16 -11
View File
@@ -9,21 +9,27 @@
},
"authorize": {
"title": "Authorize Sony Bravia TV",
"description": "Enter the PIN code shown on the Sony Bravia TV. \n\nIf the PIN code is not shown, you have to unregister Home Assistant on your TV, go to: Settings -> Network -> Remote device settings -> Deregister remote device. \n\nYou can use PSK (Pre-Shared-Key) instead of PIN. PSK is a user-defined secret key used for access control. This authentication method is recommended as more stable. To enable PSK on your TV, go to: Settings -> Network -> Home Network Setup -> IP Control. Then check «Use PSK authentication» box and enter your PSK instead of PIN.",
"description": "Make sure that «Control remotely» is enabled on your TV, go to: \nSettings -> Network -> Remote device settings -> Control remotely. \n\nThere are two authorization methods: PIN code or PSK (Pre-Shared Key). \nAuthorization via PSK is recommended as more stable.",
"data": {
"pin": "[%key:common::config_flow::data::pin%]",
"use_psk": "Use PSK authentication"
}
},
"pin": {
"title": "Authorize Sony Bravia TV",
"description": "Enter the PIN code shown on the Sony Bravia TV. \n\nIf the PIN code is not shown, you have to unregister Home Assistant on your TV, go to: Settings -> Network -> Remote device settings -> Deregister remote device.",
"data": {
"pin": "[%key:common::config_flow::data::pin%]"
}
},
"psk": {
"title": "Authorize Sony Bravia TV",
"description": "To set up PSK on your TV, go to: Settings -> Network -> Home Network Setup -> IP Control. Set «Authentication» to «Normal and Pre-Shared Key» or «Pre-Shared Key» and define your Pre-Shared-Key string (e.g. sony). \n\nThen enter your PSK here.",
"data": {
"pin": "PSK"
}
},
"confirm": {
"description": "[%key:common::config_flow::description::confirm_setup%]"
},
"reauth_confirm": {
"description": "Enter the PIN code shown on the Sony Bravia TV. \n\nIf the PIN code is not shown, you have to unregister Home Assistant on your TV, go to: Settings -> Network -> Remote device settings -> Deregister remote device. \n\nYou can use PSK (Pre-Shared-Key) instead of PIN. PSK is a user-defined secret key used for access control. This authentication method is recommended as more stable. To enable PSK on your TV, go to: Settings -> Network -> Home Network Setup -> IP Control. Then check «Use PSK authentication» box and enter your PSK instead of PIN.",
"data": {
"pin": "[%key:common::config_flow::data::pin%]",
"use_psk": "Use PSK authentication"
}
}
},
"error": {
@@ -36,8 +42,7 @@
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"no_ip_control": "IP Control is disabled on your TV or the TV is not supported.",
"not_bravia_device": "The device is not a Bravia TV.",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]",
"reauth_unsuccessful": "Re-authentication was unsuccessful, please remove the integration and set it up again."
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
}
},
"options": {
@@ -4,8 +4,7 @@
"already_configured": "Device is already configured",
"no_ip_control": "IP Control is disabled on your TV or the TV is not supported.",
"not_bravia_device": "The device is not a Bravia TV.",
"reauth_successful": "Re-authentication was successful",
"reauth_unsuccessful": "Re-authentication was unsuccessful, please remove the integration and set it up again."
"reauth_successful": "Re-authentication was successful"
},
"error": {
"cannot_connect": "Failed to connect",
@@ -16,21 +15,27 @@
"step": {
"authorize": {
"data": {
"pin": "PIN Code",
"use_psk": "Use PSK authentication"
},
"description": "Enter the PIN code shown on the Sony Bravia TV. \n\nIf the PIN code is not shown, you have to unregister Home Assistant on your TV, go to: Settings -> Network -> Remote device settings -> Deregister remote device. \n\nYou can use PSK (Pre-Shared-Key) instead of PIN. PSK is a user-defined secret key used for access control. This authentication method is recommended as more stable. To enable PSK on your TV, go to: Settings -> Network -> Home Network Setup -> IP Control. Then check \u00abUse PSK authentication\u00bb box and enter your PSK instead of PIN.",
"description": "Make sure that \u00abControl remotely\u00bb is enabled on your TV, go to: \nSettings -> Network -> Remote device settings -> Control remotely. \n\nThere are two authorization methods: PIN code or PSK (Pre-Shared Key). \nAuthorization via PSK is recommended as more stable.",
"title": "Authorize Sony Bravia TV"
},
"confirm": {
"description": "Do you want to start setup?"
},
"reauth_confirm": {
"pin": {
"data": {
"pin": "PIN Code",
"use_psk": "Use PSK authentication"
"pin": "PIN Code"
},
"description": "Enter the PIN code shown on the Sony Bravia TV. \n\nIf the PIN code is not shown, you have to unregister Home Assistant on your TV, go to: Settings -> Network -> Remote device settings -> Deregister remote device. \n\nYou can use PSK (Pre-Shared-Key) instead of PIN. PSK is a user-defined secret key used for access control. This authentication method is recommended as more stable. To enable PSK on your TV, go to: Settings -> Network -> Home Network Setup -> IP Control. Then check \u00abUse PSK authentication\u00bb box and enter your PSK instead of PIN."
"description": "Enter the PIN code shown on the Sony Bravia TV. \n\nIf the PIN code is not shown, you have to unregister Home Assistant on your TV, go to: Settings -> Network -> Remote device settings -> Deregister remote device.",
"title": "Authorize Sony Bravia TV"
},
"psk": {
"data": {
"pin": "PSK"
},
"description": "To set up PSK on your TV, go to: Settings -> Network -> Home Network Setup -> IP Control. Set \u00abAuthentication\u00bb to \u00abNormal and Pre-Shared Key\u00bb or \u00abPre-Shared Key\u00bb and define your Pre-Shared-Key string (e.g. sony). \n\nThen enter your PSK here.",
"title": "Authorize Sony Bravia TV"
},
"user": {
"data": {
@@ -17,7 +17,7 @@
"service_data_uuid": "0000fcd2-0000-1000-8000-00805f9b34fb"
}
],
"requirements": ["bthome-ble==2.4.0"],
"requirements": ["bthome-ble==2.4.1"],
"dependencies": ["bluetooth"],
"codeowners": ["@Ernst79"],
"iot_class": "local_push"
+22 -12
View File
@@ -1,7 +1,7 @@
"""Support for WebDav Calendar."""
from __future__ import annotations
from datetime import datetime, timedelta
from datetime import date, datetime, timedelta
import logging
import re
@@ -184,9 +184,9 @@ class WebDavCalendarData:
continue
event_list.append(
CalendarEvent(
summary=vevent.summary.value,
start=vevent.dtstart.value,
end=self.get_end_date(vevent),
summary=self.get_attr_value(vevent, "summary") or "",
start=self.to_local(vevent.dtstart.value),
end=self.to_local(self.get_end_date(vevent)),
location=self.get_attr_value(vevent, "location"),
description=self.get_attr_value(vevent, "description"),
)
@@ -264,11 +264,13 @@ class WebDavCalendarData:
return
# Populate the entity attributes with the event values
(summary, offset) = extract_offset(vevent.summary.value, OFFSET)
(summary, offset) = extract_offset(
self.get_attr_value(vevent, "summary") or "", OFFSET
)
self.event = CalendarEvent(
summary=summary,
start=vevent.dtstart.value,
end=self.get_end_date(vevent),
start=self.to_local(vevent.dtstart.value),
end=self.to_local(self.get_end_date(vevent)),
location=self.get_attr_value(vevent, "location"),
description=self.get_attr_value(vevent, "description"),
)
@@ -306,15 +308,23 @@ class WebDavCalendarData:
def to_datetime(obj):
"""Return a datetime."""
if isinstance(obj, datetime):
if obj.tzinfo is None:
# floating value, not bound to any time zone in particular
# represent same time regardless of which time zone is currently being observed
return obj.replace(tzinfo=dt.DEFAULT_TIME_ZONE)
return obj
return WebDavCalendarData.to_local(obj)
return dt.dt.datetime.combine(obj, dt.dt.time.min).replace(
tzinfo=dt.DEFAULT_TIME_ZONE
)
@staticmethod
def to_local(obj: datetime | date) -> datetime | date:
"""Return a datetime as a local datetime, leaving dates unchanged.
This handles giving floating times a timezone for comparison
with all day events and dropping the custom timezone object
used by the caldav client and dateutil so the datetime can be copied.
"""
if isinstance(obj, datetime):
return dt.as_local(obj)
return obj
@staticmethod
def get_attr_value(obj, attribute):
"""Return the value of the attribute if defined."""
@@ -174,7 +174,10 @@ async def async_get_trigger_capabilities(
if trigger_type == "hvac_mode_changed":
return {
"extra_fields": vol.Schema(
{vol.Optional(CONF_FOR): cv.positive_time_period_dict}
{
vol.Required(state_trigger.CONF_TO): vol.In(const.HVAC_MODES),
vol.Optional(CONF_FOR): cv.positive_time_period_dict,
}
)
}
@@ -10,6 +10,7 @@ from pycfdns.exceptions import (
CloudflareAuthenticationException,
CloudflareConnectionException,
CloudflareException,
CloudflareZoneException,
)
from homeassistant.config_entries import ConfigEntry
@@ -47,7 +48,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
zone_id = await cfupdate.get_zone_id()
except CloudflareAuthenticationException as error:
raise ConfigEntryAuthFailed from error
except CloudflareConnectionException as error:
except (CloudflareConnectionException, CloudflareZoneException) as error:
raise ConfigEntryNotReady from error
async def update_records(now):
@@ -75,7 +75,6 @@ async def async_setup(hass):
@websocket_api.websocket_command(
{
vol.Required("type"): "config/device_registry/update",
vol.Optional("aliases"): list,
vol.Optional("area_id"): vol.Any(str, None),
vol.Required("device_id"): str,
# We only allow setting disabled_by user via API.
@@ -96,10 +95,6 @@ def websocket_update_device(
msg.pop("type")
msg_id = msg.pop("id")
if "aliases" in msg:
# Convert aliases to a set
msg["aliases"] = set(msg["aliases"])
if msg.get("disabled_by") is not None:
msg["disabled_by"] = DeviceEntryDisabler(msg["disabled_by"])
@@ -165,7 +160,6 @@ async def websocket_remove_config_entry_from_device(
def _entry_dict(entry):
"""Convert entry to API format."""
return {
"aliases": entry.aliases,
"area_id": entry.area_id,
"configuration_url": entry.configuration_url,
"config_entries": list(entry.config_entries),
@@ -3,7 +3,7 @@
"name": "deCONZ",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/deconz",
"requirements": ["pydeconz==105"],
"requirements": ["pydeconz==106"],
"ssdp": [
{
"manufacturer": "Royal Philips Electronics",
@@ -21,7 +21,6 @@ from .devolo_device import DevoloDeviceEntity
DEVICE_CLASS_MAPPING = {
"battery": SensorDeviceClass.BATTERY,
"temperature": SensorDeviceClass.TEMPERATURE,
"light": SensorDeviceClass.ILLUMINANCE,
"humidity": SensorDeviceClass.HUMIDITY,
"current": SensorDeviceClass.POWER,
"total": SensorDeviceClass.ENERGY,
+46 -7
View File
@@ -28,6 +28,7 @@ from homeassistant.const import (
CONF_HOST,
CONF_PORT,
EVENT_HOMEASSISTANT_STOP,
UnitOfEnergy,
UnitOfVolume,
)
from homeassistant.core import CoreState, Event, HomeAssistant, callback
@@ -401,7 +402,7 @@ async def async_setup_entry(
)
@Throttle(min_time_between_updates)
def update_entities_telegram(telegram: dict[str, DSMRObject]) -> None:
def update_entities_telegram(telegram: dict[str, DSMRObject] | None) -> None:
"""Update entities with latest telegram and trigger state update."""
# Make all device entities aware of new telegram
for entity in entities:
@@ -445,6 +446,11 @@ async def async_setup_entry(
while hass.state == CoreState.not_running or hass.is_running:
# Start DSMR asyncio.Protocol reader
# Reflect connected state in devices state by setting an
# empty telegram resulting in `unknown` states
update_entities_telegram({})
try:
transport, protocol = await hass.loop.create_task(reader_factory())
@@ -472,8 +478,8 @@ async def async_setup_entry(
protocol = None
# Reflect disconnect state in devices state by setting an
# empty telegram resulting in `unknown` states
update_entities_telegram({})
# None telegram resulting in `unavailable` states
update_entities_telegram(None)
# throttle reconnect attempts
await asyncio.sleep(
@@ -487,11 +493,19 @@ async def async_setup_entry(
transport = None
protocol = None
# Reflect disconnect state in devices state by setting an
# None telegram resulting in `unavailable` states
update_entities_telegram(None)
# throttle reconnect attempts
await asyncio.sleep(
entry.data.get(CONF_RECONNECT_INTERVAL, DEFAULT_RECONNECT_INTERVAL)
)
except CancelledError:
# Reflect disconnect state in devices state by setting an
# None telegram resulting in `unavailable` states
update_entities_telegram(None)
if stop_listener and (
hass.state == CoreState.not_running or hass.is_running
):
@@ -534,7 +548,7 @@ class DSMREntity(SensorEntity):
"""Initialize entity."""
self.entity_description = entity_description
self._entry = entry
self.telegram: dict[str, DSMRObject] = {}
self.telegram: dict[str, DSMRObject] | None = {}
device_serial = entry.data[CONF_SERIAL_ID]
device_name = DEVICE_NAME_ELECTRICITY
@@ -551,16 +565,21 @@ class DSMREntity(SensorEntity):
self._attr_unique_id = f"{device_serial}_{entity_description.key}"
@callback
def update_data(self, telegram: dict[str, DSMRObject]) -> None:
def update_data(self, telegram: dict[str, DSMRObject] | None) -> None:
"""Update data."""
self.telegram = telegram
if self.hass and self.entity_description.obis_reference in self.telegram:
if self.hass and (
telegram is None or self.entity_description.obis_reference in telegram
):
self.async_write_ha_state()
def get_dsmr_object_attr(self, attribute: str) -> str | None:
"""Read attribute from last received telegram for this DSMR object."""
# Make sure telegram contains an object for this entities obis
if self.entity_description.obis_reference not in self.telegram:
if (
self.telegram is None
or self.entity_description.obis_reference not in self.telegram
):
return None
# Get the attribute value if the object has it
@@ -568,6 +587,26 @@ class DSMREntity(SensorEntity):
attr: str | None = getattr(dsmr_object, attribute)
return attr
@property
def available(self) -> bool:
"""Entity is only available if there is a telegram."""
return self.telegram is not None
@property
def device_class(self) -> SensorDeviceClass | None:
"""Return the device class of this entity."""
device_class = super().device_class
# Override device class for gas sensors providing energy units, like
# kWh, MWh, GJ, etc. In those cases, the class should be energy, not gas
with suppress(ValueError):
if device_class == SensorDeviceClass.GAS and UnitOfEnergy(
str(self.native_unit_of_measurement)
):
return SensorDeviceClass.ENERGY
return device_class
@property
def native_value(self) -> StateType:
"""Return the state of sensor, if available, translate if needed."""
@@ -560,8 +560,8 @@ SENSORS: tuple[DSMRReaderSensorEntityDescription, ...] = (
DSMRReaderSensorEntityDescription(
key="dsmr/consumption/quarter-hour-peak-electricity/average_delivered",
name="Previous quarter-hour peak usage",
device_class=SensorDeviceClass.ENERGY,
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
device_class=SensorDeviceClass.POWER,
native_unit_of_measurement=UnitOfPower.KILO_WATT,
),
DSMRReaderSensorEntityDescription(
key="dsmr/consumption/quarter-hour-peak-electricity/read_at_start",
@@ -3,7 +3,7 @@
"name": "Rheem EcoNet Products",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/econet",
"requirements": ["pyeconet==0.1.15"],
"requirements": ["pyeconet==0.1.18"],
"codeowners": ["@vangorra", "@w1ll1am23"],
"iot_class": "cloud_push",
"loggers": ["paho_mqtt", "pyeconet"]
+4 -4
View File
@@ -41,20 +41,20 @@ SUPPORTED_STATE_CLASSES = {
SensorStateClass.TOTAL_INCREASING,
}
VALID_ENERGY_UNITS: set[str] = {
UnitOfEnergy.WATT_HOUR,
UnitOfEnergy.GIGA_JOULE,
UnitOfEnergy.KILO_WATT_HOUR,
UnitOfEnergy.MEGA_WATT_HOUR,
UnitOfEnergy.GIGA_JOULE,
UnitOfEnergy.WATT_HOUR,
}
VALID_ENERGY_UNITS_GAS = {
UnitOfVolume.CUBIC_FEET,
UnitOfVolume.CENTUM_CUBIC_FEET,
UnitOfVolume.CUBIC_FEET,
UnitOfVolume.CUBIC_METERS,
*VALID_ENERGY_UNITS,
}
VALID_VOLUME_UNITS_WATER: set[str] = {
UnitOfVolume.CUBIC_FEET,
UnitOfVolume.CENTUM_CUBIC_FEET,
UnitOfVolume.CUBIC_FEET,
UnitOfVolume.CUBIC_METERS,
UnitOfVolume.GALLONS,
UnitOfVolume.LITERS,
+10 -5
View File
@@ -22,10 +22,10 @@ from .const import DOMAIN
ENERGY_USAGE_DEVICE_CLASSES = (sensor.SensorDeviceClass.ENERGY,)
ENERGY_USAGE_UNITS = {
sensor.SensorDeviceClass.ENERGY: (
UnitOfEnergy.GIGA_JOULE,
UnitOfEnergy.KILO_WATT_HOUR,
UnitOfEnergy.MEGA_WATT_HOUR,
UnitOfEnergy.WATT_HOUR,
UnitOfEnergy.GIGA_JOULE,
)
}
ENERGY_PRICE_UNITS = tuple(
@@ -39,12 +39,16 @@ GAS_USAGE_DEVICE_CLASSES = (
)
GAS_USAGE_UNITS = {
sensor.SensorDeviceClass.ENERGY: (
UnitOfEnergy.WATT_HOUR,
UnitOfEnergy.GIGA_JOULE,
UnitOfEnergy.KILO_WATT_HOUR,
UnitOfEnergy.MEGA_WATT_HOUR,
UnitOfEnergy.GIGA_JOULE,
UnitOfEnergy.WATT_HOUR,
),
sensor.SensorDeviceClass.GAS: (
UnitOfVolume.CENTUM_CUBIC_FEET,
UnitOfVolume.CUBIC_FEET,
UnitOfVolume.CUBIC_METERS,
),
sensor.SensorDeviceClass.GAS: (UnitOfVolume.CUBIC_METERS, UnitOfVolume.CUBIC_FEET),
}
GAS_PRICE_UNITS = tuple(
f"/{unit}" for units in GAS_USAGE_UNITS.values() for unit in units
@@ -54,8 +58,9 @@ GAS_PRICE_UNIT_ERROR = "entity_unexpected_unit_gas_price"
WATER_USAGE_DEVICE_CLASSES = (sensor.SensorDeviceClass.WATER,)
WATER_USAGE_UNITS = {
sensor.SensorDeviceClass.WATER: (
UnitOfVolume.CUBIC_METERS,
UnitOfVolume.CENTUM_CUBIC_FEET,
UnitOfVolume.CUBIC_FEET,
UnitOfVolume.CUBIC_METERS,
UnitOfVolume.GALLONS,
UnitOfVolume.LITERS,
),
@@ -228,7 +228,6 @@ AQHI_SENSOR = ECSensorEntityDescription(
key="aqhi",
name="AQHI",
device_class=SensorDeviceClass.AQI,
native_unit_of_measurement="AQI",
state_class=SensorStateClass.MEASUREMENT,
value_fn=_get_aqhi_value,
)
@@ -7,7 +7,8 @@
"zeroconf": ["_esphomelib._tcp.local."],
"dhcp": [{ "registered_devices": true }],
"codeowners": ["@OttoWinter", "@jesserockz"],
"after_dependencies": ["bluetooth", "zeroconf", "tag"],
"dependencies": ["bluetooth"],
"after_dependencies": ["zeroconf", "tag"],
"iot_class": "local_push",
"integration_type": "device",
"loggers": ["aioesphomeapi", "noiseprotocol"]
@@ -2,7 +2,7 @@
"domain": "frontend",
"name": "Home Assistant Frontend",
"documentation": "https://www.home-assistant.io/integrations/frontend",
"requirements": ["home-assistant-frontend==20221228.0"],
"requirements": ["home-assistant-frontend==20230104.0"],
"dependencies": [
"api",
"auth",
@@ -47,10 +47,19 @@ async def async_setup_services(hass: HomeAssistant) -> None:
for target in call.data[ATTR_DEVICE_ID]:
device = registry.async_get(target)
if device:
coordinator = hass.data[DOMAIN][list(device.config_entries)[0]]
# fully_method(coordinator.fully, *args, **kwargs) would make
# test_services.py fail.
await getattr(coordinator.fully, fully_method.__name__)(*args, **kwargs)
for key in device.config_entries:
entry = hass.config_entries.async_get_entry(key)
if not entry:
continue
if entry.domain != DOMAIN:
continue
coordinator = hass.data[DOMAIN][key]
# fully_method(coordinator.fully, *args, **kwargs) would make
# test_services.py fail.
await getattr(coordinator.fully, fully_method.__name__)(
*args, **kwargs
)
break
async def async_load_url(call: ServiceCall) -> None:
"""Load a URL on the Fully Kiosk Browser."""
+11 -4
View File
@@ -63,6 +63,7 @@ from . import (
load_config,
update_config,
)
from .api import get_feature_access
from .const import (
DATA_SERVICE,
DATA_STORE,
@@ -74,6 +75,7 @@ from .const import (
EVENT_START_DATE,
EVENT_START_DATETIME,
EVENT_TYPES_CONF,
FeatureAccess,
)
_LOGGER = logging.getLogger(__name__)
@@ -213,11 +215,13 @@ async def async_setup_entry(
# Prefer calendar sync down of resources when possible. However, sync does not work
# for search. Also free-busy calendars denormalize recurring events as individual
# events which is not efficient for sync
support_write = calendar_item.access_role.is_writer
support_write = (
calendar_item.access_role.is_writer
and get_feature_access(hass, config_entry) is FeatureAccess.read_write
)
if (
search := data.get(CONF_SEARCH)
or calendar_item.access_role == AccessRole.FREE_BUSY_READER
):
) or calendar_item.access_role == AccessRole.FREE_BUSY_READER:
coordinator = CalendarQueryUpdateCoordinator(
hass,
calendar_service,
@@ -265,7 +269,10 @@ async def async_setup_entry(
await hass.async_add_executor_job(append_calendars_to_config)
platform = entity_platform.async_get_current_platform()
if any(calendar_item.access_role.is_writer for calendar_item in result.items):
if (
any(calendar_item.access_role.is_writer for calendar_item in result.items)
and get_feature_access(hass, config_entry) is FeatureAccess.read_write
):
platform.async_register_entity_service(
SERVICE_CREATE_EVENT,
CREATE_EVENT_SCHEMA,
@@ -4,7 +4,7 @@
"config_flow": true,
"dependencies": ["application_credentials"],
"documentation": "https://www.home-assistant.io/integrations/calendar.google/",
"requirements": ["gcal-sync==4.1.0", "oauth2client==4.1.3"],
"requirements": ["gcal-sync==4.1.1", "oauth2client==4.1.3"],
"codeowners": ["@allenporter"],
"iot_class": "cloud_polling",
"loggers": ["googleapiclient"]
@@ -1,6 +1,8 @@
"""Helper classes for Google Assistant SDK integration."""
from __future__ import annotations
import logging
import aiohttp
from gassist_text import TextAssistant
from google.oauth2.credentials import Credentials
@@ -12,6 +14,8 @@ from homeassistant.helpers.config_entry_oauth2_flow import OAuth2Session
from .const import CONF_LANGUAGE_CODE, DOMAIN, SUPPORTED_LANGUAGE_CODES
_LOGGER = logging.getLogger(__name__)
DEFAULT_LANGUAGE_CODES = {
"de": "de-DE",
"en": "en-US",
@@ -39,7 +43,8 @@ async def async_send_text_commands(commands: list[str], hass: HomeAssistant) ->
language_code = entry.options.get(CONF_LANGUAGE_CODE, default_language_code(hass))
with TextAssistant(credentials, language_code) as assistant:
for command in commands:
assistant.assist(command)
text_response = assistant.assist(command)[0]
_LOGGER.debug("command: %s\nresponse: %s", command, text_response)
def default_language_code(hass: HomeAssistant):
@@ -4,7 +4,7 @@
"config_flow": true,
"dependencies": ["application_credentials"],
"documentation": "https://www.home-assistant.io/integrations/google_assistant_sdk/",
"requirements": ["gassist-text==0.0.5"],
"requirements": ["gassist-text==0.0.7"],
"codeowners": ["@tronikos"],
"iot_class": "cloud_polling",
"integration_type": "service"
@@ -22,7 +22,7 @@ class GrowattServerConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
def __init__(self):
"""Initialise growatt server flow."""
self.api = growattServer.GrowattApi()
self.api = None
self.user_id = None
self.data = {}
@@ -46,6 +46,10 @@ class GrowattServerConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
if not user_input:
return self._async_show_user_form()
# Initialise the library with the username & a random id each time it is started
self.api = growattServer.GrowattApi(
add_random_user_id=True, agent_identifier=user_input[CONF_USERNAME]
)
self.api.server_url = user_input[CONF_URL]
login_response = await self.hass.async_add_executor_job(
self.api.login, user_input[CONF_USERNAME], user_input[CONF_PASSWORD]
@@ -80,14 +80,8 @@ async def async_setup_entry(
config[CONF_URL] = url
hass.config_entries.async_update_entry(config_entry, data=config)
# Initialise the library with a random user id each time it is started,
# also extend the library's default identifier to include 'home-assistant'
api = growattServer.GrowattApi(
add_random_user_id=True,
agent_identifier=(
f"{growattServer.GrowattApi.agent_identifier} - home-assistant"
),
)
# Initialise the library with the username & a random id each time it is started
api = growattServer.GrowattApi(add_random_user_id=True, agent_identifier=username)
api.server_url = url
devices, plant_id = await hass.async_add_executor_job(get_device_list, api, config)
@@ -70,6 +70,7 @@ def api_error(
class AddonInfo:
"""Represent the current add-on info state."""
available: bool
hostname: str | None
options: dict[str, Any]
state: AddonState
@@ -144,6 +145,7 @@ class AddonManager:
self._logger.debug("Add-on store info: %s", addon_store_info)
if not addon_store_info["installed"]:
return AddonInfo(
available=addon_store_info["available"],
hostname=None,
options={},
state=AddonState.NOT_INSTALLED,
@@ -154,6 +156,7 @@ class AddonManager:
addon_info = await async_get_addon_info(self._hass, self.addon_slug)
addon_state = self.async_get_addon_state(addon_info)
return AddonInfo(
available=addon_info["available"],
hostname=addon_info["hostname"],
options=addon_info["options"],
state=addon_state,
@@ -184,6 +187,11 @@ class AddonManager:
@api_error("Failed to install the {addon_name} add-on")
async def async_install_addon(self) -> None:
"""Install the managed add-on."""
addon_info = await self.async_get_addon_info()
if not addon_info.available:
raise AddonError(f"{self.addon_name} add-on is not available anymore")
await async_install_addon(self._hass, self.addon_slug)
@api_error("Failed to uninstall the {addon_name} add-on")
@@ -196,6 +204,9 @@ class AddonManager:
"""Update the managed add-on if needed."""
addon_info = await self.async_get_addon_info()
if not addon_info.available:
raise AddonError(f"{self.addon_name} add-on is not available anymore")
if addon_info.state is AddonState.NOT_INSTALLED:
raise AddonError(f"{self.addon_name} add-on is not installed")
@@ -5,7 +5,6 @@ from datetime import timedelta
from http import HTTPStatus
import logging
from aiohttp.hdrs import USER_AGENT
import requests
import voluptuous as vol
@@ -160,7 +159,7 @@ class HaveIBeenPwnedData:
"""Get the latest data for current email from REST service."""
try:
url = f"{URL}{self._email}?truncateResponse=false"
header = {USER_AGENT: HA_USER_AGENT, "hibp-api-key": self._api_key}
header = {"User-Agent": HA_USER_AGENT, "hibp-api-key": self._api_key}
_LOGGER.debug("Checking for breaches for email: %s", self._email)
req = requests.get(url, headers=header, allow_redirects=True, timeout=5)
@@ -3,7 +3,7 @@
"name": "HomeKit Controller",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/homekit_controller",
"requirements": ["aiohomekit==2.4.2"],
"requirements": ["aiohomekit==2.4.3"],
"zeroconf": ["_hap._tcp.local.", "_hap._udp.local."],
"bluetooth": [{ "manufacturer_id": 76, "manufacturer_data_start": [6] }],
"dependencies": ["bluetooth", "zeroconf"],
@@ -28,7 +28,7 @@ DATA_HYDRAWISE = "hydrawise"
DOMAIN = "hydrawise"
DEFAULT_WATERING_TIME = 15
SCAN_INTERVAL = timedelta(seconds=30)
SCAN_INTERVAL = timedelta(seconds=120)
SIGNAL_UPDATE_HYDRAWISE = "hydrawise_update"
@@ -3,7 +3,7 @@
"name": "Universal Devices ISY994",
"integration_type": "hub",
"documentation": "https://www.home-assistant.io/integrations/isy994",
"requirements": ["pyisy==3.0.9"],
"requirements": ["pyisy==3.0.10"],
"codeowners": ["@bdraco", "@shbatm"],
"config_flow": true,
"ssdp": [
@@ -1,7 +1,8 @@
"""DataUpdateCoordinator for LaCrosse View."""
from __future__ import annotations
from datetime import datetime, timedelta
from datetime import timedelta
from time import time
from lacrosse_view import HTTPError, LaCrosse, Location, LoginError, Sensor
@@ -30,7 +31,7 @@ class LaCrosseUpdateCoordinator(DataUpdateCoordinator[list[Sensor]]):
) -> None:
"""Initialize DataUpdateCoordinator for LaCrosse View."""
self.api = api
self.last_update = datetime.utcnow()
self.last_update = time()
self.username = entry.data["username"]
self.password = entry.data["password"]
self.hass = hass
@@ -45,26 +46,22 @@ class LaCrosseUpdateCoordinator(DataUpdateCoordinator[list[Sensor]]):
async def _async_update_data(self) -> list[Sensor]:
"""Get the data for LaCrosse View."""
now = datetime.utcnow()
now = int(time())
if self.last_update < now - timedelta(minutes=59): # Get new token
if self.last_update < now - 59 * 60: # Get new token once in a hour
self.last_update = now
try:
await self.api.login(self.username, self.password)
except LoginError as error:
raise ConfigEntryAuthFailed from error
# Get the timestamp for yesterday at 6 PM (this is what is used in the app, i noticed it when proxying the request)
yesterday = now - timedelta(days=1)
yesterday = yesterday.replace(hour=18, minute=0, second=0, microsecond=0)
yesterday_timestamp = datetime.timestamp(yesterday)
try:
# Fetch last hour of data
sensors = await self.api.get_sensors(
location=Location(id=self.id, name=self.name),
tz=self.hass.config.time_zone,
start=str(int(yesterday_timestamp)),
end=str(int(datetime.timestamp(now))),
start=str(now - 3600),
end=str(now),
)
except HTTPError as error:
raise ConfigEntryNotReady from error
+1 -1
View File
@@ -3,7 +3,7 @@
"name": "LCN",
"config_flow": false,
"documentation": "https://www.home-assistant.io/integrations/lcn",
"requirements": ["pypck==0.7.15"],
"requirements": ["pypck==0.7.16"],
"codeowners": ["@alengwenus"],
"iot_class": "local_push",
"loggers": ["pypck"]
+2 -2
View File
@@ -194,7 +194,7 @@ class VarAbs(LcnServiceCall):
vol.Required(CONF_VARIABLE): vol.All(
vol.Upper, vol.In(VARIABLES + SETPOINTS)
),
vol.Optional(CONF_VALUE, default=0): cv.positive_int,
vol.Optional(CONF_VALUE, default=0): vol.Coerce(float),
vol.Optional(CONF_UNIT_OF_MEASUREMENT, default="native"): vol.All(
vol.Upper, vol.In(VAR_UNITS)
),
@@ -234,7 +234,7 @@ class VarRel(LcnServiceCall):
vol.Required(CONF_VARIABLE): vol.All(
vol.Upper, vol.In(VARIABLES + SETPOINTS + THRESHOLDS)
),
vol.Optional(CONF_VALUE, default=0): int,
vol.Optional(CONF_VALUE, default=0): vol.Coerce(float),
vol.Optional(CONF_UNIT_OF_MEASUREMENT, default="native"): vol.All(
vol.Upper, vol.In(VAR_UNITS)
),
@@ -4,7 +4,7 @@
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/life360",
"codeowners": ["@pnbruckner"],
"requirements": ["life360==5.3.0"],
"requirements": ["life360==5.5.0"],
"iot_class": "cloud_polling",
"loggers": ["life360"]
}
@@ -3,7 +3,7 @@
"name": "Local Calendar",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/local_calendar",
"requirements": ["ical==4.2.8"],
"requirements": ["ical==4.2.9"],
"codeowners": ["@allenporter"],
"iot_class": "local_polling",
"loggers": ["ical"]
+1 -2
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import asyncio
from typing import cast
import async_timeout
from matter_server.client import MatterClient
@@ -245,7 +244,7 @@ def _async_init_services(hass: HomeAssistant) -> None:
# This could be more efficient
for node in await matter_client.get_nodes():
if node.unique_id == unique_id:
return cast(int, node.node_id)
return node.node_id
return None
+8 -3
View File
@@ -47,8 +47,12 @@ class MatterAdapter:
for node in await self.matter_client.get_nodes():
self._setup_node(node)
def node_added_callback(event: EventType, node: MatterNode) -> None:
def node_added_callback(event: EventType, node: MatterNode | None) -> None:
"""Handle node added event."""
if node is None:
# We can clean this up when we've improved the typing in the library.
# https://github.com/home-assistant-libs/python-matter-server/pull/153
raise RuntimeError("Node added event without node")
self._setup_node(node)
self.config_entry.async_on_unload(
@@ -61,8 +65,9 @@ class MatterAdapter:
bridge_unique_id: str | None = None
if node.aggregator_device_type_instance is not None:
node_info = node.root_device_type_instance.get_cluster(all_clusters.Basic)
if node.aggregator_device_type_instance is not None and (
node_info := node.root_device_type_instance.get_cluster(all_clusters.Basic)
):
self._create_device_registry(
node_info, node_info.nodeLabel or "Hub device", None
)
@@ -39,9 +39,8 @@ class MatterBinarySensor(MatterEntity, BinarySensorEntity):
@callback
def _update_from_device(self) -> None:
"""Update from device."""
self._attr_is_on = self._device_type_instance.get_cluster(
clusters.BooleanState
).stateValue
cluster = self._device_type_instance.get_cluster(clusters.BooleanState)
self._attr_is_on = cluster.stateValue if cluster else None
class MatterOccupancySensor(MatterBinarySensor):
@@ -52,11 +51,9 @@ class MatterOccupancySensor(MatterBinarySensor):
@callback
def _update_from_device(self) -> None:
"""Update from device."""
occupancy = self._device_type_instance.get_cluster(
clusters.OccupancySensing
).occupancy
cluster = self._device_type_instance.get_cluster(clusters.OccupancySensing)
# The first bit = if occupied
self._attr_is_on = occupancy & 1 == 1
self._attr_is_on = cluster.occupancy & 1 == 1 if cluster else None
@dataclass
@@ -20,6 +20,7 @@ from homeassistant.components.hassio import (
from homeassistant.const import CONF_URL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import AbortFlow, FlowResult
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import aiohttp_client
from .addon import get_addon_manager
@@ -131,7 +132,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
try:
await self.start_task
except (CannotConnect, AddonError, AbortFlow) as err:
except (FailedConnect, AddonError, AbortFlow) as err:
self.start_task = None
LOGGER.error(err)
return self.async_show_progress_done(next_step_id="start_failed")
@@ -170,7 +171,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
else:
break
else:
raise CannotConnect("Failed to start Matter Server add-on: timeout")
raise FailedConnect("Failed to start Matter Server add-on: timeout")
finally:
# Continue the flow after show progress when the task is done.
self.hass.async_create_task(
@@ -324,3 +325,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
CONF_INTEGRATION_CREATED_ADDON: self.integration_created_addon,
},
)
class FailedConnect(HomeAssistantError):
"""Failed to connect to the Matter Server."""
+9 -1
View File
@@ -59,7 +59,15 @@ class MatterEntity(Entity):
self._unsubscribes: list[Callable] = []
# for fast lookups we create a mapping to the attribute paths
self._attributes_map: dict[type, str] = {}
self._attr_unique_id = f"{matter_client.server_info.compressed_fabric_id}-{node.unique_id}-{device_type_instance.endpoint}-{device_type_instance.device_type.device_type}"
server_info = matter_client.server_info
# The server info is set when the client connects to the server.
assert server_info is not None
self._attr_unique_id = (
f"{server_info.compressed_fabric_id}-"
f"{node.unique_id}-"
f"{device_type_instance.endpoint}-"
f"{device_type_instance.device_type.device_type}"
)
@property
def device_info(self) -> DeviceInfo | None:
+10 -7
View File
@@ -57,6 +57,9 @@ class MatterLight(MatterEntity, LightEntity):
return
level_control = self._device_type_instance.get_cluster(clusters.LevelControl)
# We check above that the device supports brightness, ie level control.
assert level_control is not None
level = round(
renormalize(
kwargs[ATTR_BRIGHTNESS],
@@ -86,20 +89,20 @@ class MatterLight(MatterEntity, LightEntity):
@callback
def _update_from_device(self) -> None:
"""Update from device."""
if self._attr_supported_color_modes is None:
if self._supports_brightness():
self._attr_supported_color_modes = {ColorMode.BRIGHTNESS}
supports_brigthness = self._supports_brightness()
if self._attr_supported_color_modes is None and supports_brigthness:
self._attr_supported_color_modes = {ColorMode.BRIGHTNESS}
if attr := self.get_matter_attribute(clusters.OnOff.Attributes.OnOff):
self._attr_is_on = attr.value
if (
clusters.LevelControl.Attributes.CurrentLevel
in self.entity_description.subscribe_attributes
):
if supports_brigthness:
level_control = self._device_type_instance.get_cluster(
clusters.LevelControl
)
# We check above that the device supports brightness, ie level control.
assert level_control is not None
# Convert brightness to Home Assistant = 0..255
self._attr_brightness = round(
@@ -3,7 +3,7 @@
"name": "Matter (BETA)",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/matter",
"requirements": ["python-matter-server==1.0.7"],
"requirements": ["python-matter-server==1.0.8"],
"dependencies": ["websocket_api"],
"codeowners": ["@home-assistant/matter"],
"iot_class": "local_push"
+2 -1
View File
@@ -56,7 +56,8 @@ class MatterSwitch(MatterEntity, SwitchEntity):
@callback
def _update_from_device(self) -> None:
"""Update from device."""
self._attr_is_on = self._device_type_instance.get_cluster(clusters.OnOff).onOff
cluster = self._device_type_instance.get_cluster(clusters.OnOff)
self._attr_is_on = cluster.onOff if cluster else None
@dataclass
+2 -4
View File
@@ -136,8 +136,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
file_path = _render_service_value(service, ATTR_FILE_PATH)
if not hass.config.is_allowed_path(file_path):
_LOGGER.error("Invalid file_path %s", file_path)
return
raise ValueError(f"Invalid file_path {file_path}")
minio_client.fput_object(bucket, key, file_path)
@@ -148,8 +147,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
file_path = _render_service_value(service, ATTR_FILE_PATH)
if not hass.config.is_allowed_path(file_path):
_LOGGER.error("Invalid file_path %s", file_path)
return
raise ValueError(f"Invalid file_path {file_path}")
minio_client.fget_object(bucket, key, file_path)
+1 -1
View File
@@ -2,7 +2,7 @@
"domain": "minio",
"name": "Minio",
"documentation": "https://www.home-assistant.io/integrations/minio",
"requirements": ["minio==5.0.10"],
"requirements": ["minio==7.1.12"],
"codeowners": ["@tkislan"],
"iot_class": "cloud_push",
"loggers": ["minio"]
@@ -34,7 +34,9 @@ def create_minio_client(
endpoint: str, access_key: str, secret_key: str, secure: bool
) -> Minio:
"""Create Minio client."""
return Minio(endpoint, access_key, secret_key, secure)
return Minio(
endpoint=endpoint, access_key=access_key, secret_key=secret_key, secure=secure
)
def get_minio_notification_response(
@@ -352,6 +352,13 @@ class MotionTiltDevice(MotionPositionDevice):
return None
return self._blind.angle * 100 / 180
@property
def is_closed(self) -> bool | None:
"""Return if the cover is closed or not."""
if self._blind.position is None:
return None
return self._blind.position >= 95
async def async_open_cover_tilt(self, **kwargs: Any) -> None:
"""Open the cover tilt."""
async with self._api_lock:
@@ -3,7 +3,7 @@
"name": "Motion Blinds",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/motion_blinds",
"requirements": ["motionblinds==0.6.13"],
"requirements": ["motionblinds==0.6.15"],
"dependencies": ["network"],
"dhcp": [
{ "registered_devices": true },
@@ -59,7 +59,7 @@ CONF_EXPIRE_AFTER = "expire_after"
PLATFORM_SCHEMA_MODERN = MQTT_RO_SCHEMA.extend(
{
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_DEVICE_CLASS): vol.Any(DEVICE_CLASSES_SCHEMA, None),
vol.Optional(CONF_EXPIRE_AFTER): cv.positive_int,
vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
+2 -2
View File
@@ -6,7 +6,7 @@ import functools
import voluptuous as vol
from homeassistant.components import button
from homeassistant.components.button import ButtonEntity
from homeassistant.components.button import DEVICE_CLASSES_SCHEMA, ButtonEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DEVICE_CLASS, CONF_NAME
from homeassistant.core import HomeAssistant
@@ -39,7 +39,7 @@ PLATFORM_SCHEMA_MODERN = MQTT_BASE_SCHEMA.extend(
{
vol.Optional(CONF_COMMAND_TEMPLATE): cv.template,
vol.Required(CONF_COMMAND_TOPIC): valid_publish_topic,
vol.Optional(CONF_DEVICE_CLASS): button.DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_DEVICE_CLASS): vol.Any(DEVICE_CLASSES_SCHEMA, None),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PAYLOAD_PRESS, default=DEFAULT_PAYLOAD_PRESS): cv.string,
vol.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean,
+1 -1
View File
@@ -161,7 +161,7 @@ def validate_options(config: ConfigType) -> ConfigType:
_PLATFORM_SCHEMA_BASE = MQTT_BASE_SCHEMA.extend(
{
vol.Optional(CONF_COMMAND_TOPIC): valid_publish_topic,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_DEVICE_CLASS): vol.Any(DEVICE_CLASSES_SCHEMA, None),
vol.Optional(CONF_GET_POSITION_TOPIC): valid_subscribe_topic,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean,
+1 -1
View File
@@ -87,7 +87,7 @@ def validate_config(config: ConfigType) -> ConfigType:
_PLATFORM_SCHEMA_BASE = MQTT_RW_SCHEMA.extend(
{
vol.Optional(CONF_COMMAND_TEMPLATE): cv.template,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_DEVICE_CLASS): vol.Any(DEVICE_CLASSES_SCHEMA, None),
vol.Optional(CONF_MAX, default=DEFAULT_MAX_VALUE): vol.Coerce(float),
vol.Optional(CONF_MIN, default=DEFAULT_MIN_VALUE): vol.Coerce(float),
vol.Optional(CONF_MODE, default=NumberMode.AUTO): vol.Coerce(NumberMode),
+1 -1
View File
@@ -115,6 +115,7 @@ class MqttSelect(MqttEntity, SelectEntity, RestoreEntity):
discovery_data: DiscoveryInfoType | None,
) -> None:
"""Initialize the MQTT select."""
self._attr_current_option = None
SelectEntity.__init__(self)
MqttEntity.__init__(self, hass, config, config_entry, discovery_data)
@@ -125,7 +126,6 @@ class MqttSelect(MqttEntity, SelectEntity, RestoreEntity):
def _setup_from_config(self, config: ConfigType) -> None:
"""(Re)Setup the entity."""
self._attr_current_option = None
self._optimistic = config[CONF_OPTIMISTIC]
self._attr_options = config[CONF_OPTIONS]
+2 -2
View File
@@ -98,13 +98,13 @@ def validate_options(conf: ConfigType) -> ConfigType:
_PLATFORM_SCHEMA_BASE = MQTT_RO_SCHEMA.extend(
{
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_DEVICE_CLASS): vol.Any(DEVICE_CLASSES_SCHEMA, None),
vol.Optional(CONF_EXPIRE_AFTER): cv.positive_int,
vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean,
vol.Optional(CONF_LAST_RESET_TOPIC): valid_subscribe_topic,
vol.Optional(CONF_LAST_RESET_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_STATE_CLASS): STATE_CLASSES_SCHEMA,
vol.Optional(CONF_STATE_CLASS): vol.Any(STATE_CLASSES_SCHEMA, None),
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
+1 -1
View File
@@ -62,7 +62,7 @@ PLATFORM_SCHEMA_MODERN = MQTT_RW_SCHEMA.extend(
vol.Optional(CONF_STATE_OFF): cv.string,
vol.Optional(CONF_STATE_ON): cv.string,
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_DEVICE_CLASS): vol.Any(DEVICE_CLASSES_SCHEMA, None),
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
+1 -1
View File
@@ -54,7 +54,7 @@ CONF_TITLE = "title"
PLATFORM_SCHEMA_MODERN = MQTT_RO_SCHEMA.extend(
{
vol.Optional(CONF_COMMAND_TOPIC): valid_publish_topic,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_DEVICE_CLASS): vol.Any(DEVICE_CLASSES_SCHEMA, None),
vol.Optional(CONF_ENTITY_PICTURE): cv.string,
vol.Optional(CONF_LATEST_VERSION_TEMPLATE): cv.template,
vol.Optional(CONF_LATEST_VERSION_TOPIC): valid_subscribe_topic,
@@ -3,7 +3,7 @@
"name": "Netatmo",
"integration_type": "hub",
"documentation": "https://www.home-assistant.io/integrations/netatmo",
"requirements": ["pyatmo==7.4.0"],
"requirements": ["pyatmo==7.5.0"],
"after_dependencies": ["cloud", "media_source"],
"dependencies": ["application_credentials", "webhook"],
"codeowners": ["@cgtobi"],
@@ -2,7 +2,7 @@
"domain": "netgear",
"name": "NETGEAR",
"documentation": "https://www.home-assistant.io/integrations/netgear",
"requirements": ["pynetgear==0.10.8"],
"requirements": ["pynetgear==0.10.9"],
"codeowners": ["@hacf-fr", "@Quentame", "@starkillerOG"],
"iot_class": "local_polling",
"config_flow": true,
@@ -24,11 +24,9 @@ async def async_setup_entry(
coordinator: Coordinator = hass.data[DOMAIN][config_entry.entry_id]
def reset_buttons():
for entity_description in UNIT_COILGROUPS.get(coordinator.series, {}).get(
"main"
):
if unit := UNIT_COILGROUPS.get(coordinator.series, {}).get("main"):
try:
yield NibeAlarmResetButton(coordinator, entity_description)
yield NibeAlarmResetButton(coordinator, unit)
except CoilNotFoundException as exception:
LOGGER.debug("Skipping button %r", exception)
@@ -46,6 +44,7 @@ class NibeAlarmResetButton(CoordinatorEntity[Coordinator], ButtonEntity):
self._reset_coil = coordinator.heatpump.get_coil_by_address(unit.alarm_reset)
self._alarm_coil = coordinator.heatpump.get_coil_by_address(unit.alarm)
super().__init__(coordinator, {self._alarm_coil.address})
self._attr_name = self._reset_coil.title
self._attr_unique_id = f"{coordinator.unique_id}-alarm_reset"
self._attr_device_info = coordinator.device_info
@@ -2,7 +2,7 @@
"domain": "nissan_leaf",
"name": "Nissan Leaf",
"documentation": "https://www.home-assistant.io/integrations/nissan_leaf",
"requirements": ["pycarwings2==2.13"],
"requirements": ["pycarwings2==2.14"],
"codeowners": ["@filcole"],
"iot_class": "cloud_polling",
"loggers": ["pycarwings2"]
+3 -3
View File
@@ -91,7 +91,7 @@ class NumberDeviceClass(StrEnum):
CURRENT = "current"
"""Current.
Unit of measurement: `A`
Unit of measurement: `A`, `mA`
"""
DATA_RATE = "data_rate"
@@ -213,7 +213,7 @@ class NumberDeviceClass(StrEnum):
POWER_FACTOR = "power_factor"
"""Power factor.
Unit of measurement: `%`
Unit of measurement: `%`, `None`
"""
POWER = "power"
@@ -296,7 +296,7 @@ class NumberDeviceClass(StrEnum):
VOLTAGE = "voltage"
"""Voltage.
Unit of measurement: `V`
Unit of measurement: `V`, `mV`
"""
VOLUME = "volume"
@@ -2,7 +2,6 @@
from __future__ import annotations
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
@@ -51,7 +50,6 @@ SENSOR_DESCRIPTIONS = (
SensorEntityDescription(
key=TYPE_CURRENT_OZONE_LEVEL,
name="Current ozone level",
device_class=SensorDeviceClass.OZONE,
native_unit_of_measurement="du",
state_class=SensorStateClass.MEASUREMENT,
),
@@ -210,7 +210,7 @@ class PhilipsTVMediaPlayer(
async def async_media_play_pause(self) -> None:
"""Send pause command to media player."""
if self._tv.quirk_playpause_spacebar:
await self._tv.sendUnicode(" ")
await self._tv.sendKey("Confirm")
else:
await self._tv.sendKey("PlayPause")
await self._async_update_soon()
@@ -509,6 +509,8 @@ class PhilipsTVMediaPlayer(
self._media_title = self._sources.get(self._tv.source_id)
self._media_channel = None
self._attr_assumed_state = True
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
+19 -6
View File
@@ -21,6 +21,7 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
@@ -69,14 +70,26 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
hass.data[DOMAIN] = {}
if DOMAIN not in config:
return True
async_create_issue(
hass,
DOMAIN,
"deprecated_yaml",
breaks_in_ha_version="2023.2.0",
is_fixable=False,
severity=IssueSeverity.WARNING,
translation_key="deprecated_yaml",
)
# import
if DOMAIN in config:
for conf in config[DOMAIN]:
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=conf
)
for conf in config[DOMAIN]:
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=conf
)
)
return True
@@ -25,5 +25,11 @@
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]"
}
},
"issues": {
"deprecated_yaml": {
"title": "The PI-Hole YAML configuration is being removed",
"description": "Configuring PI-Hole using YAML is being removed.\n\nYour existing YAML configuration has been imported into the UI automatically.\n\nRemove the PI-Hole YAML configuration from your configuration.yaml file and restart Home Assistant to fix this issue."
}
}
}
@@ -25,5 +25,11 @@
}
}
}
},
"issues": {
"deprecated_yaml": {
"description": "Die Konfiguration von PI-Hole mit YAML wird entfernt. \n\nDeine vorhandene YAML-Konfiguration wurde automatisch in die Benutzeroberfl\u00e4che importiert. \n\nEntferne die PI-Hole-YAML-Konfiguration aus deiner configuration.yaml-Datei und starte Home Assistant neu, um dieses Problem zu beheben.",
"title": "Die PI-Hole YAML-Konfiguration wird entfernt"
}
}
}
@@ -25,5 +25,11 @@
}
}
}
},
"issues": {
"deprecated_yaml": {
"description": "Configuring PI-Hole using YAML is being removed.\n\nYour existing YAML configuration has been imported into the UI automatically.\n\nRemove the PI-Hole YAML configuration from your configuration.yaml file and restart Home Assistant to fix this issue.",
"title": "The PI-Hole YAML configuration is being removed"
}
}
}
+2 -23
View File
@@ -6,12 +6,10 @@ from aiopurpleair.models.sensors import SensorModel
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE, Platform
from homeassistant.core import HomeAssistant
import homeassistant.helpers.device_registry as dr
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .config_flow import async_remove_sensor_by_device_id
from .const import CONF_LAST_UPDATE_SENSOR_ADD, DOMAIN
from .const import DOMAIN
from .coordinator import PurpleAirDataUpdateCoordinator
PLATFORMS = [Platform.SENSOR]
@@ -32,26 +30,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_handle_entry_update(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Handle an options update."""
if entry.options.get(CONF_LAST_UPDATE_SENSOR_ADD) is True:
# If the last options update was to add a sensor, we reload the config entry:
await hass.config_entries.async_reload(entry.entry_id)
async def async_remove_config_entry_device(
hass: HomeAssistant, config_entry: ConfigEntry, device_entry: dr.DeviceEntry
) -> bool:
"""Remove a config entry from a device."""
new_entry_options = async_remove_sensor_by_device_id(
hass,
config_entry,
device_entry.id,
# remove_device is set to False because in this instance, the device has
# already been removed:
remove_device=False,
)
return hass.config_entries.async_update_entry(
config_entry, options=new_entry_options
)
await hass.config_entries.async_reload(entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
@@ -1,6 +1,7 @@
"""Config flow for PurpleAir integration."""
from __future__ import annotations
import asyncio
from collections.abc import Mapping
from copy import deepcopy
from dataclasses import dataclass, field
@@ -14,13 +15,15 @@ import voluptuous as vol
from homeassistant import config_entries
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.core import HomeAssistant, callback
from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import (
aiohttp_client,
config_validation as cv,
device_registry as dr,
entity_registry as er,
)
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.helpers.selector import (
SelectOptionDict,
SelectSelector,
@@ -28,7 +31,7 @@ from homeassistant.helpers.selector import (
SelectSelectorMode,
)
from .const import CONF_LAST_UPDATE_SENSOR_ADD, CONF_SENSOR_INDICES, DOMAIN, LOGGER
from .const import CONF_SENSOR_INDICES, DOMAIN, LOGGER
CONF_DISTANCE = "distance"
CONF_NEARBY_SENSOR_OPTIONS = "nearby_sensor_options"
@@ -74,8 +77,7 @@ def async_get_nearby_sensors_options(
"""Return a set of nearby sensors as SelectOptionDict objects."""
return [
SelectOptionDict(
value=str(result.sensor.sensor_index),
label=f"{result.sensor.name} ({round(result.distance, 1)} km away)",
value=str(result.sensor.sensor_index), label=cast(str, result.sensor.name)
)
for result in nearby_sensor_results
]
@@ -118,50 +120,6 @@ def async_get_remove_sensor_schema(sensors: list[SelectOptionDict]) -> vol.Schem
)
@callback
def async_get_sensor_index(
hass: HomeAssistant, config_entry: ConfigEntry, device_entry: dr.DeviceEntry
) -> int:
"""Get the sensor index related to a config and device entry.
Note that this method expects that there will always be a single sensor index per
DeviceEntry.
"""
[sensor_index] = [
sensor_index
for sensor_index in config_entry.options[CONF_SENSOR_INDICES]
if (DOMAIN, str(sensor_index)) in device_entry.identifiers
]
return cast(int, sensor_index)
@callback
def async_remove_sensor_by_device_id(
hass: HomeAssistant,
config_entry: ConfigEntry,
device_id: str,
*,
remove_device: bool = True,
) -> dict[str, Any]:
"""Remove a sensor and return update config entry options."""
device_registry = dr.async_get(hass)
device_entry = device_registry.async_get(device_id)
assert device_entry
removed_sensor_index = async_get_sensor_index(hass, config_entry, device_entry)
options = deepcopy({**config_entry.options})
options[CONF_LAST_UPDATE_SENSOR_ADD] = False
options[CONF_SENSOR_INDICES].remove(removed_sensor_index)
if remove_device:
device_registry.async_update_device(
device_entry.id, remove_config_entry_id=config_entry.entry_id
)
return options
@dataclass
class ValidationResult:
"""Define a validation result."""
@@ -408,7 +366,6 @@ class PurpleAirOptionsFlowHandler(config_entries.OptionsFlow):
return self.async_abort(reason="already_configured")
options = deepcopy({**self.config_entry.options})
options[CONF_LAST_UPDATE_SENSOR_ADD] = True
options[CONF_SENSOR_INDICES].append(sensor_index)
return self.async_create_entry(title="", data=options)
@@ -433,8 +390,50 @@ class PurpleAirOptionsFlowHandler(config_entries.OptionsFlow):
),
)
new_entry_options = async_remove_sensor_by_device_id(
self.hass, self.config_entry, user_input[CONF_SENSOR_DEVICE_ID]
device_registry = dr.async_get(self.hass)
entity_registry = er.async_get(self.hass)
device_id = user_input[CONF_SENSOR_DEVICE_ID]
device_entry = cast(dr.DeviceEntry, device_registry.async_get(device_id))
# Determine the entity entries that belong to this device.
entity_entries = er.async_entries_for_device(
entity_registry, device_id, include_disabled_entities=True
)
return self.async_create_entry(title="", data=new_entry_options)
device_entities_removed_event = asyncio.Event()
@callback
def async_device_entity_state_changed(_: Event) -> None:
"""Listen and respond when all device entities are removed."""
if all(
self.hass.states.get(entity_entry.entity_id) is None
for entity_entry in entity_entries
):
device_entities_removed_event.set()
# Track state changes for this device's entities and when they're removed,
# finish the flow:
cancel_state_track = async_track_state_change_event(
self.hass,
[entity_entry.entity_id for entity_entry in entity_entries],
async_device_entity_state_changed,
)
device_registry.async_update_device(
device_id, remove_config_entry_id=self.config_entry.entry_id
)
await device_entities_removed_event.wait()
# Once we're done, we can cancel the state change tracker callback:
cancel_state_track()
# Build new config entry options:
removed_sensor_index = next(
sensor_index
for sensor_index in self.config_entry.options[CONF_SENSOR_INDICES]
if (DOMAIN, str(sensor_index)) in device_entry.identifiers
)
options = deepcopy({**self.config_entry.options})
options[CONF_SENSOR_INDICES].remove(removed_sensor_index)
return self.async_create_entry(title="", data=options)
@@ -5,6 +5,5 @@ DOMAIN = "purpleair"
LOGGER = logging.getLogger(__package__)
CONF_LAST_UPDATE_SENSOR_ADD = "last_update_sensor_add"
CONF_READ_KEY = "read_key"
CONF_SENSOR_INDICES = "sensor_indices"
+2 -3
View File
@@ -166,7 +166,7 @@ SENSOR_DESCRIPTIONS = [
name="Uptime",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
icon="mdi:timer",
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.MINUTES,
state_class=SensorStateClass.TOTAL_INCREASING,
value_fn=lambda sensor: sensor.uptime,
@@ -174,8 +174,7 @@ SENSOR_DESCRIPTIONS = [
PurpleAirSensorEntityDescription(
key="voc",
name="VOC",
device_class=SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS,
native_unit_of_measurement=CONCENTRATION_IAQ,
device_class=SensorDeviceClass.AQI,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda sensor: sensor.voc,
),
+27 -18
View File
@@ -9,19 +9,22 @@ import logging
from aiohttp import ClientConnectorError
import async_timeout
from reolink_ip.exceptions import ApiError, InvalidContentTypeError
from reolink_aio.exceptions import ApiError, InvalidContentTypeError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.const import EVENT_HOMEASSISTANT_STOP, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .const import DEVICE_UPDATE_INTERVAL, DOMAIN, PLATFORMS
from .const import DOMAIN
from .host import ReolinkHost
_LOGGER = logging.getLogger(__name__)
PLATFORMS = [Platform.CAMERA]
DEVICE_UPDATE_INTERVAL = 60
@dataclass
class ReolinkData:
@@ -31,14 +34,15 @@ class ReolinkData:
device_coordinator: DataUpdateCoordinator
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Set up Reolink from a config entry."""
host = ReolinkHost(hass, dict(entry.data), dict(entry.options))
host = ReolinkHost(hass, config_entry.data, config_entry.options)
try:
if not await host.async_init():
raise ConfigEntryNotReady(
f"Error while trying to setup {host.api.host}:{host.api.port}: failed to obtain data from device."
f"Error while trying to setup {host.api.host}:{host.api.port}: "
"failed to obtain data from device."
)
except (
ClientConnectorError,
@@ -50,14 +54,15 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
f'Error while trying to setup {host.api.host}:{host.api.port}: "{str(err)}".'
) from err
entry.async_on_unload(
config_entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, host.stop)
)
async def async_device_config_update():
"""Perform the update of the host config-state cache, and renew the ONVIF-subscription."""
"""Update the host state cache and renew the ONVIF-subscription."""
async with async_timeout.timeout(host.api.timeout):
await host.update_states() # Login session is implicitly updated here, so no need to explicitly do it in a timer
# Login session is implicitly updated here
await host.update_states()
coordinator_device_config_update = DataUpdateCoordinator(
hass,
@@ -69,30 +74,34 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# Fetch initial data so we have data when entities subscribe
await coordinator_device_config_update.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = ReolinkData(
hass.data.setdefault(DOMAIN, {})[config_entry.entry_id] = ReolinkData(
host=host,
device_coordinator=coordinator_device_config_update,
)
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(entry_update_listener))
config_entry.async_on_unload(
config_entry.add_update_listener(entry_update_listener)
)
return True
async def entry_update_listener(hass: HomeAssistant, entry: ConfigEntry):
async def entry_update_listener(hass: HomeAssistant, config_entry: ConfigEntry):
"""Update the configuration of the host entity."""
await hass.config_entries.async_reload(entry.entry_id)
await hass.config_entries.async_reload(config_entry.entry_id)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Unload a config entry."""
host: ReolinkHost = hass.data[DOMAIN][entry.entry_id].host
host: ReolinkHost = hass.data[DOMAIN][config_entry.entry_id].host
await host.stop()
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.data[DOMAIN].pop(entry.entry_id)
if unload_ok := await hass.config_entries.async_unload_platforms(
config_entry, PLATFORMS
):
hass.data[DOMAIN].pop(config_entry.entry_id)
return unload_ok
+16 -9
View File
@@ -8,9 +8,9 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import ReolinkData
from .const import DOMAIN
from .entity import ReolinkCoordinatorEntity
from .host import ReolinkHost
_LOGGER = logging.getLogger(__name__)
@@ -18,10 +18,11 @@ _LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_devices: AddEntitiesCallback,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up a Reolink IP Camera."""
host: ReolinkHost = hass.data[DOMAIN][config_entry.entry_id].host
reolink_data: ReolinkData = hass.data[DOMAIN][config_entry.entry_id]
host = reolink_data.host
cameras = []
for channel in host.api.channels:
@@ -30,25 +31,31 @@ async def async_setup_entry(
streams.append("ext")
for stream in streams:
cameras.append(ReolinkCamera(hass, config_entry, channel, stream))
cameras.append(ReolinkCamera(reolink_data, config_entry, channel, stream))
async_add_devices(cameras, update_before_add=True)
async_add_entities(cameras, update_before_add=True)
class ReolinkCamera(ReolinkCoordinatorEntity, Camera):
"""An implementation of a Reolink IP camera."""
_attr_supported_features: CameraEntityFeature = CameraEntityFeature.STREAM
_attr_has_entity_name = True
def __init__(self, hass, config, channel, stream):
def __init__(
self,
reolink_data: ReolinkData,
config_entry: ConfigEntry,
channel: int,
stream: str,
) -> None:
"""Initialize Reolink camera stream."""
ReolinkCoordinatorEntity.__init__(self, hass, config)
ReolinkCoordinatorEntity.__init__(self, reolink_data, config_entry, channel)
Camera.__init__(self)
self._channel = channel
self._stream = stream
self._attr_name = f"{self._host.api.camera_name(self._channel)} {self._stream}"
self._attr_name = self._stream
self._attr_unique_id = f"{self._host.unique_id}_{self._channel}_{self._stream}"
self._attr_entity_registry_enabled_default = stream == "sub"
+31 -30
View File
@@ -2,9 +2,9 @@
from __future__ import annotations
import logging
from typing import cast
from typing import Any
from reolink_ip.exceptions import ApiError, CredentialsInvalidError
from reolink_aio.exceptions import ApiError, CredentialsInvalidError
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
@@ -18,6 +18,8 @@ from .host import ReolinkHost
_LOGGER = logging.getLogger(__name__)
DEFAULT_OPTIONS = {CONF_PROTOCOL: DEFAULT_PROTOCOL}
class ReolinkOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle Reolink options."""
@@ -26,10 +28,12 @@ class ReolinkOptionsFlowHandler(config_entries.OptionsFlow):
"""Initialize ReolinkOptionsFlowHandler."""
self.config_entry = config_entry
async def async_step_init(self, user_input=None) -> FlowResult:
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Manage the Reolink options."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
return self.async_create_entry(data=user_input)
return self.async_show_form(
step_id="init",
@@ -37,9 +41,7 @@ class ReolinkOptionsFlowHandler(config_entries.OptionsFlow):
{
vol.Required(
CONF_PROTOCOL,
default=self.config_entry.options.get(
CONF_PROTOCOL, DEFAULT_PROTOCOL
),
default=self.config_entry.options[CONF_PROTOCOL],
): vol.In(["rtsp", "rtmp"]),
}
),
@@ -51,8 +53,6 @@ class ReolinkFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 1
host: ReolinkHost | None = None
@staticmethod
@callback
def async_get_options_flow(
@@ -61,14 +61,16 @@ class ReolinkFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Options callback for Reolink."""
return ReolinkOptionsFlowHandler(config_entry)
async def async_step_user(self, user_input=None) -> FlowResult:
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the initial step."""
errors = {}
placeholders = {}
if user_input is not None:
try:
await self.async_obtain_host_settings(self.hass, user_input)
host = await async_obtain_host_settings(self.hass, user_input)
except CannotConnect:
errors[CONF_HOST] = "cannot_connect"
except CredentialsInvalidError:
@@ -81,19 +83,17 @@ class ReolinkFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
placeholders["error"] = str(err)
errors[CONF_HOST] = "unknown"
self.host = cast(ReolinkHost, self.host)
if not errors:
user_input[CONF_PORT] = self.host.api.port
user_input[CONF_USE_HTTPS] = self.host.api.use_https
user_input[CONF_PORT] = host.api.port
user_input[CONF_USE_HTTPS] = host.api.use_https
await self.async_set_unique_id(
self.host.unique_id, raise_on_progress=False
)
await self.async_set_unique_id(host.unique_id, raise_on_progress=False)
self._abort_if_unique_id_configured(updates=user_input)
return self.async_create_entry(
title=str(self.host.api.nvr_name), data=user_input
title=str(host.api.nvr_name),
data=user_input,
options=DEFAULT_OPTIONS,
)
data_schema = vol.Schema(
@@ -118,19 +118,20 @@ class ReolinkFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
description_placeholders=placeholders,
)
async def async_obtain_host_settings(
self, hass: core.HomeAssistant, user_input: dict
):
"""Initialize the Reolink host and get the host information."""
host = ReolinkHost(hass, user_input, {})
try:
if not await host.async_init():
raise CannotConnect
finally:
await host.stop()
async def async_obtain_host_settings(
hass: core.HomeAssistant, user_input: dict
) -> ReolinkHost:
"""Initialize the Reolink host and get the host information."""
host = ReolinkHost(hass, user_input, DEFAULT_OPTIONS)
self.host = host
try:
if not await host.async_init():
raise CannotConnect
finally:
await host.stop()
return host
class CannotConnect(exceptions.HomeAssistantError):
@@ -1,13 +1,9 @@
"""Constants for the Reolink Camera integration."""
DOMAIN = "reolink"
PLATFORMS = ["camera"]
CONF_USE_HTTPS = "use_https"
CONF_PROTOCOL = "protocol"
DEFAULT_PROTOCOL = "rtsp"
DEFAULT_TIMEOUT = 60
HOST = "host"
DEVICE_UPDATE_INTERVAL = 60
+21 -23
View File
@@ -1,5 +1,7 @@
"""Reolink parent entity class."""
from __future__ import annotations
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
@@ -11,24 +13,20 @@ from .const import DOMAIN
class ReolinkCoordinatorEntity(CoordinatorEntity):
"""Parent class for Reolink Entities."""
def __init__(self, hass, config):
def __init__(
self, reolink_data: ReolinkData, config_entry: ConfigEntry, channel: int | None
) -> None:
"""Initialize ReolinkCoordinatorEntity."""
self._hass = hass
entry_data: ReolinkData = self._hass.data[DOMAIN][config.entry_id]
coordinator = entry_data.device_coordinator
coordinator = reolink_data.device_coordinator
super().__init__(coordinator)
self._host = entry_data.host
self._channel = None
self._host = reolink_data.host
self._channel = channel
@property
def device_info(self):
"""Information about this entity/device."""
http_s = "https" if self._host.api.use_https else "http"
conf_url = f"{http_s}://{self._host.api.host}:{self._host.api.port}"
if self._host.api.is_nvr and self._channel is not None:
return DeviceInfo(
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, f"{self._host.unique_id}_ch{self._channel}")},
via_device=(DOMAIN, self._host.unique_id),
name=self._host.api.camera_name(self._channel),
@@ -36,19 +34,19 @@ class ReolinkCoordinatorEntity(CoordinatorEntity):
manufacturer=self._host.api.manufacturer,
configuration_url=conf_url,
)
return DeviceInfo(
identifiers={(DOMAIN, self._host.unique_id)},
connections={(CONNECTION_NETWORK_MAC, self._host.api.mac_address)},
name=self._host.api.nvr_name,
model=self._host.api.model,
manufacturer=self._host.api.manufacturer,
hw_version=self._host.api.hardware_version,
sw_version=self._host.api.sw_version,
configuration_url=conf_url,
)
else:
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, self._host.unique_id)},
connections={(CONNECTION_NETWORK_MAC, self._host.api.mac_address)},
name=self._host.api.nvr_name,
model=self._host.api.model,
manufacturer=self._host.api.manufacturer,
hw_version=self._host.api.hardware_version,
sw_version=self._host.api.sw_version,
configuration_url=conf_url,
)
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._host.api.session_active
return self._host.api.session_active and super().available
+14 -17
View File
@@ -2,11 +2,13 @@
from __future__ import annotations
import asyncio
from collections.abc import Mapping
import logging
from typing import Any
import aiohttp
from reolink_ip.api import Host
from reolink_ip.exceptions import (
from reolink_aio.api import Host
from reolink_aio.exceptions import (
ApiError,
CredentialsInvalidError,
InvalidContentTypeError,
@@ -16,7 +18,7 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNA
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import format_mac
from .const import CONF_PROTOCOL, CONF_USE_HTTPS, DEFAULT_PROTOCOL, DEFAULT_TIMEOUT
from .const import CONF_PROTOCOL, CONF_USE_HTTPS, DEFAULT_TIMEOUT
_LOGGER = logging.getLogger(__name__)
@@ -27,18 +29,14 @@ class ReolinkHost:
def __init__(
self,
hass: HomeAssistant,
config: dict,
options: dict,
config: Mapping[str, Any],
options: Mapping[str, Any],
) -> None:
"""Initialize Reolink Host. Could be either NVR, or Camera."""
self._hass: HomeAssistant = hass
self._clientsession: aiohttp.ClientSession | None = None
self._unique_id: str | None = None
cur_protocol = (
DEFAULT_PROTOCOL if CONF_PROTOCOL not in options else options[CONF_PROTOCOL]
)
self._unique_id: str = ""
self._api = Host(
config[CONF_HOST],
@@ -46,12 +44,12 @@ class ReolinkHost:
config[CONF_PASSWORD],
port=config.get(CONF_PORT),
use_https=config.get(CONF_USE_HTTPS),
protocol=cur_protocol,
protocol=options[CONF_PROTOCOL],
timeout=DEFAULT_TIMEOUT,
)
@property
def unique_id(self):
def unique_id(self) -> str:
"""Create the unique ID, base for all entities."""
return self._unique_id
@@ -99,23 +97,22 @@ class ReolinkHost:
):
if enable_onvif:
_LOGGER.error(
"Unable to switch on ONVIF on %s. You need it to be ON to receive notifications",
"Failed to enable ONVIF on %s. Set it to ON to receive notifications",
self._api.nvr_name,
)
if enable_rtmp:
_LOGGER.error(
"Unable to switch on RTMP on %s. You need it to be ON",
"Failed to enable RTMP on %s. Set it to ON",
self._api.nvr_name,
)
elif enable_rtsp:
_LOGGER.error(
"Unable to switch on RTSP on %s. You need it to be ON",
"Failed to enable RTSP on %s. Set it to ON",
self._api.nvr_name,
)
if self._unique_id is None:
self._unique_id = format_mac(self._api.mac_address)
self._unique_id = format_mac(self._api.mac_address)
return True
@@ -3,10 +3,8 @@
"name": "Reolink IP NVR/camera",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/reolink",
"requirements": ["reolink-ip==0.0.40"],
"dependencies": ["webhook"],
"after_dependencies": ["http"],
"codeowners": ["@starkillerOG", "@JimStar"],
"requirements": ["reolink-aio==0.1.3"],
"codeowners": ["@starkillerOG"],
"iot_class": "local_polling",
"loggers": ["reolink-ip"]
"loggers": ["reolink-aio"]
}
+1 -1
View File
@@ -3,7 +3,7 @@
"name": "RoonLabs music player",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/roon",
"requirements": ["roonapi==0.1.1"],
"requirements": ["roonapi==0.1.2"],
"codeowners": ["@pavoni"],
"iot_class": "local_push",
"loggers": ["roonapi"]
+15 -6
View File
@@ -86,7 +86,11 @@ from homeassistant.helpers.typing import ConfigType, StateType
from homeassistant.util import dt as dt_util
from homeassistant.util.unit_conversion import (
BaseUnitConverter,
DataRateConverter,
DistanceConverter,
ElectricCurrentConverter,
ElectricPotentialConverter,
InformationConverter,
MassConverter,
PressureConverter,
SpeedConverter,
@@ -183,7 +187,7 @@ class SensorDeviceClass(StrEnum):
CURRENT = "current"
"""Current.
Unit of measurement: `A`
Unit of measurement: `A`, `mA`
"""
DATA_RATE = "data_rate"
@@ -305,7 +309,7 @@ class SensorDeviceClass(StrEnum):
POWER_FACTOR = "power_factor"
"""Power factor.
Unit of measurement: `%`
Unit of measurement: `%`, `None`
"""
POWER = "power"
@@ -388,7 +392,7 @@ class SensorDeviceClass(StrEnum):
VOLTAGE = "voltage"
"""Voltage.
Unit of measurement: `V`
Unit of measurement: `V`, `mV`
"""
VOLUME = "volume"
@@ -466,12 +470,16 @@ STATE_CLASSES: Final[list[str]] = [cls.value for cls in SensorStateClass]
# Note: this needs to be aligned with frontend: OVERRIDE_SENSOR_UNITS in
# `entity-registry-settings.ts`
UNIT_CONVERTERS: dict[SensorDeviceClass | str | None, type[BaseUnitConverter]] = {
SensorDeviceClass.DATA_RATE: DataRateConverter,
SensorDeviceClass.DATA_SIZE: InformationConverter,
SensorDeviceClass.DISTANCE: DistanceConverter,
SensorDeviceClass.CURRENT: ElectricCurrentConverter,
SensorDeviceClass.GAS: VolumeConverter,
SensorDeviceClass.PRECIPITATION: DistanceConverter,
SensorDeviceClass.PRESSURE: PressureConverter,
SensorDeviceClass.SPEED: SpeedConverter,
SensorDeviceClass.TEMPERATURE: TemperatureConverter,
SensorDeviceClass.VOLTAGE: ElectricPotentialConverter,
SensorDeviceClass.VOLUME: VolumeConverter,
SensorDeviceClass.WATER: VolumeConverter,
SensorDeviceClass.WEIGHT: MassConverter,
@@ -485,7 +493,7 @@ DEVICE_CLASS_UNITS: dict[SensorDeviceClass, set[type[StrEnum] | str | None]] = {
SensorDeviceClass.BATTERY: {PERCENTAGE},
SensorDeviceClass.CO: {CONCENTRATION_PARTS_PER_MILLION},
SensorDeviceClass.CO2: {CONCENTRATION_PARTS_PER_MILLION},
SensorDeviceClass.CURRENT: {UnitOfElectricCurrent.AMPERE},
SensorDeviceClass.CURRENT: set(UnitOfElectricCurrent),
SensorDeviceClass.DATA_RATE: set(UnitOfDataRate),
SensorDeviceClass.DATA_SIZE: set(UnitOfInformation),
SensorDeviceClass.DISTANCE: set(UnitOfLength),
@@ -513,7 +521,7 @@ DEVICE_CLASS_UNITS: dict[SensorDeviceClass, set[type[StrEnum] | str | None]] = {
SensorDeviceClass.PM1: {CONCENTRATION_MICROGRAMS_PER_CUBIC_METER},
SensorDeviceClass.PM10: {CONCENTRATION_MICROGRAMS_PER_CUBIC_METER},
SensorDeviceClass.PM25: {CONCENTRATION_MICROGRAMS_PER_CUBIC_METER},
SensorDeviceClass.POWER_FACTOR: {PERCENTAGE},
SensorDeviceClass.POWER_FACTOR: {PERCENTAGE, None},
SensorDeviceClass.POWER: {UnitOfPower.WATT, UnitOfPower.KILO_WATT},
SensorDeviceClass.PRECIPITATION: set(UnitOfPrecipitationDepth),
SensorDeviceClass.PRECIPITATION_INTENSITY: set(UnitOfVolumetricFlux),
@@ -533,7 +541,7 @@ DEVICE_CLASS_UNITS: dict[SensorDeviceClass, set[type[StrEnum] | str | None]] = {
SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS: {
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER
},
SensorDeviceClass.VOLTAGE: {UnitOfElectricPotential.VOLT},
SensorDeviceClass.VOLTAGE: set(UnitOfElectricPotential),
SensorDeviceClass.VOLUME: set(UnitOfVolume),
SensorDeviceClass.WATER: {
UnitOfVolume.CENTUM_CUBIC_FEET,
@@ -960,6 +968,7 @@ class SensorEntity(Entity):
# Validate unit of measurement used for sensors with a device class
if (
not self._invalid_unit_of_measurement_reported
and value is not None
and device_class
and (units := DEVICE_CLASS_UNITS.get(device_class)) is not None
and native_unit_of_measurement not in units
+13 -1
View File
@@ -53,6 +53,8 @@ BLE_SCANNER_OPTIONS = [
selector.SelectOptionDict(value=BLEScannerMode.PASSIVE, label="Passive"),
]
INTERNAL_WIFI_AP_IP = "192.168.33.1"
async def validate_input(
hass: HomeAssistant,
@@ -217,7 +219,17 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
current_entry := await self.async_set_unique_id(mac)
) and current_entry.data[CONF_HOST] == host:
await async_reconnect_soon(self.hass, current_entry)
self._abort_if_unique_id_configured({CONF_HOST: host})
if host == INTERNAL_WIFI_AP_IP:
# If the device is broadcasting the internal wifi ap ip
# we can't connect to it, so we should not update the
# entry with the new host as it will be unreachable
#
# This is a workaround for a bug in the firmware 0.12 (and older?)
# which should be removed once the firmware is fixed
# and the old version is no longer in use
self._abort_if_unique_id_configured()
else:
self._abort_if_unique_id_configured({CONF_HOST: host})
async def async_step_zeroconf(
self, discovery_info: zeroconf.ZeroconfServiceInfo
+3 -2
View File
@@ -706,11 +706,12 @@ async def _async_find_next_available_port(source: AddressTupleVXType) -> int:
test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
for port in range(UPNP_SERVER_MIN_PORT, UPNP_SERVER_MAX_PORT):
addr = (source[0],) + (port,) + source[2:]
try:
test_socket.bind(source)
test_socket.bind(addr)
return port
except OSError:
if port == UPNP_SERVER_MAX_PORT:
if port == UPNP_SERVER_MAX_PORT - 1:
raise
raise RuntimeError("unreachable")
@@ -45,7 +45,11 @@ PLATFORMS_BY_TYPE = {
SupportedModels.CONTACT.value: [Platform.BINARY_SENSOR, Platform.SENSOR],
SupportedModels.MOTION.value: [Platform.BINARY_SENSOR, Platform.SENSOR],
SupportedModels.HUMIDIFIER.value: [Platform.HUMIDIFIER, Platform.SENSOR],
SupportedModels.LOCK.value: [Platform.BINARY_SENSOR, Platform.LOCK],
SupportedModels.LOCK.value: [
Platform.BINARY_SENSOR,
Platform.LOCK,
Platform.SENSOR,
],
}
CLASS_BY_DEVICE = {
SupportedModels.CEILING_LIGHT.value: switchbot.SwitchbotCeilingLight,
@@ -5,7 +5,9 @@ import logging
from typing import Any
from switchbot import (
SwitchbotAccountConnectionError,
SwitchBotAdvertisement,
SwitchbotAuthenticationError,
SwitchbotLock,
SwitchbotModel,
parse_advertisement_data,
@@ -17,7 +19,12 @@ from homeassistant.components.bluetooth import (
async_discovered_service_info,
)
from homeassistant.config_entries import ConfigEntry, ConfigFlow, OptionsFlow
from homeassistant.const import CONF_ADDRESS, CONF_PASSWORD, CONF_SENSOR_TYPE
from homeassistant.const import (
CONF_ADDRESS,
CONF_PASSWORD,
CONF_SENSOR_TYPE,
CONF_USERNAME,
)
from homeassistant.core import callback
from homeassistant.data_entry_flow import AbortFlow, FlowResult
@@ -94,6 +101,8 @@ class SwitchbotConfigFlow(ConfigFlow, domain=DOMAIN):
"name": data["modelFriendlyName"],
"address": short_address(discovery_info.address),
}
if model_name == SwitchbotModel.LOCK:
return await self.async_step_lock_choose_method()
if self._discovered_adv.data["isEncrypted"]:
return await self.async_step_password()
return await self.async_step_confirm()
@@ -151,6 +160,62 @@ class SwitchbotConfigFlow(ConfigFlow, domain=DOMAIN):
},
)
async def async_step_lock_auth(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the SwitchBot API auth step."""
errors = {}
assert self._discovered_adv is not None
description_placeholders = {}
if user_input is not None:
try:
key_details = await self.hass.async_add_executor_job(
SwitchbotLock.retrieve_encryption_key,
self._discovered_adv.address,
user_input[CONF_USERNAME],
user_input[CONF_PASSWORD],
)
except SwitchbotAccountConnectionError as ex:
raise AbortFlow("cannot_connect") from ex
except SwitchbotAuthenticationError as ex:
_LOGGER.debug("Authentication failed: %s", ex, exc_info=True)
errors = {"base": "auth_failed"}
description_placeholders = {"error_detail": str(ex)}
else:
return await self.async_step_lock_key(key_details)
user_input = user_input or {}
return self.async_show_form(
step_id="lock_auth",
errors=errors,
data_schema=vol.Schema(
{
vol.Required(
CONF_USERNAME, default=user_input.get(CONF_USERNAME)
): str,
vol.Required(CONF_PASSWORD): str,
}
),
description_placeholders={
"name": name_from_discovery(self._discovered_adv),
**description_placeholders,
},
)
async def async_step_lock_choose_method(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the SwitchBot API chose method step."""
assert self._discovered_adv is not None
return self.async_show_menu(
step_id="lock_choose_method",
menu_options=["lock_auth", "lock_key"],
description_placeholders={
"name": name_from_discovery(self._discovered_adv),
},
)
async def async_step_lock_key(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
@@ -160,12 +225,11 @@ class SwitchbotConfigFlow(ConfigFlow, domain=DOMAIN):
if user_input is not None:
if not await SwitchbotLock.verify_encryption_key(
self._discovered_adv.device,
user_input.get(CONF_KEY_ID),
user_input.get(CONF_ENCRYPTION_KEY),
user_input[CONF_KEY_ID],
user_input[CONF_ENCRYPTION_KEY],
):
errors = {
CONF_KEY_ID: "key_id_invalid",
CONF_ENCRYPTION_KEY: "encryption_key_invalid",
"base": "encryption_key_invalid",
}
else:
return await self._async_create_entry_from_discovery(user_input)
@@ -229,7 +293,7 @@ class SwitchbotConfigFlow(ConfigFlow, domain=DOMAIN):
device_adv = self._discovered_advs[user_input[CONF_ADDRESS]]
await self._async_set_device(device_adv)
if device_adv.data.get("modelName") == SwitchbotModel.LOCK:
return await self.async_step_lock_key()
return await self.async_step_lock_choose_method()
if device_adv.data["isEncrypted"]:
return await self.async_step_password()
return await self._async_create_entry_from_discovery(user_input)
@@ -241,7 +305,7 @@ class SwitchbotConfigFlow(ConfigFlow, domain=DOMAIN):
device_adv = list(self._discovered_advs.values())[0]
await self._async_set_device(device_adv)
if device_adv.data.get("modelName") == SwitchbotModel.LOCK:
return await self.async_step_lock_key()
return await self.async_step_lock_choose_method()
if device_adv.data["isEncrypted"]:
return await self.async_step_password()
return await self.async_step_confirm()
@@ -2,7 +2,7 @@
"domain": "switchbot",
"name": "SwitchBot",
"documentation": "https://www.home-assistant.io/integrations/switchbot",
"requirements": ["PySwitchbot==0.33.0"],
"requirements": ["PySwitchbot==0.36.3"],
"config_flow": true,
"dependencies": ["bluetooth"],
"codeowners": [
@@ -22,11 +22,25 @@
"key_id": "Key ID",
"encryption_key": "Encryption key"
}
},
"lock_auth": {
"description": "Please provide your SwitchBot app username and password. This data won't be saved and only used to retrieve your locks encryption key. Usernames and passwords are case sensitive.",
"data": {
"username": "[%key:common::config_flow::data::username%]",
"password": "[%key:common::config_flow::data::password%]"
}
},
"lock_choose_method": {
"description": "A SwitchBot lock can be set up in Home Assistant in two different ways.\n\nYou can enter the key id and encryption key yourself, or Home Assistant can import them from your SwitchBot account.",
"menu_options": {
"lock_auth": "SwitchBot account (recommended)",
"lock_key": "Enter lock encryption key manually"
}
}
},
"error": {
"key_id_invalid": "Key ID or Encryption key is invalid",
"encryption_key_invalid": "Key ID or Encryption key is invalid"
"encryption_key_invalid": "Key ID or Encryption key is invalid",
"auth_failed": "Authentication failed: {error_detail}"
},
"abort": {
"already_configured_device": "[%key:common::config_flow::abort::already_configured_device%]",
@@ -7,11 +7,36 @@
"switchbot_unsupported_type": "Unsupported Switchbot Type.",
"unknown": "Unexpected error"
},
"error": {
"auth_failed": "Authentication failed: {error_detail}",
"encryption_key_invalid": "Key ID or Encryption key is invalid"
},
"flow_title": "{name} ({address})",
"step": {
"confirm": {
"description": "Do you want to set up {name}?"
},
"lock_auth": {
"data": {
"password": "Password",
"username": "Username"
},
"description": "Please provide your SwitchBot app username and password. This data won't be saved and only used to retrieve your locks encryption key. Usernames and passwords are case sensitive."
},
"lock_choose_method": {
"description": "A SwitchBot lock can be set up in Home Assistant in two different ways.\n\nYou can enter the key id and encryption key yourself, or Home Assistant can import them from your SwitchBot account.",
"menu_options": {
"lock_auth": "SwitchBot account (recommended)",
"lock_key": "Enter lock encryption key manually"
}
},
"lock_key": {
"data": {
"encryption_key": "Encryption key",
"key_id": "Key ID"
},
"description": "The {name} device requires encryption key, details on how to obtain it can be found in the documentation."
},
"password": {
"data": {
"password": "Password"
@@ -22,18 +47,7 @@
"data": {
"address": "Device address"
}
},
"lock_key": {
"description": "The {name} device requires encryption key, details on how to obtain it can be found in the documentation.",
"data": {
"key_id": "Key ID",
"encryption_key": "Encryption key"
}
}
},
"error": {
"key_id_invalid": "Key ID or Encryption key is invalid",
"encryption_key_invalid": "Key ID or Encryption key is invalid"
}
},
"options": {
@@ -45,4 +59,4 @@
}
}
}
}
}
@@ -7,110 +7,28 @@ from math import ceil
import pytankerkoenig
from requests.exceptions import RequestException
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import (
ATTR_ID,
CONF_API_KEY,
CONF_LATITUDE,
CONF_LOCATION,
CONF_LONGITUDE,
CONF_NAME,
CONF_RADIUS,
CONF_SCAN_INTERVAL,
CONF_SHOW_ON_MAP,
Platform,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ID, CONF_API_KEY, CONF_SHOW_ON_MAP, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
UpdateFailed,
)
from .const import (
CONF_FUEL_TYPES,
CONF_STATIONS,
DEFAULT_RADIUS,
DEFAULT_SCAN_INTERVAL,
DOMAIN,
FUEL_TYPES,
)
from .const import CONF_FUEL_TYPES, CONF_STATIONS, DEFAULT_SCAN_INTERVAL, DOMAIN
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = vol.Schema(
vol.All(
cv.deprecated(DOMAIN),
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Optional(
CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL
): cv.time_period,
vol.Optional(CONF_FUEL_TYPES, default=FUEL_TYPES): vol.All(
cv.ensure_list, [vol.In(FUEL_TYPES)]
),
vol.Inclusive(
CONF_LATITUDE,
"coordinates",
"Latitude and longitude must exist together",
): cv.latitude,
vol.Inclusive(
CONF_LONGITUDE,
"coordinates",
"Latitude and longitude must exist together",
): cv.longitude,
vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS): vol.All(
cv.positive_int, vol.Range(min=1)
),
vol.Optional(CONF_STATIONS, default=[]): vol.All(
cv.ensure_list, [cv.string]
),
vol.Optional(CONF_SHOW_ON_MAP, default=True): cv.boolean,
}
)
},
),
extra=vol.ALLOW_EXTRA,
)
PLATFORMS = [Platform.BINARY_SENSOR, Platform.SENSOR]
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set the tankerkoenig component up."""
if DOMAIN not in config:
return True
conf = config[DOMAIN]
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_NAME: "Home",
CONF_API_KEY: conf[CONF_API_KEY],
CONF_FUEL_TYPES: conf[CONF_FUEL_TYPES],
CONF_LOCATION: {
"latitude": conf.get(CONF_LATITUDE, hass.config.latitude),
"longitude": conf.get(CONF_LONGITUDE, hass.config.longitude),
},
CONF_RADIUS: conf[CONF_RADIUS],
CONF_STATIONS: conf[CONF_STATIONS],
CONF_SHOW_ON_MAP: conf[CONF_SHOW_ON_MAP],
},
)
)
return True
CONFIG_SCHEMA = cv.removed(DOMAIN, raise_if_present=False)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
@@ -67,37 +67,6 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Get the options flow for this handler."""
return OptionsFlowHandler(config_entry)
async def async_step_import(self, config: dict[str, Any]) -> FlowResult:
"""Import YAML configuration."""
await self.async_set_unique_id(
f"{config[CONF_LOCATION][CONF_LATITUDE]}_{config[CONF_LOCATION][CONF_LONGITUDE]}"
)
self._abort_if_unique_id_configured()
selected_station_ids: list[str] = []
# add all nearby stations
nearby_stations = await async_get_nearby_stations(self.hass, config)
for station in nearby_stations.get("stations", []):
selected_station_ids.append(station["id"])
# add all manual added stations
for station_id in config[CONF_STATIONS]:
selected_station_ids.append(station_id)
return self._create_entry(
data={
CONF_NAME: "Home",
CONF_API_KEY: config[CONF_API_KEY],
CONF_FUEL_TYPES: config[CONF_FUEL_TYPES],
CONF_LOCATION: config[CONF_LOCATION],
CONF_RADIUS: config[CONF_RADIUS],
CONF_STATIONS: selected_station_ids,
},
options={
CONF_SHOW_ON_MAP: config[CONF_SHOW_ON_MAP],
},
)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
@@ -3,7 +3,7 @@
"name": "Tasmota",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/tasmota",
"requirements": ["hatasmota==0.6.1"],
"requirements": ["hatasmota==0.6.2"],
"dependencies": ["mqtt"],
"mqtt": ["tasmota/discovery/#"],
"codeowners": ["@emontnemery"],

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