"""Support for covers from FHEM""" import voluptuous as vol import logging from homeassistant.components.switch import SwitchDevice, PLATFORM_SCHEMA from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from . import DATA_FHEM, device_error_reporting, CONF_FHEM_IDS _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_FHEM_IDS): vol.All(cv.ensure_list, [cv.string]), vol.Required(CONF_NAME): cv.string, }) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): connection = hass.data[DATA_FHEM] switch = FhemSwitch(connection, config[CONF_NAME], config[CONF_FHEM_IDS]) for dev_id in config[CONF_FHEM_IDS]: connection.register_device(dev_id, switch) async_add_entities([switch]) class FhemSwitch(SwitchDevice): def __init__(self, connection, name, ids): self._on = None self.connection = connection self._ids = ids self._name = name self._available = True @property def name(self): return self._name @property def should_poll(self): """No polling needed.""" return False @property def available(self) -> bool: return self._available and self.connection.connected @property def is_on(self): """Return true if device is on.""" return self._on async def async_turn_on(self, **kwargs): """Turn the device on.""" self._on = True self.connection.fhem_set(self._ids[0], 'on') async def async_turn_off(self, **kwargs): """Turn the device off.""" self._on = False self.connection.fhem_set(self._ids[0], 'off') def refresh(self): self.connection.fhem_set(self._ids[0], 'statusRequest') async def line_received(self, line): line = line.strip() _LOGGER.debug(f"Switch received line {line}") if not self._available: _LOGGER.warning(f"Line for unavailable device {self.name}: {line}") if line.startswith('level:'): self._available = True _, new_state = line.split(':') new_state = new_state.strip().lower() if new_state in ('on', '100'): self._on = True elif new_state in ('off', '0'): self._on = False await self.async_update_ha_state() elif line in ('on', 'off'): self._available = True self._on = (line == 'on') await self.async_update_ha_state() elif line.startswith('ResndFail') or line.startswith('MISSING ACK'): self._available = False _LOGGER.warning(f"FHEM device {self.name} became unavailable: {line}") await self.async_update_ha_state() else: if not self._available: _LOGGER.warning(f"Other line from unavailable FHEM device {self.name}: {line}") device_error_reporting(self.hass, line, component_type="Switch", component_name=self.entity_id)