Add option to reverse switch behaviour in KMTronic (#47532)

This commit is contained in:
Diogo Gomes 2021-03-08 21:56:24 +00:00 committed by GitHub
parent 520c4a8ee3
commit ee25723468
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 240 additions and 71 deletions

View file

@ -3,19 +3,19 @@
from homeassistant.components.switch import SwitchEntity
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DATA_COORDINATOR, DATA_HOST, DATA_HUB, DOMAIN
from .const import CONF_REVERSE, DATA_COORDINATOR, DATA_HUB, DOMAIN
async def async_setup_entry(hass, entry, async_add_entities):
"""Config entry example."""
coordinator = hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR]
hub = hass.data[DOMAIN][entry.entry_id][DATA_HUB]
host = hass.data[DOMAIN][entry.entry_id][DATA_HOST]
reverse = entry.options.get(CONF_REVERSE, False)
await hub.async_get_relays()
async_add_entities(
[
KMtronicSwitch(coordinator, host, relay, entry.unique_id)
KMtronicSwitch(coordinator, relay, reverse, entry.entry_id)
for relay in hub.relays
]
)
@ -24,17 +24,12 @@ async def async_setup_entry(hass, entry, async_add_entities):
class KMtronicSwitch(CoordinatorEntity, SwitchEntity):
"""KMtronic Switch Entity."""
def __init__(self, coordinator, host, relay, config_entry_id):
def __init__(self, coordinator, relay, reverse, config_entry_id):
"""Pass coordinator to CoordinatorEntity."""
super().__init__(coordinator)
self._host = host
self._relay = relay
self._config_entry_id = config_entry_id
@property
def available(self) -> bool:
"""Return whether the entity is available."""
return self.coordinator.last_update_success
self._reverse = reverse
@property
def name(self) -> str:
@ -46,22 +41,25 @@ class KMtronicSwitch(CoordinatorEntity, SwitchEntity):
"""Return the unique ID of the entity."""
return f"{self._config_entry_id}_relay{self._relay.id}"
@property
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
return True
@property
def is_on(self):
"""Return entity state."""
if self._reverse:
return not self._relay.is_on
return self._relay.is_on
async def async_turn_on(self, **kwargs) -> None:
"""Turn the switch on."""
await self._relay.turn_on()
if self._reverse:
await self._relay.turn_off()
else:
await self._relay.turn_on()
self.async_write_ha_state()
async def async_turn_off(self, **kwargs) -> None:
"""Turn the switch off."""
await self._relay.turn_off()
if self._reverse:
await self._relay.turn_on()
else:
await self._relay.turn_off()
self.async_write_ha_state()