def __init__(self, client, sensor_types):
        """Initialize."""
        self._client = client
        self.data = {}
        self.sensor_types = sensor_types
        self.zip_code = client.zip_code

        self.fetchers = Registry()
        self.fetchers.register(TYPE_ALLERGY_FORECAST)(
            self._client.allergens.extended)
        self.fetchers.register(TYPE_ALLERGY_OUTLOOK)(
            self._client.allergens.outlook)
        self.fetchers.register(TYPE_ALLERGY_INDEX)(
            self._client.allergens.current)
        self.fetchers.register(TYPE_ASTHMA_FORECAST)(
            self._client.asthma.extended)
        self.fetchers.register(TYPE_ASTHMA_INDEX)(self._client.asthma.current)
        self.fetchers.register(TYPE_DISEASE_FORECAST)(
            self._client.disease.extended)
        self.fetchers.register(TYPE_DISEASE_INDEX)(
            self._client.disease.current)
Example #2
0
from homeassistant.core import callback
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
    CONF_NAME, CONF_ENTITY_ID, ATTR_UNIT_OF_MEASUREMENT, ATTR_ENTITY_ID,
    ATTR_ICON, STATE_UNKNOWN, STATE_UNAVAILABLE)
import homeassistant.helpers.config_validation as cv
from homeassistant.util.decorator import Registry
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_state_change

_LOGGER = logging.getLogger(__name__)

FILTER_NAME_LOWPASS = '******'
FILTER_NAME_OUTLIER = 'outlier'
FILTER_NAME_THROTTLE = 'throttle'
FILTERS = Registry()

CONF_FILTERS = 'filters'
CONF_FILTER_NAME = 'filter'
CONF_FILTER_WINDOW_SIZE = 'window_size'
CONF_FILTER_PRECISION = 'precision'
CONF_FILTER_RADIUS = 'radius'
CONF_FILTER_TIME_CONSTANT = 'time_constant'

DEFAULT_WINDOW_SIZE = 1
DEFAULT_PRECISION = 2
DEFAULT_FILTER_RADIUS = 2.0
DEFAULT_FILTER_TIME_CONSTANT = 10

NAME_TEMPLATE = "{} filter"
ICON = 'mdi:chart-line-variant'
Example #3
0
import importlib
import logging
import types
from typing import Any, Dict, Optional

import voluptuous as vol
from voluptuous.humanize import humanize_error

from homeassistant import data_entry_flow, requirements
from homeassistant.const import CONF_ID, CONF_NAME, CONF_TYPE
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.decorator import Registry

MULTI_FACTOR_AUTH_MODULES = Registry()

MULTI_FACTOR_AUTH_MODULE_SCHEMA = vol.Schema(
    {
        vol.Required(CONF_TYPE):
        str,
        vol.Optional(CONF_NAME):
        str,
        # Specify ID if you have two mfa auth module for same type.
        vol.Optional(CONF_ID):
        str,
    },
    extra=vol.ALLOW_EXTRA,
)

DATA_REQS = "mfa_auth_module_reqs_processed"
    AlexaPlaybackStateReporter,
    AlexaPowerController,
    AlexaPowerLevelController,
    AlexaRangeController,
    AlexaSceneController,
    AlexaSecurityPanelController,
    AlexaSeekController,
    AlexaSpeaker,
    AlexaStepSpeaker,
    AlexaTemperatureSensor,
    AlexaThermostatController,
    AlexaToggleController,
)
from .const import CONF_DESCRIPTION, CONF_DISPLAY_CATEGORIES

ENTITY_ADAPTERS = Registry()

TRANSLATION_TABLE = dict.fromkeys(map(ord, r"}{\/|\"()[]+~!><*%"), None)


class DisplayCategory:
    """Possible display categories for Discovery response.

    https://developer.amazon.com/docs/device-apis/alexa-discovery.html#display-categories
    """

    # Describes a combination of devices set to a specific state, when the
    # state change must occur in a specific order. For example, a "watch
    # Netflix" scene might require the: 1. TV to be powered on & 2. Input set
    # to HDMI1. Applies to Scenes
    ACTIVITY_TRIGGER = "ACTIVITY_TRIGGER"
Example #5
0
from homeassistant.util.decorator import Registry

from homeassistant.const import ATTR_ENTITY_ID

from .const import (
    ERR_PROTOCOL_ERROR,
    ERR_DEVICE_OFFLINE,
    ERR_UNKNOWN_ERROR,
    EVENT_COMMAND_RECEIVED,
    EVENT_SYNC_RECEIVED,
    EVENT_QUERY_RECEIVED,
)
from .helpers import RequestData, GoogleEntity, async_get_entities
from .error import SmartHomeError

HANDLERS = Registry()
_LOGGER = logging.getLogger(__name__)


async def async_handle_message(hass, config, user_id, message):
    """Handle incoming API messages."""
    request_id: str = message.get("requestId")

    data = RequestData(config, user_id, request_id)

    response = await _process(hass, data, message)

    if response and "errorCode" in response["payload"]:
        _LOGGER.error("Error handling message %s: %s", message,
                      response["payload"])
Example #6
0
"""ONVIF event parsers."""
from collections.abc import Callable, Coroutine
from typing import Any

from homeassistant.util import dt as dt_util
from homeassistant.util.decorator import Registry

from .models import Event

PARSERS: Registry[str, Callable[[str, Any], Coroutine[Any, Any,
                                                      Event]]] = Registry()


@PARSERS.register("tns1:VideoSource/MotionAlarm")
# pylint: disable=protected-access
async def async_parse_motion_alarm(uid: str, msg) -> Event:
    """Handle parsing event message.

    Topic: tns1:VideoSource/MotionAlarm
    """
    try:
        source = msg.Message._value_1.Source.SimpleItem[0].Value
        return Event(
            f"{uid}_{msg.Topic._value_1}_{source}",
            f"{source} Motion Alarm",
            "binary_sensor",
            "motion",
            None,
            msg.Message._value_1.Data.SimpleItem[0].Value == "true",
        )
    except (AttributeError, KeyError):
Example #7
0
API_THERMOSTAT_MODES = {
    climate.STATE_HEAT: 'HEAT',
    climate.STATE_COOL: 'COOL',
    climate.STATE_AUTO: 'AUTO',
    climate.STATE_ECO: 'ECO',
    climate.STATE_IDLE: 'OFF',
    climate.STATE_FAN_ONLY: 'OFF',
    climate.STATE_DRY: 'OFF',
}

SMART_HOME_HTTP_ENDPOINT = '/api/alexa/smart_home'

CONF_DESCRIPTION = 'description'
CONF_DISPLAY_CATEGORIES = 'display_categories'

HANDLERS = Registry()
ENTITY_ADAPTERS = Registry()


class _DisplayCategory(object):
    """Possible display categories for Discovery response.

    https://developer.amazon.com/docs/device-apis/alexa-discovery.html#display-categories
    """

    # Describes a combination of devices set to a specific state, when the
    # state change must occur in a specific order. For example, a "watch
    # Netflix" scene might require the: 1. TV to be powered on & 2. Input set
    # to HDMI1. Applies to Scenes
    ACTIVITY_TRIGGER = "ACTIVITY_TRIGGER"
class IQVIAData:
    """Define a data object to retrieve info from IQVIA."""

    def __init__(self, client, sensor_types):
        """Initialize."""
        self._client = client
        self.data = {}
        self.sensor_types = sensor_types
        self.zip_code = client.zip_code

        self.fetchers = Registry()
        self.fetchers.register(TYPE_ALLERGY_FORECAST)(
            self._client.allergens.extended)
        self.fetchers.register(TYPE_ALLERGY_OUTLOOK)(
            self._client.allergens.outlook)
        self.fetchers.register(TYPE_ALLERGY_INDEX)(
            self._client.allergens.current)
        self.fetchers.register(TYPE_ASTHMA_FORECAST)(
            self._client.asthma.extended)
        self.fetchers.register(TYPE_ASTHMA_INDEX)(self._client.asthma.current)
        self.fetchers.register(TYPE_DISEASE_FORECAST)(
            self._client.disease.extended)
        self.fetchers.register(TYPE_DISEASE_INDEX)(
            self._client.disease.current)

    async def async_update(self):
        """Update IQVIA data."""
        tasks = {}

        for conditions, fetcher_types in FETCHER_MAPPING.items():
            if not any(c in self.sensor_types for c in conditions):
                continue

            for fetcher_type in fetcher_types:
                tasks[fetcher_type] = self.fetchers[fetcher_type]()

        results = await asyncio.gather(*tasks.values(), return_exceptions=True)

        # IQVIA sites require a bit more complicated error handling, given that
        # they sometimes have parts (but not the whole thing) go down:
        #   1. If `InvalidZipError` is thrown, quit everything immediately.
        #   2. If a single request throws any other error, try the others.
        for key, result in zip(tasks, results):
            if isinstance(result, InvalidZipError):
                _LOGGER.error("No data for ZIP: %s", self._client.zip_code)
                self.data = {}
                return

            if isinstance(result, IQVIAError):
                _LOGGER.error('Unable to get %s data: %s', key, result)
                self.data[key] = {}
                continue

            _LOGGER.debug('Loaded new %s data', key)
            self.data[key] = result
Example #9
0
    cleanup_name_for_homekit,
    convert_to_float,
    format_version,
    validate_media_player_features,
)

_LOGGER = logging.getLogger(__name__)
SWITCH_TYPES = {
    TYPE_FAUCET: "Valve",
    TYPE_OUTLET: "Outlet",
    TYPE_SHOWER: "Valve",
    TYPE_SPRINKLER: "Valve",
    TYPE_SWITCH: "Switch",
    TYPE_VALVE: "Valve",
}
TYPES: Registry[str, type[HomeAccessory]] = Registry()


def get_accessory(hass, driver, state, aid, config):  # noqa: C901
    """Take state and return an accessory object if supported."""
    if not aid:
        _LOGGER.warning(
            'The entity "%s" is not supported, since it '
            "generates an invalid aid, please change it",
            state.entity_id,
        )
        return None

    a_type = None
    name = config.get(CONF_NAME, state.name)
    features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
Example #10
0
"""Support for Alexa skill service end point."""
import enum
import logging

from homeassistant.components import http
from homeassistant.core import callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import intent
from homeassistant.util.decorator import Registry

from .const import DOMAIN, SYN_RESOLUTION_MATCH

_LOGGER = logging.getLogger(__name__)

HANDLERS = Registry()  # type: ignore[var-annotated]

INTENTS_API_ENDPOINT = "/api/alexa"


class SpeechType(enum.Enum):
    """The Alexa speech types."""

    plaintext = "PlainText"
    ssml = "SSML"


SPEECH_MAPPINGS = {"plain": SpeechType.plaintext, "ssml": SpeechType.ssml}


class CardType(enum.Enum):
    """The Alexa card types."""
Example #11
0
)
from .helpers import (
    _decrypt_payload,
    empty_okay_response,
    error_response,
    registration_context,
    safe_registration,
    supports_encryption,
    webhook_response,
)

_LOGGER = logging.getLogger(__name__)

DELAY_SAVE = 10

WEBHOOK_COMMANDS = Registry()

COMBINED_CLASSES = set(BINARY_SENSOR_CLASSES + SENSOR_CLASSES)
SENSOR_TYPES = [ATTR_SENSOR_TYPE_BINARY_SENSOR, ATTR_SENSOR_TYPE_SENSOR]

WEBHOOK_PAYLOAD_SCHEMA = vol.Schema({
    vol.Required(ATTR_WEBHOOK_TYPE):
    cv.string,
    vol.Required(ATTR_WEBHOOK_DATA, default={}):
    vol.Any(dict, list),
    vol.Optional(ATTR_WEBHOOK_ENCRYPTED, default=False):
    cv.boolean,
    vol.Optional(ATTR_WEBHOOK_ENCRYPTED_DATA):
    cv.string,
})
Example #12
0
class IQVIAData:
    """Define a data object to retrieve info from IQVIA."""
    def __init__(self, client, sensor_types):
        """Initialize."""
        self._client = client
        self.data = {}
        self.sensor_types = sensor_types
        self.zip_code = client.zip_code

        self.fetchers = Registry()
        self.fetchers.register(TYPE_ALLERGY_FORECAST)(
            self._client.allergens.extended)
        self.fetchers.register(TYPE_ALLERGY_OUTLOOK)(
            self._client.allergens.outlook)
        self.fetchers.register(TYPE_ALLERGY_INDEX)(
            self._client.allergens.current)
        self.fetchers.register(TYPE_ASTHMA_FORECAST)(
            self._client.asthma.extended)
        self.fetchers.register(TYPE_ASTHMA_INDEX)(self._client.asthma.current)
        self.fetchers.register(TYPE_DISEASE_FORECAST)(
            self._client.disease.extended)
        self.fetchers.register(TYPE_DISEASE_INDEX)(
            self._client.disease.current)

    async def async_update(self):
        """Update IQVIA data."""
        tasks = {}

        for conditions, fetcher_types in FETCHER_MAPPING.items():
            if not any(c in self.sensor_types for c in conditions):
                continue

            for fetcher_type in fetcher_types:
                tasks[fetcher_type] = self.fetchers[fetcher_type]()

        results = await asyncio.gather(*tasks.values(), return_exceptions=True)

        for key, result in zip(tasks, results):
            if isinstance(result, IQVIAError):
                _LOGGER.error("Unable to get %s data: %s", key, result)
                self.data[key] = {}
                continue

            _LOGGER.debug("Loaded new %s data", key)
            self.data[key] = result
Example #13
0
"""ONVIF event parsers."""
from homeassistant.util import dt as dt_util
from homeassistant.util.decorator import Registry

from .models import Event

PARSERS = Registry()


@PARSERS.register("tns1:VideoSource/MotionAlarm")
# pylint: disable=protected-access
async def async_parse_motion_alarm(uid: str, msg) -> Event:
    """Handle parsing event message.

    Topic: tns1:VideoSource/MotionAlarm
    """
    try:
        source = msg.Message._value_1.Source.SimpleItem[0].Value
        return Event(
            f"{uid}_{msg.Topic._value_1}_{source}",
            f"{source} Motion Alarm",
            "binary_sensor",
            "motion",
            None,
            msg.Message._value_1.Data.SimpleItem[0].Value == "true",
        )
    except (AttributeError, KeyError):
        return None


@PARSERS.register("tns1:VideoSource/ImageTooBlurry/AnalyticsService")
Example #14
0
File: core.py Project: jbouwh/core
from .const import (
    ATTR_STREAMS,
    DOMAIN,
    SEGMENT_DURATION_ADJUSTER,
    TARGET_SEGMENT_DURATION_NON_LL_HLS,
)

if TYPE_CHECKING:
    from av import CodecContext, Packet

    from . import Stream

_LOGGER = logging.getLogger(__name__)

PROVIDERS: Registry[str, type[StreamOutput]] = Registry()


@attr.s(slots=True)
class StreamSettings:
    """Stream settings."""

    ll_hls: bool = attr.ib()
    min_segment_duration: float = attr.ib()
    part_target_duration: float = attr.ib()
    hls_advance_part_limit: int = attr.ib()
    hls_part_timeout: float = attr.ib()


STREAM_SETTINGS_NON_LL_HLS = StreamSettings(
    ll_hls=False,
Example #15
0
    BadCredentialsException,
    MaintenanceException,
    NotAuthenticatedException,
    TooManyRequestsException,
)
from pyoverkiz.models import Device, Event, Place

from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util.decorator import Registry

from .const import DOMAIN, LOGGER, UPDATE_INTERVAL

EVENT_HANDLERS = Registry()


class OverkizDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Device]]):
    """Class to manage fetching data from Overkiz platform."""

    def __init__(
        self,
        hass: HomeAssistant,
        logger: logging.Logger,
        *,
        name: str,
        client: OverkizClient,
        devices: list[Device],
        places: Place,
        update_interval: timedelta | None = None,
Example #16
0
File: core.py Project: 2Fake/core
import async_timeout
import attr

from homeassistant.components.http.view import HomeAssistantView
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback
from homeassistant.helpers.event import async_call_later
from homeassistant.util.decorator import Registry

from .const import ATTR_STREAMS, DOMAIN

if TYPE_CHECKING:
    from av import CodecContext, Packet

    from . import Stream

PROVIDERS = Registry()


@attr.s(slots=True)
class StreamSettings:
    """Stream settings."""

    ll_hls: bool = attr.ib()
    min_segment_duration: float = attr.ib()
    part_target_duration: float = attr.ib()
    hls_advance_part_limit: int = attr.ib()
    hls_part_timeout: float = attr.ib()


@attr.s(slots=True)
class Part:
Example #17
0
    async_show_setup_message,
    convert_to_float,
    format_sw_version,
    validate_media_player_features,
)

_LOGGER = logging.getLogger(__name__)
SWITCH_TYPES = {
    TYPE_FAUCET: "Valve",
    TYPE_OUTLET: "Outlet",
    TYPE_SHOWER: "Valve",
    TYPE_SPRINKLER: "Valve",
    TYPE_SWITCH: "Switch",
    TYPE_VALVE: "Valve",
}
TYPES = Registry()


def get_accessory(hass, driver, state, aid, config):  # noqa: C901
    """Take state and return an accessory object if supported."""
    if not aid:
        _LOGGER.warning(
            'The entity "%s" is not supported, since it '
            "generates an invalid aid, please change it",
            state.entity_id,
        )
        return None

    a_type = None
    name = config.get(CONF_NAME, state.name)
    features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
Example #18
0
import logging

import voluptuous as vol
from voluptuous.humanize import humanize_error

from homeassistant import requirements
from homeassistant.core import callback
from homeassistant.const import CONF_TYPE, CONF_NAME, CONF_ID
from homeassistant.util.decorator import Registry

from homeassistant.auth.models import Credentials

_LOGGER = logging.getLogger(__name__)
DATA_REQS = 'auth_prov_reqs_processed'

AUTH_PROVIDERS = Registry()

AUTH_PROVIDER_SCHEMA = vol.Schema(
    {
        vol.Required(CONF_TYPE):
        str,
        vol.Optional(CONF_NAME):
        str,
        # Specify ID if you have two auth providers for same type.
        vol.Optional(CONF_ID):
        str,
    },
    extra=vol.ALLOW_EXTRA)


async def auth_provider_from_config(hass, store, config):
Example #19
0
from .helpers import (
    _decrypt_payload,
    _decrypt_payload_legacy,
    empty_okay_response,
    error_response,
    registration_context,
    safe_registration,
    supports_encryption,
    webhook_response,
)

_LOGGER = logging.getLogger(__name__)

DELAY_SAVE = 10

WEBHOOK_COMMANDS = Registry()  # type: ignore[var-annotated]

COMBINED_CLASSES = set(BINARY_SENSOR_CLASSES + SENSOR_CLASSES)
SENSOR_TYPES = [ATTR_SENSOR_TYPE_BINARY_SENSOR, ATTR_SENSOR_TYPE_SENSOR]

WEBHOOK_PAYLOAD_SCHEMA = vol.Schema({
    vol.Required(ATTR_WEBHOOK_TYPE):
    cv.string,
    vol.Required(ATTR_WEBHOOK_DATA, default={}):
    vol.Any(dict, list),
    vol.Optional(ATTR_WEBHOOK_ENCRYPTED, default=False):
    cv.boolean,
    vol.Optional(ATTR_WEBHOOK_ENCRYPTED_DATA):
    cv.string,
})