def setup(hass, config): """ Setup myhome component. """ home = MyHome(hass) room_conf = config[DOMAIN].get(CONF_ROOMS, {}) for name, conf in room_conf.items(): room = create_room(hass, name, conf) room.update_ha_state() home.add(room) # hide all the scenes related to this room for name in hass.states.entity_ids(DOMAIN_SCENE): if name.startswith('{}.{}'.format(DOMAIN_SCENE, room.name.lower())): Entity.overwrite_attribute(name, [ATTR_HIDDEN], [True]) state = hass.states.get(name) hass.states.set(name, state, {ATTR_HIDDEN: True}) register_room_services(hass, home) home.update_ha_state() _LOGGER.info('myhome loaded: %s', home) register_presence_handlers(hass, config) _LOGGER.info('registered presense handlers') return True
async def _handle_entity_call( hass: HomeAssistantType, entity: Entity, func: Union[str, Callable[..., Any]], data: Union[Dict, ha.ServiceCall], context: ha.Context, ) -> None: """Handle calling service method.""" entity.async_set_context(context) if isinstance(func, str): result = hass.async_run_job(partial(getattr(entity, func), **data)) # type: ignore else: result = hass.async_run_job(func, entity, data) # Guard because callback functions do not return a task when passed to async_run_job. if result is not None: await result if asyncio.iscoroutine(result): _LOGGER.error( "Service %s for %s incorrectly returns a coroutine object. Await result instead in service handler. Report bug to integration author", func, entity.entity_id, ) await result # type: ignore
def __init__( self, api: SynoApi, entity_type: str, entity_info: Dict[str, str], ): """Initialize the Synology DSM entity.""" super().__init__(api, entity_type, entity_info) Entity.__init__(self)
def __init__(self, mac, uom, name, entity_name): """Initialize the sensor.""" Entity.__init__(self) self._device_class = DEVICE_CLASS_BATTERY self._mac = mac self._unit_of_measurement = uom self._name = name self._entity_name = entity_name self.parameter = "battery" self._state = None self.battery = None
def __init__(self, mac, uom, name, entity_name): """Initialize the sensor.""" Entity.__init__(self) self._device_class = DEVICE_CLASS_TEMPERATURE self._mac = mac self._unit_of_measurement = uom self._name = name self._entity_name = entity_name self.parameter = "temperature" self._state = None self.temperature = None
def __init__(self, hass, inkbird_devices): """Initialize the thermometer.""" Entity.__init__(self) self._name = 'Inkbird Updater' self._state = None self._mac = None self.hass = hass self.scanner = Scanner() self.scanner.clear() self.scanner.start() self.inkbird_devices = inkbird_devices
def _compute_state(self, config): run_coroutine_threadsafe( config_util.async_process_ha_core_config(self.hass, config), self.hass.loop).result() entity = Entity() entity.entity_id = 'test.test' entity.hass = self.hass entity.schedule_update_ha_state() self.hass.block_till_done() return self.hass.states.get('test.test')
def test_name_not_set(self, mock_update): """Return the superclass name property if not set in configuration.""" config = copy(TEST_CONFIG['sensor']) del config[tcp.CONF_NAME] entity = Entity() sensor = tcp.TcpSensor(self.hass, config) assert sensor.name == entity.name
def test_name_not_set(self): """ Should return the superclass name property if not set in config """ config = copy(TEST_CONFIG) del config[tcp.CONF_NAME] entity = Entity() sensor = tcp.Sensor(self.hass, config) assert sensor.name == entity.name
def test_entity_customization(self): """Test entity customization through configuration.""" config = {CONF_LATITUDE: 50, CONF_LONGITUDE: 50, CONF_NAME: 'Test', CONF_CUSTOMIZE: {'test.test': {'hidden': True}}} bootstrap.process_ha_core_config(self.hass, config) entity = Entity() entity.entity_id = 'test.test' entity.hass = self.hass entity.update_ha_state() state = self.hass.states.get('test.test') assert state.attributes['hidden']
async def test_dump_error(hass): """Test that we cache data.""" states = [ State('input_boolean.b0', 'on'), State('input_boolean.b1', 'on'), State('input_boolean.b2', 'on'), ] entity = Entity() entity.hass = hass entity.entity_id = 'input_boolean.b0' await entity.async_internal_added_to_hass() entity = RestoreEntity() entity.hass = hass entity.entity_id = 'input_boolean.b1' await entity.async_internal_added_to_hass() data = await RestoreStateData.async_get_instance(hass) with patch('homeassistant.helpers.restore_state.Store.async_save', return_value=mock_coro(exception=HomeAssistantError) ) as mock_write_data, patch.object(hass.states, 'async_all', return_value=states): await data.async_dump_states() assert mock_write_data.called
async def test_dump_error(hass): """Test that we cache data.""" states = [ State("input_boolean.b0", "on"), State("input_boolean.b1", "on"), State("input_boolean.b2", "on"), ] entity = Entity() entity.hass = hass entity.entity_id = "input_boolean.b0" await entity.async_internal_added_to_hass() entity = RestoreEntity() entity.hass = hass entity.entity_id = "input_boolean.b1" await entity.async_internal_added_to_hass() data = await RestoreStateData.async_get_instance(hass) with patch( "homeassistant.helpers.restore_state.Store.async_save", side_effect=HomeAssistantError, ) as mock_write_data, patch.object(hass.states, "async_all", return_value=states): await data.async_dump_states() assert mock_write_data.called
def test_entity_customization(self): """ Test entity customization through config """ config = {CONF_LATITUDE: 50, CONF_LONGITUDE: 50, CONF_NAME: 'Test', CONF_CUSTOMIZE: {'test.test': {'hidden': True}}} hass = get_test_home_assistant() bootstrap.process_ha_core_config(hass, config) entity = Entity() entity.entity_id = 'test.test' entity.hass = hass entity.update_ha_state() state = hass.states.get('test.test') self.assertTrue(state.attributes['hidden']) hass.stop()
def test_entity_customization(self): """Test entity customization through configuration.""" config = {CONF_LATITUDE: 50, CONF_LONGITUDE: 50, CONF_NAME: 'Test', CONF_CUSTOMIZE: {'test.test': {'hidden': True}}} run_coroutine_threadsafe( config_util.async_process_ha_core_config(self.hass, config), self.hass.loop).result() entity = Entity() entity.entity_id = 'test.test' entity.hass = self.hass entity.update_ha_state() self.hass.block_till_done() state = self.hass.states.get('test.test') assert state.attributes['hidden']
def process_ha_core_config(hass, config): """ Processes the [homeassistant] section from the config. """ for key, attr in ((CONF_LATITUDE, 'latitude'), (CONF_LONGITUDE, 'longitude'), (CONF_NAME, 'location_name'), (CONF_TIME_ZONE, 'time_zone')): if key in config: setattr(hass.config, attr, config[key]) for entity_id, hidden in config.get(CONF_VISIBILITY, {}).items(): Entity.overwrite_hidden(entity_id, hidden == 'hide') if CONF_TEMPERATURE_UNIT in config: unit = config[CONF_TEMPERATURE_UNIT] if unit == 'C': hass.config.temperature_unit = TEMP_CELCIUS elif unit == 'F': hass.config.temperature_unit = TEMP_FAHRENHEIT hass.config.auto_detect()
def test_entity_customization(self): """Test entity customization through configuration.""" self.hass = get_test_home_assistant() config = {CONF_LATITUDE: 50, CONF_LONGITUDE: 50, CONF_NAME: 'Test', CONF_CUSTOMIZE: {'test.test': {'hidden': True}}} config_util.process_ha_core_config(self.hass, config) entity = Entity() entity.entity_id = 'test.test' entity.hass = self.hass entity.update_ha_state() self.hass.block_till_done() state = self.hass.states.get('test.test') assert state.attributes['hidden']
def test_entity_customization(self): """Test entity customization through configuration.""" config = { CONF_LATITUDE: 50, CONF_LONGITUDE: 50, CONF_NAME: 'Test', CONF_CUSTOMIZE: { 'test.test': { 'hidden': True } } } hass = get_test_home_assistant() bootstrap.process_ha_core_config(hass, config) entity = Entity() entity.entity_id = 'test.test' entity.hass = hass entity.update_ha_state() state = hass.states.get('test.test') self.assertTrue(state.attributes['hidden']) hass.stop()
def test_entity_customization(self): """Test entity customization through configuration.""" self.hass = get_test_home_assistant() config = { CONF_LATITUDE: 50, CONF_LONGITUDE: 50, CONF_NAME: 'Test', CONF_CUSTOMIZE: { 'test.test': { 'hidden': True } } } config_util.process_ha_core_config(self.hass, config) entity = Entity() entity.entity_id = 'test.test' entity.hass = self.hass entity.update_ha_state() self.hass.block_till_done() state = self.hass.states.get('test.test') assert state.attributes['hidden']
def test_entity_customization(self): """Test entity customization through configuration.""" config = { CONF_LATITUDE: 50, CONF_LONGITUDE: 50, CONF_NAME: 'Test', CONF_CUSTOMIZE: { 'test.test': { 'hidden': True } } } run_coroutine_threadsafe( config_util.async_process_ha_core_config(self.hass, config), self.hass.loop).result() entity = Entity() entity.entity_id = 'test.test' entity.hass = self.hass entity.update_ha_state() self.hass.block_till_done() state = self.hass.states.get('test.test') assert state.attributes['hidden']
def test_merge_customize(hass): """Test loading core config onto hass object.""" core_config = { 'latitude': 60, 'longitude': 50, 'elevation': 25, 'name': 'Huis', CONF_UNIT_SYSTEM: CONF_UNIT_SYSTEM_IMPERIAL, 'time_zone': 'GMT', 'customize': {'a.a': {'friendly_name': 'A'}}, 'packages': {'pkg1': {'homeassistant': {'customize': { 'b.b': {'friendly_name': 'BB'}}}}}, } yield from config_util.async_process_ha_core_config(hass, core_config) entity = Entity() entity.entity_id = 'b.b' entity.hass = hass yield from entity.async_update_ha_state() state = hass.states.get('b.b') assert state is not None assert state.attributes['friendly_name'] == 'BB'
async def _compute_state(hass, config): await config_util.async_process_ha_core_config(hass, config) entity = Entity() entity.entity_id = 'test.test' entity.hass = hass entity.schedule_update_ha_state() await hass.async_block_till_done() return hass.states.get('test.test')
def __init__(self, dev: 'AqualinkSensor'): Entity.__init__(self) self.dev = dev
async def test_dump_data(hass): """Test that we cache data.""" states = [ State("input_boolean.b0", "on"), State("input_boolean.b1", "on"), State("input_boolean.b2", "on"), State("input_boolean.b5", "unavailable", {"restored": True}), ] entity = Entity() entity.hass = hass entity.entity_id = "input_boolean.b0" await entity.async_internal_added_to_hass() entity = RestoreEntity() entity.hass = hass entity.entity_id = "input_boolean.b1" await entity.async_internal_added_to_hass() data = await RestoreStateData.async_get_instance(hass) now = dt_util.utcnow() data.last_states = { "input_boolean.b0": StoredState(State("input_boolean.b0", "off"), None, now), "input_boolean.b1": StoredState(State("input_boolean.b1", "off"), None, now), "input_boolean.b2": StoredState(State("input_boolean.b2", "off"), None, now), "input_boolean.b3": StoredState(State("input_boolean.b3", "off"), None, now), "input_boolean.b4": StoredState( State("input_boolean.b4", "off"), None, datetime(1985, 10, 26, 1, 22, tzinfo=dt_util.UTC), ), "input_boolean.b5": StoredState(State("input_boolean.b5", "off"), None, now), } with patch("homeassistant.helpers.restore_state.Store.async_save" ) as mock_write_data, patch.object(hass.states, "async_all", return_value=states): await data.async_dump_states() assert mock_write_data.called args = mock_write_data.mock_calls[0][1] written_states = args[0] # b0 should not be written, since it didn't extend RestoreEntity # b1 should be written, since it is present in the current run # b2 should not be written, since it is not registered with the helper # b3 should be written, since it is still not expired # b4 should not be written, since it is now expired # b5 should be written, since current state is restored by entity registry assert len(written_states) == 3 assert written_states[0]["state"]["entity_id"] == "input_boolean.b1" assert written_states[0]["state"]["state"] == "on" assert written_states[1]["state"]["entity_id"] == "input_boolean.b3" assert written_states[1]["state"]["state"] == "off" assert written_states[2]["state"]["entity_id"] == "input_boolean.b5" assert written_states[2]["state"]["state"] == "off" # Test that removed entities are not persisted await entity.async_remove() with patch("homeassistant.helpers.restore_state.Store.async_save" ) as mock_write_data, patch.object(hass.states, "async_all", return_value=states): await data.async_dump_states() assert mock_write_data.called args = mock_write_data.mock_calls[0][1] written_states = args[0] assert len(written_states) == 2 assert written_states[0]["state"]["entity_id"] == "input_boolean.b3" assert written_states[0]["state"]["state"] == "off" assert written_states[1]["state"]["entity_id"] == "input_boolean.b5" assert written_states[1]["state"]["state"] == "off"
async def test_dump_data(hass): """Test that we cache data.""" states = [ State('input_boolean.b0', 'on'), State('input_boolean.b1', 'on'), State('input_boolean.b2', 'on'), ] entity = Entity() entity.hass = hass entity.entity_id = 'input_boolean.b0' await entity.async_internal_added_to_hass() entity = RestoreEntity() entity.hass = hass entity.entity_id = 'input_boolean.b1' await entity.async_internal_added_to_hass() data = await RestoreStateData.async_get_instance(hass) now = dt_util.utcnow() data.last_states = { 'input_boolean.b0': StoredState(State('input_boolean.b0', 'off'), now), 'input_boolean.b1': StoredState(State('input_boolean.b1', 'off'), now), 'input_boolean.b2': StoredState(State('input_boolean.b2', 'off'), now), 'input_boolean.b3': StoredState(State('input_boolean.b3', 'off'), now), 'input_boolean.b4': StoredState(State('input_boolean.b4', 'off'), datetime(1985, 10, 26, 1, 22, tzinfo=dt_util.UTC)), } with patch('homeassistant.helpers.restore_state.Store.async_save' ) as mock_write_data, patch.object(hass.states, 'async_all', return_value=states): await data.async_dump_states() assert mock_write_data.called args = mock_write_data.mock_calls[0][1] written_states = args[0] # b0 should not be written, since it didn't extend RestoreEntity # b1 should be written, since it is present in the current run # b2 should not be written, since it is not registered with the helper # b3 should be written, since it is still not expired # b4 should not be written, since it is now expired assert len(written_states) == 2 assert written_states[0]['state']['entity_id'] == 'input_boolean.b1' assert written_states[0]['state']['state'] == 'on' assert written_states[1]['state']['entity_id'] == 'input_boolean.b3' assert written_states[1]['state']['state'] == 'off' # Test that removed entities are not persisted await entity.async_remove() with patch('homeassistant.helpers.restore_state.Store.async_save' ) as mock_write_data, patch.object(hass.states, 'async_all', return_value=states): await data.async_dump_states() assert mock_write_data.called args = mock_write_data.mock_calls[0][1] written_states = args[0] assert len(written_states) == 1 assert written_states[0]['state']['entity_id'] == 'input_boolean.b3' assert written_states[0]['state']['state'] == 'off'
def process_ha_core_config(hass, config): """ Processes the [homeassistant] section from the config. """ hac = hass.config def set_time_zone(time_zone_str): """ Helper method to set time zone in HA. """ if time_zone_str is None: return time_zone = date_util.get_time_zone(time_zone_str) if time_zone: hac.time_zone = time_zone date_util.set_default_time_zone(time_zone) else: _LOGGER.error("Received invalid time zone %s", time_zone_str) for key, attr in ((CONF_LATITUDE, "latitude"), (CONF_LONGITUDE, "longitude"), (CONF_NAME, "location_name")): if key in config: setattr(hac, attr, config[key]) set_time_zone(config.get(CONF_TIME_ZONE)) for entity_id, attrs in config.get(CONF_CUSTOMIZE, {}).items(): Entity.overwrite_attribute(entity_id, attrs.keys(), attrs.values()) if CONF_TEMPERATURE_UNIT in config: unit = config[CONF_TEMPERATURE_UNIT] if unit == "C": hac.temperature_unit = TEMP_CELCIUS elif unit == "F": hac.temperature_unit = TEMP_FAHRENHEIT # If we miss some of the needed values, auto detect them if None not in (hac.latitude, hac.longitude, hac.temperature_unit, hac.time_zone): return _LOGGER.info("Auto detecting location and temperature unit") info = util.detect_location_info() if info is None: _LOGGER.error("Could not detect location information") return if hac.latitude is None and hac.longitude is None: hac.latitude = info.latitude hac.longitude = info.longitude if hac.temperature_unit is None: if info.use_fahrenheit: hac.temperature_unit = TEMP_FAHRENHEIT else: hac.temperature_unit = TEMP_CELCIUS if hac.location_name is None: hac.location_name = info.city if hac.time_zone is None: set_time_zone(info.time_zone)
def process_ha_core_config(hass, config): """ Processes the [homeassistant] section from the config. """ hac = hass.config def set_time_zone(time_zone_str): """ Helper method to set time zone in HA. """ if time_zone_str is None: return time_zone = date_util.get_time_zone(time_zone_str) if time_zone: hac.time_zone = time_zone date_util.set_default_time_zone(time_zone) else: _LOGGER.error('Received invalid time zone %s', time_zone_str) for key, attr in ((CONF_LATITUDE, 'latitude'), (CONF_LONGITUDE, 'longitude'), (CONF_NAME, 'location_name')): if key in config: setattr(hac, attr, config[key]) set_time_zone(config.get(CONF_TIME_ZONE)) customize = config.get(CONF_CUSTOMIZE) if isinstance(customize, dict): for entity_id, attrs in config.get(CONF_CUSTOMIZE, {}).items(): if not isinstance(attrs, dict): continue Entity.overwrite_attribute(entity_id, attrs.keys(), attrs.values()) if CONF_TEMPERATURE_UNIT in config: unit = config[CONF_TEMPERATURE_UNIT] if unit == 'C': hac.temperature_unit = TEMP_CELCIUS elif unit == 'F': hac.temperature_unit = TEMP_FAHRENHEIT # If we miss some of the needed values, auto detect them if None not in (hac.latitude, hac.longitude, hac.temperature_unit, hac.time_zone): return _LOGGER.info('Auto detecting location and temperature unit') info = loc_util.detect_location_info() if info is None: _LOGGER.error('Could not detect location information') return if hac.latitude is None and hac.longitude is None: hac.latitude = info.latitude hac.longitude = info.longitude if hac.temperature_unit is None: if info.use_fahrenheit: hac.temperature_unit = TEMP_FAHRENHEIT else: hac.temperature_unit = TEMP_CELCIUS if hac.location_name is None: hac.location_name = info.city if hac.time_zone is None: set_time_zone(info.time_zone)
def __init__(self, config_entry: ConfigEntry): """Construct a FrigateEntity.""" Entity.__init__(self) self._config_entry = config_entry self._available = True
def process_ha_core_config(hass, config): """ Processes the [homeassistant] section from the config. """ hac = hass.config def set_time_zone(time_zone_str): """ Helper method to set time zone in HA. """ if time_zone_str is None: return time_zone = date_util.get_time_zone(time_zone_str) if time_zone: hac.time_zone = time_zone date_util.set_default_time_zone(time_zone) else: _LOGGER.error('Received invalid time zone %s', time_zone_str) for key, attr, typ in ((CONF_LATITUDE, 'latitude', float), (CONF_LONGITUDE, 'longitude', float), (CONF_NAME, 'location_name', str)): if key in config: try: setattr(hac, attr, typ(config[key])) except ValueError: _LOGGER.error('Received invalid %s value for %s: %s', typ.__name__, key, attr) set_time_zone(config.get(CONF_TIME_ZONE)) customize = config.get(CONF_CUSTOMIZE) if isinstance(customize, dict): for entity_id, attrs in config.get(CONF_CUSTOMIZE, {}).items(): if not isinstance(attrs, dict): continue Entity.overwrite_attribute(entity_id, attrs.keys(), attrs.values()) if CONF_TEMPERATURE_UNIT in config: unit = config[CONF_TEMPERATURE_UNIT] if unit == 'C': hac.temperature_unit = TEMP_CELCIUS elif unit == 'F': hac.temperature_unit = TEMP_FAHRENHEIT # If we miss some of the needed values, auto detect them if None not in ( hac.latitude, hac.longitude, hac.temperature_unit, hac.time_zone): return _LOGGER.info('Auto detecting location and temperature unit') info = loc_util.detect_location_info() if info is None: _LOGGER.error('Could not detect location information') return if hac.latitude is None and hac.longitude is None: hac.latitude = info.latitude hac.longitude = info.longitude if hac.temperature_unit is None: if info.use_fahrenheit: hac.temperature_unit = TEMP_FAHRENHEIT else: hac.temperature_unit = TEMP_CELCIUS if hac.location_name is None: hac.location_name = info.city if hac.time_zone is None: set_time_zone(info.time_zone)