Example #1
0
def get_service(hass, config):
    """ Get the NMA notification service. """

    if not validate_config(config,
                           {DOMAIN: [CONF_API_KEY]},
                           _LOGGER):
        return None

    try:
        # pylint: disable=unused-variable
        from requests import Session

    except ImportError:
        _LOGGER.exception(
            "Unable to import requests. "
            "Did you maybe not install the 'Requests' package?")

        return None

    nma = Session()
    response = nma.get(_RESOURCE + 'verify',
                       params={"apikey": config[DOMAIN][CONF_API_KEY]})
    tree = ET.fromstring(response.content)

    if tree[0].tag == 'error':
        _LOGGER.error("Wrong API key supplied. %s", tree[0].text)
    else:
        return NmaNotificationService(config[DOMAIN][CONF_API_KEY])
Example #2
0
def setup(hass, config):
    """Setup Insteon Hub component.

    This will automatically import associated lights.
    """
    if not validate_config(
            config, {DOMAIN: [CONF_USERNAME, CONF_PASSWORD, CONF_API_KEY]},
            _LOGGER):
        return False

    import insteon

    username = config[DOMAIN][CONF_USERNAME]
    password = config[DOMAIN][CONF_PASSWORD]
    api_key = config[DOMAIN][CONF_API_KEY]

    global INSTEON
    INSTEON = insteon.Insteon(username, password, api_key)

    if INSTEON is None:
        _LOGGER.error("Could not connect to Insteon service.")
        return

    comp_name = 'light'
    discovery = DISCOVER_LIGHTS
    component = get_component(comp_name)
    bootstrap.setup_component(hass, component.DOMAIN, config)
    hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {
        ATTR_SERVICE: discovery,
        ATTR_DISCOVERED: {}
    })
    return True
def setup(hass, config):
    """
    Setup Insteon Hub component.
    This will automatically import associated lights.
    """
    if not validate_config(
            config,
            {DOMAIN: [CONF_USERNAME, CONF_PASSWORD, CONF_API_KEY]},
            _LOGGER):
        return False

    import insteon

    username = config[DOMAIN][CONF_USERNAME]
    password = config[DOMAIN][CONF_PASSWORD]
    api_key = config[DOMAIN][CONF_API_KEY]

    global INSTEON
    INSTEON = insteon.Insteon(username, password, api_key)

    if INSTEON is None:
        _LOGGER.error("Could not connect to Insteon service.")
        return

    comp_name = 'light'
    discovery = DISCOVER_LIGHTS
    component = get_component(comp_name)
    bootstrap.setup_component(hass, component.DOMAIN, config)
    hass.bus.fire(
        EVENT_PLATFORM_DISCOVERED,
        {ATTR_SERVICE: discovery, ATTR_DISCOVERED: {}})
    return True
Example #4
0
def setup(hass, config):
    """Set up OctoPrint API."""
    if not validate_config(config, {DOMAIN: [CONF_API_KEY],
                                    DOMAIN: [CONF_HOST]},
                           _LOGGER):
        return False

    base_url = config[DOMAIN][CONF_HOST] + "/api/"
    api_key = config[DOMAIN][CONF_API_KEY]

    global OCTOPRINT
    try:
        OCTOPRINT = OctoPrintAPI(base_url, api_key)
        OCTOPRINT.get("printer")
        OCTOPRINT.get("job")
    except requests.exceptions.RequestException as conn_err:
        _LOGGER.error("Error setting up OctoPrint API: %r", conn_err)
        return False

    for component, discovery_service in (
            ('sensor', DISCOVER_SENSORS),
            ('binary_sensor', DISCOVER_BINARY_SENSORS)):
        discovery.discover(hass, discovery_service, component=component,
                           hass_config=config)

    return True
Example #5
0
def setup(hass, config):
    """ Setup the Telldus Live component. """

    # fixme: aquire app key and provide authentication
    # using username + password
    if not validate_config(config, {
            DOMAIN:
        [CONF_PUBLIC_KEY, CONF_PRIVATE_KEY, CONF_TOKEN, CONF_TOKEN_SECRET]
    }, _LOGGER):
        _LOGGER.error(
            "Configuration Error: "
            "Please make sure you have configured your keys "
            "that can be aquired from https://api.telldus.com/keys/index")
        return False

    global NETWORK
    NETWORK = TelldusLiveData(hass, config)

    if not NETWORK.validate_session():
        _LOGGER.error(
            "Authentication Error: "
            "Please make sure you have configured your keys "
            "that can be aquired from https://api.telldus.com/keys/index")
        return False

    NETWORK.discover()

    return True
Example #6
0
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Setup a MJPEG IP Camera."""
    if not validate_config({DOMAIN: config}, {DOMAIN: ['mjpeg_url']},
                           _LOGGER):
        return None

    add_devices_callback([MjpegCamera(config)])
Example #7
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup mFi sensors."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['host', CONF_USERNAME, CONF_PASSWORD]},
                           _LOGGER):
        _LOGGER.error('A host, username, and password are required')
        return False

    host = config.get('host')
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    use_tls = bool(config.get(CONF_TLS, True))
    verify_tls = bool(config.get(CONF_VERIFY_TLS, True))
    default_port = use_tls and 6443 or 6080
    port = int(config.get('port', default_port))

    from mficlient.client import FailedToLogin, MFiClient

    try:
        client = MFiClient(host,
                           username,
                           password,
                           port=port,
                           use_tls=use_tls,
                           verify=verify_tls)
    except (FailedToLogin, requests.exceptions.ConnectionError) as ex:
        _LOGGER.error('Unable to connect to mFi: %s', str(ex))
        return False

    add_devices(
        MfiSensor(port, hass) for device in client.get_devices()
        for port in device.ports.values() if port.model in SENSOR_MODELS)
Example #8
0
def setup(hass, config):
    """Setup the Netatmo devices."""
    if not validate_config(config,
                           {DOMAIN: [CONF_API_KEY,
                                     CONF_USERNAME,
                                     CONF_PASSWORD,
                                     CONF_SECRET_KEY]},
                           _LOGGER):
        return None

    import lnetatmo

    global NETATMO_AUTH
    try:
        NETATMO_AUTH = lnetatmo.ClientAuth(config[DOMAIN][CONF_API_KEY],
                                           config[DOMAIN][CONF_SECRET_KEY],
                                           config[DOMAIN][CONF_USERNAME],
                                           config[DOMAIN][CONF_PASSWORD],
                                           "read_station read_camera "
                                           "access_camera")
    except HTTPError:
        _LOGGER.error(
            "Connection error "
            "Please check your settings for NatAtmo API.")
        return False

    for component in 'camera', 'sensor':
        discovery.load_platform(hass, component, DOMAIN, {}, config)

    return True
Example #9
0
def setup(hass, config):
    """ Sets up the HTTP API and debug interface. """

    if not validate_config(config, {DOMAIN: [CONF_API_PASSWORD]}, _LOGGER):
        return False

    api_password = config[DOMAIN][CONF_API_PASSWORD]

    # If no server host is given, accept all incoming requests
    server_host = config[DOMAIN].get(CONF_SERVER_HOST, '0.0.0.0')

    server_port = config[DOMAIN].get(CONF_SERVER_PORT, SERVER_PORT)

    development = config[DOMAIN].get(CONF_DEVELOPMENT, "") == "1"

    server = HomeAssistantHTTPServer((server_host, server_port),
                                     RequestHandler, hass, api_password,
                                     development)

    hass.bus.listen_once(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event:
        threading.Thread(target=server.start, daemon=True).start())

    # If no local api set, set one with known information
    if isinstance(hass, rem.HomeAssistant) and hass.local_api is None:
        hass.local_api = \
            rem.API(util.get_local_ip(), api_password, server_port)

    return True
Example #10
0
def setup(hass, config):
    """ Setup the Verisure component. """

    if not validate_config(config, {DOMAIN: [CONF_USERNAME, CONF_PASSWORD]}, _LOGGER):
        return False

    import verisure

    global HUB
    HUB = VerisureHub(config[DOMAIN], verisure)
    if not HUB.login():
        return False

    # Load components for the devices in the ISY controller that we support
    for comp_name, discovery in (
        ("sensor", DISCOVER_SENSORS),
        ("switch", DISCOVER_SWITCHES),
        ("alarm_control_panel", DISCOVER_ALARMS),
        ("lock", DISCOVER_LOCKS),
    ):
        component = get_component(comp_name)
        bootstrap.setup_component(hass, component.DOMAIN, config)
        hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {ATTR_SERVICE: discovery, ATTR_DISCOVERED: {}})

    return True
Example #11
0
def setup(hass, config):
    """Setup lighthub component. """

    # Validate that all required config options are given
    required = {
        DOMAIN: [CONF_PORT]
    }

    if not validate_config(config, required, _LOGGER):
        return False

    try:
        port = config[DOMAIN][CONF_PORT]
        baud = int(config[DOMAIN].get(CONF_BAUD, 115200))
        timeout = float(config[DOMAIN].get(CONF_TIMEOUT, 1.0))
    except:
        _LOGGER.exception('Invalid parameter(s)')
        return False

    hub = LightSwitchHub(handlers=Handler(hass.bus))
    try:
        hub.connect(port, baud, timeout)
    except Exception as e:
        _LOGGER.exception('Error connecting to hub')
        return False

    hass.services.register(DOMAIN, SERVICE_TOGGLE,
            partial(handle_light_toggle, hass))
    hass.services.register(DOMAIN, SERVICE_DIM,
            partial(handle_light_dim, hass))
    hass.services.register(DOMAIN, SERVICE_BRIGHTEN,
            partial(handle_light_brighten, hass))

    return True
Example #12
0
def setup(hass, config):
    """Setup ISY994 component.

    This will automatically import associated lights, switches, and sensors.
    """
    import PyISY

    # pylint: disable=global-statement
    # check for required values in configuration file
    if not validate_config(config,
                           {DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},
                           _LOGGER):
        return False

    # Pull and parse standard configuration.
    user = config[DOMAIN][CONF_USERNAME]
    password = config[DOMAIN][CONF_PASSWORD]
    host = urlparse(config[DOMAIN][CONF_HOST])
    addr = host.geturl()
    if host.scheme == 'http':
        addr = addr.replace('http://', '')
        https = False
    elif host.scheme == 'https':
        addr = addr.replace('https://', '')
        https = True
    else:
        _LOGGER.error('isy994 host value in configuration file is invalid.')
        return False
    port = host.port
    addr = addr.replace(':{}'.format(port), '')

    # Pull and parse optional configuration.
    global SENSOR_STRING
    global HIDDEN_STRING
    SENSOR_STRING = str(config[DOMAIN].get('sensor_string', SENSOR_STRING))
    HIDDEN_STRING = str(config[DOMAIN].get('hidden_string', HIDDEN_STRING))
    tls_version = config[DOMAIN].get(CONF_TLS_VER, None)

    # Connect to ISY controller.
    global ISY
    ISY = PyISY.ISY(addr, port, user, password, use_https=https,
                    tls_ver=tls_version, log=_LOGGER)
    if not ISY.connected:
        return False

    # Listen for HA stop to disconnect.
    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop)

    # Load components for the devices in the ISY controller that we support.
    for comp_name, discovery in ((('sensor', DISCOVER_SENSORS),
                                  ('light', DISCOVER_LIGHTS),
                                  ('switch', DISCOVER_SWITCHES))):
        component = get_component(comp_name)
        bootstrap.setup_component(hass, component.DOMAIN, config)
        hass.bus.fire(EVENT_PLATFORM_DISCOVERED,
                      {ATTR_SERVICE: discovery,
                       ATTR_DISCOVERED: {}})

    ISY.auto_update = True
    return True
Example #13
0
def setup(hass, config):
    """Setup ISY994 component.

    This will automatically import associated lights, switches, and sensors.
    """
    import PyISY

    # pylint: disable=global-statement
    # check for required values in configuration file
    if not validate_config(config,
                           {DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},
                           _LOGGER):
        return False

    # Pull and parse standard configuration.
    user = config[DOMAIN][CONF_USERNAME]
    password = config[DOMAIN][CONF_PASSWORD]
    host = urlparse(config[DOMAIN][CONF_HOST])
    addr = host.geturl()
    if host.scheme == 'http':
        addr = addr.replace('http://', '')
        https = False
    elif host.scheme == 'https':
        addr = addr.replace('https://', '')
        https = True
    else:
        _LOGGER.error('isy994 host value in configuration file is invalid.')
        return False
    port = host.port
    addr = addr.replace(':{}'.format(port), '')

    # Pull and parse optional configuration.
    global SENSOR_STRING
    global HIDDEN_STRING
    SENSOR_STRING = str(config[DOMAIN].get('sensor_string', SENSOR_STRING))
    HIDDEN_STRING = str(config[DOMAIN].get('hidden_string', HIDDEN_STRING))
    tls_version = config[DOMAIN].get(CONF_TLS_VER, None)

    # Connect to ISY controller.
    global ISY
    ISY = PyISY.ISY(addr, port, user, password, use_https=https,
                    tls_ver=tls_version, log=_LOGGER)
    if not ISY.connected:
        return False

    # Listen for HA stop to disconnect.
    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop)

    # Load components for the devices in the ISY controller that we support.
    for comp_name, discovery in ((('sensor', DISCOVER_SENSORS),
                                  ('light', DISCOVER_LIGHTS),
                                  ('switch', DISCOVER_SWITCHES))):
        component = get_component(comp_name)
        bootstrap.setup_component(hass, component.DOMAIN, config)
        hass.bus.fire(EVENT_PLATFORM_DISCOVERED,
                      {ATTR_SERVICE: discovery,
                       ATTR_DISCOVERED: {}})

    ISY.auto_update = True
    return True
Example #14
0
def setup(hass, config):
    """Setup the Netatmo devices."""
    if not validate_config(config, {
            DOMAIN:
        [CONF_API_KEY, CONF_USERNAME, CONF_PASSWORD, CONF_SECRET_KEY]
    }, _LOGGER):
        return None

    import lnetatmo

    global NETATMO_AUTH
    try:
        NETATMO_AUTH = lnetatmo.ClientAuth(
            config[DOMAIN][CONF_API_KEY], config[DOMAIN][CONF_SECRET_KEY],
            config[DOMAIN][CONF_USERNAME], config[DOMAIN][CONF_PASSWORD],
            "read_station read_camera "
            "access_camera")
    except HTTPError:
        _LOGGER.error("Connection error "
                      "Please check your settings for NatAtmo API.")
        return False

    for component in 'camera', 'sensor':
        discovery.load_platform(hass, component, DOMAIN, {}, config)

    return True
Example #15
0
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """ Adds a generic IP Camera. """
    if not validate_config({DOMAIN: config}, {DOMAIN: ['still_image_url']},
                           _LOGGER):
        return None

    add_devices_callback([GenericCamera(config)])
Example #16
0
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Setup a Foscam IP Camera."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['username', 'password', 'ip']}, _LOGGER):
        return None

    add_devices_callback([FoscamCamera(config)])
Example #17
0
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Setup a Foscam IP Camera."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['username', 'password', 'ip']}, _LOGGER):
        return None

    add_devices_callback([FoscamCamera(config)])
Example #18
0
def get_scanner(hass, config):
    """Setup Unifi device_tracker."""
    from unifi.controller import Controller

    if not validate_config(config, {DOMAIN: [CONF_USERNAME,
                                             CONF_PASSWORD]},
                           _LOGGER):
        _LOGGER.error('Invalid configuration')
        return False

    this_config = config[DOMAIN]
    host = this_config.get(CONF_HOST, 'localhost')
    username = this_config.get(CONF_USERNAME)
    password = this_config.get(CONF_PASSWORD)
    site_id = this_config.get(CONF_SITE_ID, 'default')

    try:
        port = int(this_config.get(CONF_PORT, 8443))
    except ValueError:
        _LOGGER.error('Invalid port (must be numeric like 8443)')
        return False

    try:
        ctrl = Controller(host, username, password, port, 'v4', site_id)
    except urllib.error.HTTPError as ex:
        _LOGGER.error('Failed to connect to unifi: %s', ex)
        return False

    return UnifiScanner(ctrl)
Example #19
0
def setup(hass, config):
    """ Setup the Arduino component. """

    if not validate_config(config,
                           {DOMAIN: ['port']},
                           _LOGGER):
        return False

    import serial
    global BOARD
    try:
        BOARD = ArduinoBoard(config[DOMAIN]['port'])
    except (serial.serialutil.SerialException, FileNotFoundError):
        _LOGGER.exception("Your port is not accessible.")
        return False

    if BOARD.get_firmata()[1] <= 2:
        _LOGGER.error("The StandardFirmata sketch should be 2.2 or newer.")
        return False

    def stop_arduino(event):
        """ Stop the Arduino service. """
        BOARD.disconnect()

    def start_arduino(event):
        """ Start the Arduino service. """
        hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_arduino)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_arduino)

    return True
Example #20
0
def setup(hass, config):
    """ Sets up the HTTP API and debug interface. """

    if not validate_config(config, {DOMAIN: [CONF_API_PASSWORD]}, _LOGGER):
        return False

    api_password = config[DOMAIN][CONF_API_PASSWORD]

    # If no server host is given, accept all incoming requests
    server_host = config[DOMAIN].get(CONF_SERVER_HOST, '0.0.0.0')

    server_port = config[DOMAIN].get(CONF_SERVER_PORT, SERVER_PORT)

    development = config[DOMAIN].get(CONF_DEVELOPMENT, "") == "1"

    server = HomeAssistantHTTPServer((server_host, server_port),
                                     RequestHandler, hass, api_password,
                                     development)

    hass.bus.listen_once(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event: threading.Thread(target=server.start, daemon=True).start(
        ))

    # If no local api set, set one with known information
    if isinstance(hass, rem.HomeAssistant) and hass.local_api is None:
        hass.local_api = \
            rem.API(util.get_local_ip(), api_password, server_port)

    return True
Example #21
0
def setup(hass, config):
    """ Setup the ifttt service component """

    if not validate_config(config, {DOMAIN: ['key']}, _LOGGER):
        return False

    key = config[DOMAIN]['key']

    def trigger_service(call):
        """ Handle ifttt trigger service calls. """
        event = call.data.get(ATTR_EVENT)
        value1 = call.data.get(ATTR_VALUE1)
        value2 = call.data.get(ATTR_VALUE2)
        value3 = call.data.get(ATTR_VALUE3)
        if event is None:
            return

        try:
            import pyfttt as pyfttt
            pyfttt.send_event(key, event, value1, value2, value3)
        except requests.exceptions.RequestException:
            _LOGGER.exception("Error communicating with IFTTT")

    hass.services.register(DOMAIN, SERVICE_TRIGGER, trigger_service)

    return True
Example #22
0
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Configure the netio platform."""
    from pynetio import Netio

    if validate_config({"conf": config}, {"conf": [CONF_OUTLETS, CONF_HOST]},
                       _LOGGER):
        if len(DEVICES) == 0:
            hass.wsgi.register_view(NetioApiView)

        dev = Netio(config[CONF_HOST], config.get(CONF_PORT, DEFAULT_PORT),
                    config.get(CONF_USERNAME, DEFAULT_USERNAME),
                    config.get(CONF_PASSWORD, DEFAULT_USERNAME))

        DEVICES[config[CONF_HOST]] = Device(dev, [])

        # Throttle the update for all NetioSwitches of one Netio
        dev.update = util.Throttle(MIN_TIME_BETWEEN_SCANS)(dev.update)

        for key in config[CONF_OUTLETS]:
            switch = NetioSwitch(DEVICES[config[CONF_HOST]].netio, key,
                                 config[CONF_OUTLETS][key])
            DEVICES[config[CONF_HOST]].entities.append(switch)

        add_devices_callback(DEVICES[config[CONF_HOST]].entities)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, dispose)
    return True
Example #23
0
def setup(hass, config):
    """ Sets up the Wink component. """
    logger = logging.getLogger(__name__)

    if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger):
        return False

    import pywink
    pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN])

    # Load components for the devices in the Wink that we support
    for component_name, func_exists, discovery_type in (
        ('light', pywink.get_bulbs, DISCOVER_LIGHTS),
        ('switch', lambda: pywink.get_switches or pywink.get_sirens or pywink.
         get_powerstrip_outlets, DISCOVER_SWITCHES),
        ('binary_sensor', pywink.get_sensors, DISCOVER_BINARY_SENSORS),
        ('sensor', lambda: pywink.get_sensors or pywink.get_eggtrays,
         DISCOVER_SENSORS), ('lock', pywink.get_locks, DISCOVER_LOCKS),
        ('garage_door', pywink.get_garage_doors, DISCOVER_GARAGE_DOORS)):

        if func_exists():
            component = get_component(component_name)

            # Ensure component is loaded
            bootstrap.setup_component(hass, component.DOMAIN, config)

            # Fire discovery event
            hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {
                ATTR_SERVICE: discovery_type,
                ATTR_DISCOVERED: {}
            })

    return True
Example #24
0
def get_service(hass, config):
    """ Get the slack notification service. """

    if not validate_config(config,
                           {DOMAIN: ['default_channel', CONF_API_KEY]},
                           _LOGGER):
        return None

    try:
        # pylint: disable=no-name-in-module, unused-variable
        from slacker import Error as SlackError

    except ImportError:
        _LOGGER.exception(
            "Unable to import slacker. "
            "Did you maybe not install the 'slacker.py' package?")

        return None

    try:
        api_token = config[DOMAIN].get(CONF_API_KEY)

        return SlackNotificationService(
            config[DOMAIN]['default_channel'],
            api_token)

    except SlackError as ex:
        _LOGGER.error(
            "Slack authentication failed")
        _LOGGER.exception(ex)
Example #25
0
def setup(hass, config):
    """ Sets up the Wink component. """
    logger = logging.getLogger(__name__)

    if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger):
        return False

    pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN])

    # Load components for the devices in the Wink that we support
    for component_name, func_exists, discovery_type in (('light',
                                                         pywink.get_bulbs,
                                                         DISCOVER_LIGHTS),
                                                        ('switch',
                                                         pywink.get_switches,
                                                         DISCOVER_SWITCHES),
                                                        ('sensor',
                                                         pywink.get_sensors,
                                                         DISCOVER_SENSORS)):

        if func_exists():
            component = get_component(component_name)

            # Ensure component is loaded
            if component.DOMAIN not in hass.components:
                bootstrap.setup_component(hass, component.DOMAIN, config)

            # Fire discovery event
            hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {
                ATTR_SERVICE: discovery_type,
                ATTR_DISCOVERED: {}
            })

    return True
Example #26
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Panasonic Viera TV platform."""
    from panasonic_viera import DEFAULT_PORT, RemoteControl

    name = config.get(CONF_NAME, 'Panasonic Viera TV')
    port = config.get(CONF_PORT, DEFAULT_PORT)

    if discovery_info:
        _LOGGER.debug('%s', discovery_info)
        vals = discovery_info.split(':')
        if len(vals) > 1:
            port = vals[1]

        host = vals[0]
        remote = RemoteControl(host, port)
        add_devices([PanasonicVieraTVDevice(name, remote)])
        return True

    # Validate that all required config options are given
    if not validate_config({DOMAIN: config}, {DOMAIN: [CONF_HOST]}, _LOGGER):
        return False

    host = config.get(CONF_HOST, None)

    remote = RemoteControl(host, port)
    try:
        remote.get_mute()
    except (socket.timeout, TimeoutError, OSError):
        _LOGGER.error('Panasonic Viera TV is not available at %s:%d', host,
                      port)
        return False

    add_devices([PanasonicVieraTVDevice(name, remote)])
    return True
Example #27
0
def get_service(hass, config):
    """Return the notify service."""
    if not validate_config({DOMAIN: config}, {DOMAIN: [CONF_HOST, CONF_NAME]},
                           _LOGGER):
        return None

    host = config.get(CONF_HOST, None)

    if not host:
        _LOGGER.error('No host provided.')
        return None

    from pylgtv import WebOsClient
    from pylgtv import PyLGTVPairException

    client = WebOsClient(host)

    try:
        client.register()
    except PyLGTVPairException:
        _LOGGER.error('Pairing failed.')
        return None
    except OSError:
        _LOGGER.error('Host unreachable.')
        return None

    return LgWebOSNotificationService(client)
Example #28
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Panasonic Viera TV platform."""
    from panasonic_viera import DEFAULT_PORT, RemoteControl

    name = config.get(CONF_NAME, 'Panasonic Viera TV')
    port = config.get(CONF_PORT, DEFAULT_PORT)

    if discovery_info:
        _LOGGER.debug('%s', discovery_info)
        vals = discovery_info.split(':')
        if len(vals) > 1:
            port = vals[1]

        host = vals[0]
        remote = RemoteControl(host, port)
        add_devices([PanasonicVieraTVDevice(name, remote)])
        return True

    # Validate that all required config options are given
    if not validate_config({DOMAIN: config}, {DOMAIN: [CONF_HOST]}, _LOGGER):
        return False

    host = config.get(CONF_HOST, None)

    remote = RemoteControl(host, port)
    try:
        remote.get_mute()
    except (socket.timeout, TimeoutError, OSError):
        _LOGGER.error('Panasonic Viera TV is not available at %s:%d',
                      host, port)
        return False

    add_devices([PanasonicVieraTVDevice(name, remote)])
    return True
Example #29
0
def get_service(hass, config):
    """ Get the Jabber (XMPP) notification service. """

    if not validate_config(config,
                           {DOMAIN: ['sender',
                                     'password',
                                     'recipient']},
                           _LOGGER):
        return None

    try:
        SendNotificationBot(config[DOMAIN]['sender'] + '/home-assistant',
                            config[DOMAIN]['password'],
                            config[DOMAIN]['recipient'],
                            '')
    except ImportError:
        _LOGGER.exception(
            "Unable to contact jabber server."
            "Please check your credentials.")

        return None

    return XmppNotificationService(config[DOMAIN]['sender'],
                                   config[DOMAIN]['password'],
                                   config[DOMAIN]['recipient'])
Example #30
0
def setup(hass, config):
    """Setup Insteon Hub component.

    This will automatically import associated lights.
    """
    if not validate_config(
            config,
            {DOMAIN: [CONF_USERNAME, CONF_PASSWORD, CONF_API_KEY]},
            _LOGGER):
        return False

    import insteon

    username = config[DOMAIN][CONF_USERNAME]
    password = config[DOMAIN][CONF_PASSWORD]
    api_key = config[DOMAIN][CONF_API_KEY]

    global INSTEON
    INSTEON = insteon.Insteon(username, password, api_key)

    if INSTEON is None:
        _LOGGER.error("Could not connect to Insteon service.")
        return

    discovery.load_platform(hass, 'light', DOMAIN, {}, config)

    return True
Example #31
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup mFi sensors."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: [CONF_HOST,
                                     CONF_USERNAME,
                                     CONF_PASSWORD]},
                           _LOGGER):
        _LOGGER.error('A host, username, and password are required')
        return False

    host = config.get(CONF_HOST)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    use_tls = bool(config.get(CONF_TLS, True))
    verify_tls = bool(config.get(CONF_VERIFY_TLS, True))
    default_port = use_tls and 6443 or 6080
    port = int(config.get('port', default_port))

    from mficlient.client import FailedToLogin, MFiClient

    try:
        client = MFiClient(host, username, password, port=port,
                           use_tls=use_tls, verify=verify_tls)
    except (FailedToLogin, requests.exceptions.ConnectionError) as ex:
        _LOGGER.error('Unable to connect to mFi: %s', str(ex))
        return False

    add_devices(MfiSensor(port, hass)
                for device in client.get_devices()
                for port in device.ports.values()
                if port.model in SENSOR_MODELS)
Example #32
0
def setup(hass, config):
    """ Setup the Arduino component. """

    global PyMata  # pylint: disable=invalid-name
    if PyMata is None:
        from PyMata.pymata import PyMata as PyMata_
        PyMata = PyMata_

    import serial

    if not validate_config(config, {DOMAIN: ['port']}, _LOGGER):
        return False

    global BOARD
    try:
        BOARD = ArduinoBoard(config[DOMAIN]['port'])
    except (serial.serialutil.SerialException, FileNotFoundError):
        _LOGGER.exception("Your port is not accessible.")
        return False

    if BOARD.get_firmata()[1] <= 2:
        _LOGGER.error("The StandardFirmata sketch should be 2.2 or newer.")
        return False

    def stop_arduino(event):
        """ Stop the Arduino service. """
        BOARD.disconnect()

    def start_arduino(event):
        """ Start the Arduino service. """
        hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_arduino)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_arduino)

    return True
Example #33
0
def setup(hass, config):
    """Setup the Wink component."""
    logger = logging.getLogger(__name__)

    if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger):
        return False

    import pywink
    from pubnub import Pubnub
    pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN])
    global SUBSCRIPTION_HANDLER
    SUBSCRIPTION_HANDLER = Pubnub("N/A", pywink.get_subscription_key(),
                                  ssl_on=True)
    SUBSCRIPTION_HANDLER.set_heartbeat(120)

    # Load components for the devices in the Wink that we support
    for component_name, func_exists in (
            ('light', pywink.get_bulbs),
            ('switch', lambda: pywink.get_switches or pywink.get_sirens or
             pywink.get_powerstrip_outlets),
            ('binary_sensor', pywink.get_sensors),
            ('sensor', lambda: pywink.get_sensors or pywink.get_eggtrays),
            ('lock', pywink.get_locks),
            ('rollershutter', pywink.get_shades),
            ('garage_door', pywink.get_garage_doors)):

        if func_exists():
            discovery.load_platform(hass, component_name, DOMAIN, {}, config)

    return True
Example #34
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up mFi sensors. """

    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['host',
                                     CONF_USERNAME,
                                     CONF_PASSWORD]},
                           _LOGGER):
        _LOGGER.error('A host, username, and password are required')
        return False

    host = config.get('host')
    port = int(config.get('port', 6443))
    username = config.get('username')
    password = config.get('password')

    from mficlient.client import FailedToLogin, MFiClient

    try:
        client = MFiClient(host, username, password, port=port)
    except (FailedToLogin, requests.exceptions.ConnectionError) as ex:
        _LOGGER.error('Unable to connect to mFi: %s', str(ex))
        return False

    add_devices(MfiSwitch(port)
                for device in client.get_devices()
                for port in device.ports.values()
                if port.model in SWITCH_MODELS)
Example #35
0
def get_service(hass, config):
    """ Get the PushBullet notification service. """

    if not validate_config(config,
                           {DOMAIN: [CONF_API_KEY]},
                           _LOGGER):
        return None

    try:
        # pylint: disable=unused-variable
        from pushbullet import PushBullet, InvalidKeyError  # noqa

    except ImportError:
        _LOGGER.exception(
            "Unable to import pushbullet. "
            "Did you maybe not install the 'pushbullet.py' package?")

        return None

    try:
        return PushBulletNotificationService(config[DOMAIN][CONF_API_KEY])

    except InvalidKeyError:
        _LOGGER.error(
            "Wrong API key supplied. "
            "Get it at https://www.pushbullet.com/account")
Example #36
0
def setup(hass, config):
    """ Sets up the device tracker. """

    if not validate_config(config, {DOMAIN: [CONF_PLATFORM]}, _LOGGER):
        return False

    tracker_type = config[DOMAIN].get(CONF_PLATFORM)

    tracker_implementation = \
        prepare_setup_platform(hass, config, DOMAIN, tracker_type)

    if tracker_implementation is None:
        _LOGGER.error("Unknown device_tracker type specified: %s.",
                      tracker_type)

        return False

    device_scanner = tracker_implementation.get_scanner(hass, config)

    if device_scanner is None:
        _LOGGER.error("Failed to initialize device scanner: %s",
                      tracker_type)

        return False

    seconds = util.convert(config[DOMAIN].get(CONF_SECONDS), int,
                           DEFAULT_CONF_SECONDS)

    track_new_devices = config[DOMAIN].get(TRACK_NEW_DEVICES) or False
    _LOGGER.info("Tracking new devices: %s", track_new_devices)

    tracker = DeviceTracker(hass, device_scanner, seconds, track_new_devices)

    # We only succeeded if we got to parse the known devices file
    return not tracker.invalid_known_devices_file
Example #37
0
def get_service(hass, config):
    """ Get the pushover notification service. """

    if not validate_config(config, {DOMAIN: ['user_key', CONF_API_KEY]},
                           _LOGGER):
        return None

    try:
        # pylint: disable=no-name-in-module, unused-variable
        from pushover import InitError

    except ImportError:
        _LOGGER.exception(
            "Unable to import pushover. "
            "Did you maybe not install the 'python-pushover.py' package?")

        return None

    try:
        api_token = config[DOMAIN].get(CONF_API_KEY)
        return PushoverNotificationService(config[DOMAIN]['user_key'],
                                           api_token)

    except InitError:
        _LOGGER.error("Wrong API key supplied. "
                      "Get it at https://pushover.net")
Example #38
0
def setup(hass, config):
    """ Setup the tellduslive component """

    # fixme: aquire app key and provide authentication
    # using username + password
    if not validate_config(config,
                           {DOMAIN: [CONF_PUBLIC_KEY,
                                     CONF_PRIVATE_KEY,
                                     CONF_TOKEN,
                                     CONF_TOKEN_SECRET]},
                           _LOGGER):
        _LOGGER.error(
            "Configuration Error: "
            "Please make sure you have configured your keys "
            "that can be aquired from https://api.telldus.com/keys/index")
        return False

    global NETWORK
    NETWORK = TelldusLiveData(hass, config)

    if not NETWORK.validate_session():
        _LOGGER.error(
            "Authentication Error: "
            "Please make sure you have configured your keys "
            "that can be aquired from https://api.telldus.com/keys/index")
        return False

    NETWORK.update(hass, config)

    return True
Example #39
0
def get_service(hass, config):
    """ Get the Jabber (XMPP) notification service. """

    if not validate_config(config,
                           {DOMAIN: ['sender',
                                     'password',
                                     'recipient']},
                           _LOGGER):
        return None

    try:
        SendNotificationBot(config[DOMAIN]['sender'] + '/home-assistant',
                            config[DOMAIN]['password'],
                            config[DOMAIN]['recipient'],
                            '')
    except ImportError:
        _LOGGER.exception(
            "Unable to contact jabber server."
            "Please check your credentials.")

        return None

    return XmppNotificationService(config[DOMAIN]['sender'],
                                   config[DOMAIN]['password'],
                                   config[DOMAIN]['recipient'])
Example #40
0
def get_service(hass, config):
    """ Get the Telegram notification service. """

    if not validate_config(config,
                           {DOMAIN: [CONF_API_KEY, 'chat_id']},
                           _LOGGER):
        return None

    try:
        import telegram
    except ImportError:
        _LOGGER.exception(
            "Unable to import python-telegram-bot. "
            "Did you maybe not install the 'python-telegram-bot' package?")
        return None

    try:
        bot = telegram.Bot(token=config[DOMAIN][CONF_API_KEY])
        username = bot.getMe()['username']
        _LOGGER.info("Telegram bot is' %s'", username)
    except urllib.error.HTTPError:
        _LOGGER.error("Please check your access token.")
        return None

    return TelegramNotificationService(
        config[DOMAIN][CONF_API_KEY],
        config[DOMAIN]['chat_id'])
Example #41
0
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """ Adds a generic IP Camera. """
    if not validate_config({DOMAIN: config}, {DOMAIN: ['still_image_url']},
                           _LOGGER):
        return None

    add_devices_callback([GenericCamera(config)])
Example #42
0
def get_service(hass, config):
    """ Get the pushover notification service. """

    if not validate_config(config,
                           {DOMAIN: ['user_key', CONF_API_KEY]},
                           _LOGGER):
        return None

    try:
        # pylint: disable=no-name-in-module, unused-variable
        from pushover import InitError

    except ImportError:
        _LOGGER.exception(
            "Unable to import pushover. "
            "Did you maybe not install the 'python-pushover.py' package?")

        return None

    try:
        api_token = config[DOMAIN].get(CONF_API_KEY)
        return PushoverNotificationService(
            config[DOMAIN]['user_key'],
            api_token)

    except InitError:
        _LOGGER.error(
            "Wrong API key supplied. "
            "Get it at https://pushover.net")
Example #43
0
def setup(hass, config):
    """ Sets up the Wink component. """
    logger = logging.getLogger(__name__)

    if not validate_config(config, {DOMAIN: [CONF_ACCESS_TOKEN]}, logger):
        return False

    import pywink
    pywink.set_bearer_token(config[DOMAIN][CONF_ACCESS_TOKEN])

    # Load components for the devices in the Wink that we support
    for component_name, func_exists, discovery_type in (
            ('light', pywink.get_bulbs, DISCOVER_LIGHTS),
            ('switch', pywink.get_switches, DISCOVER_SWITCHES),
            ('sensor', pywink.get_sensors, DISCOVER_SENSORS)):

        if func_exists():
            component = get_component(component_name)

            # Ensure component is loaded
            bootstrap.setup_component(hass, component.DOMAIN, config)

            # Fire discovery event
            hass.bus.fire(EVENT_PLATFORM_DISCOVERED, {
                ATTR_SERVICE: discovery_type,
                ATTR_DISCOVERED: {}
            })

    return True
Example #44
0
def setup(hass, config):
    """ Setup the Verisure component. """

    if not validate_config(config,
                           {DOMAIN: [CONF_USERNAME, CONF_PASSWORD]},
                           _LOGGER):
        return False

    import verisure
    global HUB
    HUB = VerisureHub(config[DOMAIN], verisure)
    if not HUB.login():
        return False

    # Load components for the devices in the ISY controller that we support
    for comp_name, discovery in ((('sensor', DISCOVER_SENSORS),
                                  ('switch', DISCOVER_SWITCHES),
                                  ('alarm_control_panel', DISCOVER_ALARMS),
                                  ('lock', DISCOVER_LOCKS))):
        component = get_component(comp_name)
        bootstrap.setup_component(hass, component.DOMAIN, config)
        hass.bus.fire(EVENT_PLATFORM_DISCOVERED,
                      {ATTR_SERVICE: discovery,
                       ATTR_DISCOVERED: {}})

    return True
Example #45
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up mFi sensors. """

    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['host', CONF_USERNAME, CONF_PASSWORD]},
                           _LOGGER):
        _LOGGER.error('A host, username, and password are required')
        return False

    host = config.get('host')
    port = int(config.get('port', 6443))
    username = config.get('username')
    password = config.get('password')

    from mficlient.client import MFiClient

    try:
        client = MFiClient(host, username, password, port=port)
    except client.FailedToLogin as ex:
        _LOGGER.error('Unable to connect to mFi: %s', str(ex))
        return False

    add_devices(
        MfiSwitch(port) for device in client.get_devices()
        for port in device.ports.values() if port.model in SWITCH_MODELS)
Example #46
0
def get_scanner(hass, config):
    """ Validates config and returns FritzBoxScanner. """
    if not validate_config(config, {DOMAIN: []}, _LOGGER):
        return None

    scanner = FritzBoxScanner(config[DOMAIN])
    return scanner if scanner.success_init else None
Example #47
0
def setup(hass, config):
    """ Sets up the device tracker. """

    if not validate_config(config, {DOMAIN: [CONF_PLATFORM]}, _LOGGER):
        return False

    tracker_type = config[DOMAIN].get(CONF_PLATFORM)

    tracker_implementation = get_component(
        'device_tracker.{}'.format(tracker_type))

    if tracker_implementation is None:
        _LOGGER.error("Unknown device_tracker type specified.")

        return False

    device_scanner = tracker_implementation.get_scanner(hass, config)

    if device_scanner is None:
        _LOGGER.error("Failed to initialize device scanner for %s",
                      tracker_type)

        return False

    seconds = util.convert(config[DOMAIN].get(CONF_SECONDS), int,
                           DEFAULT_CONF_SECONDS)

    track_new_devices = config[DOMAIN].get(TRACK_NEW_DEVICES) or False
    _LOGGER.info("Tracking new devices: %s", track_new_devices)

    tracker = DeviceTracker(hass, device_scanner, seconds, track_new_devices)

    # We only succeeded if we got to parse the known devices file
    return not tracker.invalid_known_devices_file
Example #48
0
def get_service(hass, config):
    """ Get the NMA notification service. """

    if not validate_config(config, {DOMAIN: [CONF_API_KEY]}, _LOGGER):
        return None

    try:
        # pylint: disable=unused-variable
        from requests import Session

    except ImportError:
        _LOGGER.exception("Unable to import requests. "
                          "Did you maybe not install the 'Requests' package?")

        return None

    nma = Session()
    response = nma.get(_RESOURCE + 'verify',
                       params={"apikey": config[DOMAIN][CONF_API_KEY]})
    tree = ET.fromstring(response.content)

    if tree[0].tag == 'error':
        _LOGGER.error("Wrong API key supplied. %s", tree[0].text)
    else:
        return NmaNotificationService(config[DOMAIN][CONF_API_KEY])
Example #49
0
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Configure the netio platform."""
    from pynetio import Netio

    if validate_config({"conf": config}, {"conf": [CONF_OUTLETS, CONF_HOST]}, _LOGGER):
        if len(DEVICES) == 0:
            hass.wsgi.register_view(NetioApiView)

        dev = Netio(
            config[CONF_HOST],
            config.get(CONF_PORT, DEFAULT_PORT),
            config.get(CONF_USERNAME, DEFAULT_USERNAME),
            config.get(CONF_PASSWORD, DEFAULT_USERNAME),
        )

        DEVICES[config[CONF_HOST]] = Device(dev, [])

        # Throttle the update for all NetioSwitches of one Netio
        dev.update = util.Throttle(MIN_TIME_BETWEEN_SCANS)(dev.update)

        for key in config[CONF_OUTLETS]:
            switch = NetioSwitch(DEVICES[config[CONF_HOST]].netio, key, config[CONF_OUTLETS][key])
            DEVICES[config[CONF_HOST]].entities.append(switch)

        add_devices_callback(DEVICES[config[CONF_HOST]].entities)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, dispose)
    return True
Example #50
0
def setup(hass, config):
    """ Sets up the device tracker. """

    if not validate_config(config, {DOMAIN: [CONF_PLATFORM]}, _LOGGER):
        return False

    tracker_type = config[DOMAIN].get(CONF_PLATFORM)

    tracker_implementation = get_component(
        'device_tracker.{}'.format(tracker_type))

    if tracker_implementation is None:
        _LOGGER.error("Unknown device_tracker type specified.")

        return False

    device_scanner = tracker_implementation.get_scanner(hass, config)

    if device_scanner is None:
        _LOGGER.error("Failed to initialize device scanner for %s",
                      tracker_type)

        return False

    seconds = util.convert(config[DOMAIN].get(CONF_SECONDS), int,
                           DEFAULT_CONF_SECONDS)

    tracker = DeviceTracker(hass, device_scanner, seconds)

    # We only succeeded if we got to parse the known devices file
    return not tracker.invalid_known_devices_file
Example #51
0
def get_service(hass, config):
    """ Get the slack notification service. """

    if not validate_config(config, {DOMAIN: ['default_channel', CONF_API_KEY]},
                           _LOGGER):
        return None

    try:
        # pylint: disable=no-name-in-module, unused-variable
        from slacker import Error as SlackError

    except ImportError:
        _LOGGER.exception(
            "Unable to import slacker. "
            "Did you maybe not install the 'slacker.py' package?")

        return None

    try:
        api_token = config[DOMAIN].get(CONF_API_KEY)

        return SlackNotificationService(config[DOMAIN]['default_channel'],
                                        api_token)

    except SlackError as ex:
        _LOGGER.error("Slack authentication failed")
        _LOGGER.exception(ex)
Example #52
0
def get_service(hass, config):
    """Return the notify service."""
    if not validate_config({DOMAIN: config}, {DOMAIN: [CONF_HOST, CONF_NAME]},
                           _LOGGER):
        return None

    host = config.get(CONF_HOST, None)

    if not host:
        _LOGGER.error('No host provided.')
        return None

    from pylgtv import WebOsClient
    from pylgtv import PyLGTVPairException

    client = WebOsClient(host)

    try:
        client.register()
    except PyLGTVPairException:
        _LOGGER.error('Pairing failed.')
        return None
    except ConnectionRefusedError:
        _LOGGER.error('Host unreachable.')
        return None

    return LgWebOSNotificationService(client)
Example #53
0
def get_service(hass, config):
    """ Get the instapush notification service. """

    if not validate_config({DOMAIN: config},
                           {DOMAIN: [CONF_API_KEY,
                                     'app_secret',
                                     'event',
                                     'tracker']},
                           _LOGGER):
        return None

    headers = {'x-instapush-appid': config[CONF_API_KEY],
               'x-instapush-appsecret': config['app_secret']}

    try:
        response = requests.get(_RESOURCE + 'events/list',
                                headers=headers).json()
    except ValueError:
        _LOGGER.error('Unexpected answer from Instapush API.')
        return None

    if 'error' in response:
        _LOGGER.error(response['msg'])
        return None

    if len([app for app in response if app['title'] == config['event']]) == 0:
        _LOGGER.error(
            "No app match your given value. "
            "Please create an app at https://instapush.im")
        return None

    return InstapushNotificationService(
        config[CONF_API_KEY], config['app_secret'], config['event'],
        config['tracker'])
Example #54
0
def setup(hass, config):
    """Setup Insteon Hub component.

    This will automatically import associated lights.
    """
    if not validate_config(
            config, {DOMAIN: [CONF_USERNAME, CONF_PASSWORD, CONF_API_KEY]},
            _LOGGER):
        return False

    import insteon

    username = config[DOMAIN][CONF_USERNAME]
    password = config[DOMAIN][CONF_PASSWORD]
    api_key = config[DOMAIN][CONF_API_KEY]

    global INSTEON
    INSTEON = insteon.Insteon(username, password, api_key)

    if INSTEON is None:
        _LOGGER.error("Could not connect to Insteon service.")
        return

    discovery.load_platform(hass, 'light', DOMAIN, {}, config)

    return True