Esempio n. 1
0
from ..validate import docker_image, network_port
from .utils import api_process, api_process_raw, api_validate

_LOGGER: logging.Logger = logging.getLogger(__name__)

# pylint: disable=no-value-for-parameter
SCHEMA_OPTIONS = vol.Schema({
    vol.Optional(ATTR_BOOT):
    vol.Boolean(),
    vol.Optional(ATTR_IMAGE):
    docker_image,
    vol.Optional(ATTR_PORT):
    network_port,
    vol.Optional(ATTR_SSL):
    vol.Boolean(),
    vol.Optional(ATTR_WATCHDOG):
    vol.Boolean(),
    vol.Optional(ATTR_WAIT_BOOT):
    vol.All(vol.Coerce(int), vol.Range(min=60)),
    vol.Optional(ATTR_REFRESH_TOKEN):
    vol.Maybe(vol.Coerce(str)),
    vol.Optional(ATTR_AUDIO_OUTPUT):
    vol.Maybe(vol.Coerce(str)),
    vol.Optional(ATTR_AUDIO_INPUT):
    vol.Maybe(vol.Coerce(str)),
})

SCHEMA_VERSION = vol.Schema({vol.Optional(ATTR_VERSION): vol.Coerce(str)})


class APIHomeAssistant(CoreSysAttributes):
    """Handle RESTful API for Home Assistant functions."""
Esempio n. 2
0
GATEWAY_PLATFORMS_NO_KEY = [Platform.BINARY_SENSOR, Platform.SENSOR]

ATTR_GW_MAC = "gw_mac"
ATTR_RINGTONE_ID = "ringtone_id"
ATTR_RINGTONE_VOL = "ringtone_vol"

TIME_TILL_UNAVAILABLE = timedelta(minutes=150)

SERVICE_PLAY_RINGTONE = "play_ringtone"
SERVICE_STOP_RINGTONE = "stop_ringtone"
SERVICE_ADD_DEVICE = "add_device"
SERVICE_REMOVE_DEVICE = "remove_device"

SERVICE_SCHEMA_PLAY_RINGTONE = vol.Schema({
    vol.Required(ATTR_RINGTONE_ID):
    vol.All(vol.Coerce(int), vol.NotIn([9, 14, 15, 16, 17, 18, 19])),
    vol.Optional(ATTR_RINGTONE_VOL):
    vol.All(vol.Coerce(int), vol.Clamp(min=0, max=100)),
})

SERVICE_SCHEMA_REMOVE_DEVICE = vol.Schema({
    vol.Required(ATTR_DEVICE_ID):
    vol.All(cv.string, vol.Length(min=14, max=14))
})


def setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Set up the Xiaomi component."""
    def play_ringtone_service(call: ServiceCall) -> None:
        """Service to play ringtone through Gateway."""
        ring_id = call.data.get(ATTR_RINGTONE_ID)
        gateway = call.data.get(ATTR_GW_MAC)
Esempio n. 3
0
)

TYPE_SCHEMA_MAP = {
    ENTRY_CONTROL_NOTIFICATION: ENTRY_CONTROL_NOTIFICATION_SCHEMA,
    NOTIFICATION_NOTIFICATION: NOTIFICATION_NOTIFICATION_SCHEMA,
    BASIC_VALUE_NOTIFICATION: BASIC_VALUE_NOTIFICATION_SCHEMA,
    CENTRAL_SCENE_VALUE_NOTIFICATION: CENTRAL_SCENE_VALUE_NOTIFICATION_SCHEMA,
    SCENE_ACTIVATION_VALUE_NOTIFICATION: SCENE_ACTIVATION_VALUE_NOTIFICATION_SCHEMA,
    CONFIG_PARAMETER_VALUE_UPDATED: CONFIG_PARAMETER_VALUE_UPDATED_SCHEMA,
    VALUE_VALUE_UPDATED: VALUE_VALUE_UPDATED_SCHEMA,
    NODE_STATUS: NODE_STATUS_SCHEMA,
}


TRIGGER_TYPE_SCHEMA = vol.Schema(
    {vol.Required(CONF_TYPE): vol.In(TYPE_SCHEMA_MAP)}, extra=vol.ALLOW_EXTRA
)

TRIGGER_SCHEMA = vol.All(
    remove_keys_with_empty_values,
    TRIGGER_TYPE_SCHEMA,
    check_type_schema_map(TYPE_SCHEMA_MAP),
)


async def async_validate_trigger_config(
    hass: HomeAssistant, config: ConfigType
) -> ConfigType:
    """Validate config."""
    config = TRIGGER_SCHEMA(config)
Esempio n. 4
0
    cv.string,
    vol.Optional(CONF_PROFILE_IDX, default=DEFAULT_PROFILE_IDX):
    vol.All(vol.Coerce(int), vol.Range(min=0)),
    vol.Optional(CONF_CONTINUOUS_TIMEOUT_COMPLIANCE, default=True):
    cv.boolean,
})

SERVICE_PTZ_MOVE_SCHEMA = vol.Schema({
    ATTR_ENTITY_ID:
    cv.entity_ids,
    vol.Optional(ATTR_PAN, default=PTZ_NONE):
    vol.In([DIR_LEFT, DIR_RIGHT, PTZ_NONE]),
    vol.Optional(ATTR_TILT, default=PTZ_NONE):
    vol.In([DIR_UP, DIR_DOWN, PTZ_NONE]),
    vol.Optional(ATTR_ZOOM, default=PTZ_NONE):
    vol.In([ZOOM_OUT, ZOOM_IN, PTZ_NONE]),
    ATTR_MOVE_MODE:
    vol.In([CONTINUOUS_MOVE, RELATIVE_MOVE, ABSOLUTE_MOVE, STOP_MOVE]),
    vol.Optional(ATTR_CONTINUOUS_DURATION, default=0):
    cv.small_float,
    vol.Optional(ATTR_DISTANCE, default=0.1):
    cv.small_float,
    vol.Optional(ATTR_SPEED, default=0.5):
    cv.small_float,
})

SERVICE_PTZ_ADVANCED_MOVE_SCHEMA = vol.Schema({
    ATTR_ENTITY_ID:
    cv.entity_ids,
    ATTR_MOVE_MODE:
    vol.In([CONTINUOUS_MOVE, RELATIVE_MOVE, ABSOLUTE_MOVE, STOP_MOVE]),
    vol.Required(ATTR_PTZ_VECTOR):
Esempio n. 5
0
    | FEATURE_SET_LED_BRIGHTNESS
    | FEATURE_SET_TARGET_HUMIDITY
)

FEATURE_FLAGS_AIRHUMIDIFIER_CA_AND_CB = FEATURE_FLAGS_AIRHUMIDIFIER | FEATURE_SET_DRY

FEATURE_FLAGS_AIRFRESH = (
    FEATURE_SET_BUZZER
    | FEATURE_SET_CHILD_LOCK
    | FEATURE_SET_LED
    | FEATURE_SET_LED_BRIGHTNESS
    | FEATURE_RESET_FILTER
    | FEATURE_SET_EXTRA_FEATURES
)

AIRPURIFIER_SERVICE_SCHEMA = vol.Schema({vol.Optional(ATTR_ENTITY_ID): cv.entity_ids})

SERVICE_SCHEMA_LED_BRIGHTNESS = AIRPURIFIER_SERVICE_SCHEMA.extend(
    {vol.Required(ATTR_BRIGHTNESS): vol.All(vol.Coerce(int), vol.Clamp(min=0, max=2))}
)

SERVICE_SCHEMA_FAVORITE_LEVEL = AIRPURIFIER_SERVICE_SCHEMA.extend(
    {vol.Required(ATTR_LEVEL): vol.All(vol.Coerce(int), vol.Clamp(min=0, max=17))}
)

SERVICE_SCHEMA_VOLUME = AIRPURIFIER_SERVICE_SCHEMA.extend(
    {vol.Required(ATTR_VOLUME): vol.All(vol.Coerce(int), vol.Clamp(min=0, max=100))}
)

SERVICE_SCHEMA_EXTRA_FEATURES = AIRPURIFIER_SERVICE_SCHEMA.extend(
    {vol.Required(ATTR_FEATURES): vol.All(vol.Coerce(int), vol.Range(min=0))}
Esempio n. 6
0
"""The iNext Compit integration."""
import logging
import asyncio
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from .compit import Compit
from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = vol.Schema({DOMAIN: vol.Schema({})}, extra=vol.ALLOW_EXTRA)

# List the platforms that you want to support.
# For your initial PR, limit it to 1 platform.
PLATFORMS = ["climate"]


async def async_setup(hass: HomeAssistant, config: dict):
    """Set up the iNext Controllers component."""
    return True


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up iNext Controllers from a config entry."""
    _LOGGER.debug("Setting up component's entry.")
    _LOGGER.debug("Entry -> title: " + entry.title + ", data: " +
                  str(entry.data) + ", id: " + entry.entry_id + ", domain: " +
                  entry.domain)
    # Store an API object for your platforms to access
    hass.data.setdefault(DOMAIN, {})
Esempio n. 7
0
    ATTR_HS_COLOR,
    PLATFORM_SCHEMA,
    ColorMode,
    LightEntity,
)
from homeassistant.const import CONF_DEVICES, CONF_NAME, CONF_PASSWORD
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
import homeassistant.util.color as color_util

_LOGGER = logging.getLogger(__name__)

DEVICE_SCHEMA = vol.Schema({
    vol.Optional(CONF_NAME): cv.string,
    vol.Required(CONF_PASSWORD): cv.string
})

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {vol.Optional(CONF_DEVICES, default={}): {
         cv.string: DEVICE_SCHEMA
     }})


def setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Tikteck platform."""
Esempio n. 8
0
# pylint: disable=unused-import
DOMAIN = "cover"

_LOGGER = logging.getLogger(__name__)

CONF_FLOW_TYPE = "config_flow_device"
CONF_GATEWAY = "cover"
DEFAULT_GATEWAY_NAME = "LazyRolls Cover"

GATEWAY_SETTINGS = {
    vol.Required(CONF_HOST): vol.All(str, vol.Length(min=32, max=32)),
    vol.Optional(CONF_NAME, default=DEFAULT_GATEWAY_NAME): str,
}
GATEWAY_CONFIG = vol.Schema({
    vol.Required(CONF_HOST): str
}).extend(GATEWAY_SETTINGS)

CONFIG_SCHEMA = vol.Schema({vol.Optional(CONF_GATEWAY, default=False): bool})


class LazyRollsFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle a Xiaomi Miio config flow."""

    VERSION = 1
    CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL

    def __init__(self):
        """Initialize."""
        self.host = None
Esempio n. 9
0
ALMOND_SETUP_DELAY = 30

DEFAULT_OAUTH2_HOST = "https://almond.stanford.edu"
DEFAULT_LOCAL_HOST = "http://localhost:3000"

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN:
        vol.Any(
            vol.Schema(
                {
                    vol.Required(CONF_TYPE): TYPE_OAUTH2,
                    vol.Required(CONF_CLIENT_ID): cv.string,
                    vol.Required(CONF_CLIENT_SECRET): cv.string,
                    vol.Optional(CONF_HOST, default=DEFAULT_OAUTH2_HOST):
                    cv.url,
                }),
            vol.Schema({
                vol.Required(CONF_TYPE): TYPE_LOCAL,
                vol.Required(CONF_HOST): cv.url
            }),
        )
    },
    extra=vol.ALLOW_EXTRA,
)
_LOGGER = logging.getLogger(__name__)


async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Set up the Almond component."""
    hass.data[DOMAIN] = {}
Esempio n. 10
0
CONF_ITEMS = 'items'
CONF_URL = 'url'
CONF_ID = 'id'
CONF_NAME = 'name'
CONF_CURRENCY = 'currency'

ICON = 'mdi:coin'
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=2 * 60 * 60)  # 2h
MIN_TIME_BETWEEN_CURRENCY_UPDATES = timedelta(seconds=12 * 60 * 60)  # 12h

DOMAIN = 'gearbest'

_ITEM_SCHEMA = vol.All(
    vol.Schema({
        vol.Exclusive(CONF_URL, 'XOR'): cv.string,
        vol.Exclusive(CONF_ID, 'XOR'): cv.string,
        vol.Optional(CONF_NAME): cv.string,
        vol.Optional(CONF_CURRENCY): cv.string
    }), cv.has_at_least_one_key(CONF_URL, CONF_ID))

_ITEMS_SCHEMA = vol.Schema([_ITEM_SCHEMA])

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_ITEMS):
    _ITEMS_SCHEMA,
    vol.Required(CONF_CURRENCY):
    cv.string,
})


def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Gearbest sensor."""
Esempio n. 11
0
    DOMAIN,
    POWERWALL_API_CHARGE,
    POWERWALL_API_DEVICE_TYPE,
    POWERWALL_API_GRID_STATUS,
    POWERWALL_API_METERS,
    POWERWALL_API_SITE_INFO,
    POWERWALL_API_SITEMASTER,
    POWERWALL_API_STATUS,
    POWERWALL_COORDINATOR,
    POWERWALL_HTTP_SESSION,
    POWERWALL_OBJECT,
    UPDATE_INTERVAL,
)

CONFIG_SCHEMA = vol.Schema(
    {DOMAIN: vol.Schema({vol.Required(CONF_IP_ADDRESS): cv.string})},
    extra=vol.ALLOW_EXTRA,
)

PLATFORMS = ["binary_sensor", "sensor"]

_LOGGER = logging.getLogger(__name__)


async def async_setup(hass: HomeAssistant, config: dict):
    """Set up the Tesla Powerwall component."""
    hass.data.setdefault(DOMAIN, {})
    conf = config.get(DOMAIN)

    if not conf:
        return True
Esempio n. 12
0
SUPPORTED_QUALITY_SCALES = [
    "gold",
    "internal",
    "platinum",
    "silver",
]

MANIFEST_SCHEMA = vol.Schema(
    {
        vol.Required("domain"): str,
        vol.Required("name"): str,
        vol.Optional("config_flow"): bool,
        vol.Optional("zeroconf"): [str],
        vol.Optional("ssdp"): vol.Schema(
            vol.All([vol.All(vol.Schema({}, extra=vol.ALLOW_EXTRA), vol.Length(min=1))])
        ),
        vol.Optional("homekit"): vol.Schema({vol.Optional("models"): [str]}),
        vol.Required("documentation"): str,
        vol.Optional("quality_scale"): vol.In(SUPPORTED_QUALITY_SCALES),
        vol.Required("requirements"): [str],
        vol.Required("dependencies"): [str],
        vol.Optional("after_dependencies"): [str],
        vol.Required("codeowners"): [str],
    }
)


def validate_manifest(integration: Integration):
    """Validate manifest."""
    try:
        MANIFEST_SCHEMA(integration.manifest)
    except vol.Invalid as err:
Esempio n. 13
0
    'network_out': ['Sent', 'MiB', 'mdi:server-network'],
    'packets_in': ['Packets received', ' ', 'mdi:server-network'],
    'packets_out': ['Packets sent', ' ', 'mdi:server-network'],
    'process': ['Process', ' ', 'mdi:memory'],
    'processor_use': ['CPU Use', '%', 'mdi:memory'],
    'since_last_boot': ['Since Last Boot', '', 'mdi:clock'],
    'swap_free': ['Swap Free', 'GiB', 'mdi:harddisk'],
    'swap_use': ['Swap Use', 'GiB', 'mdi:harddisk'],
    'swap_use_percent': ['Swap Use', '%', 'mdi:harddisk'],
}

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_RESOURCES, default=['disk_use']):
    vol.All(cv.ensure_list, [
        vol.Schema({
            vol.Required(CONF_TYPE): vol.In(SENSOR_TYPES),
            vol.Optional('arg'): cv.string,
        })
    ])
})

IO_COUNTER = {
    'network_out': 0,
    'network_in': 1,
    'packets_out': 2,
    'packets_in': 3,
}

IF_ADDRS = {
    'ipv4_address': 0,
    'ipv6_address': 1,
}
Esempio n. 14
0
"""Config flow for Elexa Guardian integration."""
from aioguardian import Client
from aioguardian.errors import GuardianError
import voluptuous as vol

from homeassistant import config_entries, core
from homeassistant.const import CONF_IP_ADDRESS, CONF_PORT
from homeassistant.core import callback

from .const import CONF_UID, DOMAIN, LOGGER  # pylint:disable=unused-import

DATA_SCHEMA = vol.Schema(
    {vol.Required(CONF_IP_ADDRESS): str, vol.Required(CONF_PORT, default=7777): int}
)

UNIQUE_ID = "guardian_{0}"


@callback
def async_get_pin_from_discovery_hostname(hostname):
    """Get the device's 4-digit PIN from its zeroconf-discovered hostname."""
    return hostname.split(".")[0].split("-")[1]


@callback
def async_get_pin_from_uid(uid):
    """Get the device's 4-digit PIN from its UID."""
    return uid[-4:]


async def validate_input(hass: core.HomeAssistant, data):
Esempio n. 15
0
async def async_setup(hass: ha.HomeAssistant, config: dict) -> Awaitable[bool]:
    """Set up general services related to Home Assistant."""
    async def async_handle_turn_service(service):
        """Handle calls to homeassistant.turn_on/off."""
        entity_ids = await async_extract_entity_ids(hass, service)

        # Generic turn on/off method requires entity id
        if not entity_ids:
            _LOGGER.error(
                "homeassistant/%s cannot be called without entity_id",
                service.service)
            return

        # Group entity_ids by domain. groupby requires sorted data.
        by_domain = it.groupby(sorted(entity_ids),
                               lambda item: ha.split_entity_id(item)[0])

        tasks = []

        for domain, ent_ids in by_domain:
            # This leads to endless loop.
            if domain == DOMAIN:
                _LOGGER.warning(
                    "Called service homeassistant.%s with invalid entity IDs %s",
                    service.service,
                    ", ".join(ent_ids),
                )
                continue

            # We want to block for all calls and only return when all calls
            # have been processed. If a service does not exist it causes a 10
            # second delay while we're blocking waiting for a response.
            # But services can be registered on other HA instances that are
            # listening to the bus too. So as an in between solution, we'll
            # block only if the service is defined in the current HA instance.
            blocking = hass.services.has_service(domain, service.service)

            # Create a new dict for this call
            data = dict(service.data)

            # ent_ids is a generator, convert it to a list.
            data[ATTR_ENTITY_ID] = list(ent_ids)

            tasks.append(
                hass.services.async_call(domain, service.service, data,
                                         blocking))

        if tasks:
            await asyncio.gather(*tasks)

    service_schema = vol.Schema({ATTR_ENTITY_ID: cv.entity_ids},
                                extra=vol.ALLOW_EXTRA)

    hass.services.async_register(ha.DOMAIN,
                                 SERVICE_TURN_OFF,
                                 async_handle_turn_service,
                                 schema=service_schema)
    hass.services.async_register(ha.DOMAIN,
                                 SERVICE_TURN_ON,
                                 async_handle_turn_service,
                                 schema=service_schema)
    hass.services.async_register(ha.DOMAIN,
                                 SERVICE_TOGGLE,
                                 async_handle_turn_service,
                                 schema=service_schema)

    async def async_handle_core_service(call):
        """Service handler for handling core services."""
        if call.service == SERVICE_HOMEASSISTANT_STOP:
            hass.async_create_task(hass.async_stop())
            return

        try:
            errors = await conf_util.async_check_ha_config_file(hass)
        except HomeAssistantError:
            return

        if errors:
            _LOGGER.error(errors)
            hass.components.persistent_notification.async_create(
                "Config error. See [the logs](/developer-tools/logs) for details.",
                "Config validating",
                f"{ha.DOMAIN}.check_config",
            )
            return

        if call.service == SERVICE_HOMEASSISTANT_RESTART:
            hass.async_create_task(hass.async_stop(RESTART_EXIT_CODE))

    async def async_handle_update_service(call):
        """Service handler for updating an entity."""
        if call.context.user_id:
            user = await hass.auth.async_get_user(call.context.user_id)

            if user is None:
                raise UnknownUser(
                    context=call.context,
                    permission=POLICY_CONTROL,
                    user_id=call.context.user_id,
                )

            for entity in call.data[ATTR_ENTITY_ID]:
                if not user.permissions.check_entity(entity, POLICY_CONTROL):
                    raise Unauthorized(
                        context=call.context,
                        permission=POLICY_CONTROL,
                        user_id=call.context.user_id,
                        perm_category=CAT_ENTITIES,
                    )

        tasks = [
            hass.helpers.entity_component.async_update_entity(entity)
            for entity in call.data[ATTR_ENTITY_ID]
        ]

        if tasks:
            await asyncio.wait(tasks)

    hass.helpers.service.async_register_admin_service(
        ha.DOMAIN, SERVICE_HOMEASSISTANT_STOP, async_handle_core_service)
    hass.helpers.service.async_register_admin_service(
        ha.DOMAIN, SERVICE_HOMEASSISTANT_RESTART, async_handle_core_service)
    hass.helpers.service.async_register_admin_service(
        ha.DOMAIN, SERVICE_CHECK_CONFIG, async_handle_core_service)
    hass.services.async_register(
        ha.DOMAIN,
        SERVICE_UPDATE_ENTITY,
        async_handle_update_service,
        schema=SCHEMA_UPDATE_ENTITY,
    )

    async def async_handle_reload_config(call):
        """Service handler for reloading core config."""
        try:
            conf = await conf_util.async_hass_config_yaml(hass)
        except HomeAssistantError as err:
            _LOGGER.error(err)
            return

        # auth only processed during startup
        await conf_util.async_process_ha_core_config(hass,
                                                     conf.get(ha.DOMAIN) or {})

    hass.helpers.service.async_register_admin_service(
        ha.DOMAIN, SERVICE_RELOAD_CORE_CONFIG, async_handle_reload_config)

    async def async_set_location(call):
        """Service handler to set location."""
        await hass.config.async_update(latitude=call.data[ATTR_LATITUDE],
                                       longitude=call.data[ATTR_LONGITUDE])

    hass.helpers.service.async_register_admin_service(
        ha.DOMAIN,
        SERVICE_SET_LOCATION,
        async_set_location,
        vol.Schema({
            ATTR_LATITUDE: cv.latitude,
            ATTR_LONGITUDE: cv.longitude
        }),
    )

    return True
Esempio n. 16
0
ATTR_DISMISS = 'dismiss'

ATTR_JWT = 'jwt'

WS_TYPE_APPKEY = 'notify/html5/appkey'
SCHEMA_WS_APPKEY = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend(
    {vol.Required('type'): WS_TYPE_APPKEY})

# The number of days after the moment a notification is sent that a JWT
# is valid.
JWT_VALID_DAYS = 7

KEYS_SCHEMA = vol.All(
    dict,
    vol.Schema({
        vol.Required(ATTR_AUTH): cv.string,
        vol.Required(ATTR_P256DH): cv.string,
    }))

SUBSCRIPTION_SCHEMA = vol.All(
    dict,
    vol.Schema({
        # pylint: disable=no-value-for-parameter
        vol.Required(ATTR_ENDPOINT):
        vol.Url(),
        vol.Required(ATTR_KEYS):
        KEYS_SCHEMA,
        vol.Optional(ATTR_EXPIRATIONTIME):
        vol.Any(None, cv.positive_int),
    }))

DISMISS_SERVICE_SCHEMA = vol.Schema({
Esempio n. 17
0
DEFAULT_RESOLVENAMES = False
DEFAULT_PORT = 2001
DEFAULT_USERNAME = '******'
DEFAULT_PASSWORD = ''
DEFAULT_VARIABLES = False
DEFAULT_DEVICES = True
DEFAULT_DELAY = 0.5
DEFAULT_PRIMARY = False

DEVICE_SCHEMA = vol.Schema({
    vol.Required(CONF_PLATFORM):
    'homematic',
    vol.Required(ATTR_NAME):
    cv.string,
    vol.Required(ATTR_ADDRESS):
    cv.string,
    vol.Required(ATTR_PROXY):
    cv.string,
    vol.Optional(ATTR_CHANNEL, default=1):
    vol.Coerce(int),
    vol.Optional(ATTR_PARAM):
    cv.string,
})

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN:
        vol.Schema({
            vol.Required(CONF_HOSTS): {
                cv.match_all: {
                    vol.Required(CONF_IP):
                    cv.string,
Esempio n. 18
0
# The degree of precision for each platform
PRECISION_WHOLE = 1
PRECISION_HALVES = 0.5
PRECISION_TENTHS = 0.1

CONVERTIBLE_ATTRIBUTE = [
    ATTR_TEMPERATURE,
    ATTR_TARGET_TEMP_LOW,
    ATTR_TARGET_TEMP_HIGH,
]

_LOGGER = logging.getLogger(__name__)

SET_AWAY_MODE_SCHEMA = vol.Schema({
    vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
    vol.Required(ATTR_AWAY_MODE): cv.boolean,
})
SET_AUX_HEAT_SCHEMA = vol.Schema({
    vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
    vol.Required(ATTR_AUX_HEAT): cv.boolean,
})
SET_TEMPERATURE_SCHEMA = vol.Schema({
    vol.Exclusive(ATTR_TEMPERATURE, 'temperature'):
    vol.Coerce(float),
    vol.Inclusive(ATTR_TARGET_TEMP_HIGH, 'temperature'):
    vol.Coerce(float),
    vol.Inclusive(ATTR_TARGET_TEMP_LOW, 'temperature'):
    vol.Coerce(float),
    vol.Optional(ATTR_ENTITY_ID):
    cv.entity_ids,
    vol.Optional(ATTR_OPERATION_MODE):
Esempio n. 19
0
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
from homeassistant.const import (CONF_PASSWORD, CONF_USERNAME)

from . import api
from .const import (STARTUP, CONF_ENABLED, CONF_NAME, CONF_SENSOR, CONF_SWITCH)

_LOGGER = logging.getLogger(__name__)
DOMAIN = 'zaptec'

SENSOR_SCHEMA_ATTRS = {
    vol.Optional('wanted_attributes', default=[710]): cv.ensure_list,
}

SENSOR_SCHEMA = vol.Schema(SENSOR_SCHEMA_ATTRS)

# The atts is added solo so we can use both
# ways to setup the sensors/switch.
SWITCH_SCHEMA_ATTRS = {
    vol.Optional(CONF_NAME, default='zomg_kek'): cv.string,
}

SWITCH_SCHEMA = vol.Schema(SWITCH_SCHEMA_ATTRS)

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN:
        vol.Schema({
            vol.Required(CONF_USERNAME):
            cv.string,
Esempio n. 20
0
DEFAULT_PORT = 2001
DEFAULT_PATH = ''
DEFAULT_USERNAME = '******'
DEFAULT_PASSWORD = ''
DEFAULT_SSL = False
DEFAULT_VERIFY_SSL = False
DEFAULT_CHANNEL = 1

DEVICE_SCHEMA = vol.Schema({
    vol.Required(CONF_PLATFORM):
    'homematic',
    vol.Required(ATTR_NAME):
    cv.string,
    vol.Required(ATTR_ADDRESS):
    cv.string,
    vol.Required(ATTR_INTERFACE):
    cv.string,
    vol.Optional(ATTR_CHANNEL, default=DEFAULT_CHANNEL):
    vol.Coerce(int),
    vol.Optional(ATTR_PARAM):
    cv.string,
    vol.Optional(ATTR_UNIQUE_ID):
    cv.string,
})

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN:
        vol.Schema({
            vol.Optional(CONF_INTERFACES, default={}): {
                cv.match_all: {
                    vol.Required(CONF_HOST):
Esempio n. 21
0
ATTR_CONFIDENCE = "confidence"
ATTR_FACES = "faces"
ATTR_GENDER = "gender"
ATTR_GLASSES = "glasses"
ATTR_MOTION = "motion"
ATTR_TOTAL_FACES = "total_faces"

CONF_SOURCE = "source"
CONF_CONFIDENCE = "confidence"

DEFAULT_TIMEOUT = 10
DEFAULT_CONFIDENCE = 80

SOURCE_SCHEMA = vol.Schema(
    {
        vol.Required(CONF_ENTITY_ID): cv.entity_domain("camera"),
        vol.Optional(CONF_NAME): cv.string,
    }
)

PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA.extend(
    {
        vol.Optional(CONF_SOURCE): vol.All(cv.ensure_list, [SOURCE_SCHEMA]),
        vol.Optional(CONF_CONFIDENCE, default=DEFAULT_CONFIDENCE): vol.All(
            vol.Coerce(float), vol.Range(min=0, max=100)
        ),
    }
)
PLATFORM_SCHEMA_BASE = cv.PLATFORM_SCHEMA_BASE.extend(PLATFORM_SCHEMA.schema)


async def async_setup(hass, config):
from homeassistant.helpers.aiohttp_client import async_get_clientsession

_LOGGER = logging.getLogger(__name__)

DOMAIN = 'facebook_webhook'

CONF_ALLOWED = 'allowed_ids'
CONF_VERIFY_TOKEN = 'verify_token'
CONF_ACCESS_TOKEN = 'access_token'

TIMEOUT = 5

HOOK_SCHEMA = vol.Schema({
    vol.Required(CONF_VERIFY_TOKEN):
    cv.string,
    vol.Required(CONF_ACCESS_TOKEN):
    cv.string,
    vol.Required(CONF_ALLOWED, default=[]):
    vol.All(cv.ensure_list, [cv.string]),
})

CONFIG_SCHEMA = vol.Schema({DOMAIN: HOOK_SCHEMA}, extra=vol.ALLOW_EXTRA)

WEBHOOK_ENDPOINT = '/api/facebook_webhook'


class WebhookIntentsView(http.HomeAssistantView):
    """Handle Facebook requests."""

    url = WEBHOOK_ENDPOINT
    name = 'api:facebook_webhook'
    requires_auth = False
Esempio n. 23
0
 vol.Schema(
     vol.All(
         {
             vol.Required("task"):
             "publish_artifact",
             vol.Required("language",
                          description="Programming language artifact was built in."):
             vol.All(str, vol.In(["python", "scala"])),
             vol.Required("target",
                          description="List of targets to publish the artifact to"):
             vol.All([str, vol.In(["cloud_storage", "pypi", "ivy"])]),
             vol.Optional(
                 "python_file_path",
                 description=("The path relative to the root of your project to the python script"
                              "that serves as entrypoint for a databricks job"),
             ):
             str,
             "azure":
             vol.All({
                 "common": {
                     vol.Optional(
                         "artifacts_shared_storage_account_container_name",
                         description="The container for a shared storage account",
                     ):
                     str
                 }
             }),
         },
         language_must_match_target,
     ),
     extra=vol.ALLOW_EXTRA,
 ),
Esempio n. 24
0
        raise vol.Invalid(u"Could not find '{}' file. '{}' does not seem to point to an "
                          u"esphomelib copy.".format(library_json, value))
    return value


def validate_commit(value):
    value = cv.string(value)
    if re.match(r"^[0-9a-f]{7,}$", value) is None:
        raise vol.Invalid("Commit option only accepts commit hashes in hex format.")
    return value


ESPHOMELIB_VERSION_SCHEMA = vol.Any(
    validate_simple_esphomelib_version,
    vol.Schema({
        vol.Required(CONF_LOCAL): validate_local_esphomelib_version,
    }),
    vol.All(
        vol.Schema({
            vol.Optional(CONF_REPOSITORY, default=LIBRARY_URI_REPO): cv.string,
            vol.Optional(CONF_COMMIT): validate_commit,
            vol.Optional(CONF_BRANCH): cv.string,
            vol.Optional(CONF_TAG): cv.string,
        }),
        cv.has_at_most_one_key(CONF_COMMIT, CONF_BRANCH, CONF_TAG)
    ),
)


def validate_platform(value):
    value = cv.string(value)
Esempio n. 25
0
                                 EVENT_HOMEASSISTANT_START,
                                 EVENT_HOMEASSISTANT_STOP)
from homeassistant.helpers import config_validation as cv

REQUIREMENTS = ["aqualogic==1.0"]

_LOGGER = logging.getLogger(__name__)

DOMAIN = 'aqualogic'
UPDATE_TOPIC = DOMAIN + '_update'
CONF_UNIT = 'unit'
RECONNECT_INTERVAL = timedelta(seconds=10)

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Required(CONF_HOST): cv.string,
        vol.Required(CONF_PORT): cv.port,
    }),
}, extra=vol.ALLOW_EXTRA)


def setup(hass, config):
    """Set up AquaLogic platform."""
    host = config[DOMAIN][CONF_HOST]
    port = config[DOMAIN][CONF_PORT]
    processor = AquaLogicProcessor(hass, host, port)
    hass.data[DOMAIN] = processor
    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, processor.start_listen)
    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, processor.shutdown)
    _LOGGER.debug("AquaLogicProcessor %s:%i initialized", host, port)
    return True
Esempio n. 26
0
_LOGGER = logging.getLogger(__name__)

CONF_TRANSITION = 'transition'
DEFAULT_TRANSITION = 350

CONF_SAVE_ON_CHANGE = 'save_on_change'
CONF_MODE_MUSIC = 'use_music_mode'

DOMAIN = 'yeelight'

DEVICE_SCHEMA = vol.Schema({
    vol.Optional(CONF_NAME):
    cv.string,
    vol.Optional(CONF_TRANSITION, default=DEFAULT_TRANSITION):
    cv.positive_int,
    vol.Optional(CONF_MODE_MUSIC, default=False):
    cv.boolean,
    vol.Optional(CONF_SAVE_ON_CHANGE, default=True):
    cv.boolean,
})

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_DEVICES, default={}): {
        cv.string: DEVICE_SCHEMA
    },
})

SUPPORT_YEELIGHT = (SUPPORT_BRIGHTNESS | SUPPORT_TRANSITION | SUPPORT_FLASH)

SUPPORT_YEELIGHT_RGB = (SUPPORT_YEELIGHT | SUPPORT_RGB_COLOR | SUPPORT_XY_COLOR
                        | SUPPORT_EFFECT | SUPPORT_COLOR_TEMP)
    STATE_UNAVAILABLE,
]

CONF_ARM_AWAY_ACTION = "arm_away"
CONF_ARM_HOME_ACTION = "arm_home"
CONF_ARM_NIGHT_ACTION = "arm_night"
CONF_DISARM_ACTION = "disarm"
CONF_ALARM_CONTROL_PANELS = "panels"
CONF_CODE_ARM_REQUIRED = "code_arm_required"

ALARM_CONTROL_PANEL_SCHEMA = vol.Schema(
    {
        vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
        vol.Optional(CONF_DISARM_ACTION): cv.SCRIPT_SCHEMA,
        vol.Optional(CONF_ARM_AWAY_ACTION): cv.SCRIPT_SCHEMA,
        vol.Optional(CONF_ARM_HOME_ACTION): cv.SCRIPT_SCHEMA,
        vol.Optional(CONF_ARM_NIGHT_ACTION): cv.SCRIPT_SCHEMA,
        vol.Optional(CONF_CODE_ARM_REQUIRED, default=True): cv.boolean,
        vol.Optional(CONF_NAME): cv.string,
        vol.Optional(CONF_UNIQUE_ID): cv.string,
    }
)

PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_ALARM_CONTROL_PANELS): cv.schema_with_slug_keys(
            ALARM_CONTROL_PANEL_SCHEMA
        ),
    }
)

Esempio n. 28
0
    SERVICE_TOGGLE,
    SERVICE_TURN_OFF,
    SERVICE_TURN_ON,
)
import homeassistant.core as ha
from homeassistant.exceptions import HomeAssistantError, Unauthorized, UnknownUser
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.service import async_extract_entity_ids

_LOGGER = logging.getLogger(__name__)
DOMAIN = ha.DOMAIN
SERVICE_RELOAD_CORE_CONFIG = "reload_core_config"
SERVICE_CHECK_CONFIG = "check_config"
SERVICE_UPDATE_ENTITY = "update_entity"
SERVICE_SET_LOCATION = "set_location"
SCHEMA_UPDATE_ENTITY = vol.Schema({ATTR_ENTITY_ID: cv.entity_ids})


async def async_setup(hass: ha.HomeAssistant, config: dict) -> Awaitable[bool]:
    """Set up general services related to Home Assistant."""
    async def async_handle_turn_service(service):
        """Handle calls to homeassistant.turn_on/off."""
        entity_ids = await async_extract_entity_ids(hass, service)

        # Generic turn on/off method requires entity id
        if not entity_ids:
            _LOGGER.error(
                "homeassistant/%s cannot be called without entity_id",
                service.service)
            return
Esempio n. 29
0
async def async_get_trigger_capabilities(
    hass: HomeAssistant, config: ConfigType
) -> dict[str, vol.Schema]:
    """List trigger capabilities."""
    trigger_type = config[CONF_TYPE]

    node = async_get_node_from_device_id(hass, config[CONF_DEVICE_ID])

    # Add additional fields to the automation trigger UI
    if trigger_type == NOTIFICATION_NOTIFICATION:
        return {
            "extra_fields": vol.Schema(
                {
                    vol.Optional(f"{ATTR_TYPE}."): cv.string,
                    vol.Optional(ATTR_LABEL): cv.string,
                    vol.Optional(ATTR_EVENT): cv.string,
                    vol.Optional(ATTR_EVENT_LABEL): cv.string,
                }
            )
        }

    if trigger_type == ENTRY_CONTROL_NOTIFICATION:
        return {
            "extra_fields": vol.Schema(
                {
                    vol.Optional(ATTR_EVENT_TYPE): cv.string,
                    vol.Optional(ATTR_DATA_TYPE): cv.string,
                }
            )
        }

    if trigger_type == NODE_STATUS:
        return {
            "extra_fields": vol.Schema(
                {
                    vol.Optional(state.CONF_FROM): vol.In(NODE_STATUSES),
                    vol.Optional(state.CONF_TO): vol.In(NODE_STATUSES),
                    vol.Optional(state.CONF_FOR): cv.positive_time_period_dict,
                }
            )
        }

    if trigger_type in (
        BASIC_VALUE_NOTIFICATION,
        CENTRAL_SCENE_VALUE_NOTIFICATION,
        SCENE_ACTIVATION_VALUE_NOTIFICATION,
    ):
        value_schema = get_value_state_schema(get_zwave_value_from_config(node, config))

        # We should never get here, but just in case we should add a guard
        if not value_schema:
            return {}

        return {"extra_fields": vol.Schema({vol.Optional(ATTR_VALUE): value_schema})}

    if trigger_type == CONFIG_PARAMETER_VALUE_UPDATED:
        value_schema = get_value_state_schema(get_zwave_value_from_config(node, config))
        if not value_schema:
            return {}
        return {
            "extra_fields": vol.Schema(
                {
                    vol.Optional(ATTR_FROM): value_schema,
                    vol.Optional(ATTR_TO): value_schema,
                }
            )
        }

    if trigger_type == VALUE_VALUE_UPDATED:
        # Only show command classes on this node and exclude Configuration CC since it
        # is already covered
        return {
            "extra_fields": vol.Schema(
                {
                    vol.Required(ATTR_COMMAND_CLASS): vol.In(
                        {
                            CommandClass(cc.id).value: cc.name
                            for cc in sorted(node.command_classes, key=lambda cc: cc.name)  # type: ignore[no-any-return]
                            if cc.id != CommandClass.CONFIGURATION
                        }
                    ),
                    vol.Required(ATTR_PROPERTY): cv.string,
                    vol.Optional(ATTR_PROPERTY_KEY): cv.string,
                    vol.Optional(ATTR_ENDPOINT): cv.string,
                    vol.Optional(ATTR_FROM): cv.string,
                    vol.Optional(ATTR_TO): cv.string,
                }
            )
        }

    return {}
Esempio n. 30
0
    'lostTimestamp', 'locationCapable', 'deviceDisplayName', 'lostDevice',
    'deviceColor', 'wipedTimestamp', 'modelDisplayName', 'locationEnabled',
    'isMac', 'locFoundEnabled'
]

DEVICESTATUSCODES = {
    '200': 'online',
    '201': 'offline',
    '203': 'pending',
    '204': 'unregistered'
}

SERVICE_SCHEMA = vol.Schema({
    vol.Optional(ATTR_ACCOUNTNAME):
    vol.All(cv.ensure_list, [cv.slugify]),
    vol.Optional(ATTR_DEVICENAME):
    cv.slugify,
    vol.Optional(ATTR_INTERVAL):
    cv.positive_int,
})

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_USERNAME):
    cv.string,
    vol.Required(CONF_PASSWORD):
    cv.string,
    vol.Optional(ATTR_ACCOUNTNAME):
    cv.slugify,
})


def setup_scanner(hass, config: dict, see):