Making a custom comonent.
How can i control what icon or switch type is used?
Below is what I want it to loo like.
"""Platform for switch integration."""
from __future__ import annotations
from datetime import datetime
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.components.switch import SwitchEntity
from homeassistant.const import CONF_NAME
from homeassistant.core import callback
from homeassistant.helpers.typing import HomeAssistantType
import homeassistant.util.dt as dt_util
from .const import (
ATTR_MANUFACTURER,
DOMAIN,
SWITCH_TYPES,
AmberModbusSwitchEntityDescription,
)
#from .hub import *
async def async_setup_entry(hass, entry, async_add_entities):
hub_name = entry.data[CONF_NAME]
hub = hass.data[DOMAIN][hub_name]["hub"]
device_info = {
"identifiers": {(DOMAIN, hub_name)},
"name": hub_name,
"manufacturer": ATTR_MANUFACTURER,
}
entities = []
for switch_description in SWITCH_TYPES.values():
switch = AmberSwitch(
hub_name,
hub,
device_info,
switch_description,
)
entities.append(switch)
async_add_entities(entities)
return True
class AmberSwitch(CoordinatorEntity, SwitchEntity):
"""Representation of a Amber Modbus switch."""
def __init__(
self,
platform_name: str,
hub: AmberModbusHub,
device_info,
description: AmberModbusSwitchEntity,
):
"""Initialize the switch."""
self._platform_name = platform_name
self._attr_device_info = device_info
self.entity_description: AmberModbusSwitchEntity = description
self._hub = hub
self._state = None
super().__init__(coordinator=hub)
@property
def name(self):
"""Return the name."""
return f"{self._platform_name} {self.entity_description.name}"
@property
def unique_id(self) -> Optional[str]:
return f"{self._platform_name}_{self.entity_description.key}"
@property
def is_on(self) -> bool | None:
"""Return the state."""
return (
self.coordinator.data[self.entity_description.key]
if self.entity_description.key in self.coordinator.data
else None
)
async def async_turn_on(self, **kwargs):
"""Send the on command."""
self._hub.write_registers(92, 1)
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Send the off command."""
self._hub.write_registers(92, 0)
self.async_write_ha_state()
The above code renders the correct switch and also updates the state.
the only problem I have with this is that when I switch on, a few moments later the switch goes back to off and when the Modbus update comes (20sec later) the correct (on) state is set again.
Obvious this is unwanted.
I know that the address and value are hard coded, need to figure out how to get the used modbus address.