forked from home-assistant/core
Compare commits
49 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 79b1c3f573 | |||
| 46dd245560 | |||
| bbf36d1a36 | |||
| ad74d42b15 | |||
| 953963c95b | |||
| 650f2babf9 | |||
| 979dafd0a7 | |||
| 24b8545ebe | |||
| bf8bfa6321 | |||
| 7fe5fee124 | |||
| 3e7ada2056 | |||
| 7ad75493ff | |||
| 71048545fa | |||
| 49f59007df | |||
| 80b0c10a38 | |||
| 81b95f4050 | |||
| c9380d4972 | |||
| c505bf2df2 | |||
| dfd956b083 | |||
| a50cf1d00a | |||
| 6617d676e5 | |||
| 9f12226b2b | |||
| d8d48b0a21 | |||
| 0cd8dce9df | |||
| 34751fcd86 | |||
| b003d9675c | |||
| 98dd56eed5 | |||
| 66e490e55f | |||
| 0b32caa71f | |||
| 9b46796969 | |||
| 8409385fca | |||
| 27859a2784 | |||
| 28f78c0c67 | |||
| a3429848a2 | |||
| 757d05a74e | |||
| 253950f84f | |||
| af36a67b89 | |||
| b784cc011d | |||
| 7c0a933452 | |||
| 8b207df819 | |||
| d297be2698 | |||
| de67135e86 | |||
| b684007fbb | |||
| 98347345d1 | |||
| c0302e6eca | |||
| 06bc98a3a2 | |||
| 32858bcea3 | |||
| 979260f4be | |||
| 408b52de1b |
+1
-1
@@ -278,7 +278,7 @@ homeassistant/components/notion/* @bachya
|
||||
homeassistant/components/nsw_fuel_station/* @nickw444
|
||||
homeassistant/components/nsw_rural_fire_service_feed/* @exxamalte
|
||||
homeassistant/components/nuheat/* @bdraco
|
||||
homeassistant/components/nuki/* @pvizeli
|
||||
homeassistant/components/nuki/* @pschmitt @pvizeli
|
||||
homeassistant/components/numato/* @clssn
|
||||
homeassistant/components/nut/* @bdraco
|
||||
homeassistant/components/nws/* @MatthewFlamm
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"documentation": "https://www.home-assistant.io/integrations/androidtv",
|
||||
"requirements": [
|
||||
"adb-shell[async]==0.2.0",
|
||||
"androidtv[async]==0.0.45",
|
||||
"androidtv[async]==0.0.46",
|
||||
"pure-python-adb==0.2.2.dev0"
|
||||
],
|
||||
"codeowners": ["@JeffLIrion"]
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"name": "Google Cast",
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/integrations/cast",
|
||||
"requirements": ["pychromecast==7.0.1"],
|
||||
"requirements": ["pychromecast==7.1.2"],
|
||||
"after_dependencies": ["cloud","zeroconf"],
|
||||
"zeroconf": ["_googlecast._tcp.local."],
|
||||
"codeowners": ["@emontnemery"]
|
||||
|
||||
@@ -279,6 +279,8 @@ class CastDevice(MediaPlayerEntity):
|
||||
cast_info.uuid,
|
||||
cast_info.model_name,
|
||||
cast_info.friendly_name,
|
||||
None,
|
||||
None,
|
||||
),
|
||||
ChromeCastZeroconf.get_zeroconf(),
|
||||
)
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
"domain": "discord",
|
||||
"name": "Discord",
|
||||
"documentation": "https://www.home-assistant.io/integrations/discord",
|
||||
"requirements": ["discord.py==1.3.3"],
|
||||
"requirements": ["discord.py==1.3.4"],
|
||||
"codeowners": []
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ class ECWeather(WeatherEntity):
|
||||
@property
|
||||
def temperature(self):
|
||||
"""Return the temperature."""
|
||||
if self.ec_data.conditions.get("temperature").get("value"):
|
||||
if self.ec_data.conditions.get("temperature", {}).get("value"):
|
||||
return float(self.ec_data.conditions["temperature"]["value"])
|
||||
if self.ec_data.hourly_forecasts[0].get("temperature"):
|
||||
return float(self.ec_data.hourly_forecasts[0]["temperature"])
|
||||
@@ -113,35 +113,35 @@ class ECWeather(WeatherEntity):
|
||||
@property
|
||||
def humidity(self):
|
||||
"""Return the humidity."""
|
||||
if self.ec_data.conditions.get("humidity").get("value"):
|
||||
if self.ec_data.conditions.get("humidity", {}).get("value"):
|
||||
return float(self.ec_data.conditions["humidity"]["value"])
|
||||
return None
|
||||
|
||||
@property
|
||||
def wind_speed(self):
|
||||
"""Return the wind speed."""
|
||||
if self.ec_data.conditions.get("wind_speed").get("value"):
|
||||
if self.ec_data.conditions.get("wind_speed", {}).get("value"):
|
||||
return float(self.ec_data.conditions["wind_speed"]["value"])
|
||||
return None
|
||||
|
||||
@property
|
||||
def wind_bearing(self):
|
||||
"""Return the wind bearing."""
|
||||
if self.ec_data.conditions.get("wind_bearing").get("value"):
|
||||
if self.ec_data.conditions.get("wind_bearing", {}).get("value"):
|
||||
return float(self.ec_data.conditions["wind_bearing"]["value"])
|
||||
return None
|
||||
|
||||
@property
|
||||
def pressure(self):
|
||||
"""Return the pressure."""
|
||||
if self.ec_data.conditions.get("pressure").get("value"):
|
||||
if self.ec_data.conditions.get("pressure", {}).get("value"):
|
||||
return 10 * float(self.ec_data.conditions["pressure"]["value"])
|
||||
return None
|
||||
|
||||
@property
|
||||
def visibility(self):
|
||||
"""Return the visibility."""
|
||||
if self.ec_data.conditions.get("visibility").get("value"):
|
||||
if self.ec_data.conditions.get("visibility", {}).get("value"):
|
||||
return float(self.ec_data.conditions["visibility"]["value"])
|
||||
return None
|
||||
|
||||
@@ -150,7 +150,7 @@ class ECWeather(WeatherEntity):
|
||||
"""Return the weather condition."""
|
||||
icon_code = None
|
||||
|
||||
if self.ec_data.conditions.get("icon_code").get("value"):
|
||||
if self.ec_data.conditions.get("icon_code", {}).get("value"):
|
||||
icon_code = self.ec_data.conditions["icon_code"]["value"]
|
||||
elif self.ec_data.hourly_forecasts[0].get("icon_code"):
|
||||
icon_code = self.ec_data.hourly_forecasts[0]["icon_code"]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"domain": "frontend",
|
||||
"name": "Home Assistant Frontend",
|
||||
"documentation": "https://www.home-assistant.io/integrations/frontend",
|
||||
"requirements": ["home-assistant-frontend==20200715.0"],
|
||||
"requirements": ["home-assistant-frontend==20200716.0"],
|
||||
"dependencies": [
|
||||
"api",
|
||||
"auth",
|
||||
|
||||
@@ -353,7 +353,7 @@ def setup(hass: HomeAssistant, base_config):
|
||||
return True
|
||||
|
||||
|
||||
class CecDevice(Entity):
|
||||
class CecEntity(Entity):
|
||||
"""Representation of a HDMI CEC device entity."""
|
||||
|
||||
def __init__(self, device, logical) -> None:
|
||||
@@ -388,6 +388,15 @@ class CecDevice(Entity):
|
||||
"""Device status changed, schedule an update."""
|
||||
self.schedule_update_ha_state(True)
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""
|
||||
Return false.
|
||||
|
||||
CecEntity.update() is called by the HDMI network when there is new data.
|
||||
"""
|
||||
return False
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the device."""
|
||||
|
||||
@@ -43,7 +43,7 @@ from homeassistant.const import (
|
||||
STATE_PLAYING,
|
||||
)
|
||||
|
||||
from . import ATTR_NEW, CecDevice
|
||||
from . import ATTR_NEW, CecEntity
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -57,16 +57,16 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
entities = []
|
||||
for device in discovery_info[ATTR_NEW]:
|
||||
hdmi_device = hass.data.get(device)
|
||||
entities.append(CecPlayerDevice(hdmi_device, hdmi_device.logical_address))
|
||||
entities.append(CecPlayerEntity(hdmi_device, hdmi_device.logical_address))
|
||||
add_entities(entities, True)
|
||||
|
||||
|
||||
class CecPlayerDevice(CecDevice, MediaPlayerEntity):
|
||||
class CecPlayerEntity(CecEntity, MediaPlayerEntity):
|
||||
"""Representation of a HDMI device as a Media player."""
|
||||
|
||||
def __init__(self, device, logical) -> None:
|
||||
"""Initialize the HDMI device."""
|
||||
CecDevice.__init__(self, device, logical)
|
||||
CecEntity.__init__(self, device, logical)
|
||||
self.entity_id = f"{DOMAIN}.hdmi_{hex(self._logical_address)[2:]}"
|
||||
|
||||
def send_keypress(self, key):
|
||||
|
||||
@@ -4,7 +4,7 @@ import logging
|
||||
from homeassistant.components.switch import DOMAIN, SwitchEntity
|
||||
from homeassistant.const import STATE_OFF, STATE_ON, STATE_STANDBY
|
||||
|
||||
from . import ATTR_NEW, CecDevice
|
||||
from . import ATTR_NEW, CecEntity
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -18,27 +18,29 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
entities = []
|
||||
for device in discovery_info[ATTR_NEW]:
|
||||
hdmi_device = hass.data.get(device)
|
||||
entities.append(CecSwitchDevice(hdmi_device, hdmi_device.logical_address))
|
||||
entities.append(CecSwitchEntity(hdmi_device, hdmi_device.logical_address))
|
||||
add_entities(entities, True)
|
||||
|
||||
|
||||
class CecSwitchDevice(CecDevice, SwitchEntity):
|
||||
class CecSwitchEntity(CecEntity, SwitchEntity):
|
||||
"""Representation of a HDMI device as a Switch."""
|
||||
|
||||
def __init__(self, device, logical) -> None:
|
||||
"""Initialize the HDMI device."""
|
||||
CecDevice.__init__(self, device, logical)
|
||||
CecEntity.__init__(self, device, logical)
|
||||
self.entity_id = f"{DOMAIN}.hdmi_{hex(self._logical_address)[2:]}"
|
||||
|
||||
def turn_on(self, **kwargs) -> None:
|
||||
"""Turn device on."""
|
||||
self._device.turn_on()
|
||||
self._state = STATE_ON
|
||||
self.schedule_update_ha_state(force_refresh=False)
|
||||
|
||||
def turn_off(self, **kwargs) -> None:
|
||||
"""Turn device off."""
|
||||
self._device.turn_off()
|
||||
self._state = STATE_ON
|
||||
self._state = STATE_OFF
|
||||
self.schedule_update_ha_state(force_refresh=False)
|
||||
|
||||
def toggle(self, **kwargs):
|
||||
"""Toggle the entity."""
|
||||
@@ -47,6 +49,7 @@ class CecSwitchDevice(CecDevice, SwitchEntity):
|
||||
self._state = STATE_OFF
|
||||
else:
|
||||
self._state = STATE_ON
|
||||
self.schedule_update_ha_state(force_refresh=False)
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
|
||||
@@ -74,6 +74,13 @@ from .util import temperature_to_homekit, temperature_to_states
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_HVAC_MODES = [
|
||||
HVAC_MODE_HEAT,
|
||||
HVAC_MODE_COOL,
|
||||
HVAC_MODE_HEAT_COOL,
|
||||
HVAC_MODE_OFF,
|
||||
]
|
||||
|
||||
HC_HOMEKIT_VALID_MODES_WATER_HEATER = {"Heat": 1}
|
||||
UNIT_HASS_TO_HOMEKIT = {TEMP_CELSIUS: 0, TEMP_FAHRENHEIT: 1}
|
||||
|
||||
@@ -117,7 +124,6 @@ class Thermostat(HomeAccessory):
|
||||
"""Initialize a Thermostat accessory object."""
|
||||
super().__init__(*args, category=CATEGORY_THERMOSTAT)
|
||||
self._unit = self.hass.config.units.temperature_unit
|
||||
self._state_updates = 0
|
||||
self.hc_homekit_to_hass = None
|
||||
self.hc_hass_to_homekit = None
|
||||
hc_min_temp, hc_max_temp = self.get_temperature_range()
|
||||
@@ -237,14 +243,20 @@ class Thermostat(HomeAccessory):
|
||||
# Homekit will reset the mode when VIEWING the temp
|
||||
# Ignore it if its the same mode
|
||||
if char_values[CHAR_TARGET_HEATING_COOLING] != homekit_hvac_mode:
|
||||
service = SERVICE_SET_HVAC_MODE_THERMOSTAT
|
||||
hass_value = self.hc_homekit_to_hass[
|
||||
char_values[CHAR_TARGET_HEATING_COOLING]
|
||||
]
|
||||
params = {ATTR_HVAC_MODE: hass_value}
|
||||
events.append(
|
||||
f"{CHAR_TARGET_HEATING_COOLING} to {char_values[CHAR_TARGET_HEATING_COOLING]}"
|
||||
)
|
||||
target_hc = char_values[CHAR_TARGET_HEATING_COOLING]
|
||||
if target_hc in self.hc_homekit_to_hass:
|
||||
service = SERVICE_SET_HVAC_MODE_THERMOSTAT
|
||||
hass_value = self.hc_homekit_to_hass[target_hc]
|
||||
params = {ATTR_HVAC_MODE: hass_value}
|
||||
events.append(
|
||||
f"{CHAR_TARGET_HEATING_COOLING} to {char_values[CHAR_TARGET_HEATING_COOLING]}"
|
||||
)
|
||||
else:
|
||||
_LOGGER.warning(
|
||||
"The entity: %s does not have a %s mode",
|
||||
self.entity_id,
|
||||
target_hc,
|
||||
)
|
||||
|
||||
if CHAR_TARGET_TEMPERATURE in char_values:
|
||||
hc_target_temp = char_values[CHAR_TARGET_TEMPERATURE]
|
||||
@@ -321,20 +333,8 @@ class Thermostat(HomeAccessory):
|
||||
|
||||
def _configure_hvac_modes(self, state):
|
||||
"""Configure target mode characteristics."""
|
||||
hc_modes = state.attributes.get(ATTR_HVAC_MODES)
|
||||
if not hc_modes:
|
||||
# This cannot be none OR an empty list
|
||||
_LOGGER.error(
|
||||
"%s: HVAC modes not yet available. Please disable auto start for homekit",
|
||||
self.entity_id,
|
||||
)
|
||||
hc_modes = (
|
||||
HVAC_MODE_HEAT,
|
||||
HVAC_MODE_COOL,
|
||||
HVAC_MODE_HEAT_COOL,
|
||||
HVAC_MODE_OFF,
|
||||
)
|
||||
|
||||
# This cannot be none OR an empty list
|
||||
hc_modes = state.attributes.get(ATTR_HVAC_MODES) or DEFAULT_HVAC_MODES
|
||||
# Determine available modes for this entity,
|
||||
# Prefer HEAT_COOL over AUTO and COOL over FAN_ONLY, DRY
|
||||
#
|
||||
@@ -379,26 +379,23 @@ class Thermostat(HomeAccessory):
|
||||
@callback
|
||||
def async_update_state(self, new_state):
|
||||
"""Update thermostat state after state changed."""
|
||||
if self._state_updates < 3:
|
||||
# When we get the first state updates
|
||||
# we recheck valid hvac modes as the entity
|
||||
# may not have been fully setup when we saw it the
|
||||
# first time
|
||||
original_hc_hass_to_homekit = self.hc_hass_to_homekit
|
||||
self._configure_hvac_modes(new_state)
|
||||
if self.hc_hass_to_homekit != original_hc_hass_to_homekit:
|
||||
if self.char_target_heat_cool.value not in self.hc_homekit_to_hass:
|
||||
# We must make sure the char value is
|
||||
# in the new valid values before
|
||||
# setting the new valid values or
|
||||
# changing them with throw
|
||||
self.char_target_heat_cool.set_value(
|
||||
list(self.hc_homekit_to_hass)[0], should_notify=False
|
||||
)
|
||||
self.char_target_heat_cool.override_properties(
|
||||
valid_values=self.hc_hass_to_homekit
|
||||
# We always recheck valid hvac modes as the entity
|
||||
# may not have been fully setup when we saw it last
|
||||
original_hc_hass_to_homekit = self.hc_hass_to_homekit
|
||||
self._configure_hvac_modes(new_state)
|
||||
|
||||
if self.hc_hass_to_homekit != original_hc_hass_to_homekit:
|
||||
if self.char_target_heat_cool.value not in self.hc_homekit_to_hass:
|
||||
# We must make sure the char value is
|
||||
# in the new valid values before
|
||||
# setting the new valid values or
|
||||
# changing them with throw
|
||||
self.char_target_heat_cool.set_value(
|
||||
list(self.hc_homekit_to_hass)[0], should_notify=False
|
||||
)
|
||||
self._state_updates += 1
|
||||
self.char_target_heat_cool.override_properties(
|
||||
valid_values=self.hc_hass_to_homekit
|
||||
)
|
||||
|
||||
self._async_update_state(new_state)
|
||||
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
"domain": "insteon",
|
||||
"name": "Insteon",
|
||||
"documentation": "https://www.home-assistant.io/integrations/insteon",
|
||||
"requirements": ["pyinsteon==1.0.5"],
|
||||
"requirements": ["pyinsteon==1.0.7"],
|
||||
"codeowners": ["@teharris1"]
|
||||
}
|
||||
@@ -714,10 +714,10 @@ class MQTT:
|
||||
|
||||
if will_message is not None:
|
||||
self._mqttc.will_set( # pylint: disable=no-value-for-parameter
|
||||
*attr.astuple(
|
||||
will_message,
|
||||
filter=lambda attr, value: attr.name != "subscribed_topic",
|
||||
)
|
||||
topic=will_message.topic,
|
||||
payload=will_message.payload,
|
||||
qos=will_message.qos,
|
||||
retain=will_message.retain,
|
||||
)
|
||||
|
||||
async def async_publish(
|
||||
@@ -864,11 +864,10 @@ class MQTT:
|
||||
birth_message = Message(**self.conf[CONF_BIRTH_MESSAGE])
|
||||
self.hass.add_job(
|
||||
self.async_publish( # pylint: disable=no-value-for-parameter
|
||||
*attr.astuple(
|
||||
birth_message,
|
||||
filter=lambda attr, value: attr.name
|
||||
not in ["subscribed_topic", "timestamp"],
|
||||
)
|
||||
topic=birth_message.topic,
|
||||
payload=birth_message.payload,
|
||||
qos=birth_message.qos,
|
||||
retain=birth_message.retain,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -264,12 +264,13 @@ class NeatoConnectedVacuum(StateVacuumEntity):
|
||||
maps["name"],
|
||||
robot_boundaries,
|
||||
)
|
||||
self._robot_boundaries += robot_boundaries["data"]["boundaries"]
|
||||
_LOGGER.debug(
|
||||
"List of boundaries for '%s': %s",
|
||||
self.entity_id,
|
||||
self._robot_boundaries,
|
||||
)
|
||||
if "boundaries" in robot_boundaries["data"]:
|
||||
self._robot_boundaries += robot_boundaries["data"]["boundaries"]
|
||||
_LOGGER.debug(
|
||||
"List of boundaries for '%s': %s",
|
||||
self.entity_id,
|
||||
self._robot_boundaries,
|
||||
)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
|
||||
@@ -555,7 +555,7 @@ class NetatmoPublicSensor(Entity):
|
||||
@property
|
||||
def available(self):
|
||||
"""Return True if entity is available."""
|
||||
return bool(self._state)
|
||||
return self._state is not None
|
||||
|
||||
def update(self):
|
||||
"""Get the latest data from Netatmo API and updates the states."""
|
||||
|
||||
@@ -51,7 +51,7 @@ LOCK_N_GO_SERVICE_SCHEMA = vol.Schema(
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
"""Set up the Nuki lock platform."""
|
||||
bridge = NukiBridge(
|
||||
config[CONF_HOST], config[CONF_TOKEN], config[CONF_PORT], DEFAULT_TIMEOUT,
|
||||
config[CONF_HOST], config[CONF_TOKEN], config[CONF_PORT], True, DEFAULT_TIMEOUT,
|
||||
)
|
||||
|
||||
devices = [NukiLockEntity(lock) for lock in bridge.locks]
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
"domain": "nuki",
|
||||
"name": "Nuki",
|
||||
"documentation": "https://www.home-assistant.io/integrations/nuki",
|
||||
"requirements": ["pynuki==1.3.7"],
|
||||
"codeowners": ["@pvizeli"]
|
||||
"requirements": ["pynuki==1.3.8"],
|
||||
"codeowners": ["@pschmitt", "@pvizeli"]
|
||||
}
|
||||
|
||||
@@ -174,7 +174,8 @@ class ZWaveClimateEntity(ZWaveDeviceEntity, ClimateEntity):
|
||||
def hvac_mode(self):
|
||||
"""Return hvac operation ie. heat, cool mode."""
|
||||
if not self.values.mode:
|
||||
return None
|
||||
# Thermostat(valve) with no support for setting a mode is considered heating-only
|
||||
return HVAC_MODE_HEAT
|
||||
return ZW_HVAC_MODE_MAPPINGS.get(
|
||||
self.values.mode.value[VALUE_SELECTED_ID], HVAC_MODE_HEAT_COOL
|
||||
)
|
||||
@@ -197,7 +198,7 @@ class ZWaveClimateEntity(ZWaveDeviceEntity, ClimateEntity):
|
||||
@property
|
||||
def temperature_unit(self):
|
||||
"""Return the unit of measurement."""
|
||||
if self.values.temperature and self.values.temperature.units == "F":
|
||||
if self.values.temperature is not None and self.values.temperature.units == "F":
|
||||
return TEMP_FAHRENHEIT
|
||||
return TEMP_CELSIUS
|
||||
|
||||
@@ -220,6 +221,8 @@ class ZWaveClimateEntity(ZWaveDeviceEntity, ClimateEntity):
|
||||
def preset_mode(self):
|
||||
"""Return preset operation ie. eco, away."""
|
||||
# A Zwave mode that can not be translated to a hass mode is considered a preset
|
||||
if not self.values.mode:
|
||||
return None
|
||||
if self.values.mode.value[VALUE_SELECTED_ID] not in MODES_LIST:
|
||||
return self.values.mode.value[VALUE_SELECTED_LABEL]
|
||||
return PRESET_NONE
|
||||
@@ -274,8 +277,14 @@ class ZWaveClimateEntity(ZWaveDeviceEntity, ClimateEntity):
|
||||
|
||||
async def async_set_hvac_mode(self, hvac_mode):
|
||||
"""Set new target hvac mode."""
|
||||
if not self.values.mode:
|
||||
# Thermostat(valve) with no support for setting a mode
|
||||
_LOGGER.warning(
|
||||
"Thermostat %s does not support setting a mode", self.entity_id
|
||||
)
|
||||
return
|
||||
hvac_mode_value = self._hvac_modes.get(hvac_mode)
|
||||
if not hvac_mode_value:
|
||||
if hvac_mode_value is None:
|
||||
_LOGGER.warning("Received an invalid hvac mode: %s", hvac_mode)
|
||||
return
|
||||
self.values.mode.send_value(hvac_mode_value)
|
||||
@@ -320,8 +329,11 @@ class ZWaveClimateEntity(ZWaveDeviceEntity, ClimateEntity):
|
||||
|
||||
def _get_current_mode_setpoint_values(self) -> Tuple:
|
||||
"""Return a tuple of current setpoint Z-Wave value(s)."""
|
||||
current_mode = self.values.mode.value[VALUE_SELECTED_ID]
|
||||
setpoint_names = MODE_SETPOINT_MAPPINGS.get(current_mode, ())
|
||||
if not self.values.mode:
|
||||
setpoint_names = ("setpoint_heating",)
|
||||
else:
|
||||
current_mode = self.values.mode.value[VALUE_SELECTED_ID]
|
||||
setpoint_names = MODE_SETPOINT_MAPPINGS.get(current_mode, ())
|
||||
# we do not want None values in our tuple so check if the value exists
|
||||
return tuple(
|
||||
getattr(self.values, value_name)
|
||||
@@ -331,20 +343,21 @@ class ZWaveClimateEntity(ZWaveDeviceEntity, ClimateEntity):
|
||||
|
||||
def _set_modes_and_presets(self):
|
||||
"""Convert Z-Wave Thermostat modes into Home Assistant modes and presets."""
|
||||
if not self.values.mode:
|
||||
return
|
||||
all_modes = {}
|
||||
all_presets = {PRESET_NONE: None}
|
||||
# Z-Wave uses one list for both modes and presets.
|
||||
# Iterate over all Z-Wave ThermostatModes and extract the hvac modes and presets.
|
||||
for val in self.values.mode.value[VALUE_LIST]:
|
||||
if val[VALUE_ID] in MODES_LIST:
|
||||
# treat value as hvac mode
|
||||
hass_mode = ZW_HVAC_MODE_MAPPINGS.get(val[VALUE_ID])
|
||||
all_modes[hass_mode] = val[VALUE_ID]
|
||||
else:
|
||||
# treat value as hvac preset
|
||||
all_presets[val[VALUE_LABEL]] = val[VALUE_ID]
|
||||
if self.values.mode:
|
||||
# Z-Wave uses one list for both modes and presets.
|
||||
# Iterate over all Z-Wave ThermostatModes and extract the hvac modes and presets.
|
||||
for val in self.values.mode.value[VALUE_LIST]:
|
||||
if val[VALUE_ID] in MODES_LIST:
|
||||
# treat value as hvac mode
|
||||
hass_mode = ZW_HVAC_MODE_MAPPINGS.get(val[VALUE_ID])
|
||||
all_modes[hass_mode] = val[VALUE_ID]
|
||||
else:
|
||||
# treat value as hvac preset
|
||||
all_presets[val[VALUE_LABEL]] = val[VALUE_ID]
|
||||
else:
|
||||
all_modes[HVAC_MODE_HEAT] = None
|
||||
self._hvac_modes = all_modes
|
||||
self._hvac_presets = all_presets
|
||||
|
||||
|
||||
@@ -131,6 +131,37 @@ DISCOVERY_SCHEMAS = (
|
||||
},
|
||||
},
|
||||
},
|
||||
{ # Z-Wave Thermostat device without mode support
|
||||
const.DISC_COMPONENT: "climate",
|
||||
const.DISC_GENERIC_DEVICE_CLASS: (const_ozw.GENERIC_TYPE_THERMOSTAT,),
|
||||
const.DISC_SPECIFIC_DEVICE_CLASS: (
|
||||
const_ozw.SPECIFIC_TYPE_SETPOINT_THERMOSTAT,
|
||||
),
|
||||
const.DISC_VALUES: {
|
||||
const.DISC_PRIMARY: {
|
||||
const.DISC_COMMAND_CLASS: (CommandClass.THERMOSTAT_SETPOINT,)
|
||||
},
|
||||
"temperature": {
|
||||
const.DISC_COMMAND_CLASS: (CommandClass.SENSOR_MULTILEVEL,),
|
||||
const.DISC_INDEX: (1,),
|
||||
const.DISC_OPTIONAL: True,
|
||||
},
|
||||
"operating_state": {
|
||||
const.DISC_COMMAND_CLASS: (CommandClass.THERMOSTAT_OPERATING_STATE,),
|
||||
const.DISC_OPTIONAL: True,
|
||||
},
|
||||
"valve_position": {
|
||||
const.DISC_COMMAND_CLASS: (CommandClass.SWITCH_MULTILEVEL,),
|
||||
const.DISC_INDEX: (0,),
|
||||
const.DISC_OPTIONAL: True,
|
||||
},
|
||||
"setpoint_heating": {
|
||||
const.DISC_COMMAND_CLASS: (CommandClass.THERMOSTAT_SETPOINT,),
|
||||
const.DISC_INDEX: (1,),
|
||||
const.DISC_OPTIONAL: True,
|
||||
},
|
||||
},
|
||||
},
|
||||
{ # Rollershutter
|
||||
const.DISC_COMPONENT: "cover",
|
||||
const.DISC_GENERIC_DEVICE_CLASS: (const_ozw.GENERIC_TYPE_SWITCH_MULTILEVEL,),
|
||||
|
||||
@@ -215,7 +215,7 @@ def play_on_sonos(hass, service_call):
|
||||
|
||||
sonos = hass.components.sonos
|
||||
try:
|
||||
sonos_id = sonos.get_coordinator_id(entity_id)
|
||||
sonos_name = sonos.get_coordinator_name(entity_id)
|
||||
except HomeAssistantError as err:
|
||||
_LOGGER.error("Cannot get Sonos device: %s", err)
|
||||
return
|
||||
@@ -239,10 +239,10 @@ def play_on_sonos(hass, service_call):
|
||||
else:
|
||||
plex_server = next(iter(plex_servers))
|
||||
|
||||
sonos_speaker = plex_server.account.sonos_speaker_by_id(sonos_id)
|
||||
sonos_speaker = plex_server.account.sonos_speaker(sonos_name)
|
||||
if sonos_speaker is None:
|
||||
_LOGGER.error(
|
||||
"Sonos speaker '%s' could not be found on this Plex account", sonos_id
|
||||
"Sonos speaker '%s' could not be found on this Plex account", sonos_name
|
||||
)
|
||||
return
|
||||
|
||||
|
||||
@@ -23,8 +23,9 @@ from homeassistant.const import (
|
||||
UNIT_PERCENTAGE,
|
||||
UV_INDEX,
|
||||
)
|
||||
from homeassistant.core import callback
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.helpers.restore_state import RestoreEntity
|
||||
|
||||
from .const import (
|
||||
ATTR_EVENT,
|
||||
@@ -92,9 +93,15 @@ def _bytearray_string(data):
|
||||
raise vol.Invalid("Data must be a hex string with multiple of two characters")
|
||||
|
||||
|
||||
def _ensure_device(value):
|
||||
if value is None:
|
||||
return DEVICE_DATA_SCHEMA({})
|
||||
return DEVICE_DATA_SCHEMA(value)
|
||||
|
||||
|
||||
SERVICE_SEND_SCHEMA = vol.Schema({ATTR_EVENT: _bytearray_string})
|
||||
|
||||
DEVICE_SCHEMA = vol.Schema(
|
||||
DEVICE_DATA_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
|
||||
vol.Optional(CONF_FIRE_EVENT, default=False): cv.boolean,
|
||||
@@ -110,7 +117,7 @@ BASE_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Optional(CONF_DEBUG, default=False): cv.boolean,
|
||||
vol.Optional(CONF_AUTOMATIC_ADD, default=False): cv.boolean,
|
||||
vol.Optional(CONF_DEVICES, default={}): {cv.string: DEVICE_SCHEMA},
|
||||
vol.Optional(CONF_DEVICES, default={}): {cv.string: _ensure_device},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -187,7 +194,7 @@ def setup_internal(hass, config):
|
||||
"sub_type": event.device.subtype,
|
||||
"type_string": event.device.type_string,
|
||||
"id_string": event.device.id_string,
|
||||
"data": "".join(f"{x:02x}" for x in event.data),
|
||||
"data": binascii.hexlify(event.data).decode("ASCII"),
|
||||
"values": getattr(event, "values", None),
|
||||
}
|
||||
|
||||
@@ -332,28 +339,35 @@ def get_device_id(device, data_bits=None):
|
||||
if data_bits and device.packettype == DEVICE_PACKET_TYPE_LIGHTING4:
|
||||
masked_id = get_pt2262_deviceid(id_string, data_bits)
|
||||
if masked_id:
|
||||
id_string = str(masked_id)
|
||||
id_string = masked_id.decode("ASCII")
|
||||
|
||||
return (f"{device.packettype:x}", f"{device.subtype:x}", id_string)
|
||||
|
||||
|
||||
class RfxtrxDevice(Entity):
|
||||
class RfxtrxEntity(RestoreEntity):
|
||||
"""Represents a Rfxtrx device.
|
||||
|
||||
Contains the common logic for Rfxtrx lights and switches.
|
||||
"""
|
||||
|
||||
def __init__(self, device, device_id, signal_repetitions, event=None):
|
||||
def __init__(self, device, device_id, event=None):
|
||||
"""Initialize the device."""
|
||||
self.signal_repetitions = signal_repetitions
|
||||
self._name = f"{device.type_string} {device.id_string}"
|
||||
self._device = device
|
||||
self._state = None
|
||||
self._event = event
|
||||
self._device_id = device_id
|
||||
self._unique_id = "_".join(x for x in self._device_id)
|
||||
|
||||
if event:
|
||||
self._apply_event(event)
|
||||
async def async_added_to_hass(self):
|
||||
"""Restore RFXtrx device state (ON/OFF)."""
|
||||
if self._event:
|
||||
self._apply_event(self._event)
|
||||
|
||||
self.async_on_remove(
|
||||
self.hass.helpers.dispatcher.async_dispatcher_connect(
|
||||
SIGNAL_EVENT, self._handle_event
|
||||
)
|
||||
)
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
@@ -366,9 +380,11 @@ class RfxtrxDevice(Entity):
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Return true if device is on."""
|
||||
return self._state
|
||||
def device_state_attributes(self):
|
||||
"""Return the device state attributes."""
|
||||
if not self._event:
|
||||
return None
|
||||
return {ATTR_EVENT: "".join(f"{x:02x}" for x in self._event.data)}
|
||||
|
||||
@property
|
||||
def assumed_state(self):
|
||||
@@ -391,6 +407,24 @@ class RfxtrxDevice(Entity):
|
||||
|
||||
def _apply_event(self, event):
|
||||
"""Apply a received event."""
|
||||
self._event = event
|
||||
|
||||
@callback
|
||||
def _handle_event(self, event, device_id):
|
||||
"""Handle a reception of data, overridden by other classes."""
|
||||
|
||||
|
||||
class RfxtrxCommandEntity(RfxtrxEntity):
|
||||
"""Represents a Rfxtrx device.
|
||||
|
||||
Contains the common logic for Rfxtrx lights and switches.
|
||||
"""
|
||||
|
||||
def __init__(self, device, device_id, signal_repetitions=1, event=None):
|
||||
"""Initialzie a switch or light device."""
|
||||
super().__init__(device, device_id, event=event)
|
||||
self.signal_repetitions = signal_repetitions
|
||||
self._state = None
|
||||
|
||||
def _send_command(self, command, brightness=0):
|
||||
rfx_object = self.hass.data[DATA_RFXOBJECT]
|
||||
|
||||
@@ -17,14 +17,15 @@ from . import (
|
||||
CONF_AUTOMATIC_ADD,
|
||||
CONF_DATA_BITS,
|
||||
CONF_OFF_DELAY,
|
||||
DOMAIN,
|
||||
SIGNAL_EVENT,
|
||||
RfxtrxEntity,
|
||||
find_possible_pt2262_device,
|
||||
get_device_id,
|
||||
get_pt2262_cmd,
|
||||
get_rfx_object,
|
||||
)
|
||||
from .const import (
|
||||
ATTR_EVENT,
|
||||
COMMAND_OFF_LIST,
|
||||
COMMAND_ON_LIST,
|
||||
DATA_RFXTRX_CONFIG,
|
||||
@@ -54,7 +55,7 @@ async def async_setup_entry(
|
||||
_LOGGER.error("Invalid device: %s", packet_id)
|
||||
continue
|
||||
if not supported(event):
|
||||
return
|
||||
continue
|
||||
|
||||
device_id = get_device_id(event.device, data_bits=entity.get(CONF_DATA_BITS))
|
||||
if device_id in device_ids:
|
||||
@@ -105,7 +106,7 @@ async def async_setup_entry(
|
||||
)
|
||||
|
||||
|
||||
class RfxtrxBinarySensor(BinarySensorEntity):
|
||||
class RfxtrxBinarySensor(RfxtrxEntity, BinarySensorEntity):
|
||||
"""A representation of a RFXtrx binary sensor."""
|
||||
|
||||
def __init__(
|
||||
@@ -120,95 +121,49 @@ class RfxtrxBinarySensor(BinarySensorEntity):
|
||||
event=None,
|
||||
):
|
||||
"""Initialize the RFXtrx sensor."""
|
||||
self.event = None
|
||||
self._device = device
|
||||
self._name = f"{device.type_string} {device.id_string}"
|
||||
super().__init__(device, device_id, event=event)
|
||||
self._device_class = device_class
|
||||
self._data_bits = data_bits
|
||||
self._off_delay = off_delay
|
||||
self._state = False
|
||||
self.delay_listener = None
|
||||
self._state = None
|
||||
self._delay_listener = None
|
||||
self._cmd_on = cmd_on
|
||||
self._cmd_off = cmd_off
|
||||
|
||||
self._device_id = device_id
|
||||
self._unique_id = "_".join(x for x in self._device_id)
|
||||
|
||||
if event:
|
||||
self._apply_event(event)
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Restore RFXtrx switch device state (ON/OFF)."""
|
||||
"""Restore device state."""
|
||||
await super().async_added_to_hass()
|
||||
|
||||
self.async_on_remove(
|
||||
self.hass.helpers.dispatcher.async_dispatcher_connect(
|
||||
SIGNAL_EVENT, self._handle_event
|
||||
)
|
||||
)
|
||||
if self._event is None:
|
||||
old_state = await self.async_get_last_state()
|
||||
if old_state is not None:
|
||||
event = old_state.attributes.get(ATTR_EVENT)
|
||||
if event:
|
||||
self._apply_event(get_rfx_object(event))
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the device name."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def data_bits(self):
|
||||
"""Return the number of data bits."""
|
||||
return self._data_bits
|
||||
|
||||
@property
|
||||
def cmd_on(self):
|
||||
"""Return the value of the 'On' command."""
|
||||
return self._cmd_on
|
||||
|
||||
@property
|
||||
def cmd_off(self):
|
||||
"""Return the value of the 'Off' command."""
|
||||
return self._cmd_off
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""No polling needed."""
|
||||
return False
|
||||
def force_update(self) -> bool:
|
||||
"""We should force updates. Repeated states have meaning."""
|
||||
return True
|
||||
|
||||
@property
|
||||
def device_class(self):
|
||||
"""Return the sensor class."""
|
||||
return self._device_class
|
||||
|
||||
@property
|
||||
def off_delay(self):
|
||||
"""Return the off_delay attribute value."""
|
||||
return self._off_delay
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Return true if the sensor state is True."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return unique identifier of remote device."""
|
||||
return self._unique_id
|
||||
|
||||
@property
|
||||
def device_info(self):
|
||||
"""Return the device info."""
|
||||
return {
|
||||
"identifiers": {(DOMAIN, *self._device_id)},
|
||||
"name": f"{self._device.type_string} {self._device.id_string}",
|
||||
"model": self._device.type_string,
|
||||
}
|
||||
|
||||
def _apply_event_lighting4(self, event):
|
||||
"""Apply event for a lighting 4 device."""
|
||||
if self.data_bits is not None:
|
||||
cmd = get_pt2262_cmd(event.device.id_string, self.data_bits)
|
||||
if self._data_bits is not None:
|
||||
cmd = get_pt2262_cmd(event.device.id_string, self._data_bits)
|
||||
cmd = int(cmd, 16)
|
||||
if cmd == self.cmd_on:
|
||||
if cmd == self._cmd_on:
|
||||
self._state = True
|
||||
elif cmd == self.cmd_off:
|
||||
elif cmd == self._cmd_off:
|
||||
self._state = False
|
||||
else:
|
||||
self._state = True
|
||||
@@ -221,6 +176,7 @@ class RfxtrxBinarySensor(BinarySensorEntity):
|
||||
|
||||
def _apply_event(self, event):
|
||||
"""Apply command from rfxtrx."""
|
||||
super()._apply_event(event)
|
||||
if event.device.packettype == DEVICE_PACKET_TYPE_LIGHTING4:
|
||||
self._apply_event_lighting4(event)
|
||||
else:
|
||||
@@ -243,15 +199,15 @@ class RfxtrxBinarySensor(BinarySensorEntity):
|
||||
|
||||
self.async_write_ha_state()
|
||||
|
||||
if self.is_on and self.off_delay is not None and self.delay_listener is None:
|
||||
if self.is_on and self._off_delay is not None and self._delay_listener is None:
|
||||
|
||||
@callback
|
||||
def off_delay_listener(now):
|
||||
"""Switch device off after a delay."""
|
||||
self.delay_listener = None
|
||||
self._delay_listener = None
|
||||
self._state = False
|
||||
self.async_write_ha_state()
|
||||
|
||||
self.delay_listener = evt.async_call_later(
|
||||
self.hass, self.off_delay.total_seconds(), off_delay_listener
|
||||
self._delay_listener = evt.async_call_later(
|
||||
self.hass, self._off_delay.total_seconds(), off_delay_listener
|
||||
)
|
||||
|
||||
@@ -4,14 +4,14 @@ import logging
|
||||
from homeassistant.components.cover import CoverEntity
|
||||
from homeassistant.const import CONF_DEVICES, STATE_OPEN
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers.restore_state import RestoreEntity
|
||||
|
||||
from . import (
|
||||
CONF_AUTOMATIC_ADD,
|
||||
CONF_DATA_BITS,
|
||||
CONF_SIGNAL_REPETITIONS,
|
||||
DEFAULT_SIGNAL_REPETITIONS,
|
||||
SIGNAL_EVENT,
|
||||
RfxtrxDevice,
|
||||
RfxtrxCommandEntity,
|
||||
get_device_id,
|
||||
get_rfx_object,
|
||||
)
|
||||
@@ -39,7 +39,9 @@ async def async_setup_entry(
|
||||
if not supported(event):
|
||||
continue
|
||||
|
||||
device_id = get_device_id(event.device)
|
||||
device_id = get_device_id(
|
||||
event.device, data_bits=entity_info.get(CONF_DATA_BITS)
|
||||
)
|
||||
if device_id in device_ids:
|
||||
continue
|
||||
device_ids.add(device_id)
|
||||
@@ -79,27 +81,17 @@ async def async_setup_entry(
|
||||
hass.helpers.dispatcher.async_dispatcher_connect(SIGNAL_EVENT, cover_update)
|
||||
|
||||
|
||||
class RfxtrxCover(RfxtrxDevice, CoverEntity, RestoreEntity):
|
||||
class RfxtrxCover(RfxtrxCommandEntity, CoverEntity):
|
||||
"""Representation of a RFXtrx cover."""
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Restore RFXtrx cover device state (OPEN/CLOSE)."""
|
||||
"""Restore device state."""
|
||||
await super().async_added_to_hass()
|
||||
|
||||
old_state = await self.async_get_last_state()
|
||||
if old_state is not None:
|
||||
self._state = old_state.state == STATE_OPEN
|
||||
|
||||
self.async_on_remove(
|
||||
self.hass.helpers.dispatcher.async_dispatcher_connect(
|
||||
SIGNAL_EVENT, self._handle_event
|
||||
)
|
||||
)
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""Return the polling state. No polling available in RFXtrx cover."""
|
||||
return False
|
||||
if self._event is None:
|
||||
old_state = await self.async_get_last_state()
|
||||
if old_state is not None:
|
||||
self._state = old_state.state == STATE_OPEN
|
||||
|
||||
@property
|
||||
def is_closed(self):
|
||||
@@ -120,6 +112,7 @@ class RfxtrxCover(RfxtrxDevice, CoverEntity, RestoreEntity):
|
||||
|
||||
def _apply_event(self, event):
|
||||
"""Apply command from rfxtrx."""
|
||||
super()._apply_event(event)
|
||||
if event.values["Command"] in COMMAND_ON_LIST:
|
||||
self._state = True
|
||||
elif event.values["Command"] in COMMAND_OFF_LIST:
|
||||
|
||||
@@ -10,14 +10,14 @@ from homeassistant.components.light import (
|
||||
)
|
||||
from homeassistant.const import CONF_DEVICES, STATE_ON
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers.restore_state import RestoreEntity
|
||||
|
||||
from . import (
|
||||
CONF_AUTOMATIC_ADD,
|
||||
CONF_DATA_BITS,
|
||||
CONF_SIGNAL_REPETITIONS,
|
||||
DEFAULT_SIGNAL_REPETITIONS,
|
||||
SIGNAL_EVENT,
|
||||
RfxtrxDevice,
|
||||
RfxtrxCommandEntity,
|
||||
get_device_id,
|
||||
get_rfx_object,
|
||||
)
|
||||
@@ -49,9 +49,11 @@ async def async_setup_entry(
|
||||
_LOGGER.error("Invalid device: %s", packet_id)
|
||||
continue
|
||||
if not supported(event):
|
||||
return
|
||||
continue
|
||||
|
||||
device_id = get_device_id(event.device)
|
||||
device_id = get_device_id(
|
||||
event.device, data_bits=entity_info.get(CONF_DATA_BITS)
|
||||
)
|
||||
if device_id in device_ids:
|
||||
continue
|
||||
device_ids.add(device_id)
|
||||
@@ -93,7 +95,7 @@ async def async_setup_entry(
|
||||
hass.helpers.dispatcher.async_dispatcher_connect(SIGNAL_EVENT, light_update)
|
||||
|
||||
|
||||
class RfxtrxLight(RfxtrxDevice, LightEntity, RestoreEntity):
|
||||
class RfxtrxLight(RfxtrxCommandEntity, LightEntity):
|
||||
"""Representation of a RFXtrx light."""
|
||||
|
||||
_brightness = 0
|
||||
@@ -102,22 +104,11 @@ class RfxtrxLight(RfxtrxDevice, LightEntity, RestoreEntity):
|
||||
"""Restore RFXtrx device state (ON/OFF)."""
|
||||
await super().async_added_to_hass()
|
||||
|
||||
old_state = await self.async_get_last_state()
|
||||
if old_state is not None:
|
||||
self._state = old_state.state == STATE_ON
|
||||
|
||||
# Restore the brightness of dimmable devices
|
||||
if (
|
||||
old_state is not None
|
||||
and old_state.attributes.get(ATTR_BRIGHTNESS) is not None
|
||||
):
|
||||
self._brightness = int(old_state.attributes[ATTR_BRIGHTNESS])
|
||||
|
||||
self.async_on_remove(
|
||||
self.hass.helpers.dispatcher.async_dispatcher_connect(
|
||||
SIGNAL_EVENT, self._handle_event
|
||||
)
|
||||
)
|
||||
if self._event is None:
|
||||
old_state = await self.async_get_last_state()
|
||||
if old_state is not None:
|
||||
self._state = old_state.state == STATE_ON
|
||||
self._brightness = old_state.attributes.get(ATTR_BRIGHTNESS)
|
||||
|
||||
@property
|
||||
def brightness(self):
|
||||
@@ -129,6 +120,11 @@ class RfxtrxLight(RfxtrxDevice, LightEntity, RestoreEntity):
|
||||
"""Flag supported features."""
|
||||
return SUPPORT_RFXTRX
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Return true if device is on."""
|
||||
return self._state
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Turn the light on."""
|
||||
brightness = kwargs.get(ATTR_BRIGHTNESS)
|
||||
@@ -147,6 +143,7 @@ class RfxtrxLight(RfxtrxDevice, LightEntity, RestoreEntity):
|
||||
|
||||
def _apply_event(self, event):
|
||||
"""Apply command from rfxtrx."""
|
||||
super()._apply_event(event)
|
||||
if event.values["Command"] in COMMAND_ON_LIST:
|
||||
self._state = True
|
||||
elif event.values["Command"] in COMMAND_OFF_LIST:
|
||||
|
||||
@@ -11,17 +11,17 @@ from homeassistant.components.sensor import (
|
||||
)
|
||||
from homeassistant.const import CONF_DEVICES
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers.entity import Entity
|
||||
|
||||
from . import (
|
||||
CONF_AUTOMATIC_ADD,
|
||||
CONF_DATA_BITS,
|
||||
DATA_TYPES,
|
||||
DOMAIN,
|
||||
SIGNAL_EVENT,
|
||||
RfxtrxEntity,
|
||||
get_device_id,
|
||||
get_rfx_object,
|
||||
)
|
||||
from .const import DATA_RFXTRX_CONFIG
|
||||
from .const import ATTR_EVENT, DATA_RFXTRX_CONFIG
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -65,7 +65,7 @@ async def async_setup_entry(
|
||||
return isinstance(event, (ControlEvent, SensorEvent))
|
||||
|
||||
entities = []
|
||||
for packet_id in discovery_info[CONF_DEVICES]:
|
||||
for packet_id, entity in discovery_info[CONF_DEVICES].items():
|
||||
event = get_rfx_object(packet_id)
|
||||
if event is None:
|
||||
_LOGGER.error("Invalid device: %s", packet_id)
|
||||
@@ -73,7 +73,7 @@ async def async_setup_entry(
|
||||
if not supported(event):
|
||||
continue
|
||||
|
||||
device_id = get_device_id(event.device)
|
||||
device_id = get_device_id(event.device, data_bits=entity.get(CONF_DATA_BITS))
|
||||
for data_type in set(event.values) & set(DATA_TYPES):
|
||||
data_id = (*device_id, data_type)
|
||||
if data_id in data_ids:
|
||||
@@ -113,87 +113,59 @@ async def async_setup_entry(
|
||||
hass.helpers.dispatcher.async_dispatcher_connect(SIGNAL_EVENT, sensor_update)
|
||||
|
||||
|
||||
class RfxtrxSensor(Entity):
|
||||
class RfxtrxSensor(RfxtrxEntity):
|
||||
"""Representation of a RFXtrx sensor."""
|
||||
|
||||
def __init__(self, device, device_id, data_type, event=None):
|
||||
"""Initialize the sensor."""
|
||||
self.event = None
|
||||
self._device = device
|
||||
self._name = f"{device.type_string} {device.id_string} {data_type}"
|
||||
super().__init__(device, device_id, event=event)
|
||||
self.data_type = data_type
|
||||
self._unit_of_measurement = DATA_TYPES.get(data_type, "")
|
||||
self._device_id = device_id
|
||||
self._name = f"{device.type_string} {device.id_string} {data_type}"
|
||||
self._unique_id = "_".join(x for x in (*self._device_id, data_type))
|
||||
|
||||
self._device_class = DEVICE_CLASSES.get(data_type)
|
||||
self._convert_fun = CONVERT_FUNCTIONS.get(data_type, lambda x: x)
|
||||
|
||||
if event:
|
||||
self._apply_event(event)
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Restore RFXtrx switch device state (ON/OFF)."""
|
||||
"""Restore device state."""
|
||||
await super().async_added_to_hass()
|
||||
|
||||
self.async_on_remove(
|
||||
self.hass.helpers.dispatcher.async_dispatcher_connect(
|
||||
SIGNAL_EVENT, self._handle_event
|
||||
)
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
"""Return the name of the sensor."""
|
||||
return self._name
|
||||
if self._event is None:
|
||||
old_state = await self.async_get_last_state()
|
||||
if old_state is not None:
|
||||
event = old_state.attributes.get(ATTR_EVENT)
|
||||
if event:
|
||||
self._apply_event(get_rfx_object(event))
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the sensor."""
|
||||
if not self.event:
|
||||
if not self._event:
|
||||
return None
|
||||
value = self.event.values.get(self.data_type)
|
||||
value = self._event.values.get(self.data_type)
|
||||
return self._convert_fun(value)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Get the name of the sensor."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the device state attributes."""
|
||||
if not self.event:
|
||||
return None
|
||||
return self.event.values
|
||||
|
||||
@property
|
||||
def unit_of_measurement(self):
|
||||
"""Return the unit this state is expressed in."""
|
||||
return self._unit_of_measurement
|
||||
|
||||
@property
|
||||
def should_poll(self):
|
||||
"""No polling needed."""
|
||||
return False
|
||||
|
||||
@property
|
||||
def force_update(self) -> bool:
|
||||
"""We should force updates. Repeated states have meaning."""
|
||||
return True
|
||||
|
||||
@property
|
||||
def device_class(self):
|
||||
"""Return a device class for sensor."""
|
||||
return self._device_class
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return unique identifier of remote device."""
|
||||
return self._unique_id
|
||||
|
||||
@property
|
||||
def device_info(self):
|
||||
"""Return the device info."""
|
||||
return {
|
||||
"identifiers": {(DOMAIN, *self._device_id)},
|
||||
"name": f"{self._device.type_string} {self._device.id_string}",
|
||||
"model": self._device.type_string,
|
||||
}
|
||||
|
||||
def _apply_event(self, event):
|
||||
"""Apply command from rfxtrx."""
|
||||
self.event = event
|
||||
|
||||
@callback
|
||||
def _handle_event(self, event, device_id):
|
||||
"""Check if event applies to me and update."""
|
||||
|
||||
@@ -6,15 +6,15 @@ import RFXtrx as rfxtrxmod
|
||||
from homeassistant.components.switch import SwitchEntity
|
||||
from homeassistant.const import CONF_DEVICES, STATE_ON
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers.restore_state import RestoreEntity
|
||||
|
||||
from . import (
|
||||
CONF_AUTOMATIC_ADD,
|
||||
CONF_DATA_BITS,
|
||||
CONF_SIGNAL_REPETITIONS,
|
||||
DEFAULT_SIGNAL_REPETITIONS,
|
||||
DOMAIN,
|
||||
SIGNAL_EVENT,
|
||||
RfxtrxDevice,
|
||||
RfxtrxCommandEntity,
|
||||
get_device_id,
|
||||
get_rfx_object,
|
||||
)
|
||||
@@ -49,7 +49,9 @@ async def async_setup_entry(
|
||||
if not supported(event):
|
||||
continue
|
||||
|
||||
device_id = get_device_id(event.device)
|
||||
device_id = get_device_id(
|
||||
event.device, data_bits=entity_info.get(CONF_DATA_BITS)
|
||||
)
|
||||
if device_id in device_ids:
|
||||
continue
|
||||
device_ids.add(device_id)
|
||||
@@ -89,25 +91,21 @@ async def async_setup_entry(
|
||||
hass.helpers.dispatcher.async_dispatcher_connect(SIGNAL_EVENT, switch_update)
|
||||
|
||||
|
||||
class RfxtrxSwitch(RfxtrxDevice, SwitchEntity, RestoreEntity):
|
||||
class RfxtrxSwitch(RfxtrxCommandEntity, SwitchEntity):
|
||||
"""Representation of a RFXtrx switch."""
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Restore RFXtrx switch device state (ON/OFF)."""
|
||||
"""Restore device state."""
|
||||
await super().async_added_to_hass()
|
||||
|
||||
old_state = await self.async_get_last_state()
|
||||
if old_state is not None:
|
||||
self._state = old_state.state == STATE_ON
|
||||
|
||||
self.async_on_remove(
|
||||
self.hass.helpers.dispatcher.async_dispatcher_connect(
|
||||
SIGNAL_EVENT, self._handle_event
|
||||
)
|
||||
)
|
||||
if self._event is None:
|
||||
old_state = await self.async_get_last_state()
|
||||
if old_state is not None:
|
||||
self._state = old_state.state == STATE_ON
|
||||
|
||||
def _apply_event(self, event):
|
||||
"""Apply command from rfxtrx."""
|
||||
super()._apply_event(event)
|
||||
if event.values["Command"] in COMMAND_ON_LIST:
|
||||
self._state = True
|
||||
elif event.values["Command"] in COMMAND_OFF_LIST:
|
||||
@@ -123,6 +121,11 @@ class RfxtrxSwitch(RfxtrxDevice, SwitchEntity, RestoreEntity):
|
||||
|
||||
self.async_write_ha_state()
|
||||
|
||||
@property
|
||||
def is_on(self):
|
||||
"""Return true if device is on."""
|
||||
return self._state
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Turn the device on."""
|
||||
self._send_command("turn_on")
|
||||
|
||||
@@ -4,7 +4,7 @@ import logging
|
||||
from typing import List
|
||||
|
||||
import boto3
|
||||
from ipify import exceptions, get_ip
|
||||
import requests
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.const import CONF_DOMAIN, CONF_TTL, CONF_ZONE, HTTP_OK
|
||||
@@ -84,16 +84,12 @@ def _update_route53(
|
||||
|
||||
# Get the IP Address and build an array of changes
|
||||
try:
|
||||
ipaddress = get_ip()
|
||||
ipaddress = requests.get("https://api.ipify.org/", timeout=5).text
|
||||
|
||||
except exceptions.ConnectionError:
|
||||
except requests.RequestException:
|
||||
_LOGGER.warning("Unable to reach the ipify service")
|
||||
return
|
||||
|
||||
except exceptions.ServiceError:
|
||||
_LOGGER.warning("Unable to complete the ipfy request")
|
||||
return
|
||||
|
||||
changes = []
|
||||
for record in records:
|
||||
_LOGGER.debug("Processing record: %s", record)
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
"domain": "route53",
|
||||
"name": "AWS Route53",
|
||||
"documentation": "https://www.home-assistant.io/integrations/route53",
|
||||
"requirements": ["boto3==1.9.252", "ipify==1.0.0"],
|
||||
"requirements": ["boto3==1.9.252"],
|
||||
"codeowners": []
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Support for SimpliSafe alarm systems."""
|
||||
import asyncio
|
||||
import logging
|
||||
from uuid import UUID
|
||||
|
||||
from simplipy import API
|
||||
from simplipy.errors import InvalidCredentialsError, SimplipyError
|
||||
@@ -55,11 +55,10 @@ from .const import (
|
||||
DATA_CLIENT,
|
||||
DEFAULT_SCAN_INTERVAL,
|
||||
DOMAIN,
|
||||
LOGGER,
|
||||
VOLUMES,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONF_ACCOUNTS = "accounts"
|
||||
|
||||
DATA_LISTENER = "listener"
|
||||
@@ -161,6 +160,13 @@ def _async_save_refresh_token(hass, config_entry, token):
|
||||
)
|
||||
|
||||
|
||||
async def async_get_client_id(hass):
|
||||
"""Get a client ID (based on the HASS unique ID) for the SimpliSafe API."""
|
||||
hass_id = await hass.helpers.instance_id.async_get()
|
||||
# SimpliSafe requires full, "dashed" versions of UUIDs:
|
||||
return str(UUID(hass_id))
|
||||
|
||||
|
||||
async def async_register_base_station(hass, system, config_entry_id):
|
||||
"""Register a new bridge."""
|
||||
device_registry = await dr.async_get_registry(hass)
|
||||
@@ -220,17 +226,18 @@ async def async_setup_entry(hass, config_entry):
|
||||
|
||||
_verify_domain_control = verify_domain_control(hass, DOMAIN)
|
||||
|
||||
client_id = await async_get_client_id(hass)
|
||||
websession = aiohttp_client.async_get_clientsession(hass)
|
||||
|
||||
try:
|
||||
api = await API.login_via_token(
|
||||
config_entry.data[CONF_TOKEN], session=websession
|
||||
config_entry.data[CONF_TOKEN], client_id=client_id, session=websession
|
||||
)
|
||||
except InvalidCredentialsError:
|
||||
_LOGGER.error("Invalid credentials provided")
|
||||
LOGGER.error("Invalid credentials provided")
|
||||
return False
|
||||
except SimplipyError as err:
|
||||
_LOGGER.error("Config entry failed: %s", err)
|
||||
LOGGER.error("Config entry failed: %s", err)
|
||||
raise ConfigEntryNotReady
|
||||
|
||||
_async_save_refresh_token(hass, config_entry, api.refresh_token)
|
||||
@@ -252,7 +259,7 @@ async def async_setup_entry(hass, config_entry):
|
||||
"""Decorate."""
|
||||
system_id = int(call.data[ATTR_SYSTEM_ID])
|
||||
if system_id not in simplisafe.systems:
|
||||
_LOGGER.error("Unknown system ID in service call: %s", system_id)
|
||||
LOGGER.error("Unknown system ID in service call: %s", system_id)
|
||||
return
|
||||
await coro(call)
|
||||
|
||||
@@ -266,7 +273,7 @@ async def async_setup_entry(hass, config_entry):
|
||||
"""Decorate."""
|
||||
system = simplisafe.systems[int(call.data[ATTR_SYSTEM_ID])]
|
||||
if system.version != 3:
|
||||
_LOGGER.error("Service only available on V3 systems")
|
||||
LOGGER.error("Service only available on V3 systems")
|
||||
return
|
||||
await coro(call)
|
||||
|
||||
@@ -280,7 +287,7 @@ async def async_setup_entry(hass, config_entry):
|
||||
try:
|
||||
await system.clear_notifications()
|
||||
except SimplipyError as err:
|
||||
_LOGGER.error("Error during service call: %s", err)
|
||||
LOGGER.error("Error during service call: %s", err)
|
||||
return
|
||||
|
||||
@verify_system_exists
|
||||
@@ -291,7 +298,7 @@ async def async_setup_entry(hass, config_entry):
|
||||
try:
|
||||
await system.remove_pin(call.data[ATTR_PIN_LABEL_OR_VALUE])
|
||||
except SimplipyError as err:
|
||||
_LOGGER.error("Error during service call: %s", err)
|
||||
LOGGER.error("Error during service call: %s", err)
|
||||
return
|
||||
|
||||
@verify_system_exists
|
||||
@@ -302,7 +309,7 @@ async def async_setup_entry(hass, config_entry):
|
||||
try:
|
||||
await system.set_pin(call.data[ATTR_PIN_LABEL], call.data[ATTR_PIN_VALUE])
|
||||
except SimplipyError as err:
|
||||
_LOGGER.error("Error during service call: %s", err)
|
||||
LOGGER.error("Error during service call: %s", err)
|
||||
return
|
||||
|
||||
@verify_system_exists
|
||||
@@ -320,7 +327,7 @@ async def async_setup_entry(hass, config_entry):
|
||||
}
|
||||
)
|
||||
except SimplipyError as err:
|
||||
_LOGGER.error("Error during service call: %s", err)
|
||||
LOGGER.error("Error during service call: %s", err)
|
||||
return
|
||||
|
||||
for service, method, schema in [
|
||||
@@ -373,16 +380,16 @@ class SimpliSafeWebsocket:
|
||||
@staticmethod
|
||||
def _on_connect():
|
||||
"""Define a handler to fire when the websocket is connected."""
|
||||
_LOGGER.info("Connected to websocket")
|
||||
LOGGER.info("Connected to websocket")
|
||||
|
||||
@staticmethod
|
||||
def _on_disconnect():
|
||||
"""Define a handler to fire when the websocket is disconnected."""
|
||||
_LOGGER.info("Disconnected from websocket")
|
||||
LOGGER.info("Disconnected from websocket")
|
||||
|
||||
def _on_event(self, event):
|
||||
"""Define a handler to fire when a new SimpliSafe event arrives."""
|
||||
_LOGGER.debug("New websocket event: %s", event)
|
||||
LOGGER.debug("New websocket event: %s", event)
|
||||
async_dispatcher_send(
|
||||
self._hass, TOPIC_UPDATE_WEBSOCKET.format(event.system_id), event
|
||||
)
|
||||
@@ -451,7 +458,7 @@ class SimpliSafe:
|
||||
if not to_add:
|
||||
return
|
||||
|
||||
_LOGGER.debug("New system notifications: %s", to_add)
|
||||
LOGGER.debug("New system notifications: %s", to_add)
|
||||
|
||||
self._system_notifications[system.system_id].update(to_add)
|
||||
|
||||
@@ -492,7 +499,7 @@ class SimpliSafe:
|
||||
system.system_id
|
||||
] = await system.get_latest_event()
|
||||
except SimplipyError as err:
|
||||
_LOGGER.error("Error while fetching initial event: %s", err)
|
||||
LOGGER.error("Error while fetching initial event: %s", err)
|
||||
self.initial_event_to_use[system.system_id] = {}
|
||||
|
||||
async def refresh(event_time):
|
||||
@@ -512,7 +519,7 @@ class SimpliSafe:
|
||||
"""Update a system."""
|
||||
await system.update()
|
||||
self._async_process_new_notifications(system)
|
||||
_LOGGER.debug('Updated REST API data for "%s"', system.address)
|
||||
LOGGER.debug('Updated REST API data for "%s"', system.address)
|
||||
async_dispatcher_send(
|
||||
self._hass, TOPIC_UPDATE_REST_API.format(system.system_id)
|
||||
)
|
||||
@@ -523,27 +530,37 @@ class SimpliSafe:
|
||||
for result in results:
|
||||
if isinstance(result, InvalidCredentialsError):
|
||||
if self._emergency_refresh_token_used:
|
||||
_LOGGER.error(
|
||||
"SimpliSafe authentication disconnected. Please restart HASS"
|
||||
LOGGER.error(
|
||||
"Token disconnected or invalid. Please re-auth the "
|
||||
"SimpliSafe integration in HASS"
|
||||
)
|
||||
remove_listener = self._hass.data[DOMAIN][DATA_LISTENER].pop(
|
||||
self._config_entry.entry_id
|
||||
self._hass.async_create_task(
|
||||
self._hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": "reauth"},
|
||||
data=self._config_entry.data,
|
||||
)
|
||||
)
|
||||
remove_listener()
|
||||
return
|
||||
|
||||
_LOGGER.warning("SimpliSafe cloud error; trying stored refresh token")
|
||||
LOGGER.warning("SimpliSafe cloud error; trying stored refresh token")
|
||||
self._emergency_refresh_token_used = True
|
||||
return await self._api.refresh_access_token(
|
||||
self._config_entry.data[CONF_TOKEN]
|
||||
)
|
||||
|
||||
try:
|
||||
await self._api.refresh_access_token(
|
||||
self._config_entry.data[CONF_TOKEN]
|
||||
)
|
||||
return
|
||||
except SimplipyError as err:
|
||||
LOGGER.error("Error while using stored refresh token: %s", err)
|
||||
return
|
||||
|
||||
if isinstance(result, SimplipyError):
|
||||
_LOGGER.error("SimpliSafe error while updating: %s", result)
|
||||
LOGGER.error("SimpliSafe error while updating: %s", result)
|
||||
return
|
||||
|
||||
if isinstance(result, SimplipyError):
|
||||
_LOGGER.error("Unknown error while updating: %s", result)
|
||||
if isinstance(result, Exception): # pylint: disable=broad-except
|
||||
LOGGER.error("Unknown error while updating: %s", result)
|
||||
return
|
||||
|
||||
if self._api.refresh_token != self._config_entry.data[CONF_TOKEN]:
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""Support for SimpliSafe alarm control panels."""
|
||||
import logging
|
||||
import re
|
||||
|
||||
from simplipy.errors import SimplipyError
|
||||
@@ -50,11 +49,10 @@ from .const import (
|
||||
ATTR_VOICE_PROMPT_VOLUME,
|
||||
DATA_CLIENT,
|
||||
DOMAIN,
|
||||
LOGGER,
|
||||
VOLUME_STRING_MAP,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ATTR_BATTERY_BACKUP_POWER_LEVEL = "battery_backup_power_level"
|
||||
ATTR_GSM_STRENGTH = "gsm_strength"
|
||||
ATTR_PIN_NAME = "pin_name"
|
||||
@@ -146,7 +144,7 @@ class SimpliSafeAlarm(SimpliSafeEntity, AlarmControlPanelEntity):
|
||||
return True
|
||||
|
||||
if not code or code != self._simplisafe.options[CONF_CODE]:
|
||||
_LOGGER.warning(
|
||||
LOGGER.warning(
|
||||
"Incorrect alarm code entered (target state: %s): %s", state, code
|
||||
)
|
||||
return False
|
||||
@@ -161,7 +159,7 @@ class SimpliSafeAlarm(SimpliSafeEntity, AlarmControlPanelEntity):
|
||||
try:
|
||||
await self._system.set_off()
|
||||
except SimplipyError as err:
|
||||
_LOGGER.error('Error while disarming "%s": %s', self._system.name, err)
|
||||
LOGGER.error('Error while disarming "%s": %s', self._system.name, err)
|
||||
return
|
||||
|
||||
self._state = STATE_ALARM_DISARMED
|
||||
@@ -174,7 +172,7 @@ class SimpliSafeAlarm(SimpliSafeEntity, AlarmControlPanelEntity):
|
||||
try:
|
||||
await self._system.set_home()
|
||||
except SimplipyError as err:
|
||||
_LOGGER.error('Error while arming "%s" (home): %s', self._system.name, err)
|
||||
LOGGER.error('Error while arming "%s" (home): %s', self._system.name, err)
|
||||
return
|
||||
|
||||
self._state = STATE_ALARM_ARMED_HOME
|
||||
@@ -187,7 +185,7 @@ class SimpliSafeAlarm(SimpliSafeEntity, AlarmControlPanelEntity):
|
||||
try:
|
||||
await self._system.set_away()
|
||||
except SimplipyError as err:
|
||||
_LOGGER.error('Error while arming "%s" (away): %s', self._system.name, err)
|
||||
LOGGER.error('Error while arming "%s" (away): %s', self._system.name, err)
|
||||
return
|
||||
|
||||
self._state = STATE_ALARM_ARMING
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
"""Config flow to configure the SimpliSafe component."""
|
||||
from simplipy import API
|
||||
from simplipy.errors import SimplipyError
|
||||
from simplipy.errors import (
|
||||
InvalidCredentialsError,
|
||||
PendingAuthorizationError,
|
||||
SimplipyError,
|
||||
)
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant import config_entries
|
||||
@@ -8,7 +12,8 @@ from homeassistant.const import CONF_CODE, CONF_PASSWORD, CONF_TOKEN, CONF_USERN
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers import aiohttp_client
|
||||
|
||||
from .const import DOMAIN # pylint: disable=unused-import
|
||||
from . import async_get_client_id
|
||||
from .const import DOMAIN, LOGGER # pylint: disable=unused-import
|
||||
|
||||
|
||||
class SimpliSafeFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
@@ -19,21 +24,18 @@ class SimpliSafeFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize the config flow."""
|
||||
self.data_schema = vol.Schema(
|
||||
self.full_data_schema = vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_USERNAME): str,
|
||||
vol.Required(CONF_PASSWORD): str,
|
||||
vol.Optional(CONF_CODE): str,
|
||||
}
|
||||
)
|
||||
self.password_data_schema = vol.Schema({vol.Required(CONF_PASSWORD): str})
|
||||
|
||||
async def _show_form(self, errors=None):
|
||||
"""Show the form to the user."""
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
data_schema=self.data_schema,
|
||||
errors=errors if errors else {},
|
||||
)
|
||||
self._code = None
|
||||
self._password = None
|
||||
self._username = None
|
||||
|
||||
@staticmethod
|
||||
@callback
|
||||
@@ -41,34 +43,112 @@ class SimpliSafeFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
"""Define the config flow to handle options."""
|
||||
return SimpliSafeOptionsFlowHandler(config_entry)
|
||||
|
||||
async def _async_get_simplisafe_api(self):
|
||||
"""Get an authenticated SimpliSafe API client."""
|
||||
client_id = await async_get_client_id(self.hass)
|
||||
websession = aiohttp_client.async_get_clientsession(self.hass)
|
||||
|
||||
return await API.login_via_credentials(
|
||||
self._username, self._password, client_id=client_id, session=websession,
|
||||
)
|
||||
|
||||
async def _async_login_during_step(self, *, step_id, form_schema):
|
||||
"""Attempt to log into the API from within a config flow step."""
|
||||
errors = {}
|
||||
|
||||
try:
|
||||
simplisafe = await self._async_get_simplisafe_api()
|
||||
except PendingAuthorizationError:
|
||||
LOGGER.info("Awaiting confirmation of MFA email click")
|
||||
return await self.async_step_mfa()
|
||||
except InvalidCredentialsError:
|
||||
errors = {"base": "invalid_credentials"}
|
||||
except SimplipyError as err:
|
||||
LOGGER.error("Unknown error while logging into SimpliSafe: %s", err)
|
||||
errors = {"base": "unknown"}
|
||||
|
||||
if errors:
|
||||
return self.async_show_form(
|
||||
step_id=step_id, data_schema=form_schema, errors=errors,
|
||||
)
|
||||
|
||||
return await self.async_step_finish(
|
||||
{
|
||||
CONF_USERNAME: self._username,
|
||||
CONF_TOKEN: simplisafe.refresh_token,
|
||||
CONF_CODE: self._code,
|
||||
}
|
||||
)
|
||||
|
||||
async def async_step_finish(self, user_input=None):
|
||||
"""Handle finish config entry setup."""
|
||||
existing_entry = await self.async_set_unique_id(self._username)
|
||||
if existing_entry:
|
||||
self.hass.config_entries.async_update_entry(existing_entry, data=user_input)
|
||||
return self.async_abort(reason="reauth_successful")
|
||||
return self.async_create_entry(title=self._username, data=user_input)
|
||||
|
||||
async def async_step_import(self, import_config):
|
||||
"""Import a config entry from configuration.yaml."""
|
||||
return await self.async_step_user(import_config)
|
||||
|
||||
async def async_step_mfa(self, user_input=None):
|
||||
"""Handle multi-factor auth confirmation."""
|
||||
if user_input is None:
|
||||
return self.async_show_form(step_id="mfa")
|
||||
|
||||
try:
|
||||
simplisafe = await self._async_get_simplisafe_api()
|
||||
except PendingAuthorizationError:
|
||||
LOGGER.error("Still awaiting confirmation of MFA email click")
|
||||
return self.async_show_form(
|
||||
step_id="mfa", errors={"base": "still_awaiting_mfa"}
|
||||
)
|
||||
|
||||
return await self.async_step_finish(
|
||||
{
|
||||
CONF_USERNAME: self._username,
|
||||
CONF_TOKEN: simplisafe.refresh_token,
|
||||
CONF_CODE: self._code,
|
||||
}
|
||||
)
|
||||
|
||||
async def async_step_reauth(self, config):
|
||||
"""Handle configuration by re-auth."""
|
||||
self._code = config.get(CONF_CODE)
|
||||
self._username = config[CONF_USERNAME]
|
||||
|
||||
return await self.async_step_reauth_confirm()
|
||||
|
||||
async def async_step_reauth_confirm(self, user_input=None):
|
||||
"""Handle re-auth completion."""
|
||||
if not user_input:
|
||||
return self.async_show_form(
|
||||
step_id="reauth_confirm", data_schema=self.password_data_schema
|
||||
)
|
||||
|
||||
self._password = user_input[CONF_PASSWORD]
|
||||
|
||||
return await self._async_login_during_step(
|
||||
step_id="reauth_confirm", form_schema=self.password_data_schema
|
||||
)
|
||||
|
||||
async def async_step_user(self, user_input=None):
|
||||
"""Handle the start of the config flow."""
|
||||
if not user_input:
|
||||
return await self._show_form()
|
||||
return self.async_show_form(
|
||||
step_id="user", data_schema=self.full_data_schema
|
||||
)
|
||||
|
||||
await self.async_set_unique_id(user_input[CONF_USERNAME])
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
websession = aiohttp_client.async_get_clientsession(self.hass)
|
||||
self._code = user_input.get(CONF_CODE)
|
||||
self._password = user_input[CONF_PASSWORD]
|
||||
self._username = user_input[CONF_USERNAME]
|
||||
|
||||
try:
|
||||
simplisafe = await API.login_via_credentials(
|
||||
user_input[CONF_USERNAME], user_input[CONF_PASSWORD], session=websession
|
||||
)
|
||||
except SimplipyError:
|
||||
return await self._show_form(errors={"base": "invalid_credentials"})
|
||||
|
||||
return self.async_create_entry(
|
||||
title=user_input[CONF_USERNAME],
|
||||
data={
|
||||
CONF_USERNAME: user_input[CONF_USERNAME],
|
||||
CONF_TOKEN: simplisafe.refresh_token,
|
||||
CONF_CODE: user_input.get(CONF_CODE),
|
||||
},
|
||||
return await self._async_login_during_step(
|
||||
step_id="user", form_schema=self.full_data_schema
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
"""Define constants for the SimpliSafe component."""
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
from simplipy.system.v3 import VOLUME_HIGH, VOLUME_LOW, VOLUME_MEDIUM, VOLUME_OFF
|
||||
|
||||
LOGGER = logging.getLogger(__package__)
|
||||
|
||||
DOMAIN = "simplisafe"
|
||||
|
||||
DATA_CLIENT = "client"
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
"""Support for SimpliSafe locks."""
|
||||
import logging
|
||||
|
||||
from simplipy.errors import SimplipyError
|
||||
from simplipy.lock import LockStates
|
||||
from simplipy.websocket import EVENT_LOCK_LOCKED, EVENT_LOCK_UNLOCKED
|
||||
@@ -9,9 +7,7 @@ from homeassistant.components.lock import LockEntity
|
||||
from homeassistant.core import callback
|
||||
|
||||
from . import SimpliSafeEntity
|
||||
from .const import DATA_CLIENT, DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
from .const import DATA_CLIENT, DOMAIN, LOGGER
|
||||
|
||||
ATTR_LOCK_LOW_BATTERY = "lock_low_battery"
|
||||
ATTR_JAMMED = "jammed"
|
||||
@@ -52,7 +48,7 @@ class SimpliSafeLock(SimpliSafeEntity, LockEntity):
|
||||
try:
|
||||
await self._lock.lock()
|
||||
except SimplipyError as err:
|
||||
_LOGGER.error('Error while locking "%s": %s', self._lock.name, err)
|
||||
LOGGER.error('Error while locking "%s": %s', self._lock.name, err)
|
||||
return
|
||||
|
||||
self._is_locked = True
|
||||
@@ -62,7 +58,7 @@ class SimpliSafeLock(SimpliSafeEntity, LockEntity):
|
||||
try:
|
||||
await self._lock.unlock()
|
||||
except SimplipyError as err:
|
||||
_LOGGER.error('Error while unlocking "%s": %s', self._lock.name, err)
|
||||
LOGGER.error('Error while unlocking "%s": %s', self._lock.name, err)
|
||||
return
|
||||
|
||||
self._is_locked = False
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
"name": "SimpliSafe",
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/integrations/simplisafe",
|
||||
"requirements": ["simplisafe-python==9.2.0"],
|
||||
"requirements": ["simplisafe-python==9.2.1"],
|
||||
"codeowners": ["@bachya"]
|
||||
}
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"mfa": {
|
||||
"title": "SimpliSafe Multi-Factor Authentication",
|
||||
"description": "Check your email for a link from SimpliSafe. After verifying the link, return here to complete the installation of the integration."
|
||||
},
|
||||
"reauth_confirm": {
|
||||
"title": "Re-link SimpliSafe Account",
|
||||
"description": "Your access token has expired or been revoked. Enter your password to re-link your account.",
|
||||
"data": {
|
||||
"password": "[%key:common::config_flow::data::password%]"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "Fill in your information.",
|
||||
"data": {
|
||||
@@ -12,10 +23,13 @@
|
||||
},
|
||||
"error": {
|
||||
"identifier_exists": "Account already registered",
|
||||
"invalid_credentials": "Invalid credentials"
|
||||
"invalid_credentials": "Invalid credentials",
|
||||
"still_awaiting_mfa": "Still awaiting MFA email click",
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "This SimpliSafe account is already in use."
|
||||
"already_configured": "This SimpliSafe account is already in use.",
|
||||
"reauth_successful": "SimpliSafe successfully reauthenticated."
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
@@ -28,4 +42,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,32 @@
|
||||
{
|
||||
"config": {
|
||||
"abort": {
|
||||
"already_configured": "This SimpliSafe account is already in use."
|
||||
"already_configured": "This SimpliSafe account is already in use.",
|
||||
"reauth_successful": "SimpliSafe successfully reauthenticated."
|
||||
},
|
||||
"error": {
|
||||
"identifier_exists": "Account already registered",
|
||||
"invalid_credentials": "Invalid credentials"
|
||||
"invalid_credentials": "Invalid credentials",
|
||||
"still_awaiting_mfa": "Still awaiting MFA email click",
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
},
|
||||
"step": {
|
||||
"mfa": {
|
||||
"description": "Check your email for a link from SimpliSafe. After verifying the link, return here to complete the installation of the integration.",
|
||||
"title": "SimpliSafe Multi-Factor Authentication"
|
||||
},
|
||||
"reauth_confirm": {
|
||||
"data": {
|
||||
"password": "[%key:common::config_flow::data::password%]"
|
||||
},
|
||||
"description": "Your access token has expired or been revoked. Enter your password to re-link your account.",
|
||||
"title": "Re-link SimpliSafe Account"
|
||||
},
|
||||
"user": {
|
||||
"data": {
|
||||
"code": "Code (used in Home Assistant UI)",
|
||||
"password": "Password",
|
||||
"username": "Email"
|
||||
"password": "[%key:common::config_flow::data::password%]",
|
||||
"username": "[%key:common::config_flow::data::email%]"
|
||||
},
|
||||
"title": "Fill in your information."
|
||||
}
|
||||
|
||||
@@ -224,7 +224,10 @@ class SlackNotificationService(BaseNotificationService):
|
||||
|
||||
async def async_send_message(self, message, **kwargs):
|
||||
"""Send a message to Slack."""
|
||||
data = kwargs.get(ATTR_DATA, {})
|
||||
data = kwargs.get(ATTR_DATA)
|
||||
|
||||
if data is None:
|
||||
data = {}
|
||||
|
||||
try:
|
||||
DATA_SCHEMA(data)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"name": "SmartThings",
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/integrations/smartthings",
|
||||
"requirements": ["pysmartapp==0.3.2", "pysmartthings==0.7.1"],
|
||||
"requirements": ["pysmartapp==0.3.2", "pysmartthings==0.7.2"],
|
||||
"dependencies": ["webhook"],
|
||||
"after_dependencies": ["cloud"],
|
||||
"codeowners": ["@andrewsayre"]
|
||||
|
||||
@@ -58,8 +58,10 @@ async def async_setup_entry(hass, entry):
|
||||
|
||||
|
||||
@bind_hass
|
||||
def get_coordinator_id(hass, entity_id):
|
||||
"""Obtain the unique_id of a device's coordinator.
|
||||
def get_coordinator_name(hass, entity_id):
|
||||
"""Obtain the room/name of a device's coordinator.
|
||||
|
||||
Used by the Plex integration.
|
||||
|
||||
This function is safe to run inside the event loop.
|
||||
"""
|
||||
@@ -71,5 +73,5 @@ def get_coordinator_id(hass, entity_id):
|
||||
)
|
||||
|
||||
if device.is_coordinator:
|
||||
return device.unique_id
|
||||
return device.coordinator.unique_id
|
||||
return device.name
|
||||
return device.coordinator.name
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"name": "Sonos",
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/integrations/sonos",
|
||||
"requirements": ["pysonos==0.0.31"],
|
||||
"requirements": ["pysonos==0.0.32"],
|
||||
"ssdp": [
|
||||
{
|
||||
"st": "urn:schemas-upnp-org:device:ZonePlayer:1"
|
||||
|
||||
@@ -224,7 +224,7 @@ SENSOR_ENTITIES = {
|
||||
"power_meter_reading_low": {
|
||||
ATTR_NAME: "Electricity Meter Feed IN Tariff 2",
|
||||
ATTR_SECTION: "power_usage",
|
||||
ATTR_MEASUREMENT: "meter_high",
|
||||
ATTR_MEASUREMENT: "meter_low",
|
||||
ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR,
|
||||
ATTR_DEVICE_CLASS: None,
|
||||
ATTR_ICON: "mdi:power-plug",
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
"domain": "xbox_live",
|
||||
"name": "Xbox Live",
|
||||
"documentation": "https://www.home-assistant.io/integrations/xbox_live",
|
||||
"requirements": ["xboxapi==0.1.1"],
|
||||
"requirements": ["xboxapi==2.0.0"],
|
||||
"codeowners": ["@MartinHjelmare"]
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ from datetime import timedelta
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
from xboxapi import xbox_api
|
||||
from xboxapi import Client
|
||||
|
||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||
from homeassistant.const import CONF_API_KEY, CONF_SCAN_INTERVAL
|
||||
@@ -28,17 +28,17 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
"""Set up the Xbox platform."""
|
||||
api = xbox_api.XboxApi(config[CONF_API_KEY])
|
||||
api = Client(api_key=config[CONF_API_KEY])
|
||||
entities = []
|
||||
|
||||
# request personal profile to check api connection
|
||||
profile = api.get_profile()
|
||||
if profile.get("error_code") is not None:
|
||||
# request profile info to check api connection
|
||||
response = api.api_get("profile")
|
||||
if not response.ok:
|
||||
_LOGGER.error(
|
||||
"Can't setup XboxAPI connection. Check your account or "
|
||||
"api key on xboxapi.com. Code: %s Description: %s ",
|
||||
profile.get("error_code", "unknown"),
|
||||
profile.get("error_message", "unknown"),
|
||||
"Can't setup X API connection. Check your account or "
|
||||
"api key on xapi.us. Code: %s Description: %s ",
|
||||
response.status_code,
|
||||
response.reason,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -59,7 +59,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
|
||||
def get_user_gamercard(api, xuid):
|
||||
"""Get profile info."""
|
||||
gamercard = api.get_user_gamercard(xuid)
|
||||
gamercard = api.gamer(gamertag="", xuid=xuid).get("gamercard")
|
||||
_LOGGER.debug("User gamercard: %s", gamercard)
|
||||
|
||||
if gamercard.get("success", True) and gamercard.get("code") is None:
|
||||
@@ -82,11 +82,11 @@ class XboxSensor(Entity):
|
||||
self._presence = []
|
||||
self._xuid = xuid
|
||||
self._api = api
|
||||
self._gamertag = gamercard.get("gamertag")
|
||||
self._gamerscore = gamercard.get("gamerscore")
|
||||
self._gamertag = gamercard["gamertag"]
|
||||
self._gamerscore = gamercard["gamerscore"]
|
||||
self._interval = interval
|
||||
self._picture = gamercard.get("gamerpicSmallSslImagePath")
|
||||
self._tier = gamercard.get("tier")
|
||||
self._picture = gamercard["gamerpicSmallSslImagePath"]
|
||||
self._tier = gamercard["tier"]
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
@@ -111,10 +111,8 @@ class XboxSensor(Entity):
|
||||
attributes["tier"] = self._tier
|
||||
|
||||
for device in self._presence:
|
||||
for title in device.get("titles"):
|
||||
attributes[
|
||||
f'{device.get("type")} {title.get("placement")}'
|
||||
] = title.get("name")
|
||||
for title in device["titles"]:
|
||||
attributes[f'{device["type"]} {title["placement"]}'] = title["name"]
|
||||
|
||||
return attributes
|
||||
|
||||
@@ -140,7 +138,7 @@ class XboxSensor(Entity):
|
||||
|
||||
def update(self):
|
||||
"""Update state data from Xbox API."""
|
||||
presence = self._api.get_user_presence(self._xuid)
|
||||
presence = self._api.gamer(gamertag="", xuid=self._xuid).get("presence")
|
||||
_LOGGER.debug("User presence: %s", presence)
|
||||
self._state = presence.get("state")
|
||||
self._state = presence["state"]
|
||||
self._presence = presence.get("devices", [])
|
||||
|
||||
@@ -209,6 +209,11 @@ def setup(hass, config):
|
||||
return
|
||||
|
||||
info = info_from_service(service_info)
|
||||
if not info:
|
||||
# Prevent the browser thread from collapsing
|
||||
_LOGGER.debug("Failed to get addresses for device %s", name)
|
||||
return
|
||||
|
||||
_LOGGER.debug("Discovered new device %s %s", name, info)
|
||||
|
||||
# If we can handle it as a HomeKit discovery, we do that here.
|
||||
@@ -310,6 +315,9 @@ def info_from_service(service):
|
||||
except UnicodeDecodeError:
|
||||
pass
|
||||
|
||||
if not service.addresses:
|
||||
return None
|
||||
|
||||
address = service.addresses[0]
|
||||
|
||||
info = {
|
||||
|
||||
@@ -245,7 +245,7 @@ class ZigbeeChannel(LogMixin):
|
||||
self._cluster,
|
||||
[attribute],
|
||||
allow_cache=from_cache,
|
||||
only_cache=from_cache,
|
||||
only_cache=from_cache and not self._ch_pool.is_mains_powered,
|
||||
manufacturer=manufacturer,
|
||||
)
|
||||
return result.get(attribute)
|
||||
@@ -260,7 +260,7 @@ class ZigbeeChannel(LogMixin):
|
||||
result, _ = await self.cluster.read_attributes(
|
||||
attributes,
|
||||
allow_cache=from_cache,
|
||||
only_cache=from_cache,
|
||||
only_cache=from_cache and not self._ch_pool.is_mains_powered,
|
||||
manufacturer=manufacturer,
|
||||
)
|
||||
return result
|
||||
|
||||
@@ -4,7 +4,7 @@ from typing import Optional
|
||||
|
||||
import zigpy.zcl.clusters.homeautomation as homeautomation
|
||||
|
||||
from .. import registries, typing as zha_typing
|
||||
from .. import registries
|
||||
from ..const import (
|
||||
CHANNEL_ELECTRICAL_MEASUREMENT,
|
||||
REPORT_CONFIG_DEFAULT,
|
||||
@@ -51,14 +51,6 @@ class ElectricalMeasurementChannel(ZigbeeChannel):
|
||||
|
||||
REPORT_CONFIG = ({"attr": "active_power", "config": REPORT_CONFIG_DEFAULT},)
|
||||
|
||||
def __init__(
|
||||
self, cluster: zha_typing.ZigpyClusterType, ch_pool: zha_typing.ChannelPoolType
|
||||
) -> None:
|
||||
"""Initialize Metering."""
|
||||
super().__init__(cluster, ch_pool)
|
||||
self._divisor = None
|
||||
self._multiplier = None
|
||||
|
||||
async def async_update(self):
|
||||
"""Retrieve latest state."""
|
||||
self.debug("async_update")
|
||||
@@ -80,7 +72,9 @@ class ElectricalMeasurementChannel(ZigbeeChannel):
|
||||
|
||||
async def fetch_config(self, from_cache):
|
||||
"""Fetch config from device and updates format specifier."""
|
||||
results = await self.get_attributes(
|
||||
|
||||
# prime the cache
|
||||
await self.get_attributes(
|
||||
[
|
||||
"ac_power_divisor",
|
||||
"power_divisor",
|
||||
@@ -89,22 +83,20 @@ class ElectricalMeasurementChannel(ZigbeeChannel):
|
||||
],
|
||||
from_cache=from_cache,
|
||||
)
|
||||
self._divisor = results.get(
|
||||
"ac_power_divisor", results.get("power_divisor", self._divisor)
|
||||
)
|
||||
self._multiplier = results.get(
|
||||
"ac_power_multiplier", results.get("power_multiplier", self._multiplier)
|
||||
)
|
||||
|
||||
@property
|
||||
def divisor(self) -> Optional[int]:
|
||||
"""Return active power divisor."""
|
||||
return self._divisor or 1
|
||||
return self.cluster.get(
|
||||
"ac_power_divisor", self.cluster.get("power_divisor", 1)
|
||||
)
|
||||
|
||||
@property
|
||||
def multiplier(self) -> Optional[int]:
|
||||
"""Return active power divisor."""
|
||||
return self._multiplier or 1
|
||||
return self.cluster.get(
|
||||
"ac_power_multiplier", self.cluster.get("power_multiplier", 1)
|
||||
)
|
||||
|
||||
|
||||
@registries.ZIGBEE_CHANNEL_REGISTRY.register(
|
||||
|
||||
@@ -3,7 +3,7 @@ import logging
|
||||
|
||||
import zigpy.zcl.clusters.smartenergy as smartenergy
|
||||
|
||||
from homeassistant.const import LENGTH_FEET, TIME_HOURS, TIME_SECONDS
|
||||
from homeassistant.const import LENGTH_FEET, POWER_WATT, TIME_HOURS, TIME_SECONDS
|
||||
from homeassistant.core import callback
|
||||
|
||||
from .. import registries, typing as zha_typing
|
||||
@@ -60,7 +60,7 @@ class Metering(ZigbeeChannel):
|
||||
REPORT_CONFIG = [{"attr": "instantaneous_demand", "config": REPORT_CONFIG_DEFAULT}]
|
||||
|
||||
unit_of_measure_map = {
|
||||
0x00: "kW",
|
||||
0x00: POWER_WATT,
|
||||
0x01: f"m³/{TIME_HOURS}",
|
||||
0x02: f"{LENGTH_FEET}³/{TIME_HOURS}",
|
||||
0x03: f"ccf/{TIME_HOURS}",
|
||||
@@ -135,6 +135,12 @@ class Metering(ZigbeeChannel):
|
||||
|
||||
def formatter_function(self, value):
|
||||
"""Return formatted value for display."""
|
||||
if self.unit_of_measurement == POWER_WATT:
|
||||
# Zigbee spec power unit is kW, but we show the value in W
|
||||
value_watt = value * 1000
|
||||
if value_watt < 100:
|
||||
return round(value_watt, 1)
|
||||
return round(value_watt)
|
||||
return self._format_spec.format(value).lstrip()
|
||||
|
||||
|
||||
|
||||
@@ -31,7 +31,11 @@ from homeassistant.components.light import (
|
||||
)
|
||||
from homeassistant.const import ATTR_SUPPORTED_FEATURES, STATE_ON, STATE_UNAVAILABLE
|
||||
from homeassistant.core import State, callback
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
from homeassistant.helpers.debounce import Debouncer
|
||||
from homeassistant.helpers.dispatcher import (
|
||||
async_dispatcher_connect,
|
||||
async_dispatcher_send,
|
||||
)
|
||||
from homeassistant.helpers.event import async_track_time_interval
|
||||
import homeassistant.util.color as color_util
|
||||
|
||||
@@ -71,6 +75,7 @@ UNSUPPORTED_ATTRIBUTE = 0x86
|
||||
STRICT_MATCH = functools.partial(ZHA_ENTITIES.strict_match, light.DOMAIN)
|
||||
GROUP_MATCH = functools.partial(ZHA_ENTITIES.group_match, light.DOMAIN)
|
||||
PARALLEL_UPDATES = 0
|
||||
SIGNAL_LIGHT_GROUP_STATE_CHANGED = "zha_light_group_state_changed"
|
||||
|
||||
SUPPORT_GROUP_LIGHT = (
|
||||
SUPPORT_BRIGHTNESS
|
||||
@@ -378,6 +383,12 @@ class Light(BaseLight, ZhaEntity):
|
||||
self._cancel_refresh_handle = async_track_time_interval(
|
||||
self.hass, self._refresh, timedelta(seconds=refresh_interval)
|
||||
)
|
||||
await self.async_accept_signal(
|
||||
None,
|
||||
SIGNAL_LIGHT_GROUP_STATE_CHANGED,
|
||||
self._maybe_force_refresh,
|
||||
signal_override=True,
|
||||
)
|
||||
|
||||
async def async_will_remove_from_hass(self) -> None:
|
||||
"""Disconnect entity object when removed."""
|
||||
@@ -406,7 +417,7 @@ class Light(BaseLight, ZhaEntity):
|
||||
|
||||
async def async_get_state(self, from_cache=True):
|
||||
"""Attempt to retrieve on off state from the light."""
|
||||
self.debug("polling current state")
|
||||
self.debug("polling current state - from cache: %s", from_cache)
|
||||
if self._on_off_channel:
|
||||
state = await self._on_off_channel.get_attribute_value(
|
||||
"on_off", from_cache=from_cache
|
||||
@@ -468,6 +479,12 @@ class Light(BaseLight, ZhaEntity):
|
||||
await self.async_get_state(from_cache=False)
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def _maybe_force_refresh(self, signal):
|
||||
"""Force update the state if the signal contains the entity id for this entity."""
|
||||
if self.entity_id in signal["entity_ids"]:
|
||||
await self.async_get_state(from_cache=False)
|
||||
self.async_write_ha_state()
|
||||
|
||||
|
||||
@STRICT_MATCH(
|
||||
channel_names=CHANNEL_ON_OFF,
|
||||
@@ -494,6 +511,30 @@ class LightGroup(BaseLight, ZhaGroupEntity):
|
||||
self._level_channel = group.endpoint[LevelControl.cluster_id]
|
||||
self._color_channel = group.endpoint[Color.cluster_id]
|
||||
self._identify_channel = group.endpoint[Identify.cluster_id]
|
||||
self._debounced_member_refresh = None
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Run when about to be added to hass."""
|
||||
await super().async_added_to_hass()
|
||||
if self._debounced_member_refresh is None:
|
||||
force_refresh_debouncer = Debouncer(
|
||||
self.hass,
|
||||
_LOGGER,
|
||||
cooldown=3,
|
||||
immediate=True,
|
||||
function=self._force_member_updates,
|
||||
)
|
||||
self._debounced_member_refresh = force_refresh_debouncer
|
||||
|
||||
async def async_turn_on(self, **kwargs):
|
||||
"""Turn the entity on."""
|
||||
await super().async_turn_on(**kwargs)
|
||||
await self._debounced_member_refresh.async_call()
|
||||
|
||||
async def async_turn_off(self, **kwargs):
|
||||
"""Turn the entity off."""
|
||||
await super().async_turn_off(**kwargs)
|
||||
await self._debounced_member_refresh.async_call()
|
||||
|
||||
async def async_update(self) -> None:
|
||||
"""Query all members and determine the light group state."""
|
||||
@@ -541,3 +582,11 @@ class LightGroup(BaseLight, ZhaGroupEntity):
|
||||
# Bitwise-and the supported features with the GroupedLight's features
|
||||
# so that we don't break in the future when a new feature is added.
|
||||
self._supported_features &= SUPPORT_GROUP_LIGHT
|
||||
|
||||
async def _force_member_updates(self):
|
||||
"""Force the update of member entities to ensure the states are correct for bulbs that don't report their state."""
|
||||
async_dispatcher_send(
|
||||
self.hass,
|
||||
SIGNAL_LIGHT_GROUP_STATE_CHANGED,
|
||||
{"entity_ids": self._entity_ids},
|
||||
)
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
"config_flow": true,
|
||||
"documentation": "https://www.home-assistant.io/integrations/zha",
|
||||
"requirements": [
|
||||
"bellows==0.17.0",
|
||||
"bellows==0.18.0",
|
||||
"pyserial==3.4",
|
||||
"zha-quirks==0.0.42",
|
||||
"zigpy-cc==0.4.4",
|
||||
"zigpy-deconz==0.9.2",
|
||||
"zigpy==0.22.1",
|
||||
"zigpy==0.22.2",
|
||||
"zigpy-xbee==0.12.1",
|
||||
"zigpy-zigate==0.6.1"
|
||||
],
|
||||
|
||||
@@ -511,8 +511,8 @@ async def async_process_ha_core_config(hass: HomeAssistant, config: Dict) -> Non
|
||||
elif LEGACY_CONF_WHITELIST_EXTERNAL_DIRS in config:
|
||||
_LOGGER.warning(
|
||||
"Key %s has been replaced with %s. Please update your config",
|
||||
CONF_ALLOWLIST_EXTERNAL_DIRS,
|
||||
LEGACY_CONF_WHITELIST_EXTERNAL_DIRS,
|
||||
CONF_ALLOWLIST_EXTERNAL_DIRS,
|
||||
)
|
||||
hac.allowlist_external_dirs.update(
|
||||
set(config[LEGACY_CONF_WHITELIST_EXTERNAL_DIRS])
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Constants used by Home Assistant components."""
|
||||
MAJOR_VERSION = 0
|
||||
MINOR_VERSION = 113
|
||||
PATCH_VERSION = "0b0"
|
||||
PATCH_VERSION = "1"
|
||||
__short_version__ = f"{MAJOR_VERSION}.{MINOR_VERSION}"
|
||||
__version__ = f"{__short_version__}.{PATCH_VERSION}"
|
||||
REQUIRED_PYTHON_VER = (3, 7, 1)
|
||||
|
||||
+16
-1
@@ -23,6 +23,7 @@ from typing import (
|
||||
Callable,
|
||||
Coroutine,
|
||||
Dict,
|
||||
Iterable,
|
||||
List,
|
||||
Mapping,
|
||||
Optional,
|
||||
@@ -98,6 +99,9 @@ CORE_STORAGE_VERSION = 1
|
||||
|
||||
DOMAIN = "homeassistant"
|
||||
|
||||
# How long to wait to log tasks that are blocking
|
||||
BLOCK_LOG_TIMEOUT = 60
|
||||
|
||||
# How long we wait for the result of a service call
|
||||
SERVICE_CALL_LIMIT = 10 # seconds
|
||||
|
||||
@@ -393,10 +397,21 @@ class HomeAssistant:
|
||||
pending = [task for task in self._pending_tasks if not task.done()]
|
||||
self._pending_tasks.clear()
|
||||
if pending:
|
||||
await asyncio.wait(pending)
|
||||
await self._await_and_log_pending(pending)
|
||||
else:
|
||||
await asyncio.sleep(0)
|
||||
|
||||
async def _await_and_log_pending(self, pending: Iterable[Awaitable[Any]]) -> None:
|
||||
"""Await and log tasks that take a long time."""
|
||||
wait_time = 0
|
||||
while pending:
|
||||
_, pending = await asyncio.wait(pending, timeout=BLOCK_LOG_TIMEOUT)
|
||||
if not pending:
|
||||
return
|
||||
wait_time += BLOCK_LOG_TIMEOUT
|
||||
for task in pending:
|
||||
_LOGGER.debug("Waited %s seconds for task: %s", wait_time, task)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stop Home Assistant and shuts down all threads."""
|
||||
if self.state == CoreState.not_running: # just ignore
|
||||
|
||||
@@ -135,7 +135,9 @@ track_state_change = threaded_listener_factory(async_track_state_change)
|
||||
|
||||
@bind_hass
|
||||
def async_track_state_change_event(
|
||||
hass: HomeAssistant, entity_ids: Iterable[str], action: Callable[[Event], None]
|
||||
hass: HomeAssistant,
|
||||
entity_ids: Union[str, Iterable[str]],
|
||||
action: Callable[[Event], None],
|
||||
) -> Callable[[], None]:
|
||||
"""Track specific state change events indexed by entity_id.
|
||||
|
||||
@@ -161,7 +163,7 @@ def async_track_state_change_event(
|
||||
if entity_id not in entity_callbacks:
|
||||
return
|
||||
|
||||
for action in entity_callbacks[entity_id]:
|
||||
for action in entity_callbacks[entity_id][:]:
|
||||
try:
|
||||
hass.async_run_job(action, event)
|
||||
except Exception: # pylint: disable=broad-except
|
||||
@@ -173,13 +175,13 @@ def async_track_state_change_event(
|
||||
EVENT_STATE_CHANGED, _async_state_change_dispatcher
|
||||
)
|
||||
|
||||
if isinstance(entity_ids, str):
|
||||
entity_ids = [entity_ids]
|
||||
|
||||
entity_ids = [entity_id.lower() for entity_id in entity_ids]
|
||||
|
||||
for entity_id in entity_ids:
|
||||
if entity_id not in entity_callbacks:
|
||||
entity_callbacks[entity_id] = []
|
||||
|
||||
entity_callbacks[entity_id].append(action)
|
||||
entity_callbacks.setdefault(entity_id, []).append(action)
|
||||
|
||||
@callback
|
||||
def remove_listener() -> None:
|
||||
@@ -247,7 +249,7 @@ def async_track_same_state(
|
||||
hass: HomeAssistant,
|
||||
period: timedelta,
|
||||
action: Callable[..., None],
|
||||
async_check_same_func: Callable[[str, State, State], bool],
|
||||
async_check_same_func: Callable[[str, Optional[State], Optional[State]], bool],
|
||||
entity_ids: Union[str, Iterable[str]] = MATCH_ALL,
|
||||
) -> CALLBACK_TYPE:
|
||||
"""Track the state of entities for a period and run an action.
|
||||
@@ -279,10 +281,12 @@ def async_track_same_state(
|
||||
hass.async_run_job(action)
|
||||
|
||||
@callback
|
||||
def state_for_cancel_listener(
|
||||
entity: str, from_state: State, to_state: State
|
||||
) -> None:
|
||||
def state_for_cancel_listener(event: Event) -> None:
|
||||
"""Fire on changes and cancel for listener if changed."""
|
||||
entity: str = event.data["entity_id"]
|
||||
from_state: Optional[State] = event.data.get("old_state")
|
||||
to_state: Optional[State] = event.data.get("new_state")
|
||||
|
||||
if not async_check_same_func(entity, from_state, to_state):
|
||||
clear_listener()
|
||||
|
||||
@@ -290,9 +294,16 @@ def async_track_same_state(
|
||||
hass, state_for_listener, dt_util.utcnow() + period
|
||||
)
|
||||
|
||||
async_remove_state_for_cancel = async_track_state_change(
|
||||
hass, entity_ids, state_for_cancel_listener
|
||||
)
|
||||
if entity_ids == MATCH_ALL:
|
||||
async_remove_state_for_cancel = hass.bus.async_listen(
|
||||
EVENT_STATE_CHANGED, state_for_cancel_listener
|
||||
)
|
||||
else:
|
||||
async_remove_state_for_cancel = async_track_state_change_event(
|
||||
hass,
|
||||
[entity_ids] if isinstance(entity_ids, str) else entity_ids,
|
||||
state_for_cancel_listener,
|
||||
)
|
||||
|
||||
return clear_listener
|
||||
|
||||
|
||||
@@ -140,7 +140,7 @@ class _ScriptRun:
|
||||
) -> None:
|
||||
self._hass = hass
|
||||
self._script = script
|
||||
self._variables = variables
|
||||
self._variables = variables or {}
|
||||
self._context = context
|
||||
self._log_exceptions = log_exceptions
|
||||
self._step = -1
|
||||
@@ -431,22 +431,23 @@ class _ScriptRun:
|
||||
|
||||
async def _async_repeat_step(self):
|
||||
"""Repeat a sequence."""
|
||||
|
||||
description = self._action.get(CONF_ALIAS, "sequence")
|
||||
repeat = self._action[CONF_REPEAT]
|
||||
|
||||
async def async_run_sequence(iteration, extra_msg="", extra_vars=None):
|
||||
saved_repeat_vars = self._variables.get("repeat")
|
||||
|
||||
def set_repeat_var(iteration, count=None):
|
||||
repeat_vars = {"first": iteration == 1, "index": iteration}
|
||||
if count:
|
||||
repeat_vars["last"] = iteration == count
|
||||
self._variables["repeat"] = repeat_vars
|
||||
|
||||
# pylint: disable=protected-access
|
||||
script = self._script._get_repeat_script(self._step)
|
||||
|
||||
async def async_run_sequence(iteration, extra_msg=""):
|
||||
self._log("Repeating %s: Iteration %i%s", description, iteration, extra_msg)
|
||||
repeat_vars = {"repeat": {"first": iteration == 1, "index": iteration}}
|
||||
if extra_vars:
|
||||
repeat_vars["repeat"].update(extra_vars)
|
||||
# pylint: disable=protected-access
|
||||
await self._async_run_script(
|
||||
self._script._get_repeat_script(self._step),
|
||||
# Add repeat to variables. Override if it already exists in case of
|
||||
# nested calls.
|
||||
{**(self._variables or {}), **repeat_vars},
|
||||
)
|
||||
await self._async_run_script(script)
|
||||
|
||||
if CONF_COUNT in repeat:
|
||||
count = repeat[CONF_COUNT]
|
||||
@@ -461,10 +462,10 @@ class _ScriptRun:
|
||||
level=logging.ERROR,
|
||||
)
|
||||
raise _StopScript
|
||||
extra_msg = f" of {count}"
|
||||
for iteration in range(1, count + 1):
|
||||
await async_run_sequence(
|
||||
iteration, f" of {count}", {"last": iteration == count}
|
||||
)
|
||||
set_repeat_var(iteration, count)
|
||||
await async_run_sequence(iteration, extra_msg)
|
||||
if self._stop.is_set():
|
||||
break
|
||||
|
||||
@@ -473,6 +474,7 @@ class _ScriptRun:
|
||||
await self._async_get_condition(config) for config in repeat[CONF_WHILE]
|
||||
]
|
||||
for iteration in itertools.count(1):
|
||||
set_repeat_var(iteration)
|
||||
if self._stop.is_set() or not all(
|
||||
cond(self._hass, self._variables) for cond in conditions
|
||||
):
|
||||
@@ -484,12 +486,18 @@ class _ScriptRun:
|
||||
await self._async_get_condition(config) for config in repeat[CONF_UNTIL]
|
||||
]
|
||||
for iteration in itertools.count(1):
|
||||
set_repeat_var(iteration)
|
||||
await async_run_sequence(iteration)
|
||||
if self._stop.is_set() or all(
|
||||
cond(self._hass, self._variables) for cond in conditions
|
||||
):
|
||||
break
|
||||
|
||||
if saved_repeat_vars:
|
||||
self._variables["repeat"] = saved_repeat_vars
|
||||
else:
|
||||
del self._variables["repeat"]
|
||||
|
||||
async def _async_choose_step(self):
|
||||
"""Choose a sequence."""
|
||||
# pylint: disable=protected-access
|
||||
@@ -503,11 +511,11 @@ class _ScriptRun:
|
||||
if choose_data["default"]:
|
||||
await self._async_run_script(choose_data["default"])
|
||||
|
||||
async def _async_run_script(self, script, variables=None):
|
||||
async def _async_run_script(self, script):
|
||||
"""Execute a script."""
|
||||
await self._async_run_long_action(
|
||||
self._hass.async_create_task(
|
||||
script.async_run(variables or self._variables, self._context)
|
||||
script.async_run(self._variables, self._context)
|
||||
)
|
||||
)
|
||||
|
||||
@@ -760,14 +768,16 @@ class Script:
|
||||
raise
|
||||
|
||||
async def _async_stop(self, update_state):
|
||||
await asyncio.wait([run.async_stop() for run in self._runs])
|
||||
aws = [run.async_stop() for run in self._runs]
|
||||
if not aws:
|
||||
return
|
||||
await asyncio.wait(aws)
|
||||
if update_state:
|
||||
self._changed()
|
||||
|
||||
async def async_stop(self, update_state: bool = True) -> None:
|
||||
"""Stop running script."""
|
||||
if self.is_running:
|
||||
await asyncio.shield(self._async_stop(update_state))
|
||||
await asyncio.shield(self._async_stop(update_state))
|
||||
|
||||
async def _async_get_condition(self, config):
|
||||
config_cache_key = frozenset((k, str(v)) for k, v in config.items())
|
||||
|
||||
@@ -13,10 +13,11 @@ defusedxml==0.6.0
|
||||
distro==1.5.0
|
||||
emoji==0.5.4
|
||||
hass-nabucasa==0.34.7
|
||||
home-assistant-frontend==20200715.0
|
||||
home-assistant-frontend==20200716.0
|
||||
importlib-metadata==1.6.0;python_version<'3.8'
|
||||
jinja2>=2.11.1
|
||||
netdisco==2.8.0
|
||||
paho-mqtt==1.5.0
|
||||
pip>=8.0.3
|
||||
python-slugify==4.0.0
|
||||
pytz>=2020.1
|
||||
|
||||
+12
-15
@@ -231,7 +231,7 @@ ambiclimate==0.2.1
|
||||
amcrest==1.7.0
|
||||
|
||||
# homeassistant.components.androidtv
|
||||
androidtv[async]==0.0.45
|
||||
androidtv[async]==0.0.46
|
||||
|
||||
# homeassistant.components.anel_pwrctrl
|
||||
anel_pwrctrl-homeassistant==0.0.1.dev2
|
||||
@@ -319,7 +319,7 @@ beautifulsoup4==4.9.0
|
||||
beewi_smartclim==0.0.7
|
||||
|
||||
# homeassistant.components.zha
|
||||
bellows==0.17.0
|
||||
bellows==0.18.0
|
||||
|
||||
# homeassistant.components.bmw_connected_drive
|
||||
bimmer_connected==0.7.7
|
||||
@@ -473,7 +473,7 @@ directv==0.3.0
|
||||
discogs_client==2.2.2
|
||||
|
||||
# homeassistant.components.discord
|
||||
discord.py==1.3.3
|
||||
discord.py==1.3.4
|
||||
|
||||
# homeassistant.components.updater
|
||||
distro==1.5.0
|
||||
@@ -724,7 +724,7 @@ hole==0.5.1
|
||||
holidays==0.10.2
|
||||
|
||||
# homeassistant.components.frontend
|
||||
home-assistant-frontend==20200715.0
|
||||
home-assistant-frontend==20200716.0
|
||||
|
||||
# homeassistant.components.zwave
|
||||
homeassistant-pyozw==0.1.10
|
||||
@@ -783,9 +783,6 @@ influxdb==5.2.3
|
||||
# homeassistant.components.iperf3
|
||||
iperf3==0.1.11
|
||||
|
||||
# homeassistant.components.route53
|
||||
ipify==1.0.0
|
||||
|
||||
# homeassistant.components.rest
|
||||
# homeassistant.components.verisure
|
||||
jsonpath==0.82
|
||||
@@ -1244,7 +1241,7 @@ pycfdns==0.0.1
|
||||
pychannels==1.0.0
|
||||
|
||||
# homeassistant.components.cast
|
||||
pychromecast==7.0.1
|
||||
pychromecast==7.1.2
|
||||
|
||||
# homeassistant.components.cmus
|
||||
pycmus==0.1.1
|
||||
@@ -1380,7 +1377,7 @@ pyialarm==0.3
|
||||
pyicloud==0.9.7
|
||||
|
||||
# homeassistant.components.insteon
|
||||
pyinsteon==1.0.5
|
||||
pyinsteon==1.0.7
|
||||
|
||||
# homeassistant.components.intesishome
|
||||
pyintesishome==1.7.5
|
||||
@@ -1491,7 +1488,7 @@ pynetgear==0.6.1
|
||||
pynetio==0.1.9.1
|
||||
|
||||
# homeassistant.components.nuki
|
||||
pynuki==1.3.7
|
||||
pynuki==1.3.8
|
||||
|
||||
# homeassistant.components.nut
|
||||
pynut2==2.1.2
|
||||
@@ -1608,7 +1605,7 @@ pysmappee==0.1.5
|
||||
pysmartapp==0.3.2
|
||||
|
||||
# homeassistant.components.smartthings
|
||||
pysmartthings==0.7.1
|
||||
pysmartthings==0.7.2
|
||||
|
||||
# homeassistant.components.smarty
|
||||
pysmarty==0.8
|
||||
@@ -1623,7 +1620,7 @@ pysnmp==4.4.12
|
||||
pysoma==0.0.10
|
||||
|
||||
# homeassistant.components.sonos
|
||||
pysonos==0.0.31
|
||||
pysonos==0.0.32
|
||||
|
||||
# homeassistant.components.spc
|
||||
pyspcwebgw==0.4.0
|
||||
@@ -1942,7 +1939,7 @@ simplehound==0.3
|
||||
simplepush==1.1.4
|
||||
|
||||
# homeassistant.components.simplisafe
|
||||
simplisafe-python==9.2.0
|
||||
simplisafe-python==9.2.1
|
||||
|
||||
# homeassistant.components.sisyphus
|
||||
sisyphus-control==2.2.1
|
||||
@@ -2207,7 +2204,7 @@ wled==0.4.3
|
||||
xbee-helper==0.0.7
|
||||
|
||||
# homeassistant.components.xbox_live
|
||||
xboxapi==0.1.1
|
||||
xboxapi==2.0.0
|
||||
|
||||
# homeassistant.components.xfinity
|
||||
xfinity-gateway==0.0.4
|
||||
@@ -2269,7 +2266,7 @@ zigpy-xbee==0.12.1
|
||||
zigpy-zigate==0.6.1
|
||||
|
||||
# homeassistant.components.zha
|
||||
zigpy==0.22.1
|
||||
zigpy==0.22.2
|
||||
|
||||
# homeassistant.components.zoneminder
|
||||
zm-py==0.4.0
|
||||
|
||||
@@ -132,7 +132,7 @@ airly==0.0.2
|
||||
ambiclimate==0.2.1
|
||||
|
||||
# homeassistant.components.androidtv
|
||||
androidtv[async]==0.0.45
|
||||
androidtv[async]==0.0.46
|
||||
|
||||
# homeassistant.components.apns
|
||||
apns2==0.3.0
|
||||
@@ -166,7 +166,7 @@ azure-eventhub==5.1.0
|
||||
base36==0.1.1
|
||||
|
||||
# homeassistant.components.zha
|
||||
bellows==0.17.0
|
||||
bellows==0.18.0
|
||||
|
||||
# homeassistant.components.blebox
|
||||
blebox_uniapi==1.3.2
|
||||
@@ -350,7 +350,7 @@ hole==0.5.1
|
||||
holidays==0.10.2
|
||||
|
||||
# homeassistant.components.frontend
|
||||
home-assistant-frontend==20200715.0
|
||||
home-assistant-frontend==20200716.0
|
||||
|
||||
# homeassistant.components.zwave
|
||||
homeassistant-pyozw==0.1.10
|
||||
@@ -577,7 +577,7 @@ pyblackbird==0.5
|
||||
pybotvac==0.0.17
|
||||
|
||||
# homeassistant.components.cast
|
||||
pychromecast==7.0.1
|
||||
pychromecast==7.1.2
|
||||
|
||||
# homeassistant.components.coolmaster
|
||||
pycoolmasternet==0.0.4
|
||||
@@ -737,13 +737,13 @@ pysmappee==0.1.5
|
||||
pysmartapp==0.3.2
|
||||
|
||||
# homeassistant.components.smartthings
|
||||
pysmartthings==0.7.1
|
||||
pysmartthings==0.7.2
|
||||
|
||||
# homeassistant.components.soma
|
||||
pysoma==0.0.10
|
||||
|
||||
# homeassistant.components.sonos
|
||||
pysonos==0.0.31
|
||||
pysonos==0.0.32
|
||||
|
||||
# homeassistant.components.spc
|
||||
pyspcwebgw==0.4.0
|
||||
@@ -857,7 +857,7 @@ sentry-sdk==0.13.5
|
||||
simplehound==0.3
|
||||
|
||||
# homeassistant.components.simplisafe
|
||||
simplisafe-python==9.2.0
|
||||
simplisafe-python==9.2.1
|
||||
|
||||
# homeassistant.components.sleepiq
|
||||
sleepyq==0.7
|
||||
@@ -999,4 +999,4 @@ zigpy-xbee==0.12.1
|
||||
zigpy-zigate==0.6.1
|
||||
|
||||
# homeassistant.components.zha
|
||||
zigpy==0.22.1
|
||||
zigpy==0.22.2
|
||||
|
||||
@@ -297,8 +297,11 @@ def gather_constraints():
|
||||
return (
|
||||
"\n".join(
|
||||
sorted(
|
||||
core_requirements()
|
||||
+ list(gather_recursive_requirements("default_config"))
|
||||
{
|
||||
*core_requirements(),
|
||||
*gather_recursive_requirements("default_config"),
|
||||
*gather_recursive_requirements("mqtt"),
|
||||
}
|
||||
)
|
||||
+ [""]
|
||||
)
|
||||
|
||||
@@ -799,13 +799,15 @@ async def test_no_birth_message(hass, mqtt_client_mock, mqtt_mock):
|
||||
)
|
||||
async def test_custom_will_message(hass, mqtt_client_mock, mqtt_mock):
|
||||
"""Test will message."""
|
||||
mqtt_client_mock.will_set.assert_called_with("death", "death", 0, False, None)
|
||||
mqtt_client_mock.will_set.assert_called_with(
|
||||
topic="death", payload="death", qos=0, retain=False
|
||||
)
|
||||
|
||||
|
||||
async def test_default_will_message(hass, mqtt_client_mock, mqtt_mock):
|
||||
"""Test will message."""
|
||||
mqtt_client_mock.will_set.assert_called_with(
|
||||
"homeassistant/status", "offline", 0, False, None
|
||||
topic="homeassistant/status", payload="offline", qos=0, retain=False
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ from homeassistant.components.climate.const import (
|
||||
ATTR_FAN_MODES,
|
||||
ATTR_HVAC_ACTION,
|
||||
ATTR_HVAC_MODES,
|
||||
ATTR_PRESET_MODE,
|
||||
ATTR_PRESET_MODES,
|
||||
ATTR_TARGET_TEMP_HIGH,
|
||||
ATTR_TARGET_TEMP_LOW,
|
||||
@@ -218,3 +219,47 @@ async def test_climate(hass, climate_data, sent_messages, climate_msg, caplog):
|
||||
)
|
||||
assert len(sent_messages) == 8
|
||||
assert "Received an invalid preset mode: invalid preset mode" in caplog.text
|
||||
|
||||
# test thermostat device without a mode commandclass
|
||||
state = hass.states.get("climate.danfoss_living_connect_z_v1_06_014g0013_heating_1")
|
||||
assert state is not None
|
||||
assert state.state == HVAC_MODE_HEAT
|
||||
assert state.attributes[ATTR_HVAC_MODES] == [
|
||||
HVAC_MODE_HEAT,
|
||||
]
|
||||
assert state.attributes.get(ATTR_CURRENT_TEMPERATURE) is None
|
||||
assert round(state.attributes[ATTR_TEMPERATURE], 0) == 21
|
||||
assert state.attributes.get(ATTR_TARGET_TEMP_LOW) is None
|
||||
assert state.attributes.get(ATTR_TARGET_TEMP_HIGH) is None
|
||||
assert state.attributes.get(ATTR_PRESET_MODE) is None
|
||||
assert state.attributes.get(ATTR_PRESET_MODES) is None
|
||||
|
||||
# Test set target temperature
|
||||
await hass.services.async_call(
|
||||
"climate",
|
||||
"set_temperature",
|
||||
{
|
||||
"entity_id": "climate.danfoss_living_connect_z_v1_06_014g0013_heating_1",
|
||||
"temperature": 28.0,
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
assert len(sent_messages) == 9
|
||||
msg = sent_messages[-1]
|
||||
assert msg["topic"] == "OpenZWave/1/command/setvalue/"
|
||||
assert msg["payload"] == {
|
||||
"Value": 28.0,
|
||||
"ValueIDKey": 281475116220434,
|
||||
}
|
||||
|
||||
await hass.services.async_call(
|
||||
"climate",
|
||||
"set_hvac_mode",
|
||||
{
|
||||
"entity_id": "climate.danfoss_living_connect_z_v1_06_014g0013_heating_1",
|
||||
"hvac_mode": HVAC_MODE_HEAT,
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
assert len(sent_messages) == 9
|
||||
assert "does not support setting a mode" in caplog.text
|
||||
|
||||
@@ -78,9 +78,9 @@ class MockPlexAccount:
|
||||
"""Mock the PlexAccount resources listing method."""
|
||||
return self._resources
|
||||
|
||||
def sonos_speaker_by_id(self, machine_identifier):
|
||||
def sonos_speaker(self, speaker_name):
|
||||
"""Mock the PlexAccount Sonos lookup method."""
|
||||
return MockPlexSonosClient(machine_identifier)
|
||||
return MockPlexSonosClient(speaker_name)
|
||||
|
||||
|
||||
class MockPlexSystemAccount:
|
||||
@@ -378,9 +378,9 @@ class MockPlexMediaTrack(MockPlexMediaItem):
|
||||
class MockPlexSonosClient:
|
||||
"""Mock a PlexSonosClient instance."""
|
||||
|
||||
def __init__(self, machine_identifier):
|
||||
def __init__(self, name):
|
||||
"""Initialize the object."""
|
||||
self.machineIdentifier = machine_identifier
|
||||
self.name = name
|
||||
|
||||
def playMedia(self, item):
|
||||
"""Mock the playMedia method."""
|
||||
|
||||
@@ -39,7 +39,7 @@ async def test_sonos_playback(hass):
|
||||
|
||||
# Test Sonos integration lookup failure
|
||||
with patch.object(
|
||||
hass.components.sonos, "get_coordinator_id", side_effect=HomeAssistantError
|
||||
hass.components.sonos, "get_coordinator_name", side_effect=HomeAssistantError
|
||||
):
|
||||
assert await hass.services.async_call(
|
||||
DOMAIN,
|
||||
@@ -55,7 +55,7 @@ async def test_sonos_playback(hass):
|
||||
# Test success with dict
|
||||
with patch.object(
|
||||
hass.components.sonos,
|
||||
"get_coordinator_id",
|
||||
"get_coordinator_name",
|
||||
return_value="media_player.sonos_kitchen",
|
||||
), patch("plexapi.playqueue.PlayQueue.create"):
|
||||
assert await hass.services.async_call(
|
||||
@@ -72,7 +72,7 @@ async def test_sonos_playback(hass):
|
||||
# Test success with plex_key
|
||||
with patch.object(
|
||||
hass.components.sonos,
|
||||
"get_coordinator_id",
|
||||
"get_coordinator_name",
|
||||
return_value="media_player.sonos_kitchen",
|
||||
), patch("plexapi.playqueue.PlayQueue.create"):
|
||||
assert await hass.services.async_call(
|
||||
@@ -89,7 +89,7 @@ async def test_sonos_playback(hass):
|
||||
# Test invalid Plex server requested
|
||||
with patch.object(
|
||||
hass.components.sonos,
|
||||
"get_coordinator_id",
|
||||
"get_coordinator_name",
|
||||
return_value="media_player.sonos_kitchen",
|
||||
):
|
||||
assert await hass.services.async_call(
|
||||
@@ -105,10 +105,10 @@ async def test_sonos_playback(hass):
|
||||
|
||||
# Test no speakers available
|
||||
with patch.object(
|
||||
loaded_server.account, "sonos_speaker_by_id", return_value=None
|
||||
loaded_server.account, "sonos_speaker", return_value=None
|
||||
), patch.object(
|
||||
hass.components.sonos,
|
||||
"get_coordinator_id",
|
||||
"get_coordinator_name",
|
||||
return_value="media_player.sonos_kitchen",
|
||||
):
|
||||
assert await hass.services.async_call(
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
"""The tests for the Rfxtrx sensor platform."""
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.rfxtrx.const import ATTR_EVENT
|
||||
from homeassistant.core import State
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.util.dt import utcnow
|
||||
|
||||
from . import _signal_event
|
||||
|
||||
from tests.common import async_fire_time_changed
|
||||
from tests.common import async_fire_time_changed, mock_restore_cache
|
||||
|
||||
|
||||
async def test_one(hass, rfxtrx):
|
||||
@@ -59,6 +63,27 @@ async def test_one_pt2262(hass, rfxtrx):
|
||||
assert state.state == "off"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"state,event",
|
||||
[["on", "0b1100cd0213c7f230010f71"], ["off", "0b1100cd0213c7f230000f71"]],
|
||||
)
|
||||
async def test_state_restore(hass, rfxtrx, state, event):
|
||||
"""State restoration."""
|
||||
|
||||
entity_id = "binary_sensor.ac_213c7f2_48"
|
||||
|
||||
mock_restore_cache(hass, [State(entity_id, state, attributes={ATTR_EVENT: event})])
|
||||
|
||||
assert await async_setup_component(
|
||||
hass,
|
||||
"rfxtrx",
|
||||
{"rfxtrx": {"device": "abcd", "devices": {"0b1100cd0213c7f230010f71": {}}}},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(entity_id).state == state
|
||||
|
||||
|
||||
async def test_several(hass, rfxtrx):
|
||||
"""Test with 3."""
|
||||
assert await async_setup_component(
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
"""The tests for the Rfxtrx cover platform."""
|
||||
from unittest.mock import call
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.core import State
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from . import _signal_event
|
||||
|
||||
from tests.common import mock_restore_cache
|
||||
|
||||
|
||||
async def test_one_cover(hass, rfxtrx):
|
||||
"""Test with 1 cover."""
|
||||
@@ -46,6 +51,24 @@ async def test_one_cover(hass, rfxtrx):
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("state", ["open", "closed"])
|
||||
async def test_state_restore(hass, rfxtrx, state):
|
||||
"""State restoration."""
|
||||
|
||||
entity_id = "cover.lightwaverf_siemens_0213c7_242"
|
||||
|
||||
mock_restore_cache(hass, [State(entity_id, state)])
|
||||
|
||||
assert await async_setup_component(
|
||||
hass,
|
||||
"rfxtrx",
|
||||
{"rfxtrx": {"device": "abcd", "devices": {"0b1400cd0213c7f20d010f51": {}}}},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(entity_id).state == state
|
||||
|
||||
|
||||
async def test_several_covers(hass, rfxtrx):
|
||||
"""Test with 3 covers."""
|
||||
assert await async_setup_component(
|
||||
|
||||
@@ -3,10 +3,14 @@ from unittest.mock import call
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.light import ATTR_BRIGHTNESS
|
||||
from homeassistant.core import State
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from . import _signal_event
|
||||
|
||||
from tests.common import mock_restore_cache
|
||||
|
||||
|
||||
async def test_one_light(hass, rfxtrx):
|
||||
"""Test with 1 light."""
|
||||
@@ -83,6 +87,27 @@ async def test_one_light(hass, rfxtrx):
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("state,brightness", [["on", 100], ["on", 50], ["off", None]])
|
||||
async def test_state_restore(hass, rfxtrx, state, brightness):
|
||||
"""State restoration."""
|
||||
|
||||
entity_id = "light.ac_213c7f2_16"
|
||||
|
||||
mock_restore_cache(
|
||||
hass, [State(entity_id, state, attributes={ATTR_BRIGHTNESS: brightness})]
|
||||
)
|
||||
|
||||
assert await async_setup_component(
|
||||
hass,
|
||||
"rfxtrx",
|
||||
{"rfxtrx": {"device": "abcd", "devices": {"0b1100cd0213c7f210020f51": {}}}},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(entity_id).state == state
|
||||
assert hass.states.get(entity_id).attributes.get(ATTR_BRIGHTNESS) == brightness
|
||||
|
||||
|
||||
async def test_several_lights(hass, rfxtrx):
|
||||
"""Test with 3 lights."""
|
||||
assert await async_setup_component(
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
"""The tests for the Rfxtrx sensor platform."""
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.rfxtrx.const import ATTR_EVENT
|
||||
from homeassistant.const import TEMP_CELSIUS, UNIT_PERCENTAGE
|
||||
from homeassistant.core import State
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from . import _signal_event
|
||||
|
||||
from tests.common import mock_restore_cache
|
||||
|
||||
|
||||
async def test_default_config(hass, rfxtrx):
|
||||
"""Test with 0 sensor."""
|
||||
@@ -34,6 +40,27 @@ async def test_one_sensor(hass, rfxtrx):
|
||||
assert state.attributes.get("unit_of_measurement") == TEMP_CELSIUS
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"state,event",
|
||||
[["18.4", "0a520801070100b81b0279"], ["17.9", "0a52085e070100b31b0279"]],
|
||||
)
|
||||
async def test_state_restore(hass, rfxtrx, state, event):
|
||||
"""State restoration."""
|
||||
|
||||
entity_id = "sensor.wt260_wt260h_wt440h_wt450_wt450h_07_01_temperature"
|
||||
|
||||
mock_restore_cache(hass, [State(entity_id, state, attributes={ATTR_EVENT: event})])
|
||||
|
||||
assert await async_setup_component(
|
||||
hass,
|
||||
"rfxtrx",
|
||||
{"rfxtrx": {"device": "abcd", "devices": {"0a520801070100b81b0279": {}}}},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(entity_id).state == state
|
||||
|
||||
|
||||
async def test_one_sensor_no_datatype(hass, rfxtrx):
|
||||
"""Test with 1 sensor."""
|
||||
assert await async_setup_component(
|
||||
|
||||
@@ -3,10 +3,13 @@ from unittest.mock import call
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.core import State
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from . import _signal_event
|
||||
|
||||
from tests.common import mock_restore_cache
|
||||
|
||||
|
||||
async def test_one_switch(hass, rfxtrx):
|
||||
"""Test with 1 switch."""
|
||||
@@ -42,6 +45,24 @@ async def test_one_switch(hass, rfxtrx):
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("state", ["on", "off"])
|
||||
async def test_state_restore(hass, rfxtrx, state):
|
||||
"""State restoration."""
|
||||
|
||||
entity_id = "switch.ac_213c7f2_16"
|
||||
|
||||
mock_restore_cache(hass, [State(entity_id, state)])
|
||||
|
||||
assert await async_setup_component(
|
||||
hass,
|
||||
"rfxtrx",
|
||||
{"rfxtrx": {"device": "abcd", "devices": {"0b1100cd0213c7f210010f51": {}}}},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(entity_id).state == state
|
||||
|
||||
|
||||
async def test_several_switches(hass, rfxtrx):
|
||||
"""Test with 3 switches."""
|
||||
assert await async_setup_component(
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
"""Define tests for the SimpliSafe config flow."""
|
||||
import json
|
||||
|
||||
from simplipy.errors import SimplipyError
|
||||
from simplipy.errors import (
|
||||
InvalidCredentialsError,
|
||||
PendingAuthorizationError,
|
||||
SimplipyError,
|
||||
)
|
||||
|
||||
from homeassistant import data_entry_flow
|
||||
from homeassistant.components.simplisafe import DOMAIN
|
||||
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
|
||||
from homeassistant.const import CONF_CODE, CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME
|
||||
|
||||
from tests.async_mock import MagicMock, PropertyMock, mock_open, patch
|
||||
from tests.async_mock import MagicMock, PropertyMock, patch
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
@@ -21,11 +23,17 @@ def mock_api():
|
||||
|
||||
async def test_duplicate_error(hass):
|
||||
"""Test that errors are shown when duplicates are added."""
|
||||
conf = {CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"}
|
||||
conf = {
|
||||
CONF_USERNAME: "user@email.com",
|
||||
CONF_PASSWORD: "password",
|
||||
CONF_CODE: "1234",
|
||||
}
|
||||
|
||||
MockConfigEntry(domain=DOMAIN, unique_id="user@email.com", data=conf).add_to_hass(
|
||||
hass
|
||||
)
|
||||
MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
unique_id="user@email.com",
|
||||
data={CONF_USERNAME: "user@email.com", CONF_TOKEN: "12345", CONF_CODE: "1234"},
|
||||
).add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}, data=conf
|
||||
@@ -40,7 +48,7 @@ async def test_invalid_credentials(hass):
|
||||
conf = {CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"}
|
||||
|
||||
with patch(
|
||||
"simplipy.API.login_via_credentials", side_effect=SimplipyError,
|
||||
"simplipy.API.login_via_credentials", side_effect=InvalidCredentialsError,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}, data=conf
|
||||
@@ -75,15 +83,12 @@ async def test_options_flow(hass):
|
||||
|
||||
async def test_show_form(hass):
|
||||
"""Test that the form is served with no input."""
|
||||
with patch(
|
||||
"homeassistant.components.simplisafe.async_setup_entry", return_value=True
|
||||
):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_IMPORT}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_IMPORT}
|
||||
)
|
||||
|
||||
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
|
||||
assert result["step_id"] == "user"
|
||||
|
||||
|
||||
async def test_step_import(hass):
|
||||
@@ -94,17 +99,9 @@ async def test_step_import(hass):
|
||||
CONF_CODE: "1234",
|
||||
}
|
||||
|
||||
mop = mock_open(read_data=json.dumps({"refresh_token": "12345"}))
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.simplisafe.async_setup_entry", return_value=True
|
||||
), patch("simplipy.API.login_via_credentials", return_value=mock_api()), patch(
|
||||
"homeassistant.util.json.open", mop, create=True
|
||||
), patch(
|
||||
"homeassistant.util.json.os.open", return_value=0
|
||||
), patch(
|
||||
"homeassistant.util.json.os.replace"
|
||||
):
|
||||
), patch("simplipy.API.login_via_credentials", return_value=mock_api()):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}, data=conf
|
||||
)
|
||||
@@ -118,25 +115,48 @@ async def test_step_import(hass):
|
||||
}
|
||||
|
||||
|
||||
async def test_step_reauth(hass):
|
||||
"""Test that the reauth step works."""
|
||||
MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
unique_id="user@email.com",
|
||||
data={CONF_USERNAME: "user@email.com", CONF_TOKEN: "12345", CONF_CODE: "1234"},
|
||||
).add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN,
|
||||
context={"source": "reauth"},
|
||||
data={CONF_CODE: "1234", CONF_USERNAME: "user@email.com"},
|
||||
)
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.simplisafe.async_setup_entry", return_value=True
|
||||
), patch("simplipy.API.login_via_credentials", return_value=mock_api()):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_PASSWORD: "password"}
|
||||
)
|
||||
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
|
||||
assert len(hass.config_entries.async_entries()) == 1
|
||||
|
||||
|
||||
async def test_step_user(hass):
|
||||
"""Test that the user step works."""
|
||||
"""Test that the user step works (without MFA)."""
|
||||
conf = {
|
||||
CONF_USERNAME: "user@email.com",
|
||||
CONF_PASSWORD: "password",
|
||||
CONF_CODE: "1234",
|
||||
}
|
||||
|
||||
mop = mock_open(read_data=json.dumps({"refresh_token": "12345"}))
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.simplisafe.async_setup_entry", return_value=True
|
||||
), patch("simplipy.API.login_via_credentials", return_value=mock_api()), patch(
|
||||
"homeassistant.util.json.open", mop, create=True
|
||||
), patch(
|
||||
"homeassistant.util.json.os.open", return_value=0
|
||||
), patch(
|
||||
"homeassistant.util.json.os.replace"
|
||||
):
|
||||
), patch("simplipy.API.login_via_credentials", return_value=mock_api()):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}, data=conf
|
||||
)
|
||||
@@ -148,3 +168,58 @@ async def test_step_user(hass):
|
||||
CONF_TOKEN: "12345abc",
|
||||
CONF_CODE: "1234",
|
||||
}
|
||||
|
||||
|
||||
async def test_step_user_mfa(hass):
|
||||
"""Test that the user step works when MFA is in the middle."""
|
||||
conf = {
|
||||
CONF_USERNAME: "user@email.com",
|
||||
CONF_PASSWORD: "password",
|
||||
CONF_CODE: "1234",
|
||||
}
|
||||
|
||||
with patch(
|
||||
"simplipy.API.login_via_credentials", side_effect=PendingAuthorizationError
|
||||
):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}, data=conf
|
||||
)
|
||||
assert result["step_id"] == "mfa"
|
||||
|
||||
with patch(
|
||||
"simplipy.API.login_via_credentials", side_effect=PendingAuthorizationError
|
||||
):
|
||||
# Simulate the user pressing the MFA submit button without having clicked
|
||||
# the link in the MFA email:
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={}
|
||||
)
|
||||
assert result["step_id"] == "mfa"
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.simplisafe.async_setup_entry", return_value=True
|
||||
), patch("simplipy.API.login_via_credentials", return_value=mock_api()):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={}
|
||||
)
|
||||
|
||||
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
|
||||
assert result["title"] == "user@email.com"
|
||||
assert result["data"] == {
|
||||
CONF_USERNAME: "user@email.com",
|
||||
CONF_TOKEN: "12345abc",
|
||||
CONF_CODE: "1234",
|
||||
}
|
||||
|
||||
|
||||
async def test_unknown_error(hass):
|
||||
"""Test that an unknown error raises the correct error."""
|
||||
conf = {CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"}
|
||||
|
||||
with patch(
|
||||
"simplipy.API.login_via_credentials", side_effect=SimplipyError,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}, data=conf
|
||||
)
|
||||
assert result["errors"] == {"base": "unknown"}
|
||||
|
||||
@@ -249,7 +249,7 @@ def subscription_factory_fixture():
|
||||
def device_factory_fixture():
|
||||
"""Fixture for creating mock devices."""
|
||||
api = Mock(Api)
|
||||
api.post_device_command.return_value = {}
|
||||
api.post_device_command.return_value = {"results": [{"status": "ACCEPTED"}]}
|
||||
|
||||
def _factory(label, capabilities, status: dict = None):
|
||||
device_data = {
|
||||
|
||||
@@ -49,6 +49,20 @@ def get_service_info_mock(service_type, name):
|
||||
)
|
||||
|
||||
|
||||
def get_service_info_mock_without_an_address(service_type, name):
|
||||
"""Return service info for get_service_info without any addresses."""
|
||||
return ServiceInfo(
|
||||
service_type,
|
||||
name,
|
||||
addresses=[],
|
||||
port=80,
|
||||
weight=0,
|
||||
priority=0,
|
||||
server="name.local.",
|
||||
properties=PROPERTIES,
|
||||
)
|
||||
|
||||
|
||||
def get_homekit_info_mock(model, pairing_status):
|
||||
"""Return homekit info for get_service_info for an homekit device."""
|
||||
|
||||
@@ -286,6 +300,15 @@ async def test_info_from_service_non_utf8(hass):
|
||||
assert raw_info["non-utf8-value"] is NON_UTF8_VALUE
|
||||
|
||||
|
||||
async def test_info_from_service_with_addresses(hass):
|
||||
"""Test info_from_service does not throw when there are no addresses."""
|
||||
service_type = "_test._tcp.local."
|
||||
info = zeroconf.info_from_service(
|
||||
get_service_info_mock_without_an_address(service_type, f"test.{service_type}")
|
||||
)
|
||||
assert info is None
|
||||
|
||||
|
||||
async def test_get_instance(hass, mock_zeroconf):
|
||||
"""Test we get an instance."""
|
||||
assert await hass.components.zeroconf.async_get_instance() is mock_zeroconf
|
||||
|
||||
@@ -265,3 +265,58 @@ async def test_temp_uom(
|
||||
assert state is not None
|
||||
assert round(float(state.state)) == expected
|
||||
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == uom
|
||||
|
||||
|
||||
async def test_electrical_measurement_init(
|
||||
hass, zigpy_device_mock, zha_device_joined,
|
||||
):
|
||||
"""Test proper initialization of the electrical measurement cluster."""
|
||||
|
||||
cluster_id = homeautomation.ElectricalMeasurement.cluster_id
|
||||
zigpy_device = zigpy_device_mock(
|
||||
{
|
||||
1: {
|
||||
"in_clusters": [cluster_id, general.Basic.cluster_id],
|
||||
"out_cluster": [],
|
||||
"device_type": 0x0000,
|
||||
}
|
||||
}
|
||||
)
|
||||
cluster = zigpy_device.endpoints[1].in_clusters[cluster_id]
|
||||
zha_device = await zha_device_joined(zigpy_device)
|
||||
entity_id = await find_entity_id(DOMAIN, zha_device, hass)
|
||||
|
||||
# allow traffic to flow through the gateway and devices
|
||||
await async_enable_traffic(hass, [zha_device])
|
||||
|
||||
# test that the sensor now have a state of unknown
|
||||
assert hass.states.get(entity_id).state == STATE_UNKNOWN
|
||||
|
||||
await send_attributes_report(hass, cluster, {0: 1, 1291: 100, 10: 1000})
|
||||
assert int(hass.states.get(entity_id).state) == 100
|
||||
|
||||
channel = zha_device.channels.pools[0].all_channels["1:0x0b04"]
|
||||
assert channel.divisor == 1
|
||||
assert channel.multiplier == 1
|
||||
|
||||
# update power divisor
|
||||
await send_attributes_report(hass, cluster, {0: 1, 1291: 20, 0x0403: 5, 10: 1000})
|
||||
assert channel.divisor == 5
|
||||
assert channel.multiplier == 1
|
||||
assert hass.states.get(entity_id).state == "4.0"
|
||||
|
||||
await send_attributes_report(hass, cluster, {0: 1, 1291: 30, 0x0605: 10, 10: 1000})
|
||||
assert channel.divisor == 10
|
||||
assert channel.multiplier == 1
|
||||
assert hass.states.get(entity_id).state == "3.0"
|
||||
|
||||
# update power multiplier
|
||||
await send_attributes_report(hass, cluster, {0: 1, 1291: 20, 0x0402: 6, 10: 1000})
|
||||
assert channel.divisor == 10
|
||||
assert channel.multiplier == 6
|
||||
assert hass.states.get(entity_id).state == "12.0"
|
||||
|
||||
await send_attributes_report(hass, cluster, {0: 1, 1291: 30, 0x0604: 20, 10: 1000})
|
||||
assert channel.divisor == 10
|
||||
assert channel.multiplier == 20
|
||||
assert hass.states.get(entity_id).state == "60.0"
|
||||
|
||||
+36
File diff suppressed because one or more lines are too long
@@ -188,8 +188,8 @@ async def test_platform_warn_slow_setup(hass):
|
||||
assert mock_call.called
|
||||
|
||||
# mock_calls[0] is the warning message for component setup
|
||||
# mock_calls[5] is the warning message for platform setup
|
||||
timeout, logger_method = mock_call.mock_calls[5][1][:2]
|
||||
# mock_calls[6] is the warning message for platform setup
|
||||
timeout, logger_method = mock_call.mock_calls[6][1][:2]
|
||||
|
||||
assert timeout == entity_platform.SLOW_SETUP_WARNING
|
||||
assert logger_method == _LOGGER.warning
|
||||
|
||||
@@ -1011,3 +1011,104 @@ async def test_async_call_later(hass):
|
||||
assert p_action is action
|
||||
assert p_point == now + timedelta(seconds=3)
|
||||
assert remove is mock()
|
||||
|
||||
|
||||
async def test_track_state_change_event_chain_multple_entity(hass):
|
||||
"""Test that adding a new state tracker inside a tracker does not fire right away."""
|
||||
tracker_called = []
|
||||
chained_tracker_called = []
|
||||
|
||||
chained_tracker_unsub = []
|
||||
tracker_unsub = []
|
||||
|
||||
@ha.callback
|
||||
def chained_single_run_callback(event):
|
||||
old_state = event.data.get("old_state")
|
||||
new_state = event.data.get("new_state")
|
||||
|
||||
chained_tracker_called.append((old_state, new_state))
|
||||
|
||||
@ha.callback
|
||||
def single_run_callback(event):
|
||||
old_state = event.data.get("old_state")
|
||||
new_state = event.data.get("new_state")
|
||||
|
||||
tracker_called.append((old_state, new_state))
|
||||
|
||||
chained_tracker_unsub.append(
|
||||
async_track_state_change_event(
|
||||
hass, ["light.bowl", "light.top"], chained_single_run_callback
|
||||
)
|
||||
)
|
||||
|
||||
tracker_unsub.append(
|
||||
async_track_state_change_event(
|
||||
hass, ["light.bowl", "light.top"], single_run_callback
|
||||
)
|
||||
)
|
||||
|
||||
hass.states.async_set("light.bowl", "on")
|
||||
hass.states.async_set("light.top", "on")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(tracker_called) == 2
|
||||
assert len(chained_tracker_called) == 1
|
||||
assert len(tracker_unsub) == 1
|
||||
assert len(chained_tracker_unsub) == 2
|
||||
|
||||
hass.states.async_set("light.bowl", "off")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(tracker_called) == 3
|
||||
assert len(chained_tracker_called) == 3
|
||||
assert len(tracker_unsub) == 1
|
||||
assert len(chained_tracker_unsub) == 3
|
||||
|
||||
|
||||
async def test_track_state_change_event_chain_single_entity(hass):
|
||||
"""Test that adding a new state tracker inside a tracker does not fire right away."""
|
||||
tracker_called = []
|
||||
chained_tracker_called = []
|
||||
|
||||
chained_tracker_unsub = []
|
||||
tracker_unsub = []
|
||||
|
||||
@ha.callback
|
||||
def chained_single_run_callback(event):
|
||||
old_state = event.data.get("old_state")
|
||||
new_state = event.data.get("new_state")
|
||||
|
||||
chained_tracker_called.append((old_state, new_state))
|
||||
|
||||
@ha.callback
|
||||
def single_run_callback(event):
|
||||
old_state = event.data.get("old_state")
|
||||
new_state = event.data.get("new_state")
|
||||
|
||||
tracker_called.append((old_state, new_state))
|
||||
|
||||
chained_tracker_unsub.append(
|
||||
async_track_state_change_event(
|
||||
hass, "light.bowl", chained_single_run_callback
|
||||
)
|
||||
)
|
||||
|
||||
tracker_unsub.append(
|
||||
async_track_state_change_event(hass, "light.bowl", single_run_callback)
|
||||
)
|
||||
|
||||
hass.states.async_set("light.bowl", "on")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(tracker_called) == 1
|
||||
assert len(chained_tracker_called) == 0
|
||||
assert len(tracker_unsub) == 1
|
||||
assert len(chained_tracker_unsub) == 1
|
||||
|
||||
hass.states.async_set("light.bowl", "off")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(tracker_called) == 2
|
||||
assert len(chained_tracker_called) == 1
|
||||
assert len(tracker_unsub) == 1
|
||||
assert len(chained_tracker_unsub) == 2
|
||||
|
||||
@@ -854,6 +854,122 @@ async def test_repeat_conditional(hass, condition):
|
||||
assert event.data.get("index") == str(index + 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("condition", ["while", "until"])
|
||||
async def test_repeat_var_in_condition(hass, condition):
|
||||
"""Test repeat action w/ while option."""
|
||||
event = "test_event"
|
||||
events = async_capture_events(hass, event)
|
||||
|
||||
sequence = {"repeat": {"sequence": {"event": event}}}
|
||||
if condition == "while":
|
||||
sequence["repeat"]["while"] = {
|
||||
"condition": "template",
|
||||
"value_template": "{{ repeat.index <= 2 }}",
|
||||
}
|
||||
else:
|
||||
sequence["repeat"]["until"] = {
|
||||
"condition": "template",
|
||||
"value_template": "{{ repeat.index == 2 }}",
|
||||
}
|
||||
script_obj = script.Script(hass, cv.SCRIPT_SCHEMA(sequence))
|
||||
|
||||
with mock.patch(
|
||||
"homeassistant.helpers.condition._LOGGER.error",
|
||||
side_effect=AssertionError("Template Error"),
|
||||
):
|
||||
await script_obj.async_run()
|
||||
|
||||
assert len(events) == 2
|
||||
|
||||
|
||||
async def test_repeat_nested(hass):
|
||||
"""Test nested repeats."""
|
||||
event = "test_event"
|
||||
events = async_capture_events(hass, event)
|
||||
|
||||
sequence = cv.SCRIPT_SCHEMA(
|
||||
[
|
||||
{
|
||||
"event": event,
|
||||
"event_data_template": {
|
||||
"repeat": "{{ None if repeat is not defined else repeat }}"
|
||||
},
|
||||
},
|
||||
{
|
||||
"repeat": {
|
||||
"count": 2,
|
||||
"sequence": [
|
||||
{
|
||||
"event": event,
|
||||
"event_data_template": {
|
||||
"first": "{{ repeat.first }}",
|
||||
"index": "{{ repeat.index }}",
|
||||
"last": "{{ repeat.last }}",
|
||||
},
|
||||
},
|
||||
{
|
||||
"repeat": {
|
||||
"count": 2,
|
||||
"sequence": {
|
||||
"event": event,
|
||||
"event_data_template": {
|
||||
"first": "{{ repeat.first }}",
|
||||
"index": "{{ repeat.index }}",
|
||||
"last": "{{ repeat.last }}",
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
{
|
||||
"event": event,
|
||||
"event_data_template": {
|
||||
"first": "{{ repeat.first }}",
|
||||
"index": "{{ repeat.index }}",
|
||||
"last": "{{ repeat.last }}",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"event": event,
|
||||
"event_data_template": {
|
||||
"repeat": "{{ None if repeat is not defined else repeat }}"
|
||||
},
|
||||
},
|
||||
]
|
||||
)
|
||||
script_obj = script.Script(hass, sequence, "test script")
|
||||
|
||||
with mock.patch(
|
||||
"homeassistant.helpers.condition._LOGGER.error",
|
||||
side_effect=AssertionError("Template Error"),
|
||||
):
|
||||
await script_obj.async_run()
|
||||
|
||||
assert len(events) == 10
|
||||
assert events[0].data == {"repeat": "None"}
|
||||
assert events[-1].data == {"repeat": "None"}
|
||||
for index, result in enumerate(
|
||||
(
|
||||
("True", "1", "False"),
|
||||
("True", "1", "False"),
|
||||
("False", "2", "True"),
|
||||
("True", "1", "False"),
|
||||
("False", "2", "True"),
|
||||
("True", "1", "False"),
|
||||
("False", "2", "True"),
|
||||
("False", "2", "True"),
|
||||
),
|
||||
1,
|
||||
):
|
||||
assert events[index].data == {
|
||||
"first": result[0],
|
||||
"index": result[1],
|
||||
"last": result[2],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("var,result", [(1, "first"), (2, "second"), (3, "default")])
|
||||
async def test_choose(hass, var, result):
|
||||
"""Test choose action."""
|
||||
|
||||
@@ -1393,3 +1393,24 @@ async def test_start_events(hass):
|
||||
EVENT_HOMEASSISTANT_STARTED,
|
||||
]
|
||||
assert core_states == [ha.CoreState.starting, ha.CoreState.running]
|
||||
|
||||
|
||||
async def test_log_blocking_events(hass, caplog):
|
||||
"""Ensure we log which task is blocking startup when debug logging is on."""
|
||||
caplog.set_level(logging.DEBUG)
|
||||
|
||||
async def _wait_a_bit_1():
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
async def _wait_a_bit_2():
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
hass.async_create_task(_wait_a_bit_1())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
with patch.object(ha, "BLOCK_LOG_TIMEOUT", 0.00001):
|
||||
hass.async_create_task(_wait_a_bit_2())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert "_wait_a_bit_2" in caplog.text
|
||||
assert "_wait_a_bit_1" not in caplog.text
|
||||
|
||||
Reference in New Issue
Block a user