Python homeassistant.core.HomeAssistant() Examples

The following are 30 code examples of homeassistant.core.HomeAssistant(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module homeassistant.core , or try the search function .
Example #1
Source File: helper.py    From havcs with Apache License 2.0 6 votes vote down vote up
def all(self, hass: HomeAssistant = None, init_flag: bool = False) -> list:
        if not self._devices_cache or init_flag:
            self._devices_cache.clear()
            for device_id, device_attributes in hass.data[INTEGRATION][DATA_HAVCS_ITEMS].items():
                if ATTR_DEVICE_VISABLE not in device_attributes:
                    pass
                elif isinstance(device_attributes.get(ATTR_DEVICE_VISABLE) , str) and self._platform == device_attributes.get(ATTR_DEVICE_VISABLE):
                    pass
                elif isinstance(device_attributes.get(ATTR_DEVICE_VISABLE) , list) and self._platform in device_attributes.get(ATTR_DEVICE_VISABLE):
                    pass
                else:
                    continue
                if isinstance(device_attributes.get(ATTR_DEVICE_ENTITY_ID) , str):
                    device_attributes[ATTR_DEVICE_ENTITY_ID]= [device_attributes.get(ATTR_DEVICE_ENTITY_ID)]

                self._devices_cache.update(self.get(device_id, hass, device_attributes))

        return list(self._devices_cache.values()) 
Example #2
Source File: dummy_repository.py    From integration with MIT License 6 votes vote down vote up
def dummy_repository_base(repository=None):
    if repository is None:
        repository = HacsRepository()
    repository.hacs.hass = HomeAssistant()
    repository.hacs.hass.data = {"custom_components": []}
    repository.hacs.system.config_path = tempfile.gettempdir()
    repository.logger = Logger("hacs.test.test")
    repository.data.full_name = "test/test"
    repository.data.domain = "test"
    repository.data.last_version = "3"
    repository.data.selected_tag = "3"
    repository.ref = version_to_install(repository)
    repository.integration_manifest = {"config_flow": False, "domain": "test"}
    repository.data.published_tags = ["1", "2", "3"]
    repository.data.update_data(repository_data)
    return repository 
Example #3
Source File: __init__.py    From blueprint with MIT License 6 votes vote down vote up
def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Handle removal of an entry."""
    coordinator = hass.data[DOMAIN][entry.entry_id]
    unloaded = all(
        await asyncio.gather(
            *[
                hass.config_entries.async_forward_entry_unload(entry, platform)
                for platform in PLATFORMS
                if platform in coordinator.platforms
            ]
        )
    )
    if unloaded:
        hass.data[DOMAIN].pop(entry.entry_id)

    return unloaded 
Example #4
Source File: sensor.py    From hass-opensprinkler with MIT License 6 votes vote down vote up
def _create_entities(hass: HomeAssistant, entry: dict):
    entities = []

    controller = hass.data[DOMAIN][entry.entry_id]["controller"]
    coordinator = hass.data[DOMAIN][entry.entry_id]["coordinator"]
    name = entry.data[CONF_NAME]

    entities.append(LastRunSensor(entry, name, controller, coordinator))
    entities.append(RainDelayStopTimeSensor(entry, name, controller, coordinator))
    entities.append(WaterLevelSensor(entry, name, controller, coordinator))
    entities.append(FlowRateSensor(entry, name, controller, coordinator))

    for _, station in controller.stations.items():
        entities.append(StationStatusSensor(entry, name, station, coordinator))

    return entities 
Example #5
Source File: __init__.py    From homeassistant-homeconnect with MIT License 6 votes vote down vote up
def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Home Connect from a config entry."""
    implementation = await config_entry_oauth2_flow.async_get_config_entry_implementation(
        hass, entry
    )

    hc_api = api.ConfigEntryAuth(hass, entry, implementation)

    hass.data[DOMAIN][entry.entry_id] = hc_api

    await update_all_devices(hass, entry)

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component)
        )

    return True 
Example #6
Source File: switch.py    From hass-opensprinkler with MIT License 6 votes vote down vote up
def _create_entities(hass: HomeAssistant, entry: dict):
    entities = []

    controller = hass.data[DOMAIN][entry.entry_id]["controller"]
    coordinator = hass.data[DOMAIN][entry.entry_id]["coordinator"]
    name = entry.data[CONF_NAME]

    entities.append(ControllerOperationSwitch(entry, name, controller, coordinator))

    for _, program in controller.programs.items():
        entities.append(ProgramEnabledSwitch(entry, name, program, coordinator))

    for _, station in controller.stations.items():
        entities.append(StationEnabledSwitch(entry, name, station, coordinator))

    return entities 
Example #7
Source File: __init__.py    From visonic with Apache License 2.0 6 votes vote down vote up
def async_options_updated(hass: HomeAssistant, entry: ConfigEntry):
    """Edit visonic entry."""
    log.info("************* update connection here ************** {0}".format(entry.entry_id))
    #log.info("     options {0}".format(entry.options))
    #log.info("     data    {0}".format(entry.data))

    client = hass.data[DOMAIN][DOMAINCLIENT][entry.unique_id]

    # convert python map to dictionary
    conf = {}
    # the entry.data dictionary contains all the old data used on creation and is a complete set
    for k in entry.data:
        conf[k] = entry.data[k]
    # the entry.config dictionary contains the latest/updated values but may not be a complete set
    for k in entry.options:
        conf[k] = entry.options[k]
       
    # save the parameters for control flow editing
    set_defaults(conf)
    
    # update the client parameter set
    client.updateConfig(conf)
    
    return True 
Example #8
Source File: binary_sensor.py    From hass-opensprinkler with MIT License 6 votes vote down vote up
def _create_entities(hass: HomeAssistant, entry: dict):
    entities = []

    controller = hass.data[DOMAIN][entry.entry_id]["controller"]
    coordinator = hass.data[DOMAIN][entry.entry_id]["coordinator"]
    name = entry.data[CONF_NAME]

    entities.append(
        ControllerSensorActive(entry, name, "sensor_1", controller, coordinator)
    )
    entities.append(
        ControllerSensorActive(entry, name, "sensor_2", controller, coordinator)
    )
    entities.append(
        ControllerSensorActive(entry, name, "rain_delay", controller, coordinator)
    )

    for _, program in controller.programs.items():
        entities.append(ProgramIsRunningBinarySensor(entry, name, program, coordinator))

    for _, station in controller.stations.items():
        entities.append(StationIsRunningBinarySensor(entry, name, station, coordinator))

    return entities 
Example #9
Source File: __init__.py    From hass-opensprinkler with MIT License 5 votes vote down vote up
def async_setup(hass: HomeAssistant, config: dict):
    """Set up the openSprinkler component from YAML."""
    return True 
Example #10
Source File: helper.py    From havcs with Apache License 2.0 5 votes vote down vote up
def get_device_zone(self, hass, entity_id, raw_attributes, places = [], zone_constraints = []) ->str:
        zone = '未指定'
        if ATTR_DEVICE_ZONE in raw_attributes:
            zone = raw_attributes[ATTR_DEVICE_ZONE]
        else:
            device_name = raw_attributes.get(ATTR_DEVICE_NAME)
            # Guess from friendly_name
            state = hass.states.get(entity_id)
            if not device_name and state:
                device_name = state.attributes.get('friendly_name')

            if device_name:
                for place in places:
                    if  device_name.startswith(place):
                        zone = place
                        break
        if zone == '未指定':
            # Guess from HomeAssistant group which contains entity 
            for state in hass.states.async_all():
                group_entity_id = state.entity_id
                if group_entity_id.startswith('group.') and not group_entity_id.startswith('group.all_') and group_entity_id != 'group.default_view':
                    if entity_id in state.attributes.get(ATTR_DEVICE_ENTITY_ID):
                        for place in places:
                            if place in state.attributes.get('friendly_name'):
                                zone = place
                                break
        if zone_constraints:
            return zone if zone in zone_constraints else None
        else:
            return zone 
Example #11
Source File: switch.py    From hass-opensprinkler with MIT License 5 votes vote down vote up
def async_setup_entry(
    hass: HomeAssistant, entry: dict, async_add_entities: Callable,
):
    """Set up the OpenSprinkler switches."""
    entities = _create_entities(hass, entry)
    async_add_entities(entities)

    platform = entity_platform.current_platform.get()
    platform.async_register_entity_service(
        SERVICE_RUN, SCHEMA_SERVICE_RUN, "run",
    )
    platform.async_register_entity_service(
        SERVICE_STOP, SCHEMA_SERVICE_STOP, "stop",
    ) 
Example #12
Source File: binary_sensor.py    From hass-opensprinkler with MIT License 5 votes vote down vote up
def async_setup_entry(
    hass: HomeAssistant, entry: dict, async_add_entities: Callable,
):
    """Set up the OpenSprinkler binary sensors."""
    entities = _create_entities(hass, entry)
    async_add_entities(entities)

    platform = entity_platform.current_platform.get()
    platform.async_register_entity_service(
        SERVICE_RUN, SCHEMA_SERVICE_RUN, "run",
    )
    platform.async_register_entity_service(
        SERVICE_STOP, SCHEMA_SERVICE_STOP, "stop",
    ) 
Example #13
Source File: api.py    From homeassistant-homeconnect with MIT License 5 votes vote down vote up
def __init__(
        self,
        hass: core.HomeAssistant,
        config_entry: config_entries.ConfigEntry,
        implementation: config_entry_oauth2_flow.AbstractOAuth2Implementation,
    ):
        """Initialize Home Connect Auth."""
        self.hass = hass
        self.config_entry = config_entry
        self.session = config_entry_oauth2_flow.OAuth2Session(
            hass, config_entry, implementation
        )
        super().__init__(self.session.token)
        self.devices = [] 
Example #14
Source File: __init__.py    From hass-opensprinkler with MIT License 5 votes vote down vote up
def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Unload a config entry."""
    unload_ok = all(
        await asyncio.gather(
            *[
                hass.config_entries.async_forward_entry_unload(entry, component)
                for component in PLATFORMS
            ]
        )
    )
    if unload_ok:
        hass.data[DOMAIN].pop(entry.entry_id)

    return unload_ok 
Example #15
Source File: sensor.py    From hass-opensprinkler with MIT License 5 votes vote down vote up
def async_setup_entry(
    hass: HomeAssistant, entry: dict, async_add_entities: Callable,
):
    """Set up the OpenSprinkler sensors."""
    entities = _create_entities(hass, entry)
    async_add_entities(entities)

    platform = entity_platform.current_platform.get()
    platform.async_register_entity_service(
        SERVICE_RUN, SCHEMA_SERVICE_RUN, "run",
    )
    platform.async_register_entity_service(
        SERVICE_STOP, SCHEMA_SERVICE_STOP, "stop",
    ) 
Example #16
Source File: __init__.py    From blueprint with MIT License 5 votes vote down vote up
def async_setup(hass: HomeAssistant, config: Config):
    """Set up this integration using YAML is not supported."""
    return True 
Example #17
Source File: __init__.py    From blueprint with MIT License 5 votes vote down vote up
def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up this integration using UI."""
    if hass.data.get(DOMAIN) is None:
        hass.data.setdefault(DOMAIN, {})
        _LOGGER.info(STARTUP_MESSAGE)

    username = entry.data.get(CONF_USERNAME)
    password = entry.data.get(CONF_PASSWORD)

    coordinator = BlueprintDataUpdateCoordinator(
        hass, username=username, password=password
    )
    await coordinator.async_refresh()

    if not coordinator.last_update_success:
        raise ConfigEntryNotReady

    hass.data[DOMAIN][entry.entry_id] = coordinator

    for platform in PLATFORMS:
        if entry.options.get(platform, True):
            coordinator.platforms.append(platform)
            hass.async_add_job(
                hass.config_entries.async_forward_entry_setup(entry, platform)
            )

    entry.add_update_listener(async_reload_entry)
    return True 
Example #18
Source File: __init__.py    From blueprint with MIT License 5 votes vote down vote up
def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Reload config entry."""
    await async_unload_entry(hass, entry)
    await async_setup_entry(hass, entry) 
Example #19
Source File: helper.py    From havcs with Apache License 2.0 5 votes vote down vote up
def get(self, device_id: str, hass: HomeAssistant = None, raw_attributes: dict = None) -> dict:
        if raw_attributes is None:
            return self._devices_cache.get(device_id)
       
        device_name = raw_attributes.get(ATTR_DEVICE_NAME)
        device_type = None
        zone = None
        device_type = raw_attributes.get(ATTR_DEVICE_TYPE)
        # zone = raw_attributes.get(ATTR_DEVICE_ZONE)
        entity_ids = self.get_device_related_entities(hass, raw_attributes, device_type)
        actions = []
        properties = []

        for entity_id in entity_ids:
            device_name = self.get_device_name(hass, entity_id, raw_attributes, self._places, self._device_name_constraints) if device_name is None else device_name
            device_type = self.get_device_type(hass, entity_id, raw_attributes, device_name) if device_type is None else device_type
            zone = self.get_device_zone(hass, entity_id, raw_attributes, self._places, self._zone_constraints) if zone is None else zone
            properties += self.get_device_properties(hass, entity_id, raw_attributes)         
            actions += self.get_device_actions(hass, entity_id, raw_attributes, device_type)

        actions = list(set(actions))            
        # properties = list(set(properties))
            
        attributes = {
            ATTR_DEVICE_ID: device_id,
            ATTR_DEVICE_ENTITY_ID: entity_ids,
            ATTR_DEVICE_TYPE: device_type,
            ATTR_DEVICE_NAME: device_name,
            ATTR_DEVICE_ZONE: zone,
            ATTR_DEVICE_PROPERTIES: properties,
            ATTR_DEVICE_ACTIONS: actions
        }
        device = VoiceControllDevice(hass, self._entry, attributes, raw_attributes)
        return {device_id: device} 
Example #20
Source File: test_store.py    From integration with MIT License 5 votes vote down vote up
def test_save(tmpdir):
    hass = HomeAssistant()
    hass.config.config_dir = tmpdir.dirname
    await async_save_to_store(hass, "repositories", REPOSITORIES) 
Example #21
Source File: __init__.py    From homeassistant-homeconnect with MIT License 5 votes vote down vote up
def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    unload_ok = all(
        await asyncio.gather(
            *[
                hass.config_entries.async_forward_entry_unload(entry, component)
                for component in PLATFORMS
            ]
        )
    )
    if unload_ok:
        hass.data[DOMAIN].pop(entry.entry_id)

    return unload_ok 
Example #22
Source File: __init__.py    From homeassistant-homeconnect with MIT License 5 votes vote down vote up
def _get_appliance_by_entity_id(
    hass: HomeAssistant, entity_id: str
) -> Optional[api.HomeConnectDevice]:
    """Return a Home Connect appliance instance given an entity_id."""
    for entry_id in hass.data[DOMAIN]:
        for device in entry_id.devices:
            for entity in device.entities:
                if entity.entity_id == entity_id:
                    return device.appliance
    _LOGGER.error("Appliance for %s not found.", entity_id)
    return None 
Example #23
Source File: alarm_control_panel.py    From visonic with Apache License 2.0 5 votes vote down vote up
def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None:
    #_LOGGER.info("alarm control panel async_setup_entry called")
    client = hass.data[DOMAIN][DOMAINCLIENT][entry.unique_id]
    va = VisonicAlarm(hass, client, 1)
    devices = [va]
    async_add_entities(devices) 
Example #24
Source File: client.py    From visonic with Apache License 2.0 5 votes vote down vote up
def __init__(self, hass: HomeAssistant, cf, entry: ConfigEntry):
        """Initialize the config flow."""
        self.hass = hass
        self.entry = entry
        # Get the user defined config
        self.config = cf

        #_LOGGER.info("init self.config = {0} {1}".format( PYVConst.DownloadCode, self.config))

        self.exclude_sensor_list = self.config.get(CONF_EXCLUDE_SENSOR)
        if self.exclude_sensor_list is None or len(self.exclude_sensor_list) == 0:
            self.exclude_sensor_list = []
        if isinstance(self.exclude_sensor_list, str) and len(self.exclude_sensor_list) > 0:
            self.exclude_sensor_list = [int(e) if e.isdigit() else e for e in self.exclude_sensor_list.split(',')]
            
        self.exclude_x10_list = self.config.get(CONF_EXCLUDE_X10)
        if self.exclude_x10_list is None or len(self.exclude_x10_list) == 0:
            self.exclude_x10_list = []
        if isinstance(self.exclude_x10_list, str) and len(self.exclude_x10_list) > 0:
            self.exclude_x10_list = [int(e) if e.isdigit() else e for e in self.exclude_x10_list.split(',')]

        self.visonic_event_name = 'alarm_panel_state_update'
        self.panel_exception_counter = 0
        self.myTask = None
        self.SystemStarted = False

        # variables for creating the event log for csv and xml
        self.csvdata = None
        self.templatedata = None
        self.visprotocol = None

        #self.hass.data[DOMAIN]["command_queue"] = asyncio.Queue()
        self.hass.data[DOMAIN]["binary_sensor"] = list()
        self.hass.data[DOMAIN]["switch"] = list()
        self.hass.data[DOMAIN]["alarm_control_panel"] = list()

        _LOGGER.info("Exclude sensor list = {0}     Exclude x10 list = {1}".format(self.exclude_sensor_list, self.exclude_x10_list)) 
Example #25
Source File: __init__.py    From visonic with Apache License 2.0 5 votes vote down vote up
def async_setup(hass: HomeAssistant, base_config: dict):
    """Set up the visonic component."""
    # initially empty the settings for this component
    hass.data[DOMAIN] = {}
    hass.data[DOMAIN][DOMAINDATA] = {}
    hass.data[DOMAIN][DOMAINCLIENT] = {}

    # if there are no configuration.yaml settings then terminate
    if DOMAIN not in base_config:
        return True

    # has there been a flow configured panel connection before    
    configured = configured_hosts(hass)
        
    # if there is not a flow configured connection previously
    #   then create a flow connection from the configuration.yaml data
    if len(configured) == 0:
        # get the configuration.yaml settings and make a 'flow' task :)
        #   this will run 'async_step_import' in config_flow.py
        conf = base_config.get(DOMAIN)
        log.info("      Adding job")
        # hass.async_add_job (
        hass.async_create_task (
            hass.config_entries.flow.async_init(
                DOMAIN, 
                context={"source": config_entries.SOURCE_IMPORT},
                data=conf
            )
        )
    return True

# This function is called with the flow data to create a client connection to the alarm panel
# from one of:
#    - the imported configuration.yaml values that have created a control flow
#    - the original control flow if it existed 
Example #26
Source File: binary_sensor.py    From visonic with Apache License 2.0 5 votes vote down vote up
def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None:
    """Set up the Visonic Alarm Binary Sensors"""
    
    _LOGGER.info("************* binary sensor async_setup_entry **************")
    #_LOGGER.info("     options {0}".format(entry.options))
    #_LOGGER.info("     data    {0}".format(entry.data))
    
#    @callback
#    def async_add_binary_sensor(binary_sensor):
#        """Add Visonic binary sensor."""
#        _LOGGER.info(f"   got device {binary_sensor.getDeviceID()}")
#        async_add_entities([binary_sensor], True)

#    async_dispatcher_connect(hass, "visonic_new_binary_sensor", async_add_binary_sensor)

    if DOMAIN in hass.data:
        _LOGGER.info("   In binary sensor async_setup_entry")
        sensors = [
            VisonicSensor(device)
            for device in hass.data[DOMAIN]['binary_sensor']   
        ]
        # empty the list as we have copied the entries so far in to sensors
        hass.data[DOMAIN]["binary_sensor"] = list()       
        async_add_entities(sensors, True)

#   Each Sensor in Visonic Alarms can be Armed/Bypassed individually 
Example #27
Source File: switch.py    From visonic with Apache License 2.0 5 votes vote down vote up
def __init__(self, hass: HomeAssistant, client, visonic_device):
        """Initialise a Visonic X10 Device."""
        #_LOGGER.info("Creating X10 Switch {0}".format(visonic_device.name))
        self.client = client
        self.visonic_device = visonic_device
        self.x10id = self.visonic_device.id
        self._name = "Visonic " + self.visonic_device.name
        # Append device id to prevent name clashes in HA.
        self.visonic_id = slugify(self._name) # VISONIC_ID_FORMAT.format( slugify(self._name), visonic_device.getDeviceID())
        self.entity_id = ENTITY_ID_FORMAT.format(self.visonic_id)
        self.current_value = self.visonic_device.state
        self.visonic_device.install_change_handler(self.onChange) 
Example #28
Source File: switch.py    From visonic with Apache License 2.0 5 votes vote down vote up
def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None:
    """Set up the Visonic Alarm Binary Sensors"""
    if DOMAIN in hass.data:
        client = hass.data[DOMAIN][DOMAINCLIENT][entry.unique_id]
        devices = [
            VisonicSwitch(hass, client, device)
            for device in hass.data[DOMAIN]['switch']   
        ]
        hass.data[DOMAIN]["switch"] = list()
        async_add_entities(devices) 
Example #29
Source File: test_sensor.py    From integration with MIT License 5 votes vote down vote up
def test_setup_entry():
    await async_setup_entry(hass, {}, mock_setup) 
Example #30
Source File: test_sensor.py    From integration with MIT License 5 votes vote down vote up
def test_setup_platform():
    await async_setup_platform(hass, {}, mock_setup)