|
| 1 | +""" |
| 2 | +Copyright (c) 2017 Fabian Affolter <fabian@affolter-engineering.ch> |
| 3 | +
|
| 4 | +Licensed under MIT. All rights reserved. |
| 5 | +""" |
| 6 | +import asyncio |
| 7 | +import logging |
| 8 | + |
| 9 | +import aiohttp |
| 10 | +import async_timeout |
| 11 | + |
| 12 | +from . import exceptions |
| 13 | + |
| 14 | +_LOGGER = logging.getLogger(__name__) |
| 15 | +_RESOURCE = 'https://api.luftdaten.info/v1' |
| 16 | + |
| 17 | +VOLUME_MICROGRAMS_PER_CUBIC_METER = 'µg/m3' |
| 18 | + |
| 19 | +SENSOR_TEMPERATURE = 'temperature' |
| 20 | +SENSOR_HUMIDITY = 'humidity' |
| 21 | +SENSOR_PM10 = 'P1' |
| 22 | +SENSOR_PM2_5 = 'P2' |
| 23 | + |
| 24 | +SENSOR_TYPES = { |
| 25 | + SENSOR_TEMPERATURE: ['Temperature', '°C'], |
| 26 | + SENSOR_HUMIDITY: ['Humidity', '%'], |
| 27 | + SENSOR_PM10: ['PM10', VOLUME_MICROGRAMS_PER_CUBIC_METER], |
| 28 | + SENSOR_PM2_5: ['PM2.5', VOLUME_MICROGRAMS_PER_CUBIC_METER] |
| 29 | +} |
| 30 | + |
| 31 | + |
| 32 | +class Luftdaten(object): |
| 33 | + """A class for handling connections from Luftdaten.info.""" |
| 34 | + |
| 35 | + def __init__(self, sensor_id, loop, session): |
| 36 | + """Initialize the connection.""" |
| 37 | + self._loop = loop |
| 38 | + self._session = session |
| 39 | + self.sensor_id = sensor_id |
| 40 | + self.data = None |
| 41 | + self.values = { |
| 42 | + 'humidity': None, |
| 43 | + 'P1': None, |
| 44 | + 'P2': None, |
| 45 | + 'pressure': None, |
| 46 | + 'temperature': None, |
| 47 | + } |
| 48 | + self.meta = {} |
| 49 | + |
| 50 | + @asyncio.coroutine |
| 51 | + def async_get_data(self): |
| 52 | + url = '{}/{}/{}/'.format(_RESOURCE, 'sensor', self.sensor_id) |
| 53 | + |
| 54 | + try: |
| 55 | + with async_timeout.timeout(5, loop=self._loop): |
| 56 | + response = yield from self._session.get(url) |
| 57 | + |
| 58 | + _LOGGER.debug( |
| 59 | + "Response from luftdaten.info: %s", response.status) |
| 60 | + data = yield from response.json() |
| 61 | + _LOGGER.debug(data) |
| 62 | + except (asyncio.TimeoutError, aiohttp.ClientError): |
| 63 | + _LOGGER.error("Can not load data from luftdaten.info") |
| 64 | + raise exceptions.LuftdatenConnectionError() |
| 65 | + |
| 66 | + try: |
| 67 | + self.data = data |
| 68 | + |
| 69 | + for sensor_data in self.data: |
| 70 | + entry = sensor_data['sensordatavalues'][0] |
| 71 | + for measurement in self.values.keys(): |
| 72 | + if measurement == entry['value_type']: |
| 73 | + self.values[measurement] = float(entry['value']) |
| 74 | + |
| 75 | + self.meta['sensor_id'] = self.sensor_id |
| 76 | + self.meta['longitude'] = float(data[-1]['location']['longitude']) |
| 77 | + self.meta['latitude'] = float(data[-1]['location']['latitude']) |
| 78 | + |
| 79 | + except (TypeError, IndexError): |
| 80 | + raise exceptions.LuftdatenError() |
0 commit comments