Use EventType for state changed [a-h] (#97116)

This commit is contained in:
Marc Mueller 2023-07-24 08:04:13 +02:00 committed by GitHub
parent 5b73bd2f8e
commit 0cc396b863
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 85 additions and 41 deletions

View File

@ -25,16 +25,17 @@ from homeassistant.const import (
STATE_OFF, STATE_OFF,
STATE_ON, STATE_ON,
) )
from homeassistant.core import Event, HassJob, HomeAssistant from homeassistant.core import HassJob, HomeAssistant
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.event import ( from homeassistant.helpers.event import (
EventStateChangedData,
async_track_point_in_time, async_track_point_in_time,
async_track_state_change_event, async_track_state_change_event,
) )
from homeassistant.helpers.template import Template from homeassistant.helpers.template import Template
from homeassistant.helpers.typing import ConfigType from homeassistant.helpers.typing import ConfigType, EventType
from homeassistant.util.dt import now from homeassistant.util.dt import now
from .const import ( from .const import (
@ -196,11 +197,13 @@ class Alert(Entity):
return STATE_ON return STATE_ON
return STATE_IDLE return STATE_IDLE
async def watched_entity_change(self, event: Event) -> None: async def watched_entity_change(
self, event: EventType[EventStateChangedData]
) -> None:
"""Determine if the alert should start or stop.""" """Determine if the alert should start or stop."""
if (to_state := event.data.get("new_state")) is None: if (to_state := event.data["new_state"]) is None:
return return
LOGGER.debug("Watched entity (%s) has changed", event.data.get("entity_id")) LOGGER.debug("Watched entity (%s) has changed", event.data["entity_id"])
if to_state.state == self._alert_state and not self._firing: if to_state.state == self._alert_state and not self._firing:
await self.begin_alerting() await self.begin_alerting()
if to_state.state != self._alert_state and self._firing: if to_state.state != self._alert_state and self._firing:

View File

@ -17,10 +17,13 @@ from homeassistant.const import (
CONF_UNIT_OF_MEASUREMENT, CONF_UNIT_OF_MEASUREMENT,
STATE_UNKNOWN, STATE_UNKNOWN,
) )
from homeassistant.core import Event, HomeAssistant, State, callback from homeassistant.core import HomeAssistant, State, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.event import (
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType EventStateChangedData,
async_track_state_change_event,
)
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, EventType
from .const import ( from .const import (
CONF_COMPENSATION, CONF_COMPENSATION,
@ -124,10 +127,12 @@ class CompensationSensor(SensorEntity):
return ret return ret
@callback @callback
def _async_compensation_sensor_state_listener(self, event: Event) -> None: def _async_compensation_sensor_state_listener(
self, event: EventType[EventStateChangedData]
) -> None:
"""Handle sensor state changes.""" """Handle sensor state changes."""
new_state: State | None new_state: State | None
if (new_state := event.data.get("new_state")) is None: if (new_state := event.data["new_state"]) is None:
return return
if self.native_unit_of_measurement is None and self._source_attribute is None: if self.native_unit_of_measurement is None and self._source_attribute is None:
@ -140,7 +145,7 @@ class CompensationSensor(SensorEntity):
else: else:
value = None if new_state.state == STATE_UNKNOWN else new_state.state value = None if new_state.state == STATE_UNKNOWN else new_state.state
try: try:
x_value = float(value) x_value = float(value) # type: ignore[arg-type]
if self._minimum is not None and x_value <= self._minimum[0]: if self._minimum is not None and x_value <= self._minimum[0]:
y_value = self._minimum[1] y_value = self._minimum[1]
elif self._maximum is not None and x_value >= self._maximum[0]: elif self._maximum is not None and x_value >= self._maximum[0]:

View File

@ -18,7 +18,7 @@ from homeassistant.const import (
STATE_UNKNOWN, STATE_UNKNOWN,
UnitOfTime, UnitOfTime,
) )
from homeassistant.core import Event, HomeAssistant, State, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import ( from homeassistant.helpers import (
config_validation as cv, config_validation as cv,
device_registry as dr, device_registry as dr,
@ -26,8 +26,11 @@ from homeassistant.helpers import (
) )
from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.event import (
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType EventStateChangedData,
async_track_state_change_event,
)
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, EventType
from .const import ( from .const import (
CONF_ROUND_DIGITS, CONF_ROUND_DIGITS,
@ -210,14 +213,12 @@ class DerivativeSensor(RestoreSensor, SensorEntity):
_LOGGER.warning("Could not restore last state: %s", err) _LOGGER.warning("Could not restore last state: %s", err)
@callback @callback
def calc_derivative(event: Event) -> None: def calc_derivative(event: EventType[EventStateChangedData]) -> None:
"""Handle the sensor state changes.""" """Handle the sensor state changes."""
old_state: State | None
new_state: State | None
if ( if (
(old_state := event.data.get("old_state")) is None (old_state := event.data["old_state"]) is None
or old_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE) or old_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE)
or (new_state := event.data.get("new_state")) is None or (new_state := event.data["new_state"]) is None
or new_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE) or new_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE)
): ):
return return

View File

@ -63,7 +63,11 @@ from homeassistant.const import (
STATE_UNAVAILABLE, STATE_UNAVAILABLE,
) )
from homeassistant.core import State from homeassistant.core import State
from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.event import (
EventStateChangedData,
async_track_state_change_event,
)
from homeassistant.helpers.typing import EventType
from homeassistant.util.json import json_loads from homeassistant.util.json import json_loads
from homeassistant.util.network import is_local from homeassistant.util.network import is_local
@ -888,7 +892,7 @@ async def wait_for_state_change_or_timeout(
ev = asyncio.Event() ev = asyncio.Event()
@core.callback @core.callback
def _async_event_changed(event: core.Event) -> None: def _async_event_changed(event: EventType[EventStateChangedData]) -> None:
ev.set() ev.set()
unsub = async_track_state_change_event(hass, [entity_id], _async_event_changed) unsub = async_track_state_change_event(hass, [entity_id], _async_event_changed)

View File

@ -34,7 +34,10 @@ from homeassistant.helpers import template
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
import homeassistant.helpers.device_registry as dr import homeassistant.helpers.device_registry as dr
from homeassistant.helpers.device_registry import format_mac from homeassistant.helpers.device_registry import format_mac
from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.event import (
EventStateChangedData,
async_track_state_change_event,
)
from homeassistant.helpers.issue_registry import ( from homeassistant.helpers.issue_registry import (
IssueSeverity, IssueSeverity,
async_create_issue, async_create_issue,
@ -42,6 +45,7 @@ from homeassistant.helpers.issue_registry import (
) )
from homeassistant.helpers.service import async_set_service_schema from homeassistant.helpers.service import async_set_service_schema
from homeassistant.helpers.template import Template from homeassistant.helpers.template import Template
from homeassistant.helpers.typing import EventType
from .bluetooth import async_connect_scanner from .bluetooth import async_connect_scanner
from .const import ( from .const import (
@ -270,11 +274,13 @@ class ESPHomeManager:
"""Subscribe and forward states for requested entities.""" """Subscribe and forward states for requested entities."""
hass = self.hass hass = self.hass
async def send_home_assistant_state_event(event: Event) -> None: async def send_home_assistant_state_event(
event: EventType[EventStateChangedData],
) -> None:
"""Forward Home Assistant states updates to ESPHome.""" """Forward Home Assistant states updates to ESPHome."""
event_data = event.data event_data = event.data
new_state: State | None = event_data.get("new_state") new_state = event_data["new_state"]
old_state: State | None = event_data.get("old_state") old_state = event_data["old_state"]
if new_state is None or old_state is None: if new_state is None or old_state is None:
return return

View File

@ -34,13 +34,21 @@ from homeassistant.const import (
STATE_UNAVAILABLE, STATE_UNAVAILABLE,
STATE_UNKNOWN, STATE_UNKNOWN,
) )
from homeassistant.core import Event, HomeAssistant, State, callback from homeassistant.core import HomeAssistant, State, callback
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.event import (
EventStateChangedData,
async_track_state_change_event,
)
from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.start import async_at_started from homeassistant.helpers.start import async_at_started
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, StateType from homeassistant.helpers.typing import (
ConfigType,
DiscoveryInfoType,
EventType,
StateType,
)
from homeassistant.util.decorator import Registry from homeassistant.util.decorator import Registry
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
@ -217,10 +225,12 @@ class SensorFilter(SensorEntity):
self._attr_extra_state_attributes = {ATTR_ENTITY_ID: entity_id} self._attr_extra_state_attributes = {ATTR_ENTITY_ID: entity_id}
@callback @callback
def _update_filter_sensor_state_event(self, event: Event) -> None: def _update_filter_sensor_state_event(
self, event: EventType[EventStateChangedData]
) -> None:
"""Handle device state changes.""" """Handle device state changes."""
_LOGGER.debug("Update filter on event: %s", event) _LOGGER.debug("Update filter on event: %s", event)
self._update_filter_sensor_state(event.data.get("new_state")) self._update_filter_sensor_state(event.data["new_state"])
@callback @callback
def _update_filter_sensor_state( def _update_filter_sensor_state(

View File

@ -37,18 +37,25 @@ from homeassistant.const import (
STATE_UNAVAILABLE, STATE_UNAVAILABLE,
STATE_UNKNOWN, STATE_UNKNOWN,
) )
from homeassistant.core import DOMAIN as HA_DOMAIN, CoreState, HomeAssistant, callback from homeassistant.core import (
DOMAIN as HA_DOMAIN,
CoreState,
HomeAssistant,
State,
callback,
)
from homeassistant.exceptions import ConditionError from homeassistant.exceptions import ConditionError
from homeassistant.helpers import condition from homeassistant.helpers import condition
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import ( from homeassistant.helpers.event import (
EventStateChangedData,
async_track_state_change_event, async_track_state_change_event,
async_track_time_interval, async_track_time_interval,
) )
from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, EventType
from . import DOMAIN, PLATFORMS from . import DOMAIN, PLATFORMS
@ -395,9 +402,11 @@ class GenericThermostat(ClimateEntity, RestoreEntity):
# Get default temp from super class # Get default temp from super class
return super().max_temp return super().max_temp
async def _async_sensor_changed(self, event): async def _async_sensor_changed(
self, event: EventType[EventStateChangedData]
) -> None:
"""Handle temperature changes.""" """Handle temperature changes."""
new_state = event.data.get("new_state") new_state = event.data["new_state"]
if new_state is None or new_state.state in (STATE_UNAVAILABLE, STATE_UNKNOWN): if new_state is None or new_state.state in (STATE_UNAVAILABLE, STATE_UNKNOWN):
return return
@ -418,10 +427,10 @@ class GenericThermostat(ClimateEntity, RestoreEntity):
await self._async_heater_turn_off() await self._async_heater_turn_off()
@callback @callback
def _async_switch_changed(self, event): def _async_switch_changed(self, event: EventType[EventStateChangedData]) -> None:
"""Handle heater switch state changes.""" """Handle heater switch state changes."""
new_state = event.data.get("new_state") new_state = event.data["new_state"]
old_state = event.data.get("old_state") old_state = event.data["old_state"]
if new_state is None: if new_state is None:
return return
if old_state is None: if old_state is None:
@ -429,7 +438,7 @@ class GenericThermostat(ClimateEntity, RestoreEntity):
self.async_write_ha_state() self.async_write_ha_state()
@callback @callback
def _async_update_temp(self, state): def _async_update_temp(self, state: State) -> None:
"""Update thermostat with latest state from sensor.""" """Update thermostat with latest state from sensor."""
try: try:
cur_temp = float(state.state) cur_temp = float(state.state)

View File

@ -5,10 +5,14 @@ from datetime import timedelta
import logging import logging
from typing import Any from typing import Any
from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, callback from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback
from homeassistant.exceptions import TemplateError from homeassistant.exceptions import TemplateError
from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.event import (
EventStateChangedData,
async_track_state_change_event,
)
from homeassistant.helpers.start import async_at_start from homeassistant.helpers.start import async_at_start
from homeassistant.helpers.typing import EventType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .data import HistoryStats, HistoryStatsState from .data import HistoryStats, HistoryStatsState
@ -82,7 +86,9 @@ class HistoryStatsUpdateCoordinator(DataUpdateCoordinator[HistoryStatsState]):
self.hass, [self._history_stats.entity_id], self._async_update_from_event self.hass, [self._history_stats.entity_id], self._async_update_from_event
) )
async def _async_update_from_event(self, event: Event) -> None: async def _async_update_from_event(
self, event: EventType[EventStateChangedData]
) -> None:
"""Process an update from an event.""" """Process an update from an event."""
self.async_set_updated_data(await self._history_stats.async_update(event)) self.async_set_updated_data(await self._history_stats.async_update(event))