Skip to content

Commit

Permalink
Possible fix for not receiving any data (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
JohNan authored Feb 11, 2024
1 parent fa248d3 commit 7cf3b29
Show file tree
Hide file tree
Showing 6 changed files with 32 additions and 39 deletions.
14 changes: 6 additions & 8 deletions custom_components/pollenprognos/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@
import logging
from datetime import timedelta, datetime

from .api import PollenApi
from .const import DOMAIN, PLATFORMS, CONF_URL
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, Config
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import UpdateFailed, DataUpdateCoordinator
from .api import PollenApi
from .const import DOMAIN, PLATFORMS, CONF_URL

SCAN_INTERVAL = timedelta(hours=4)

Expand All @@ -21,8 +20,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
if hass.data.get(DOMAIN) is None:
hass.data.setdefault(DOMAIN, {})

session = async_get_clientsession(hass)
client = PollenApi(session, entry.data[CONF_URL])
client = PollenApi(hass, entry.data[CONF_URL])

coordinator = PollenprognosDataUpdateCoordinator(hass, client=client)
await coordinator.async_refresh()
Expand All @@ -47,7 +45,7 @@ class PollenprognosDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching data from the API."""

def __init__(
self, hass: HomeAssistant, client: PollenApi
self, hass: HomeAssistant, client: PollenApi
) -> None:
"""Initialize."""
self.api = client
Expand Down Expand Up @@ -87,4 +85,4 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Reload config entry."""
await async_unload_entry(hass, entry)
await async_setup_entry(hass, entry)
await async_setup_entry(hass, entry)
16 changes: 10 additions & 6 deletions custom_components/pollenprognos/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import aiohttp
import async_timeout

from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession

TIMEOUT = 10

_LOGGER: logging.Logger = logging.getLogger(__package__)
Expand All @@ -16,8 +19,8 @@


class PollenApi:
def __init__(self, session: aiohttp.ClientSession, url) -> None:
self._session = session
def __init__(self, hass: HomeAssistant, url) -> None:
self._hass = hass
self._url = url

async def async_get_data(self) -> dict:
Expand All @@ -29,19 +32,20 @@ async def api_wrapper(
) -> dict:
"""Get information from the API."""
try:
session = async_get_clientsession(self._hass)
async with async_timeout.timeout(TIMEOUT):
if method == "get":
response = await self._session.get(url, headers=headers)
response = await session.get(url, headers=headers)
return await response.json()

elif method == "put":
await self._session.put(url, headers=headers, json=data)
await session.put(url, headers=headers, json=data)

elif method == "patch":
await self._session.patch(url, headers=headers, json=data)
await session.patch(url, headers=headers, json=data)

elif method == "post":
await self._session.post(url, headers=headers, json=data)
await session.post(url, headers=headers, json=data)

except asyncio.TimeoutError as exception:
_LOGGER.error(
Expand Down
14 changes: 6 additions & 8 deletions custom_components/pollenprognos/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import logging

import homeassistant.helpers.config_validation as cv
import voluptuous as vol

from .api import PollenApi
import homeassistant.helpers.config_validation as cv
from homeassistant import config_entries
from .api import PollenApi
from .const import DOMAIN, CONF_ALLERGENS, CONF_NAME, CONF_CITY, CONF_URL
from homeassistant.helpers.aiohttp_client import async_create_clientsession

_LOGGER: logging.Logger = logging.getLogger(__package__)

Expand Down Expand Up @@ -71,10 +70,10 @@ async def async_step_select_city(self, user_input=None):
if user_input is not None:
self._init_info[CONF_CITY] = user_input[CONF_CITY]
self._init_info[CONF_NAME] = next(item for item in self.data.get('cities', []).get('cities', []) if
item["id"] == self._init_info[CONF_CITY])['name']
item["id"] == self._init_info[CONF_CITY])['name']
return await self.async_step_select_pollen()

cities = {city['id']: city['name'] for city in self.data.get('cities', []).get('cities', []) }
cities = {city['id']: city['name'] for city in self.data.get('cities', []).get('cities', [])}
return self.async_show_form(
step_id="select_city",
data_schema=vol.Schema(
Expand Down Expand Up @@ -106,11 +105,10 @@ async def async_step_select_pollen(self, user_input=None):

async def _async_task_fetch_cities(self, url):
try:
session = async_create_clientsession(self.hass)
client = PollenApi(session, url)
client = PollenApi(self.hass, url)
self.data = await client.async_get_data()
_LOGGER.debug("Fetched data: %s", self.data)
finally:
self.hass.async_create_task(
self.hass.config_entries.flow.async_configure(flow_id=self.flow_id)
)
)
3 changes: 2 additions & 1 deletion custom_components/pollenprognos/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,6 @@ def add_state_attributes(self):
"""Return the state attributes."""
return {
"update_success": self.coordinator.last_update_success,
"last_updated": self.coordinator.last_updated.strftime("%Y-%m-%d %H:%M:%S") if self.coordinator.last_updated else None
"last_updated": self.coordinator.last_updated.strftime(
"%Y-%m-%d %H:%M:%S") if self.coordinator.last_updated else None
}
20 changes: 6 additions & 14 deletions custom_components/pollenprognos/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,24 @@
"""

import logging
import json

from collections import namedtuple
from datetime import timedelta
from typing import Any

import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.components.sensor import ENTITY_ID_FORMAT

from dateutil import parser
from datetime import datetime
from .const import VERSION, DOMAIN, SENSOR_ICONS, CONF_CITY, CONF_ALLERGENS, CONF_NAME
from .const import DOMAIN, SENSOR_ICONS, CONF_CITY, CONF_ALLERGENS, CONF_NAME
from .entity import PollenEntity

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass, entry, async_add_devices):
"""Setup sensor platform."""
coordinator = hass.data[DOMAIN][entry.entry_id]
if not coordinator.data:
return False

city = next(item for item in coordinator.data.get('cities', []).get('cities', []) if item["id"] == entry.data[CONF_CITY])
allergens = {pollen['type_code']: pollen['type'] for pollen in city.get('pollen', []) if pollen['type_code'] in entry.data[CONF_ALLERGENS]}
city = next(
item for item in coordinator.data.get('cities', []).get('cities', []) if item["id"] == entry.data[CONF_CITY])
allergens = {pollen['type_code']: pollen['type'] for pollen in city.get('pollen', []) if
pollen['type_code'] in entry.data[CONF_ALLERGENS]}
async_add_devices([
PollenSensor(name, allergen, coordinator, entry)
for (allergen, name) in allergens.items()
Expand Down
4 changes: 2 additions & 2 deletions manage/update_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ def update_manifest():
manifest["version"] = version

with open(
f"{os.getcwd()}/custom_components/pollenprognos/manifest.json", "w"
f"{os.getcwd()}/custom_components/pollenprognos/manifest.json", "w"
) as manifestfile:
manifestfile.write(json.dumps(manifest, indent=4, sort_keys=True))


update_manifest()
update_manifest()

0 comments on commit 7cf3b29

Please sign in to comment.