Skip to content

Commit

Permalink
Async functions
Browse files Browse the repository at this point in the history
  • Loading branch information
fwestenberg committed Nov 30, 2023
1 parent 190c4ff commit ec1706e
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 47 deletions.
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
setup(
name = 'stookwijzer',
packages = ['stookwijzer'],
version = '1.4.4',
version = '1.4.5',
license='MIT',
description = 'Stookwijzer package',
long_description_content_type="text/markdown",
Expand Down
32 changes: 21 additions & 11 deletions stookwijzer/example.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
"""Example usage of the Stookwijzer API."""
import sys
import aiohttp
import asyncio
import stookwijzerapi

if __name__ == "__main__":
x, y = stookwijzerapi.Stookwijzer.transform_coordinates(52.123456, 6.123456)
async def main():
session = aiohttp.ClientSession()

x, y = await stookwijzerapi.Stookwijzer.transform_coordinates(session, 52.123456, 6.123456)
print(x)
print(y)

sw = stookwijzerapi.Stookwijzer(x, y)
sw.update()
if x and y:
sw = stookwijzerapi.Stookwijzer(session, x, y)
await sw.update()

print(sw.state)
print(sw.alert)
print(sw.windspeed_bft)
print(sw.windspeed_ms)
print(sw.lki)
print(sw.forecast)

print(sw.state)
print(sw.alert)
print(sw.windspeed_bft)
print(sw.windspeed_ms)
print(sw.lki)
print(sw.forecast)

await session.close()

if __name__ == "__main__":
asyncio.run(main())
83 changes: 48 additions & 35 deletions stookwijzer/stookwijzerapi.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,25 @@
"""The Stookwijze API."""
from datetime import datetime, timedelta
import logging

import aiohttp
import asyncio
import json
import logging
import pytz
import requests

_LOGGER = logging.getLogger(__name__)


class Stookwijzer(object):
"""The Stookwijze API."""

def __init__(self, latitude, longitude):
self._boundary_box = self.get_boundary_box(latitude, longitude)
def __init__(self, session: aiohttp.ClientSession, x: float, y: float):
self._boundary_box = self.get_boundary_box(x, y)
self._state = None
self._alert = None
self._last_updated = None
self._stookwijzer = None

@staticmethod
def transform_coordinates(latitude: float,longitude: float):
"""Transform the coordinates from EPSG:4326 to EPSG:28992."""
url = f"https://epsg.io/srs/transform/{longitude},{latitude}.json?key=default&s_srs=4326&t_srs=28992"

try:
response = requests.get(
url,
timeout=10,
)
coordinates = response.json()

return coordinates["results"][0]["x"],coordinates["results"][0]["y"]

except requests.exceptions.RequestException:
_LOGGER.error("Error requesting coordinate conversion")
return None
except KeyError:
_LOGGER.error("Received invalid response transforming coordinates")
return None
self._session = session

@property
def state(self):
Expand Down Expand Up @@ -86,9 +68,32 @@ def last_updated(self):
"""Get the last updated date."""
return self._last_updated

def update(self):
@staticmethod
async def transform_coordinates(session: aiohttp.ClientSession, latitude: float,longitude: float):
"""Transform the coordinates from EPSG:4326 to EPSG:28992."""
url = f"https://epsg.io/srs/transform/{longitude},{latitude}.json?key=default&s_srs=4326&t_srs=28992"
try:
async with session.get(
url=url, timeout=10
) as response:
response = await response.read()

coordinates = json.loads(response)
return coordinates["results"][0]["x"],coordinates["results"][0]["y"]

except aiohttp.ClientConnectorError:
_LOGGER.error("Error requesting coordinate conversion")
return None, None
except asyncio.TimeoutError:
_LOGGER.error("Timeout requesting coordinate conversion")
return None, None
except KeyError:
_LOGGER.error("Received invalid response transforming coordinates")
return None, None

async def update(self) -> None:
"""Get the stookwijzer data."""
self._stookwijzer = self.get_stookwijzer()
self._stookwijzer = await self.get_stookwijzer()

advice = self.get_property("advies_0")
if advice:
Expand All @@ -104,7 +109,7 @@ def get_forecast_at_offset(self, runtime: datetime, offset: int) -> dict:
"alert": self.get_property("alert_" + str(offset)) == '1',
}

def get_boundary_box(self, x: str, y: str) -> str | None:
def get_boundary_box(self, x: float, y: float) -> str | None:
"""Create a boundary box with the coordinates"""
return (str(x) + "%2C" + str(y) + "%2C" + str(x + 10) + "%2C" + str(y + 10))

Expand All @@ -126,19 +131,27 @@ def get_property(self, prop: str) -> str:
_LOGGER.error("Property %s not available", prop)
return ""

def get_stookwijzer(self):
async def get_stookwijzer(self):
"""Get the stookwijzer data."""
url = (
"https://data.rivm.nl/geo/alo/wms?service=WMS&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetFeatureInfo&FORMAT=application%2Fjson&QUERY_LAYERS=stookwijzer&LAYERS=stookwijzer&servicekey=82b124ad-834d-4c10-8bd0-ee730d5c1cc8&STYLES=&BUFFER=1&info_format=application%2Fjson&feature_count=1&I=1&J=1&WIDTH=1&HEIGHT=1&CRS=EPSG%3A28992&BBOX="
+ self._boundary_box
)

try:
response = requests.get(
url,
timeout=10,
)
return response.json()
async with self._session.get(
url=url, allow_redirects=False, timeout=10
) as response:
response = await response.read()

return json.loads(response)

except requests.exceptions.RequestException:
except aiohttp.ClientConnectorError:
_LOGGER.error("Error getting Stookwijzer data")
return None
except asyncio.TimeoutError:
_LOGGER.error("Timeout getting Stookwijzer data")
return None
except KeyError:
_LOGGER.error("Received invalid response from Stookwijzer")
return None

0 comments on commit ec1706e

Please sign in to comment.