Beispiel #1
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the REST binary sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = config.get(CONF_METHOD)
    payload = config.get(CONF_PAYLOAD)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    headers = config.get(CONF_HEADERS)
    sensor_class = config.get(CONF_SENSOR_CLASS)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    if value_template is not None:
        value_template.hass = hass

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = HTTPDigestAuth(username, password)
        else:
            auth = HTTPBasicAuth(username, password)
    else:
        auth = None

    rest = RestData(method, resource, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch REST data from %s", resource)
        return False

    add_devices([RestBinarySensor(
        hass, rest, name, sensor_class, value_template)])
Beispiel #2
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the REST binary sensor."""
    resource = config.get('resource', None)
    method = config.get('method', DEFAULT_METHOD)
    payload = config.get('payload', None)
    verify_ssl = config.get('verify_ssl', True)

    sensor_class = config.get('sensor_class')
    if sensor_class not in SENSOR_CLASSES:
        _LOGGER.warning('Unknown sensor class: %s', sensor_class)
        sensor_class = None

    rest = RestData(method, resource, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error('Unable to fetch REST data')
        return False

    add_devices([RestBinarySensor(
        hass,
        rest,
        config.get('name', DEFAULT_NAME),
        sensor_class,
        config.get(CONF_VALUE_TEMPLATE))])
class MoonPhaseHereAPI(object):
    """Get the latest data and update the states."""

    def __init__(self, app_id, app_code, zipcode):
        """Initialize the data object."""
        from homeassistant.components.sensor.rest import RestData

        resource = "{}app_id={}&app_code={}&zipcode={}".format(
            _ENDPOINT, app_id, app_code, zipcode)
        _LOGGER.error("Moon sensor updated")
        self._rest = RestData('GET', resource, None, None, None, False)
        self.data = None
        self.available = True
        self.update()

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Get the latest data from Here."""
        try:
            self._rest.update()
            self.data = json.loads(self._rest.data)
            self.available = True
        except TypeError:
            _LOGGER.error("Unable to fetch data from Here")
            self.available = False
Beispiel #4
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Doomsday Clock sensor."""
    name = config.get(CONF_NAME)
    resource = CONF_RESOURCE
    method = 'GET'
    selector = CONF_SELECTOR
    payload = headers = auth = None
    verify_ssl = False
    unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT)
    icon = config.get(CONF_ICON)
    value_template = config.get(CONF_VALUE_TEMPLATE)

    if value_template is not None:
        value_template.hass = hass

    rest = RestData(method, resource, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch URL: %s", resource)
        return False

    add_entities([
        DoomsdayClockSensor(rest, name, selector, unit_of_measurement, icon,
            value_template)
        ], True)
 def _rss_news(time=None):
     nonlocal news_rss
     resource = "https://www.nrk.no/nyheter/"
     method = 'GET'
     payload = auth = headers = None
     rest = RestData(method,
                     resource,
                     auth,
                     headers,
                     payload,
                     verify_ssl=True)
     rest.update()
     news_rss = []
     if rest.data is None:
         return
     raw_data = BeautifulSoup(rest.data, 'html.parser')
     prew_text = ""
     for raw_text in raw_data.select("p"):
         text = strip_tags(str(raw_text))
         if text == prew_text:
             continue
         prew_text = text
         news_rss.append(text)
         if len(news_rss) > 2:
             break
     _feed = feedparser.parse(
         "http://www.yr.no/sted/Norge/S%C3%B8r-Tr%C3%B8ndelag/Trondheim/Trondheim/varsel.xml"
     )
     summary = _feed.feed.get("summary")
     if summary is None:
         return
     news_rss.append("Værvarsel " + strip_tags(summary).replace(
         "<strong>", "").replace("</strong>", ""))
Beispiel #6
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Pi-Hole sensor."""
    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    method = "GET"
    payload = None
    auth = None
    headers = None
    verify_ssl = config.get(CONF_VERIFY_SSL)
    use_ssl = config.get(CONF_SSL)

    if use_ssl:
        uri_scheme = "https://"
    else:
        uri_scheme = "http://"

    resource = "{}{}{}".format(uri_scheme, host, _ENDPOINT)

    rest = RestData(method, resource, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch REST data")
        return False

    add_devices([PiHoleSensor(hass, rest, name)])
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Pollen sensor."""
    name = config.get(CONF_NAME)
    sensors = config.get(CONF_SENSORS)
    state_as_string = config.get(CONF_STATE_AS_STRING)
    method = 'GET'
    payload = ''
    auth = ''
    verify_ssl = DEFAULT_VERIFY_SSL
    headers = {}

    rest = RestData(method, _ENDPOINT, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch data from Pollenkollen")
        return False

    devices = []

    for sensor in sensors:
        if 'days_to_track' in sensor:
            for day in range(int(sensor['days_to_track'])):
                for allergen in sensor['allergens']:
                    devices.append(
                        PollenkollSensor(rest, name, sensor, allergen,
                                         state_as_string, day))
        else:
            for allergen in sensor['allergens']:
                devices.append(
                    PollenkollSensor(rest, name, sensor, allergen,
                                     state_as_string))

    add_devices(devices, True)
Beispiel #8
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Pi-Hole sensor."""
    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    method = 'GET'
    payload = None
    auth = None
    headers = None
    verify_ssl = config.get(CONF_VERIFY_SSL)
    use_ssl = config.get(CONF_SSL)

    if use_ssl:
        uri_scheme = 'https://'
    else:
        uri_scheme = 'http://'

    resource = "{}{}{}".format(uri_scheme, host, _ENDPOINT)

    rest = RestData(method, resource, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch data from Pi-Hole")
        return False

    add_devices([PiHoleSensor(hass, rest, name)])
Beispiel #9
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the REST binary sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = config.get(CONF_METHOD)
    payload = config.get(CONF_PAYLOAD)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    headers = config.get(CONF_HEADERS)
    device_class = get_deprecated(config, CONF_DEVICE_CLASS, CONF_SENSOR_CLASS)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    if value_template is not None:
        value_template.hass = hass

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = HTTPDigestAuth(username, password)
        else:
            auth = HTTPBasicAuth(username, password)
    else:
        auth = None

    rest = RestData(method, resource, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch REST data from %s", resource)
        return False

    add_devices([RestBinarySensor(
        hass, rest, name, device_class, value_template)])
Beispiel #10
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the REST binary sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = config.get(CONF_METHOD)
    payload = config.get(CONF_PAYLOAD)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    timeout = config.get(CONF_TIMEOUT)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    headers = config.get(CONF_HEADERS)
    device_class = config.get(CONF_DEVICE_CLASS)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    if value_template is not None:
        value_template.hass = hass

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = HTTPDigestAuth(username, password)
        else:
            auth = HTTPBasicAuth(username, password)
    else:
        auth = None

    rest = RestData(method, resource, auth, headers, payload, verify_ssl,
                    timeout)
    rest.update()
    if rest.data is None:
        raise PlatformNotReady

    # No need to update the sensor now because it will determine its state
    # based in the rest resource that has just been retrieved.
    add_entities([RestBinarySensor(
        hass, rest, name, device_class, value_template)])
Beispiel #11
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the Web scrape sensor."""
    _LOGGER.info('SGNEAWEB loaded')
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    area = config.get(CONF_AREA)

    method = 'GET'
    payload = None
    headers = {
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
    }
    verify_ssl = 0
    auth = None

    try:
        rest = RestData(method, resource, auth, headers, payload, verify_ssl)
        rest.update()
    except (aiohttp.client_exceptions.ClientConnectorError,
            asyncio.TimeoutError):
        _LOGGER.exception('Failed to connect to servers.')
        raise PlatformNotReady
    async_add_entities([NeaSensorWeb(rest, name, area)], True)
Beispiel #12
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the REST binary sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = config.get(CONF_METHOD)
    payload = config.get(CONF_PAYLOAD)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    timeout = config.get(CONF_TIMEOUT)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    headers = config.get(CONF_HEADERS)
    device_class = config.get(CONF_DEVICE_CLASS)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    if value_template is not None:
        value_template.hass = hass

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = HTTPDigestAuth(username, password)
        else:
            auth = HTTPBasicAuth(username, password)
    else:
        auth = None

    rest = RestData(method, resource, auth, headers, payload, verify_ssl,
                    timeout)
    rest.update()
    if rest.data is None:
        raise PlatformNotReady

    # No need to update the sensor now because it will determine its state
    # based in the rest resource that has just been retrieved.
    add_entities(
        [RestBinarySensor(hass, rest, name, device_class, value_template)])
Beispiel #13
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Web scrape sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = 'GET'
    payload = None
    headers = config.get(CONF_HEADERS)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    xpath = config.get(CONF_XPATH)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    if value_template is not None:
        value_template.hass = hass

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = HTTPDigestAuth(username, password)
        else:
            auth = HTTPBasicAuth(username, password)
    else:
        auth = None
    rest = RestData(method, resource, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch data from %s", resource)
        return False

    add_entities([ScrapeSensor(rest, name, xpath, value_template, unit)], True)
Beispiel #14
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Web scrape sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = 'GET'
    payload = headers = None
    verify_ssl = config.get(CONF_VERIFY_SSL)
    select = config.get(CONF_SELECT)
    attr = config.get(CONF_ATTR)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    if value_template is not None:
        value_template.hass = hass

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = HTTPDigestAuth(username, password)
        else:
            auth = HTTPBasicAuth(username, password)
    else:
        auth = None
    rest = RestData(method, resource, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch data from %s", resource)
        return False

    add_entities([
        ScrapeSensor(rest, name, select, attr, value_template, unit)], True)
Beispiel #15
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Web scrape sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = 'GET'
    payload = None
    headers = config.get(CONF_HEADERS)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    select = config.get(CONF_SELECT)
    attr = config.get(CONF_ATTR)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    if value_template is not None:
        value_template.hass = hass

    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = HTTPDigestAuth(username, password)
        else:
            auth = HTTPBasicAuth(username, password)
    else:
        auth = None
    rest = RestData(method, resource, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        raise PlatformNotReady

    add_entities(
        [ScrapeSensor(rest, name, select, attr, value_template, unit)], True)
Beispiel #16
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    name = config.get(CONF_NAME)
    method = 'GET'
    zones = config['zones']
    endpoint = _ENDPOINT + ','.join(zones)
    payload = auth = None
    verify_ssl = DEFAULT_VERIFY_SSL
    headers = {
        'User-Agent': 'Homeassistant',
        'Accept': 'application/geo+json',
    }

    rest = RestData(method, endpoint, auth, headers, payload, verify_ssl)
    rest.update()

    add_entities([NWSAlert(rest, name)], True)
Beispiel #17
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup REST binary sensors."""
    resource = config.get('resource', None)
    method = config.get('method', DEFAULT_METHOD)
    payload = config.get('payload', None)
    verify_ssl = config.get('verify_ssl', True)

    rest = RestData(method, resource, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error('Unable to fetch Rest data')
        return False

    add_devices([RestBinarySensor(
        hass, rest, config.get('name', DEFAULT_NAME),
        config.get(CONF_VALUE_TEMPLATE))])
Beispiel #18
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup REST binary sensors."""
    resource = config.get('resource', None)
    method = config.get('method', DEFAULT_METHOD)
    payload = config.get('payload', None)
    verify_ssl = config.get('verify_ssl', True)

    rest = RestData(method, resource, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error('Unable to fetch Rest data')
        return False

    add_devices([RestBinarySensor(
        hass, rest, config.get('name', DEFAULT_NAME),
        config.get(CONF_VALUE_TEMPLATE))])
Beispiel #19
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the PVOutput sensor."""
    name = config.get(CONF_NAME)
    api_key = config.get(CONF_API_KEY)
    system_id = config.get(CONF_SYSTEM_ID)
    method = "GET"
    payload = auth = None
    verify_ssl = DEFAULT_VERIFY_SSL
    headers = {"X-Pvoutput-Apikey": api_key, "X-Pvoutput-SystemId": system_id}

    rest = RestData(method, _ENDPOINT, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch data from PVOutput")
        return False

    add_devices([PvoutputSensor(rest, name)])
Beispiel #20
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the PVOutput sensor."""
    name = config.get(CONF_NAME)
    sensors = config.get(CONF_SENSORS)
    method = 'GET'
    payload = ''
    auth = ''
    verify_ssl = DEFAULT_VERIFY_SSL
    headers = {}

    rest = RestData(method, _ENDPOINT, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch data from Pollenkollen")
        return False

    for item in sensors:
        add_devices([PollenkollSensor(rest, name, item)], True)
Beispiel #21
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the REST binary sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = config.get(CONF_METHOD)
    payload = config.get(CONF_PAYLOAD)
    verify_ssl = config.get(CONF_VERIFY_SSL)
    sensor_class = config.get(CONF_SENSOR_CLASS)
    value_template = config.get(CONF_VALUE_TEMPLATE)

    rest = RestData(method, resource, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error('Unable to fetch REST data')
        return False

    add_devices([RestBinarySensor(
        hass, rest, name, sensor_class, value_template)])
Beispiel #22
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the REST binary sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = config.get(CONF_METHOD)
    payload = config.get(CONF_PAYLOAD)
    verify_ssl = config.get('verify_ssl', True)
    sensor_class = config.get(CONF_SENSOR_CLASS)
    value_template = config.get(CONF_VALUE_TEMPLATE)

    rest = RestData(method, resource, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error('Unable to fetch REST data')
        return False

    add_devices([RestBinarySensor(
        hass, rest, name, sensor_class, value_template)])
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the PVOutput sensor."""
    name = config.get(CONF_NAME)
    api_key = config.get(CONF_API_KEY)
    system_id = config.get(CONF_SYSTEM_ID)
    method = 'GET'
    payload = auth = None
    verify_ssl = DEFAULT_VERIFY_SSL
    headers = {
        'X-Pvoutput-Apikey': api_key,
        'X-Pvoutput-SystemId': system_id,
    }

    rest = RestData(method, _ENDPOINT, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch data from PVOutput")
        return False

    add_devices([PvoutputSensor(rest, name)], True)
Beispiel #24
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Web scrape sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = 'GET'
    payload = auth = headers = None
    verify_ssl = config.get(CONF_VERIFY_SSL)
    select = config.get(CONF_SELECT)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    if value_template is not None:
        value_template.hass = hass

    rest = RestData(method, resource, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch data from %s", resource)
        return False

    add_devices([ScrapeSensor(hass, rest, name, select, value_template, unit)])
Beispiel #25
0
class WundergroundAPI(object):
    """Get the latest data and update the states."""
    def __init__(self, api_key, pws_id):
        """Initialize the data object."""
        from homeassistant.components.sensor.rest import RestData

        resource = "{}{}&apiKey={}".format(_ENDPOINT, pws_id, api_key)
        self._rest = RestData('GET', resource, None, None, None, False)
        self.data = None
        self.available = True
        self.update()

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Get the latest data from Wunderground."""
        try:
            self._rest.update()
            self.data = json.loads(self._rest.data)
            self.available = True
        except TypeError:
            _LOGGER.error("Unable to fetch data from Wunderground")
            self.available = False
Beispiel #26
0
class PiHoleAPI(object):
    """Get the latest data and update the states."""
    def __init__(self, host, use_ssl, verify_ssl):
        """Initialize the data object."""
        from homeassistant.components.sensor.rest import RestData

        uri_scheme = 'https://' if use_ssl else 'http://'
        resource = "{}{}{}".format(uri_scheme, host, _ENDPOINT)

        self._rest = RestData('GET', resource, None, None, None, verify_ssl)
        self.data = None

        self.update()

    @Throttle(MIN_TIME_BETWEEN_UPDATES)
    def update(self):
        """Get the latest data from the Pi-Hole."""
        try:
            self._rest.update()
            self.data = json.loads(self._rest.data)
        except TypeError:
            _LOGGER.error("Unable to fetch data from Pi-Hole")
 def GetDepartureData(self, stop_code, service_number):
     try:
         departure_resource = "{}{}?key={}&stops={}".format(
             REQUEST_URL, DEPARTURE_BOARD,
             "73367e9efb0028ebed0669c9061fcec2", stop_code)
         departure_rest = RestData('GET', departure_resource, None, None,
                                   None, True)
         departure_rest.update()
         json_string = departure_rest.data
         json_obj = json.loads(json_string)
         ourService = None
         services = json_obj[0]["services"]
         for service in services:
             if service["service_name"] == service_number:
                 ourService = service
                 break
         destination = ourService["departures"][0]["destination"]
         real_time = ourService["departures"][0]["real_time"]
         minutes = ourService["departures"][0]["minutes"]
     except:
         return None
     return destination, real_time, minutes
Beispiel #28
0
class PiHoleAPI(object):
    """Get the latest data and update the states."""

    def __init__(self, host, use_ssl, verify_ssl):
        """Initialize the data object."""
        from homeassistant.components.sensor.rest import RestData

        uri_scheme = 'https://' if use_ssl else 'http://'
        resource = "{}{}{}".format(uri_scheme, host, _ENDPOINT)

        self._rest = RestData('GET', resource, None, None, None, verify_ssl)
        self.data = None

        self.update()

    def update(self):
        """Get the latest data from the Pi-Hole."""
        try:
            self._rest.update()
            self.data = json.loads(self._rest.data)
        except TypeError:
            _LOGGER.error("Unable to fetch data from Pi-Hole")
Beispiel #29
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the REST binary sensor."""
    resource = config.get('resource', None)
    method = config.get('method', DEFAULT_METHOD)
    payload = config.get('payload', None)
    verify_ssl = config.get('verify_ssl', True)

    sensor_class = config.get('sensor_class')
    if sensor_class not in SENSOR_CLASSES:
        _LOGGER.warning('Unknown sensor class: %s', sensor_class)
        sensor_class = None

    rest = RestData(method, resource, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error('Unable to fetch Rest data')
        return False

    add_devices([
        RestBinarySensor(hass, rest, config.get('name', DEFAULT_NAME),
                         sensor_class, config.get(CONF_VALUE_TEMPLATE))
    ])
Beispiel #30
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Web scrape sensor."""
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    method = 'GET'
    payload = auth = headers = None
    verify_ssl = config.get(CONF_VERIFY_SSL)
    select = config.get(CONF_SELECT)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    value_template = config.get(CONF_VALUE_TEMPLATE)
    if value_template is not None:
        value_template.hass = hass

    rest = RestData(method, resource, auth, headers, payload, verify_ssl)
    rest.update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch data from %s", resource)
        return False

    add_devices([
        ScrapeSensor(hass, rest, name, select, value_template, unit)
    ])
Beispiel #31
0
async def async_setup_platform(hass, config, async_add_entities,
                               discovery_info=None):

    """Set up the Web scrape sensor."""
    _LOGGER.info('SGNEAWEB loaded')
    name = config.get(CONF_NAME)
    resource = config.get(CONF_RESOURCE)
    area = config.get(CONF_AREA)

    method = 'GET'
    payload = None
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
    verify_ssl = 0
    auth = None

    try:
        rest = RestData(method, resource, auth, headers, payload, verify_ssl)
        rest.update()
    except (aiohttp.client_exceptions.ClientConnectorError,
            asyncio.TimeoutError):
        _LOGGER.exception('Failed to connect to servers.')
        raise PlatformNotReady
    async_add_entities([NeaSensorWeb(rest, name, area)], True)       
class TautulliAPI(object):
    """Get the latest data and update the states."""
    def __init__(self, host, use_ssl, verify_ssl, token):
        """Initialize the data object."""
        from homeassistant.components.sensor.rest import RestData

        uri_scheme = 'https://' if use_ssl else 'http://'
        resource = "{}{}{}?cmd=get_activity&apikey={}".format(
            uri_scheme, host, _ENDPOINT, token)

        self._rest = RestData('GET', resource, None, None, None, verify_ssl)
        self.data = None
        self.available = True
        self.update()

    def update(self):
        """Get the latest data from the Tautulli."""
        try:
            self._rest.update()
            self.data = json.loads(self._rest.data)
            self.available = True
        except TypeError:
            _LOGGER.error("Unable to fetch data from Tautulli")
            self.available = False
class DwdWeatherWarningsAPI:
    """Get the latest data and update the states."""
    def __init__(self, region_name):
        """Initialize the data object."""
        resource = "{}{}{}?{}".format(
            'https://', 'www.dwd.de',
            '/DWD/warnungen/warnapp_landkreise/json/warnings.json',
            'jsonp=loadWarnings')

        self._rest = RestData('GET', resource, None, None, None, True)
        self.region_name = region_name
        self.region_id = None
        self.region_state = None
        self.data = None
        self.available = True
        self.update()

    @Throttle(SCAN_INTERVAL)
    def update(self):
        """Get the latest data from the DWD-Weather-Warnings."""
        try:
            self._rest.update()

            json_string = self._rest.data[24:len(self._rest.data) - 2]
            json_obj = json.loads(json_string)

            data = {'time': json_obj['time']}

            for mykey, myvalue in {
                    'current': 'warnings',
                    'advance': 'vorabInformation'
            }.items():

                _LOGGER.debug("Found %d %s global DWD warnings",
                              len(json_obj[myvalue]), mykey)

                data['{}_warning_level'.format(mykey)] = 0
                my_warnings = []

                if self.region_id is not None:
                    # get a specific region_id
                    if self.region_id in json_obj[myvalue]:
                        my_warnings = json_obj[myvalue][self.region_id]

                else:
                    # loop through all items to find warnings, region_id
                    # and region_state for region_name
                    for key in json_obj[myvalue]:
                        my_region = json_obj[myvalue][key][0]['regionName']
                        if my_region != self.region_name:
                            continue
                        my_warnings = json_obj[myvalue][key]
                        my_state = json_obj[myvalue][key][0]['stateShort']
                        self.region_id = key
                        self.region_state = my_state
                        break

                # Get max warning level
                maxlevel = data['{}_warning_level'.format(mykey)]
                for event in my_warnings:
                    if event['level'] >= maxlevel:
                        data['{}_warning_level'.format(mykey)] = event['level']

                data['{}_warning_count'.format(mykey)] = len(my_warnings)
                data['{}_warnings'.format(mykey)] = my_warnings

                _LOGGER.debug("Found %d %s local DWD warnings",
                              len(my_warnings), mykey)

            self.data = data
            self.available = True
        except TypeError:
            _LOGGER.error("Unable to fetch data from DWD-Weather-Warnings")
            self.available = False
class DwdWeatherWarningsAPI:
    """Get the latest data and update the states."""

    def __init__(self, region_name):
        """Initialize the data object."""
        resource = "{}{}{}?{}".format(
            'https://',
            'www.dwd.de',
            '/DWD/warnungen/warnapp_landkreise/json/warnings.json',
            'jsonp=loadWarnings'
        )

        self._rest = RestData('GET', resource, None, None, None, True)
        self.region_name = region_name
        self.region_id = None
        self.region_state = None
        self.data = None
        self.available = True
        self.update()

    @Throttle(SCAN_INTERVAL)
    def update(self):
        """Get the latest data from the DWD-Weather-Warnings."""
        try:
            self._rest.update()

            json_string = self._rest.data[24:len(self._rest.data) - 2]
            json_obj = json.loads(json_string)

            data = {'time': json_obj['time']}

            for mykey, myvalue in {
                    'current': 'warnings',
                    'advance': 'vorabInformation'
            }.items():

                _LOGGER.debug("Found %d %s global DWD warnings",
                              len(json_obj[myvalue]), mykey)

                data['{}_warning_level'.format(mykey)] = 0
                my_warnings = []

                if self.region_id is not None:
                    # get a specific region_id
                    if self.region_id in json_obj[myvalue]:
                        my_warnings = json_obj[myvalue][self.region_id]

                else:
                    # loop through all items to find warnings, region_id
                    # and region_state for region_name
                    for key in json_obj[myvalue]:
                        my_region = json_obj[myvalue][key][0]['regionName']
                        if my_region != self.region_name:
                            continue
                        my_warnings = json_obj[myvalue][key]
                        my_state = json_obj[myvalue][key][0]['stateShort']
                        self.region_id = key
                        self.region_state = my_state
                        break

                # Get max warning level
                maxlevel = data['{}_warning_level'.format(mykey)]
                for event in my_warnings:
                    if event['level'] >= maxlevel:
                        data['{}_warning_level'.format(mykey)] = event['level']

                data['{}_warning_count'.format(mykey)] = len(my_warnings)
                data['{}_warnings'.format(mykey)] = my_warnings

                _LOGGER.debug("Found %d %s local DWD warnings",
                              len(my_warnings), mykey)

            self.data = data
            self.available = True
        except TypeError:
            _LOGGER.error("Unable to fetch data from DWD-Weather-Warnings")
            self.available = False