コード例 #1
0
ファイル: unifi.py プロジェクト: bdfoster/blumate
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)

    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')
    except urllib.error.HTTPError as ex:
        _LOGGER.error('Failed to connect to unifi: %s', ex)
        return False

    return UnifiScanner(ctrl)
コード例 #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
コード例 #3
0
ファイル: insteon_hub.py プロジェクト: bdfoster/blumate
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
コード例 #4
0
ファイル: mfi.py プロジェクト: bdfoster/blumate
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('username')
    password = config.get('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(MfiSwitch(port)
                for device in client.get_devices()
                for port in device.ports.values()
                if port.model in SWITCH_MODELS)
コード例 #5
0
ファイル: octoprint.py プロジェクト: bdfoster/blumate
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
コード例 #6
0
ファイル: netatmo.py プロジェクト: bdfoster/blumate
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, discovery_service in (
            ('camera', DISCOVER_CAMERAS), ('sensor', DISCOVER_SENSORS)):
        discovery.discover(hass, discovery_service, component=component,
                           hass_config=config)

    return True
コード例 #7
0
ファイル: octoprint.py プロジェクト: lumavp/blumate
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
コード例 #8
0
ファイル: foscam.py プロジェクト: bdfoster/blumate
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)])
コード例 #9
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, discovery_service in (('camera', DISCOVER_CAMERAS),
                                         ('sensor', DISCOVER_SENSORS)):
        discovery.discover(hass,
                           discovery_service,
                           component=component,
                           hass_config=config)

    return True
コード例 #10
0
ファイル: mfi.py プロジェクト: lumavp/blumate
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)
コード例 #11
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
    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
コード例 #12
0
ファイル: panasonic_viera.py プロジェクト: lumavp/blumate
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
コード例 #13
0
ファイル: tellduslive.py プロジェクト: lumavp/blumate
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
コード例 #14
0
ファイル: webostv.py プロジェクト: lumavp/blumate
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)
コード例 #15
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)])
コード例 #16
0
ファイル: generic.py プロジェクト: lumavp/blumate
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Setup a generic IP Camera."""
    if not validate_config({DOMAIN: config}, {DOMAIN: ['still_image_url']},
                           _LOGGER):
        return None

    add_devices_callback([GenericCamera(config)])
コード例 #17
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_BLUMATE_STOP, stop_arduino)

    hass.bus.listen_once(EVENT_BLUMATE_START, start_arduino)

    return True
コード例 #18
0
ファイル: wink.py プロジェクト: bdfoster/blumate
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
    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
コード例 #19
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_BLUMATE_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
コード例 #20
0
ファイル: instapush.py プロジェクト: lumavp/blumate
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'])
コード例 #21
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)

    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')
    except urllib.error.HTTPError as ex:
        _LOGGER.error('Failed to connect to unifi: %s', ex)
        return False

    return UnifiScanner(ctrl)
コード例 #22
0
ファイル: ifttt.py プロジェクト: lumavp/blumate
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[ATTR_EVENT]
        value1 = call.data.get(ATTR_VALUE1)
        value2 = call.data.get(ATTR_VALUE2)
        value3 = call.data.get(ATTR_VALUE3)

        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,
                           schema=SERVICE_TRIGGER_SCHEMA)

    return True
コード例 #23
0
ファイル: netio.py プロジェクト: lumavp/blumate
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_BLUMATE_STOP, dispose)
    return True
コード例 #24
0
ファイル: mjpeg.py プロジェクト: bdfoster/blumate
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)])
コード例 #25
0
ファイル: actiontec.py プロジェクト: lumavp/blumate
def get_scanner(hass, config):
    """Validate the configuration and return an Actiontec scanner."""
    if not validate_config(config,
                           {DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD]},
                           _LOGGER):
        return None
    scanner = ActiontecDeviceScanner(config[DOMAIN])
    return scanner if scanner.success_init else None
コード例 #26
0
ファイル: nmap_tracker.py プロジェクト: lumavp/blumate
def get_scanner(hass, config):
    """Validate the configuration and return a Nmap scanner."""
    if not validate_config(config, {DOMAIN: [CONF_HOSTS]}, _LOGGER):
        return None

    scanner = NmapDeviceScanner(config[DOMAIN])

    return scanner if scanner.success_init else None
コード例 #27
0
def get_scanner(hass, config):
    """Validate the configuration and returns a Tomato scanner."""
    if not validate_config(config, {
            DOMAIN: [CONF_HOST, CONF_USERNAME, CONF_PASSWORD, CONF_HTTP_ID]
    }, _LOGGER):
        return None

    return TomatoDeviceScanner(config[DOMAIN])
コード例 #28
0
ファイル: free_mobile.py プロジェクト: lumavp/blumate
def get_service(hass, config):
    """Get the Free Mobile SMS notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: [CONF_USERNAME, CONF_ACCESS_TOKEN]},
                           _LOGGER):
        return None

    return FreeSMSNotificationService(config[CONF_USERNAME],
                                      config[CONF_ACCESS_TOKEN])
コード例 #29
0
ファイル: tomato.py プロジェクト: bdfoster/blumate
def get_scanner(hass, config):
    """Validate the configuration and returns a Tomato scanner."""
    if not validate_config(config,
                           {DOMAIN: [CONF_HOST, CONF_USERNAME,
                                     CONF_PASSWORD, CONF_HTTP_ID]},
                           _LOGGER):
        return None

    return TomatoDeviceScanner(config[DOMAIN])
コード例 #30
0
ファイル: fritz.py プロジェクト: lumavp/blumate
def get_scanner(hass, config):
    """Validate the configuration and return FritzBoxScanner."""
    if not validate_config(config,
                           {DOMAIN: []},
                           _LOGGER):
        return None

    scanner = FritzBoxScanner(config[DOMAIN])
    return scanner if scanner.success_init else None
コード例 #31
0
def get_service(hass, config):
    """Get the Command Line notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['command']},
                           _LOGGER):
        return None

    command = config['command']

    return CommandLineNotificationService(command)
コード例 #32
0
ファイル: free_mobile.py プロジェクト: bdfoster/blumate
def get_service(hass, config):
    """Get the Free Mobile SMS notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: [CONF_USERNAME,
                                     CONF_ACCESS_TOKEN]},
                           _LOGGER):
        return None

    return FreeSMSNotificationService(config[CONF_USERNAME],
                                      config[CONF_ACCESS_TOKEN])
コード例 #33
0
ファイル: googlevoice.py プロジェクト: lumavp/blumate
def get_service(hass, config):
    """Get the Google Voice SMS notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: [CONF_USERNAME,
                                     CONF_PASSWORD]},
                           _LOGGER):
        return None

    return GoogleVoiceSMSNotificationService(config[CONF_USERNAME],
                                             config[CONF_PASSWORD])
コード例 #34
0
ファイル: snmp.py プロジェクト: bdfoster/blumate
def get_scanner(hass, config):
    """Validate the configuration and return an snmp scanner."""
    if not validate_config(config,
                           {DOMAIN: [CONF_HOST, CONF_COMMUNITY, CONF_BASEOID]},
                           _LOGGER):
        return None

    scanner = SnmpScanner(config[DOMAIN])

    return scanner if scanner.success_init else None
コード例 #35
0
ファイル: file.py プロジェクト: lumavp/blumate
def get_service(hass, config):
    """Get the file notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['filename', 'timestamp']}, _LOGGER):
        return None

    filename = config['filename']
    timestamp = config['timestamp']

    return FileNotificationService(hass, filename, timestamp)
コード例 #36
0
ファイル: sendgrid.py プロジェクト: lumavp/blumate
def get_service(hass, config):
    """Get the SendGrid notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['api_key', 'sender', 'recipient']},
                           _LOGGER):
        return None

    api_key = config['api_key']
    sender = config['sender']
    recipient = config['recipient']
    return SendgridNotificationService(api_key, sender, recipient)
コード例 #37
0
ファイル: sendgrid.py プロジェクト: bdfoster/blumate
def get_service(hass, config):
    """Get the SendGrid notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['api_key', 'sender', 'recipient']},
                           _LOGGER):
        return None

    api_key = config['api_key']
    sender = config['sender']
    recipient = config['recipient']
    return SendgridNotificationService(api_key, sender, recipient)
コード例 #38
0
ファイル: splunk.py プロジェクト: bdfoster/blumate
def setup(hass, config):
    """Setup the Splunk component."""
    if not validate_config(config, {DOMAIN: ['token']}, _LOGGER):
        _LOGGER.error("You must include the token for your HTTP "
                      "Event Collector input in Splunk.")
        return False

    conf = config[DOMAIN]

    host = conf[CONF_HOST]
    port = util.convert(conf.get(CONF_PORT), int, DEFAULT_PORT)
    token = util.convert(conf.get(CONF_TOKEN), str)
    use_ssl = util.convert(conf.get(CONF_SSL), bool, DEFAULT_SSL)
    if use_ssl:
        uri_scheme = "https://"
    else:
        uri_scheme = "http://"
    event_collector = uri_scheme + host + ":" + str(port) + \
        "/services/collector/event"
    headers = {'Authorization': 'Splunk ' + token}

    def splunk_event_listener(event):
        """Listen for new messages on the bus and sends them to Splunk."""
        state = event.data.get('new_state')

        if state is None:
            return

        try:
            _state = state_helper.state_as_number(state)
        except ValueError:
            _state = state.state

        json_body = [
            {
                'domain': state.domain,
                'entity_id': state.object_id,
                'attributes': dict(state.attributes),
                'time': str(event.time_fired),
                'value': _state,
            }
        ]

        try:
            payload = {"host": event_collector,
                       "event": json_body}
            requests.post(event_collector, data=json.dumps(payload),
                          headers=headers)
        except requests.exceptions.RequestException as error:
            _LOGGER.exception('Error saving event to Splunk: %s', error)

    hass.bus.listen(EVENT_STATE_CHANGED, splunk_event_listener)

    return True
コード例 #39
0
def get_service(hass, config):
    """Get the Jabber (XMPP) notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['sender', 'password', 'recipient']},
                           _LOGGER):
        return None

    return XmppNotificationService(
        config.get('sender'),
        config.get('password'),
        config.get('recipient'),
        config.get('tls', True))
コード例 #40
0
ファイル: file.py プロジェクト: bdfoster/blumate
def get_service(hass, config):
    """Get the file notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['filename',
                                     'timestamp']},
                           _LOGGER):
        return None

    filename = config['filename']
    timestamp = config['timestamp']

    return FileNotificationService(hass, filename, timestamp)
コード例 #41
0
def setup(hass, config):
    """Setup the Splunk component."""
    if not validate_config(config, {DOMAIN: ['token']}, _LOGGER):
        _LOGGER.error("You must include the token for your HTTP "
                      "Event Collector input in Splunk.")
        return False

    conf = config[DOMAIN]

    host = conf[CONF_HOST]
    port = util.convert(conf.get(CONF_PORT), int, DEFAULT_PORT)
    token = util.convert(conf.get(CONF_TOKEN), str)
    use_ssl = util.convert(conf.get(CONF_SSL), bool, DEFAULT_SSL)
    if use_ssl:
        uri_scheme = "https://"
    else:
        uri_scheme = "http://"
    event_collector = uri_scheme + host + ":" + str(port) + \
        "/services/collector/event"
    headers = {'Authorization': 'Splunk ' + token}

    def splunk_event_listener(event):
        """Listen for new messages on the bus and sends them to Splunk."""
        state = event.data.get('new_state')

        if state is None:
            return

        try:
            _state = state_helper.state_as_number(state)
        except ValueError:
            _state = state.state

        json_body = [{
            'domain': state.domain,
            'entity_id': state.object_id,
            'attributes': dict(state.attributes),
            'time': str(event.time_fired),
            'value': _state,
        }]

        try:
            payload = {"host": event_collector, "event": json_body}
            requests.post(event_collector,
                          data=json.dumps(payload),
                          headers=headers)
        except requests.exceptions.RequestException as error:
            _LOGGER.exception('Error saving event to Splunk: %s', error)

    hass.bus.listen(EVENT_STATE_CHANGED, splunk_event_listener)

    return True
コード例 #42
0
ファイル: smtp.py プロジェクト: bdfoster/blumate
def get_service(hass, config):
    """Get the mail notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['recipient']},
                           _LOGGER):
        return None

    smtp_server = config.get('server', 'localhost')
    port = int(config.get('port', '25'))
    username = config.get('username', None)
    password = config.get('password', None)
    starttls = int(config.get('starttls', 0))
    debug = config.get('debug', 0)

    server = None
    try:
        server = smtplib.SMTP(smtp_server, port, timeout=5)
        server.set_debuglevel(debug)
        server.ehlo()
        if starttls == 1:
            server.starttls()
            server.ehlo()
        if username and password:
            try:
                server.login(username, password)

            except (smtplib.SMTPException, smtplib.SMTPSenderRefused):
                _LOGGER.exception("Please check your settings.")
                return None

    except smtplib.socket.gaierror:
        _LOGGER.exception(
            "SMTP server not found (%s:%s). "
            "Please check the IP address or hostname of your SMTP server.",
            smtp_server, port)

        return None

    except smtplib.SMTPAuthenticationError:
        _LOGGER.exception(
            "Login not possible. "
            "Please check your setting and/or your credentials.")

        return None

    finally:
        if server:
            server.quit()

    return MailNotificationService(
        smtp_server, port, config['sender'], starttls, username, password,
        config['recipient'], debug)
コード例 #43
0
def get_service(hass, config):
    """Get the Twitter notification service."""
    if not validate_config({DOMAIN: config}, {
            DOMAIN: [
                CONF_CONSUMER_KEY, CONF_CONSUMER_SECRET, CONF_ACCESS_TOKEN,
                CONF_ACCESS_TOKEN_SECRET
            ]
    }, _LOGGER):
        return None

    return TwitterNotificationService(config[CONF_CONSUMER_KEY],
                                      config[CONF_CONSUMER_SECRET],
                                      config[CONF_ACCESS_TOKEN],
                                      config[CONF_ACCESS_TOKEN_SECRET])
コード例 #44
0
ファイル: syslog.py プロジェクト: lumavp/blumate
def get_service(hass, config):
    """Get the syslog notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: ['facility', 'option', 'priority']},
                           _LOGGER):
        return None

    import syslog

    _facility = {
        'kernel': syslog.LOG_KERN,
        'user': syslog.LOG_USER,
        'mail': syslog.LOG_MAIL,
        'daemon': syslog.LOG_DAEMON,
        'auth': syslog.LOG_KERN,
        'LPR': syslog.LOG_LPR,
        'news': syslog.LOG_NEWS,
        'uucp': syslog.LOG_UUCP,
        'cron': syslog.LOG_CRON,
        'syslog': syslog.LOG_SYSLOG,
        'local0': syslog.LOG_LOCAL0,
        'local1': syslog.LOG_LOCAL1,
        'local2': syslog.LOG_LOCAL2,
        'local3': syslog.LOG_LOCAL3,
        'local4': syslog.LOG_LOCAL4,
        'local5': syslog.LOG_LOCAL5,
        'local6': syslog.LOG_LOCAL6,
        'local7': syslog.LOG_LOCAL7,
    }.get(config['facility'], 40)

    _option = {
        'pid': syslog.LOG_PID,
        'cons': syslog.LOG_CONS,
        'ndelay': syslog.LOG_NDELAY,
        'nowait': syslog.LOG_NOWAIT,
        'perror': syslog.LOG_PERROR
    }.get(config['option'], 10)

    _priority = {
        5: syslog.LOG_EMERG,
        4: syslog.LOG_ALERT,
        3: syslog.LOG_CRIT,
        2: syslog.LOG_ERR,
        1: syslog.LOG_WARNING,
        0: syslog.LOG_NOTICE,
        -1: syslog.LOG_INFO,
        -2: syslog.LOG_DEBUG
    }.get(config['priority'], -1)

    return SyslogNotificationService(_facility, _option, _priority)
コード例 #45
0
ファイル: smtp.py プロジェクト: lumavp/blumate
def get_service(hass, config):
    """Get the mail notification service."""
    if not validate_config({DOMAIN: config}, {DOMAIN: ['recipient']}, _LOGGER):
        return None

    smtp_server = config.get('server', 'localhost')
    port = int(config.get('port', '25'))
    username = config.get('username', None)
    password = config.get('password', None)
    starttls = int(config.get('starttls', 0))
    debug = config.get('debug', 0)

    server = None
    try:
        server = smtplib.SMTP(smtp_server, port, timeout=5)
        server.set_debuglevel(debug)
        server.ehlo()
        if starttls == 1:
            server.starttls()
            server.ehlo()
        if username and password:
            try:
                server.login(username, password)

            except (smtplib.SMTPException, smtplib.SMTPSenderRefused):
                _LOGGER.exception("Please check your settings.")
                return None

    except smtplib.socket.gaierror:
        _LOGGER.exception(
            "SMTP server not found (%s:%s). "
            "Please check the IP address or hostname of your SMTP server.",
            smtp_server, port)

        return None

    except smtplib.SMTPAuthenticationError:
        _LOGGER.exception("Login not possible. "
                          "Please check your setting and/or your credentials.")

        return None

    finally:
        if server:
            server.quit()

    return MailNotificationService(smtp_server, port, config['sender'],
                                   starttls, username, password,
                                   config['recipient'], debug)
コード例 #46
0
ファイル: nma.py プロジェクト: bdfoster/blumate
def get_service(hass, config):
    """Get the NMA notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: [CONF_API_KEY]},
                           _LOGGER):
        return None

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

    if tree[0].tag == 'error':
        _LOGGER.error("Wrong API key supplied. %s", tree[0].text)
        return None

    return NmaNotificationService(config[CONF_API_KEY])
コード例 #47
0
ファイル: twilio_sms.py プロジェクト: bdfoster/blumate
def get_service(hass, config):
    """Get the Twilio SMS notification service."""
    if not validate_config({DOMAIN: config},
                           {DOMAIN: [CONF_ACCOUNT_SID,
                                     CONF_AUTH_TOKEN,
                                     CONF_FROM_NUMBER]},
                           _LOGGER):
        return None

    # pylint: disable=import-error
    from twilio.rest import TwilioRestClient

    twilio_client = TwilioRestClient(config[CONF_ACCOUNT_SID],
                                     config[CONF_AUTH_TOKEN])

    return TwilioSMSNotificationService(twilio_client,
                                        config[CONF_FROM_NUMBER])
コード例 #48
0
ファイル: edimax.py プロジェクト: bdfoster/blumate
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """Find and return Edimax Smart Plugs."""
    from pyedimax.smartplug import SmartPlug

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

    host = config.get(CONF_HOST)
    auth = (config.get(CONF_USERNAME, DEFAULT_USERNAME),
            config.get(CONF_PASSWORD, DEFAULT_PASSWORD))
    name = config.get(CONF_NAME, DEVICE_DEFAULT_NAME)

    add_devices_callback([SmartPlugSwitch(SmartPlug(host, auth), name)])