hass-core/homeassistant/components/homekit_controller/switch.py
Jc2k 647d137daa
Refactor homekit_controller entity update to work more like update coordinator (#32670)
* Clean up use of get_characteristic_types

* Get rid of get_hk_char_value helper

* Get rid of _update_fn callbacks

* Call async_write_has_state directly as async_state_changed doesnt do anything any more
2020-03-11 07:40:47 -04:00

59 lines
2 KiB
Python

"""Support for Homekit switches."""
import logging
from aiohomekit.model.characteristics import CharacteristicsTypes
from homeassistant.components.switch import SwitchDevice
from homeassistant.core import callback
from . import KNOWN_DEVICES, HomeKitEntity
OUTLET_IN_USE = "outlet_in_use"
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Homekit lock."""
hkid = config_entry.data["AccessoryPairingID"]
conn = hass.data[KNOWN_DEVICES][hkid]
@callback
def async_add_service(aid, service):
if service["stype"] not in ("switch", "outlet"):
return False
info = {"aid": aid, "iid": service["iid"]}
async_add_entities([HomeKitSwitch(conn, info)], True)
return True
conn.add_listener(async_add_service)
class HomeKitSwitch(HomeKitEntity, SwitchDevice):
"""Representation of a Homekit switch."""
def get_characteristic_types(self):
"""Define the homekit characteristics the entity cares about."""
return [CharacteristicsTypes.ON, CharacteristicsTypes.OUTLET_IN_USE]
@property
def is_on(self):
"""Return true if device is on."""
return self.service.value(CharacteristicsTypes.ON)
async def async_turn_on(self, **kwargs):
"""Turn the specified switch on."""
characteristics = [{"aid": self._aid, "iid": self._chars["on"], "value": True}]
await self._accessory.put_characteristics(characteristics)
async def async_turn_off(self, **kwargs):
"""Turn the specified switch off."""
characteristics = [{"aid": self._aid, "iid": self._chars["on"], "value": False}]
await self._accessory.put_characteristics(characteristics)
@property
def device_state_attributes(self):
"""Return the optional state attributes."""
outlet_in_use = self.service.value(CharacteristicsTypes.OUTLET_IN_USE)
if outlet_in_use is not None:
return {OUTLET_IN_USE: outlet_in_use}