Beispiel #1
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Scrape from a config entry."""

    resource: str = entry.options[CONF_RESOURCE]
    method: str = "GET"
    payload: str | None = None
    headers: str | None = entry.options.get(CONF_HEADERS)
    verify_ssl: bool = entry.options[CONF_VERIFY_SSL]
    username: str | None = entry.options.get(CONF_USERNAME)
    password: str | None = entry.options.get(CONF_PASSWORD)

    auth: httpx.DigestAuth | tuple[str, str] | None = None
    if username and password:
        if entry.options.get(
                CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = httpx.DigestAuth(username, password)
        else:
            auth = (username, password)

    rest = RestData(hass, method, resource, auth, headers, None, payload,
                    verify_ssl)
    await rest.async_update()

    if rest.data is None:
        raise ConfigEntryNotReady

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = rest

    entry.async_on_unload(entry.add_update_listener(async_update_listener))

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Beispiel #2
0
async def async_setup_platform(hass, config, async_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)
    index = config.get(CONF_INDEX)
    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)
    await rest.async_update()

    if rest.data is None:
        raise PlatformNotReady

    async_add_entities(
        [ScrapeSensor(rest, name, select, attr, index, value_template, unit)], True
    )
 def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry):
     """Initialize the Feed Entity Manager."""
     self._hass = hass
     self._config_entry = config_entry
     self._district_name = config_entry.data[CONF_DISTRICT_NAME]
     self._config_entry_id = config_entry.entry_id
     self._scan_interval = timedelta(
         seconds=config_entry.data[CONF_SCAN_INTERVAL])
     self._track_time_remove_callback = None
     if MAJOR_VERSION >= 1 or MINOR_VERSION >= 119:
         self._rest = RestData(DEFAULT_METHOD, URL, None, None, None, None,
                               DEFAULT_VERIFY_SSL)
     else:
         self._rest = RestData(DEFAULT_METHOD, URL, None, None, None,
                               DEFAULT_VERIFY_SSL)
     self._attributes = None
Beispiel #4
0
async def add_sensors(hass,
                      config,
                      async_add_devices,
                      name,
                      location,
                      discovery_info=None):
    method = "GET"
    payload = ""
    auth = None
    verify_ssl = DEFAULT_VERIFY_SSL
    headers = {}
    params = {}
    timeout = 5000
    endpoint = _ENDPOINT + location
    rest = RestData(hass, method, endpoint, auth, headers, payload, params,
                    verify_ssl, timeout)
    await rest.async_update()

    if rest.data is None:
        _LOGGER.error("Unable to fetch data from Sjöfartsverket")
        return False
    _LOGGER.debug("rest.data: %s", rest.data)
    restData = json.loads(rest.data)
    sensors = []
    location = restData["GetSingleStationResult"]["Name"]
    for data in restData["GetSingleStationResult"]["Samples"]:
        sensors.append(entityRepresentation(rest, name, location, data))
    async_add_devices(sensors, True)
Beispiel #5
0
 def updateRestData(self):
     # changed to async, update deprecated
     # RestData.update(self)
     try:
         asyncio.run_coroutine_threadsafe(RestData.async_update(self),
                                          self._hass.loop).result(5)
         self._lastUpdate = datetime.now()
     except Exception as e:
         _LOGGER.warning("updateRestData exception %s", e)
Beispiel #6
0
async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the Web scrape sensor."""
    name: str = config[CONF_NAME]
    resource: str = config[CONF_RESOURCE]
    method: str = "GET"
    payload: str | None = None
    headers: str | None = config.get(CONF_HEADERS)
    verify_ssl: bool = config[CONF_VERIFY_SSL]
    select: str | None = config.get(CONF_SELECT)
    attr: str | None = config.get(CONF_ATTR)
    index: int = config[CONF_INDEX]
    unit: str | None = config.get(CONF_UNIT_OF_MEASUREMENT)
    device_class: str | None = config.get(CONF_DEVICE_CLASS)
    state_class: str | None = config.get(CONF_STATE_CLASS)
    username: str | None = config.get(CONF_USERNAME)
    password: str | None = config.get(CONF_PASSWORD)
    value_template: Template | None = config.get(CONF_VALUE_TEMPLATE)

    if value_template is not None:
        value_template.hass = hass

    auth: httpx.DigestAuth | tuple[str, str] | None = None
    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = httpx.DigestAuth(username, password)
        else:
            auth = (username, password)

    rest = RestData(hass, method, resource, auth, headers, None, payload,
                    verify_ssl)
    await rest.async_update()

    if rest.data is None:
        raise PlatformNotReady

    async_add_entities(
        [
            ScrapeSensor(
                rest,
                name,
                select,
                attr,
                index,
                value_template,
                unit,
                device_class,
                state_class,
            )
        ],
        True,
    )
Beispiel #7
0
    def __init__(
        self,
        hass,
        method,
        resource,
        auth,
        headers,
        data,
        verify_ssl=False,
        httptimeout=5,
        cacheTimeout=20,
    ):
        RestData.__init__(self, hass, method, resource, auth, headers, None,
                          data, verify_ssl, httptimeout)

        self._lastUpdate = None
        self._cacheTimeout = cacheTimeout
        self._hass = hass
        self._isUpdating = False
Beispiel #8
0
    async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None):
        """Invoked when a user initiates a flow via the user interface."""
        _LOGGER.debug(f"async_step_user({user_input})")
        errors: Dict[str, str] = {}
        if user_input is not None:
            try:
                _LOGGER.debug("user_input not None")
                if user_input[CONF_NAME] in configured_instances(self.hass, CONF_NAME):
                    raise ConfigFlowException("name_exists")
                if user_input[CONF_WALLET] in configured_instances(
                    self.hass, CONF_WALLET
                ):
                    raise ConfigFlowException("wallet_exists")

                resource = (
                    "https://web.xmrpool.eu:8119/stats_address?address="
                    + user_input[CONF_WALLET]
                )
                rest = RestData(
                    self.hass,
                    "GET",
                    resource,
                    auth=None,
                    headers=None,
                    params=None,
                    data=None,
                    verify_ssl=True,
                )
                await rest.async_update()
                if rest.data is None:
                    raise ConfigFlowException("no_answer")
                data = json.loads(rest.data)
                if "error" in data.keys():
                    _LOGGER.debug("Invalid answer: %s", data["error"])
                    raise ConfigFlowException("invalid_answer")
            except ConfigFlowException as ex:
                _LOGGER.warning("Configuration error: %s", ex.error)
                errors["base"] = ex.error
            except:
                _LOGGER.warning("Unexpected exception")
                errors["base"] = "unknown_exception"
                raise
            if not errors:
                # Input is valid, set data.
                self.data = user_input
                return self.async_create_entry(
                    title=user_input[CONF_NAME], data=self.data
                )

        _LOGGER.debug("Show input form...")
        return self.async_show_form(
            step_id="user", data_schema=AUTH_SCHEMA, errors=errors
        )
 def __init__(self, hass):
     self.hass = hass
     self.rest = RestData(
         self.hass,
         DEFAULT_METHOD,
         self.URL,
         None,
         None,
         None,
         None,
         DEFAULT_VERIFY_SSL,
     )
     self._data = None
Beispiel #10
0
 def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
     """Initialize the Feed Entity Manager."""
     self.hass = hass
     self._district_name = config_entry.data[CONF_DISTRICT_NAME]
     self._rest = RestData(hass, DEFAULT_METHOD, URL_DATA, None, None, None,
                           None, DEFAULT_VERIFY_SSL)
     super().__init__(
         self.hass,
         _LOGGER,
         name=DOMAIN,
         update_method=self.async_update,
         update_interval=timedelta(
             seconds=config_entry.data[CONF_SCAN_INTERVAL]),
     )
Beispiel #11
0
async def async_setup_platform(hass, config, async_add_entities, 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, None, payload, verify_ssl)
    await rest.async_update()

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

    async_add_entities([PvoutputSensor(rest, name)], True)
Beispiel #12
0
 def __init__(self, hass: HomeAssistant,
              config_entry: config_entries.ConfigEntry) -> None:
     """Initialize controller"""
     self._lock = asyncio.Lock()
     self._hass = hass
     self._name: str = config_entry.data[CONF_NAME]
     self._scheduledUpdateCallback = None
     resource = ("https://web.xmrpool.eu:8119/stats_address?address=" +
                 config_entry.data[CONF_WALLET])
     self._rest = RestData(
         self._hass,
         "GET",
         resource,
         auth=None,
         headers=None,
         params=None,
         data=None,
         verify_ssl=True,
     )
     self._statData: Dict[str, Any] = None
     self._workersData: Dict[str, Dict[str, Any]] = None
     self.listeners = []
     self.entity_id = config_entry.entry_id
Beispiel #13
0
    state_class = config.get(CONF_STATE_CLASS)
    username = config.get(CONF_USERNAME)
    password = config.get(CONF_PASSWORD)

    if (value_template := config.get(CONF_VALUE_TEMPLATE)) is not None:
        value_template.hass = hass

    auth: httpx.DigestAuth | tuple[str, str] | None
    if username and password:
        if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION:
            auth = httpx.DigestAuth(username, password)
        else:
            auth = (username, password)
    else:
        auth = None
    rest = RestData(hass, method, resource, auth, headers, None, payload,
                    verify_ssl)
    await rest.async_update()

    if rest.data is None:
        raise PlatformNotReady

    async_add_entities(
        [
            ScrapeSensor(
                rest,
                name,
                select,
                attr,
                index,
                value_template,
                unit,