Skip to content

Commit

Permalink
Added sensor translations. Breaking change: entity id's now follow HA…
Browse files Browse the repository at this point in the history
… standard. You may need to update your automations.
  • Loading branch information
MarcoGos committed Jun 25, 2024
1 parent a4840fd commit 4a429fd
Show file tree
Hide file tree
Showing 10 changed files with 390 additions and 224 deletions.
12 changes: 12 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"python.analysis.diagnosticSeverityOverrides": {
"reportMissingTypeStubs": "none",
"reportMissingTypeArgument": "none",
"reportUnknownMemberType": "none"
},
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter"
},
"python.formatting.provider": "black"
}

58 changes: 34 additions & 24 deletions custom_components/kleenex_pollenradar/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,26 @@

from typing import Any

from .api import PollenApi
from .const import DOMAIN, PLATFORMS, CONF_REGION

import logging
from homeassistant.config_entries import ConfigEntry, ConfigType

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.core import Config
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.const import (
CONF_LATITUDE,
CONF_LONGITUDE
)

from .api import PollenApi
from .const import (
DOMAIN,
NAME,
PLATFORMS,
CONF_REGION,
MODEL,
MANUFACTURER
)
from .coordinator import PollenDataUpdateCoordinator

_LOGGER: logging.Logger = logging.getLogger(__package__)
Expand All @@ -29,34 +37,36 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
if hass.data.get(DOMAIN) is None:
hass.data.setdefault(DOMAIN, {})

region = entry.data[CONF_REGION]
latitude = entry.data[CONF_LATITUDE]
longitude = entry.data[CONF_LONGITUDE]

_LOGGER.debug(f"entry.data: {entry.data}")

session = async_get_clientsession(hass)
api = PollenApi(
session=session,
region=entry.data[CONF_REGION],
latitude=entry.data[CONF_LATITUDE],
longitude=entry.data[CONF_LONGITUDE],
region=region,
latitude=latitude,
longitude=longitude,
)

coordinator = PollenDataUpdateCoordinator(hass, api=api)
_LOGGER.debug("Trying to perform async_refresh")
await coordinator.async_refresh()

if not coordinator.last_update_success:
raise ConfigEntryNotReady

_LOGGER.debug(f"Info about entry: {entry.entry_id}")
device_info = DeviceInfo(
entry_type=DeviceEntryType.SERVICE,
identifiers={(DOMAIN, f"{latitude}x{longitude}")},
name=f"{NAME} ({entry.data['name']})",
model=MODEL,
manufacturer=MANUFACTURER,
)

hass.data[DOMAIN][entry.entry_id] = coordinator
hass.data[DOMAIN][entry.entry_id] = coordinator = PollenDataUpdateCoordinator(
hass, api=api, device_info=device_info)

for platform in PLATFORMS:
_LOGGER.debug(f"Adding platform: {platform}")
coordinator.platforms.append(platform)
await coordinator.async_config_entry_first_refresh()

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))

entry.add_update_listener(async_reload_entry)
return True


Expand Down
20 changes: 10 additions & 10 deletions custom_components/kleenex_pollenradar/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,30 +37,30 @@ def __init__(
longitude: float = 0,
) -> None:
self._session = session
self._region = region
self._latitude = latitude
self._longitude = longitude
self.region = region
self.latitude = latitude
self.longitude = longitude

async def async_get_data(self) -> list[dict[str, Any]]:
"""Get data from the API."""
await self.refresh_data()
return self._pollen

async def refresh_data(self):
if self._latitude != 0 and self._longitude != 0:
if self.latitude != 0 and self.longitude != 0:
success = await self.__request_by_latitude_longitude()
if success:
_LOGGER.debug("Trying to __decode_raw_data")
self.__decode_raw_data()
if success:
_LOGGER.debug("Trying to __decode_raw_data")
self.__decode_raw_data()

async def __request_by_latitude_longitude(self) -> bool:
data = {"lat": self._latitude, "lng": self._longitude}
data = {"lat": self.latitude, "lng": self.longitude}
_LOGGER.debug(f"__request_by_latitude_longitude, data={data}")
success = await self.__perform_request(self.__get_url_by_region(), data)
return success

def __get_url_by_region(self) -> str:
return REGIONS[self._region]["url"]
return REGIONS[self.region]["url"]

async def __perform_request(self, url: str, data: Any) -> bool:
_LOGGER.debug(f"Send {data} to {url} with headers {self._headers}")
Expand Down Expand Up @@ -135,4 +135,4 @@ def __determine_pollen_date(self, day_no: int) -> date:

@property
def position(self) -> str:
return f"{self._latitude}x{self._longitude}"
return f"{self.latitude}x{self.longitude}"
13 changes: 10 additions & 3 deletions custom_components/kleenex_pollenradar/coordinator.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from datetime import datetime, timedelta
from homeassistant.helpers.update_coordinator import UpdateFailed, DataUpdateCoordinator
from zoneinfo import ZoneInfo
import logging
from homeassistant.helpers.update_coordinator import UpdateFailed, DataUpdateCoordinator
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.core import HomeAssistant
from .api import PollenApi
from .const import (
Expand All @@ -14,11 +16,16 @@
class PollenDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching data from the API."""

def __init__(self, hass: HomeAssistant, api: PollenApi) -> None:
def __init__(self, hass: HomeAssistant, api: PollenApi, device_info: DeviceInfo) -> None:
"""Initialize."""
self.api = api
self.platforms: list[str] = []
self.last_updated = None
self.device_info = device_info
self._hass = hass
self.latitude = api.latitude
self.longitude = api.longitude
self.region = api.region

super().__init__(
hass,
Expand All @@ -31,7 +38,7 @@ async def _async_update_data(self):
"""Update data via library."""
try:
data = await self.api.async_get_data()
self.last_updated = datetime.now()
self.last_updated = datetime.now().replace(tzinfo=ZoneInfo(self._hass.config.time_zone))
return data
except Exception as exception:
_LOGGER.error(f"Error _async_update_data: {exception}")
Expand Down
2 changes: 1 addition & 1 deletion custom_components/kleenex_pollenradar/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"domain": "kleenex_pollenradar",
"name": "Kleenex Pollen Radar",
"version": "0.0.5",
"version": "1.0.0",
"config_flow": true,
"documentation": "https://github.com/MarcoGos/kleenex_pollenradar",
"requirements": [
Expand Down
Loading

0 comments on commit 4a429fd

Please sign in to comment.