Example #1
0
    def __init__(self, hass, session, api_key, latitude, longitude, update_interval):
        """Initialize."""
        self.latitude = latitude
        self.longitude = longitude
        self.airly = Airly(api_key, session)

        super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)
Example #2
0
class AirlyDataUpdateCoordinator(DataUpdateCoordinator):
    """Define an object to hold Airly data."""

    def __init__(
        self,
        hass,
        session,
        api_key,
        latitude,
        longitude,
        update_interval,
        use_nearest,
    ):
        """Initialize."""
        self.latitude = latitude
        self.longitude = longitude
        self.airly = Airly(api_key, session)
        self.use_nearest = use_nearest

        super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)

    async def _async_update_data(self):
        """Update data via library."""
        data = {}
        if self.use_nearest:
            measurements = self.airly.create_measurements_session_nearest(
                self.latitude, self.longitude, max_distance_km=5
            )
        else:
            measurements = self.airly.create_measurements_session_point(
                self.latitude, self.longitude
            )
        with async_timeout.timeout(20):
            try:
                await measurements.update()
            except (AirlyError, ClientConnectorError) as error:
                raise UpdateFailed(error) from error

        _LOGGER.debug(
            "Requests remaining: %s/%s",
            self.airly.requests_remaining,
            self.airly.requests_per_day,
        )

        values = measurements.current["values"]
        index = measurements.current["indexes"][0]
        standards = measurements.current["standards"]

        if index["description"] == NO_AIRLY_SENSORS:
            raise UpdateFailed("Can't retrieve data: no Airly sensors in this area")
        for value in values:
            data[value["name"]] = value["value"]
        for standard in standards:
            data[f"{standard['pollutant']}_LIMIT"] = standard["limit"]
            data[f"{standard['pollutant']}_PERCENT"] = standard["percent"]
        data[ATTR_API_CAQI] = index["value"]
        data[ATTR_API_CAQI_LEVEL] = index["level"].lower().replace("_", " ")
        data[ATTR_API_CAQI_DESCRIPTION] = index["description"]
        data[ATTR_API_ADVICE] = index["advice"]
        return data
Example #3
0
    def __init__(self, session, api_key, latitude, longitude, language, **kwargs):
        """Initialize."""
        self.latitude = latitude
        self.longitude = longitude
        self.language = language
        self.airly = Airly(api_key, session, language=self.language)
        self.data = {}

        self.async_update = Throttle(kwargs[CONF_SCAN_INTERVAL])(self._async_update)
    async def _test_api_key(self, client, api_key):
        """Return true if api_key is valid."""

        with async_timeout.timeout(10):
            airly = Airly(api_key, client)
            measurements = airly.create_measurements_session_point(
                latitude=52.24131, longitude=20.99101)
            try:
                await measurements.update()
            except AirlyError:
                return False
            return True
    async def _test_location(self, client, api_key, latitude, longitude):
        """Return true if location is valid."""

        with async_timeout.timeout(10):
            airly = Airly(api_key, client)
            measurements = airly.create_measurements_session_point(
                latitude=latitude, longitude=longitude)

            await measurements.update()
        current = measurements.current
        if current["indexes"][0]["description"] == NO_AIRLY_SENSORS:
            return False
        return True
Example #6
0
async def main():
    pyairly_logger = logging.getLogger('pyairly')
    pyairly_logger.setLevel(logging.DEBUG)
    pyairly_logger.addHandler(logging.StreamHandler(sys.stdout))
    async with aiohttp.ClientSession() as http_session:
        airly = Airly(API_KEY, http_session)

        print('Installation %d:' % INSTALLATION_ID)
        sys.stdout.flush()
        installation = await airly.load_installation_by_id(INSTALLATION_ID)
        sys.stdout.flush()
        print("{}, {}.\n{}: {}".format(installation.address.displayAddress1,
                                       installation.address.displayAddress2,
                                       installation.sponsor.description,
                                       installation.sponsor.name))

        print('\nInstallations {:.2f} km apart from latitude {:f} and '
              'longitude {:f}:\n'.format(MAX_DIST_KM, LATITUDE, LONGITUDE))
        sys.stdout.flush()
        installations_list = await airly.load_installation_nearest(
            LATITUDE, LONGITUDE, max_distance_km=MAX_DIST_KM, max_results=-1)
        sys.stdout.flush()
        for i in installations_list:
            print("{}, {}.\n{}: {}\n".format(i.address.displayAddress1,
                                             i.address.displayAddress2,
                                             i.sponsor.description,
                                             i.sponsor.name))
Example #7
0
    def __init__(
        self,
        hass: HomeAssistant,
        session: ClientSession,
        api_key: str,
        latitude: float,
        longitude: float,
        update_interval: timedelta,
        use_nearest: bool,
    ) -> None:
        """Initialize."""
        self.latitude = latitude
        self.longitude = longitude
        self.airly = Airly(api_key, session)
        self.use_nearest = use_nearest

        super().__init__(hass,
                         _LOGGER,
                         name=DOMAIN,
                         update_interval=update_interval)
Example #8
0
async def test_location(client,
                        api_key,
                        latitude,
                        longitude,
                        use_nearest=False):
    """Return true if location is valid."""
    airly = Airly(api_key, client)
    if use_nearest:
        measurements = airly.create_measurements_session_nearest(
            latitude=latitude, longitude=longitude, max_distance_km=5)
    else:
        measurements = airly.create_measurements_session_point(
            latitude=latitude, longitude=longitude)
    with async_timeout.timeout(10):
        await measurements.update()

    current = measurements.current

    if current["indexes"][0]["description"] == NO_AIRLY_SENSORS["en"]:
        return False
    return True
Example #9
0
async def main():
    pyairly_logger = logging.getLogger('pyairly')
    pyairly_logger.setLevel(logging.DEBUG)
    pyairly_logger.addHandler(logging.StreamHandler(sys.stdout))
    async with aiohttp.ClientSession() as http_session:
        airly = Airly(API_KEY, http_session)
        measurements_clients = OrderedDict([
            ('for nearest installation',
             airly.create_measurements_session_nearest(LATITUDE, LONGITUDE)),
        ])

        for description, client in measurements_clients.items():
            print()
            sys.stdout.flush()
            await client.update()
            sys.stdout.flush()
            current = client.current
            print("Measurements %s:" % description)
            for m in Measurement.MEASUREMENTS_TYPES:
                #print("%s: %s" % (m, current.values.get(m)))
                weather_dict.append((m, current.values.get(m)))
Example #10
0
    def __init__(
        self,
        hass,
        session,
        api_key,
        latitude,
        longitude,
        language,
        scan_interval,
        use_nearest,
    ):
        """Initialize."""
        self.airly = Airly(api_key, session, language=language)
        self.language = language
        self.latitude = latitude
        self.longitude = longitude
        self.use_nearest = use_nearest

        super().__init__(hass,
                         _LOGGER,
                         name=DOMAIN,
                         update_interval=scan_interval)
Example #11
0
class AirlyData:
    """Define an object to hold Airly data."""
    def __init__(self, session, api_key, latitude, longitude):
        """Initialize."""
        self.latitude = latitude
        self.longitude = longitude
        self.airly = Airly(api_key, session)
        self.data = {}

    @Throttle(DEFAULT_SCAN_INTERVAL)
    async def async_update(self):
        """Update Airly data."""

        try:
            with async_timeout.timeout(10):
                measurements = self.airly.create_measurements_session_point(
                    self.latitude, self.longitude)
                await measurements.update()

            values = measurements.current["values"]
            index = measurements.current["indexes"][0]
            standards = measurements.current["standards"]

            if index["description"] == NO_AIRLY_SENSORS:
                _LOGGER.error(
                    "Can't retrieve data: no Airly sensors in this area")
                return
            for value in values:
                self.data[value["name"]] = value["value"]
            for standard in standards:
                self.data[f"{standard['pollutant']}_LIMIT"] = standard["limit"]
                self.data[f"{standard['pollutant']}_PERCENT"] = standard[
                    "percent"]
            self.data[ATTR_API_CAQI] = index["value"]
            self.data[ATTR_API_CAQI_LEVEL] = index["level"].lower().replace(
                "_", " ")
            self.data[ATTR_API_CAQI_DESCRIPTION] = index["description"]
            self.data[ATTR_API_ADVICE] = index["advice"]
            _LOGGER.debug("Data retrieved from Airly")
        except (
                ValueError,
                AirlyError,
                asyncio.TimeoutError,
                ClientConnectorError,
        ) as error:
            _LOGGER.error(error)
            self.data = {}
Example #12
0
class AirlyDataUpdateCoordinator(DataUpdateCoordinator):
    """Class to manage fetching Airly data API."""

    def __init__(
        self, hass, session, api_key, latitude, longitude, language, scan_interval
    ):
        """Initialize."""
        self.airly = Airly(api_key, session, language=language)
        self.language = language
        self.latitude = latitude
        self.longitude = longitude

        super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=scan_interval)

    async def _async_update_data(self):
        """Update data via library."""
        data = {}
        with timeout(20):
            measurements = self.airly.create_measurements_session_point(
                self.latitude, self.longitude
            )
            try:
                await measurements.update()
            except (AirlyError, ClientConnectorError) as error:
                raise UpdateFailed(error) from error

        values = measurements.current["values"]
        index = measurements.current["indexes"][0]
        standards = measurements.current["standards"]

        if index["description"] == NO_AIRLY_SENSORS:
            raise UpdateFailed("Can't retrieve data: no Airly sensors in this area")
        for value in values:
            data[value["name"]] = value["value"]
        for standard in standards:
            data[f"{standard['pollutant']}_LIMIT"] = standard["limit"]
            data[f"{standard['pollutant']}_PERCENT"] = standard["percent"]
        data[ATTR_CAQI] = index["value"]
        data[ATTR_CAQI_LEVEL] = index["level"].lower().replace("_", " ")
        data[ATTR_CAQI_DESCRIPTION] = index["description"]
        data[ATTR_CAQI_ADVICE] = index["advice"]
        return data
Example #13
0
 def __init__(self, session, api_key, latitude, longitude):
     """Initialize."""
     self.latitude = latitude
     self.longitude = longitude
     self.airly = Airly(api_key, session)
     self.data = {}
Example #14
0
if __name__ == '__main__':
    if not os.path.exists('/mnt/OpenShare/weather/'):
        with open(f'{os.path.dirname(os.path.realpath(__file__))}/.bot_token',
                  'r') as token_file:
            TOKEN, CHAT_ID = token_file.readline().split('|')
            send_text = f'https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id={CHAT_ID}&text=OpenShareDOWN'
            response = requests.get(send_text)
            sys.exit(0)

    Krakow = [466, 232]
    url = f"http://www.meteo.pl/um/metco/mgram_pict.php?ntype=0u&" \
          f"row={Krakow[0]}&" \
          f"col={Krakow[1]}&" \
          f"lang=pl"
    output = "/mnt/OpenShare/weather/weather-script-output.png"
    airly = Airly()
    airly.fill_template()
    airly.plot_caqi_history()

    while True:
        try:
            urllib.request.urlretrieve(url, output)
            img = Image.open(output)
            img = img.convert("RGB")
        except [SyntaxError, OSError, ContentTooShortError]:
            print("\nDownload failed... retry in 15 seconds.\n")
            sleep(15)
            continue
        break

    img = crop(img)