Example #1
0
async def async_setup_entry(opp, config_entry, async_add_entities):
    """Set up a Broadlink remote."""
    device = opp.data[DOMAIN].devices[config_entry.entry_id]
    remote = BroadlinkRemote(
        device,
        Store(opp, CODE_STORAGE_VERSION, f"broadlink_remote_{device.unique_id}_codes"),
        Store(opp, FLAG_STORAGE_VERSION, f"broadlink_remote_{device.unique_id}_flags"),
    )
    async_add_entities([remote], False)
Example #2
0
async def async_setup(opp: OpenPeerPower, config: ConfigType) -> bool:
    """Set up an input slider."""
    component = EntityComponent(_LOGGER, DOMAIN, opp)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.sync_entity_lifecycle(opp, DOMAIN, DOMAIN, component,
                                     yaml_collection, InputNumber.from_yaml)

    storage_collection = NumberStorageCollection(
        Store(opp, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.sync_entity_lifecycle(opp, DOMAIN, DOMAIN, component,
                                     storage_collection, InputNumber)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **(conf or {})
    } for id_, conf in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(opp)

    async def reload_service_handler(service_call: ServiceCall) -> None:
        """Reload yaml entities."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            conf = {DOMAIN: {}}
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **conf
        } for id_, conf in conf.get(DOMAIN, {}).items()])

    openpeerpower.helpers.service.async_register_admin_service(
        opp,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )

    component.async_register_entity_service(
        SERVICE_SET_VALUE,
        {vol.Required(ATTR_VALUE): vol.Coerce(float)},
        "async_set_value",
    )

    component.async_register_entity_service(SERVICE_INCREMENT, {},
                                            "async_increment")

    component.async_register_entity_service(SERVICE_DECREMENT, {},
                                            "async_decrement")

    return True
Example #3
0
 def __init__(self, opp: OpenPeerPower, image_dir: pathlib.Path) -> None:
     """Initialize media storage collection."""
     super().__init__(
         Store(opp, STORAGE_VERSION, STORAGE_KEY),
         logging.getLogger(f"{__name__}.storage_collection"),
     )
     self.async_add_listener(self._change_listener)
     self.image_dir = image_dir
Example #4
0
async def async_setup(opp: OpenPeerPower, config: ConfigType) -> bool:
    """Set up an input select."""
    component = EntityComponent(_LOGGER, DOMAIN, opp)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.sync_entity_lifecycle(opp, DOMAIN, DOMAIN, component,
                                     yaml_collection, Timer.from_yaml)

    storage_collection = TimerStorageCollection(
        Store(opp, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.sync_entity_lifecycle(opp, DOMAIN, DOMAIN, component,
                                     storage_collection, Timer)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **cfg
    } for id_, cfg in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(opp)

    async def reload_service_handler(service_call: ServiceCall) -> None:
        """Reload yaml entities."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            conf = {DOMAIN: {}}
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **cfg
        } for id_, cfg in conf.get(DOMAIN, {}).items()])

    openpeerpower.helpers.service.async_register_admin_service(
        opp,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )
    component.async_register_entity_service(
        SERVICE_START,
        {
            vol.Optional(ATTR_DURATION, default=DEFAULT_DURATION):
            cv.time_period
        },
        "async_start",
    )
    component.async_register_entity_service(SERVICE_PAUSE, {}, "async_pause")
    component.async_register_entity_service(SERVICE_CANCEL, {}, "async_cancel")
    component.async_register_entity_service(SERVICE_FINISH, {}, "async_finish")

    return True
Example #5
0
async def async_setup(opp: OpenPeerPowerType, config: ConfigType) -> bool:
    """Set up an input text."""
    component = EntityComponent(_LOGGER, DOMAIN, opp)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.attach_entity_component_collection(component, yaml_collection,
                                                  InputText.from_yaml)

    storage_collection = InputTextStorageCollection(
        Store(opp, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.attach_entity_component_collection(component,
                                                  storage_collection,
                                                  InputText)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **(conf or {})
    } for id_, conf in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(opp)

    collection.attach_entity_registry_cleaner(opp, DOMAIN, DOMAIN,
                                              yaml_collection)
    collection.attach_entity_registry_cleaner(opp, DOMAIN, DOMAIN,
                                              storage_collection)

    async def reload_service_handler(service_call: ServiceCallType) -> None:
        """Reload yaml entities."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            conf = {DOMAIN: {}}
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **(cfg or {})
        } for id_, cfg in conf.get(DOMAIN, {}).items()])

    openpeerpower.helpers.service.async_register_admin_service(
        opp,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )

    component.async_register_entity_service(
        SERVICE_SET_VALUE, {vol.Required(ATTR_VALUE): cv.string},
        "async_set_value")

    return True
 def __init__(self, opp: OpenPeerPower) -> None:
     """Initialize the restore state data class."""
     self.opp: OpenPeerPower = opp
     self.store: Store = Store(opp,
                               STORAGE_VERSION,
                               STORAGE_KEY,
                               encoder=JSONEncoder)
     self.last_states: Dict[str, StoredState] = {}
     self.entity_ids: Set[str] = set()
Example #7
0
async def async_setup(opp: OpenPeerPower, config: ConfigType) -> bool:
    """Set up an input boolean."""
    component = EntityComponent(_LOGGER, DOMAIN, opp)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.sync_entity_lifecycle(opp, DOMAIN, DOMAIN, component,
                                     yaml_collection, InputBoolean.from_yaml)

    storage_collection = InputBooleanStorageCollection(
        Store(opp, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.sync_entity_lifecycle(opp, DOMAIN, DOMAIN, component,
                                     storage_collection, InputBoolean)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **(conf or {})
    } for id_, conf in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(opp)

    async def reload_service_handler(service_call: ServiceCall) -> None:
        """Remove all input booleans and load new ones from config."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            return
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **(conf or {})
        } for id_, conf in conf.get(DOMAIN, {}).items()])

    openpeerpower.helpers.service.async_register_admin_service(
        opp,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )

    component.async_register_entity_service(SERVICE_TURN_ON, {},
                                            "async_turn_on")

    component.async_register_entity_service(SERVICE_TURN_OFF, {},
                                            "async_turn_off")

    component.async_register_entity_service(SERVICE_TOGGLE, {}, "async_toggle")

    return True
Example #8
0
 def __init__(self, opp, risco, eid, scan_interval):
     """Initialize global risco data updater."""
     self.risco = risco
     self._store = Store(
         opp, LAST_EVENT_STORAGE_VERSION, f"risco_{eid}_last_event_timestamp"
     )
     interval = timedelta(seconds=scan_interval)
     super().__init__(
         opp,
         _LOGGER,
         name=f"{DOMAIN}_events",
         update_interval=interval,
     )
Example #9
0
async def async_setup(opp: OpenPeerPower, config: dict):
    """Set up the Tag component."""
    opp.data[DOMAIN] = {}
    id_manager = TagIDManager()
    opp.data[DOMAIN][TAGS] = storage_collection = TagStorageCollection(
        Store(opp, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    await storage_collection.async_load()
    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(opp)

    return True
Example #10
0
class GoogleConfigStore:
    """A configuration store for google assistant."""

    _STORAGE_VERSION = 1
    _STORAGE_KEY = DOMAIN

    def __init__(self, opp):
        """Initialize a configuration store."""
        self._opp = opp
        self._store = Store(opp, self._STORAGE_VERSION, self._STORAGE_KEY)
        self._data = {STORE_AGENT_USER_IDS: {}}

    @property
    def agent_user_ids(self):
        """Return a list of connected agent user_ids."""
        return self._data[STORE_AGENT_USER_IDS]

    @callback
    def add_agent_user_id(self, agent_user_id):
        """Add an agent user id to store."""
        if agent_user_id not in self._data[STORE_AGENT_USER_IDS]:
            self._data[STORE_AGENT_USER_IDS][agent_user_id] = {}
            self._store.async_delay_save(lambda: self._data, 1.0)

    @callback
    def pop_agent_user_id(self, agent_user_id):
        """Remove agent user id from store."""
        if agent_user_id in self._data[STORE_AGENT_USER_IDS]:
            self._data[STORE_AGENT_USER_IDS].pop(agent_user_id, None)
            self._store.async_delay_save(lambda: self._data, 1.0)

    async def async_load(self):
        """Store current configuration to disk."""
        data = await self._store.async_load()
        if data:
            self._data = data
Example #11
0
async def async_setup(opp: OpenPeerPower, config: ConfigType) -> bool:
    """Set up an input select."""
    component = EntityComponent(_LOGGER, DOMAIN, opp)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.sync_entity_lifecycle(opp, DOMAIN, DOMAIN, component,
                                     yaml_collection, InputSelect.from_yaml)

    storage_collection = InputSelectStorageCollection(
        Store(opp, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.sync_entity_lifecycle(opp, DOMAIN, DOMAIN, component,
                                     storage_collection, InputSelect)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **cfg
    } for id_, cfg in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(opp)

    async def reload_service_handler(service_call: ServiceCall) -> None:
        """Reload yaml entities."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            conf = {DOMAIN: {}}
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **cfg
        } for id_, cfg in conf.get(DOMAIN, {}).items()])

    openpeerpower.helpers.service.async_register_admin_service(
        opp,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )

    component.async_register_entity_service(
        SERVICE_SELECT_OPTION,
        {vol.Required(ATTR_OPTION): cv.string},
        "async_select_option",
    )

    component.async_register_entity_service(
        SERVICE_SELECT_NEXT,
        {vol.Optional(ATTR_CYCLE, default=True): bool},
        "async_next",
    )

    component.async_register_entity_service(
        SERVICE_SELECT_PREVIOUS,
        {vol.Optional(ATTR_CYCLE, default=True): bool},
        "async_previous",
    )

    component.async_register_entity_service(
        SERVICE_SELECT_FIRST,
        {},
        callback(lambda entity, call: entity.async_select_index(0)),
    )

    component.async_register_entity_service(
        SERVICE_SELECT_LAST,
        {},
        callback(lambda entity, call: entity.async_select_index(-1)),
    )

    component.async_register_entity_service(
        SERVICE_SET_OPTIONS,
        {
            vol.Required(ATTR_OPTIONS):
            vol.All(cv.ensure_list, vol.Length(min=1), [cv.string])
        },
        "async_set_options",
    )

    return True
Example #12
0
 def __init__(self, opp):
     """Create a new entity map store."""
     self.opp = opp
     self.store = Store(opp, ENTITY_MAP_STORAGE_VERSION,
                        ENTITY_MAP_STORAGE_KEY)
     self.storage_data = {}
Example #13
0
class EntityMapStorage:
    """
    Holds a cache of entity structure data from a paired HomeKit device.

    HomeKit has a cacheable entity map that describes how an IP or BLE
    endpoint is structured. This object holds the latest copy of that data.

    An endpoint is made of accessories, services and characteristics. It is
    safe to cache this data until the c# discovery data changes.

    Caching this data means we can add HomeKit devices to HA immediately at
    start even if discovery hasn't seen them yet or they are out of range. It
    is also important for BLE devices - accessing the entity structure is
    very slow for these devices.
    """
    def __init__(self, opp):
        """Create a new entity map store."""
        self.opp = opp
        self.store = Store(opp, ENTITY_MAP_STORAGE_VERSION,
                           ENTITY_MAP_STORAGE_KEY)
        self.storage_data = {}

    async def async_initialize(self):
        """Get the pairing cache data."""
        raw_storage = await self.store.async_load()
        if not raw_storage:
            # There is no cached data about HomeKit devices yet
            return

        self.storage_data = raw_storage.get("pairings", {})

    def get_map(self, homekit_id):
        """Get a pairing cache item."""
        return self.storage_data.get(homekit_id)

    @callback
    def async_create_or_update_map(self, homekit_id, config_num, accessories):
        """Create a new pairing cache."""
        data = {"config_num": config_num, "accessories": accessories}
        self.storage_data[homekit_id] = data
        self._async_schedule_save()
        return data

    @callback
    def async_delete_map(self, homekit_id):
        """Delete pairing cache."""
        if homekit_id not in self.storage_data:
            return

        self.storage_data.pop(homekit_id)
        self._async_schedule_save()

    @callback
    def _async_schedule_save(self):
        """Schedule saving the entity map cache."""
        self.store.async_delay_save(self._data_to_save, ENTITY_MAP_SAVE_DELAY)

    @callback
    def _data_to_save(self):
        """Return data of entity map to store in a file."""
        return {"pairings": self.storage_data}
Example #14
0
async def async_setup(opp: OpenPeerPower, config: ConfigType) -> bool:
    """Set up an input datetime."""
    component = EntityComponent(_LOGGER, DOMAIN, opp)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.sync_entity_lifecycle(opp, DOMAIN, DOMAIN, component,
                                     yaml_collection, InputDatetime.from_yaml)

    storage_collection = DateTimeStorageCollection(
        Store(opp, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.sync_entity_lifecycle(opp, DOMAIN, DOMAIN, component,
                                     storage_collection, InputDatetime)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **cfg
    } for id_, cfg in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(opp)

    async def reload_service_handler(service_call: ServiceCall) -> None:
        """Reload yaml entities."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            conf = {DOMAIN: {}}
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **cfg
        } for id_, cfg in conf.get(DOMAIN, {}).items()])

    openpeerpower.helpers.service.async_register_admin_service(
        opp,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )

    component.async_register_entity_service(
        "set_datetime",
        vol.All(
            vol.Schema(
                {
                    vol.Optional(ATTR_DATE): cv.date,
                    vol.Optional(ATTR_TIME): cv.time,
                    vol.Optional(ATTR_DATETIME): cv.datetime,
                    vol.Optional(ATTR_TIMESTAMP): vol.Coerce(float),
                },
                extra=vol.ALLOW_EXTRA,
            ),
            cv.has_at_least_one_key(ATTR_DATE, ATTR_TIME, ATTR_DATETIME,
                                    ATTR_TIMESTAMP),
            validate_set_datetime_attrs,
        ),
        "async_set_datetime",
    )

    return True
Example #15
0
async def async_setup(opp: OpenPeerPowerType, config: ConfigType) -> bool:
    """Set up an input datetime."""
    component = EntityComponent(_LOGGER, DOMAIN, opp)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager
    )
    collection.attach_entity_component_collection(
        component, yaml_collection, InputDatetime.from_yaml
    )

    storage_collection = DateTimeStorageCollection(
        Store(opp, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.attach_entity_component_collection(
        component, storage_collection, InputDatetime
    )

    await yaml_collection.async_load(
        [{CONF_ID: id_, **cfg} for id_, cfg in config.get(DOMAIN, {}).items()]
    )
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(
        storage_collection, DOMAIN, DOMAIN, CREATE_FIELDS, UPDATE_FIELDS
    ).async_setup(opp)

    collection.attach_entity_registry_cleaner(opp, DOMAIN, DOMAIN, yaml_collection)
    collection.attach_entity_registry_cleaner(opp, DOMAIN, DOMAIN, storage_collection)

    async def reload_service_handler(service_call: ServiceCallType) -> None:
        """Reload yaml entities."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            conf = {DOMAIN: {}}
        await yaml_collection.async_load(
            [{CONF_ID: id_, **cfg} for id_, cfg in conf.get(DOMAIN, {}).items()]
        )

    openpeerpower.helpers.service.async_register_admin_service(
        opp,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )

    async def async_set_datetime_service(entity, call):
        """Handle a call to the input datetime 'set datetime' service."""
        time = call.data.get(ATTR_TIME)
        date = call.data.get(ATTR_DATE)
        dttm = call.data.get(ATTR_DATETIME)
        if (
            dttm
            and (date or time)
            or entity.has_date
            and not (date or dttm)
            or entity.has_time
            and not (time or dttm)
        ):
            _LOGGER.error(
                "Invalid service data for %s input_datetime.set_datetime: %s",
                entity.entity_id,
                str(call.data),
            )
            return

        if dttm:
            date = dttm.date()
            time = dttm.time()
        entity.async_set_datetime(date, time)

    component.async_register_entity_service(
        SERVICE_SET_DATETIME,
        {
            vol.Optional(ATTR_DATE): cv.date,
            vol.Optional(ATTR_TIME): cv.time,
            vol.Optional(ATTR_DATETIME): cv.datetime,
        },
        async_set_datetime_service,
    )

    return True
Example #16
0
 def __init__(self, opp):
     """Initialize a configuration store."""
     self._opp = opp
     self._store = Store(opp, self._STORAGE_VERSION, self._STORAGE_KEY)
     self._data = {STORE_AGENT_USER_IDS: {}}