Skip to content

Commit 3724065

Browse files
committed
Refactor sensor check
1 parent e974862 commit 3724065

File tree

2 files changed

+25
-9
lines changed

2 files changed

+25
-9
lines changed

example.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,22 @@
99

1010
from luftdaten import Luftdaten
1111

12+
SENSOR_ID = 155
13+
1214

1315
async def main():
1416
"""Sample code to retrieve the data."""
1517
async with aiohttp.ClientSession() as session:
16-
data = Luftdaten(155, loop, session)
17-
await data.get_data()
18+
data = Luftdaten(SENSOR_ID, loop, session)
19+
20+
valid = await data.validate_sensor(SENSOR_ID)
1821

19-
if not data.valid_sensor:
22+
if not valid:
2023
print("Station is not available:", data.sensor_id)
2124
return
2225

26+
await data.get_data()
27+
2328
if data.values and data.meta:
2429
# Print the sensor values
2530
print("Sensor values:", data.values)

luftdaten/__init__.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,14 @@ def __init__(self, sensor_id, loop, session):
3131
'temperature': None,
3232
}
3333
self.meta = {}
34+
self.url = '{}/{}'.format(_RESOURCE, 'sensor')
3435

3536
async def get_data(self):
3637
"""Retrieve the data."""
37-
url = '{}/{}/{}/'.format(_RESOURCE, 'sensor', self.sensor_id)
38-
3938
try:
4039
with async_timeout.timeout(5, loop=self._loop):
41-
response = await self._session.get(url)
40+
response = await self._session.get(
41+
'{}/{}/'.format(self.url, self.sensor_id))
4242

4343
_LOGGER.debug(
4444
"Response from luftdaten.info: %s", response.status)
@@ -69,7 +69,18 @@ async def get_data(self):
6969
except (TypeError, IndexError):
7070
raise exceptions.LuftdatenError()
7171

72-
@property
73-
def valid_sensor(self):
72+
async def validate_sensor(self, sensor_id):
7473
"""Return True if the sensor ID is valid."""
75-
return True if self.values else False
74+
try:
75+
with async_timeout.timeout(5, loop=self._loop):
76+
response = await self._session.get(
77+
'{}/{}/'.format(self.url, sensor_id))
78+
79+
_LOGGER.debug(
80+
"Response from luftdaten.info: %s", response.status)
81+
data = await response.json()
82+
except (asyncio.TimeoutError, aiohttp.ClientError):
83+
_LOGGER.error("Can not load data from luftdaten.info")
84+
raise exceptions.LuftdatenConnectionError()
85+
86+
return True if data else False

0 commit comments

Comments
 (0)