Migrate esphome switch platform to use _on_static_info_update (#94962)

This commit is contained in:
J. Nick Koston 2023-06-21 15:41:24 +02:00 committed by GitHub
parent e24c2ae55c
commit 367644afe1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,11 +3,11 @@ from __future__ import annotations
from typing import Any
from aioesphomeapi import SwitchInfo, SwitchState
from aioesphomeapi import EntityInfo, SwitchInfo, SwitchState
from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util.enum import try_parse_enum
@ -32,10 +32,15 @@ async def async_setup_entry(
class EsphomeSwitch(EsphomeEntity[SwitchInfo, SwitchState], SwitchEntity):
"""A switch implementation for ESPHome."""
@property
def assumed_state(self) -> bool:
"""Return true if we do optimistic updates."""
return self._static_info.assumed_state
@callback
def _on_static_info_update(self, static_info: EntityInfo) -> None:
"""Set attrs from static info."""
super()._on_static_info_update(static_info)
static_info = self._static_info
self._attr_assumed_state = static_info.assumed_state
self._attr_device_class = try_parse_enum(
SwitchDeviceClass, static_info.device_class
)
@property
@esphome_state_property
@ -43,15 +48,10 @@ class EsphomeSwitch(EsphomeEntity[SwitchInfo, SwitchState], SwitchEntity):
"""Return true if the switch is on."""
return self._state.state
@property
def device_class(self) -> SwitchDeviceClass | None:
"""Return the class of this device."""
return try_parse_enum(SwitchDeviceClass, self._static_info.device_class)
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the entity on."""
await self._client.switch_command(self._static_info.key, True)
await self._client.switch_command(self._key, True)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the entity off."""
await self._client.switch_command(self._static_info.key, False)
await self._client.switch_command(self._key, False)