Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions custom_components/postnl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> True:
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up PostNL from config entry."""
_LOGGER.debug("Setup Entry PostNL")

Expand All @@ -40,8 +40,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> True:
'auth': auth
}

_LOGGER.debug('Using access token: %s', auth.access_token)

postnl_login_api = PostNLLoginAPI(auth.access_token)

try:
Expand Down Expand Up @@ -88,7 +86,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> True:

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload PostNL config entry."""
_LOGGER.debug('Reloading PostNL integration')
_LOGGER.debug('Unloading PostNL integration')
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

if unload_ok:
Expand Down Expand Up @@ -126,7 +124,7 @@ async def check_and_refresh_token(self) -> str:

except (ClientResponseError, ClientError) as exception:
_LOGGER.debug("API error: %s", exception)
if exception.status == 400:
if isinstance(exception, ClientResponseError) and exception.status == 400:
self.oauth_session.config_entry.async_start_reauth(
self.oauth_session.hass
)
Expand Down
4 changes: 3 additions & 1 deletion custom_components/postnl/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from datetime import timedelta

import requests
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import (DataUpdateCoordinator,
UpdateFailed)
Expand All @@ -19,14 +20,15 @@ class PostNLCoordinator(DataUpdateCoordinator):
graphq_api: PostNLGraphql
jouw_api: PostNLJouwAPI

def __init__(self, hass: HomeAssistant) -> None:
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize PostNL coordinator."""
super().__init__(
hass,
_LOGGER,
name="PostNL",
update_interval=timedelta(seconds=90),
)
self.config_entry = entry
_LOGGER.debug("PostNLCoordinator initialized with update interval: %s", self.update_interval)

async def _async_update_data(self) -> dict[str, list[Package]]:
Expand Down
4 changes: 2 additions & 2 deletions custom_components/postnl/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
"integration_type": "hub",
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/arjenbos/ha-postnl/issues",
"requirements": ["gql"],
"version": "2.1.1"
"requirements": ["gql", "requests"],
"version": "2.2.0"
}
33 changes: 16 additions & 17 deletions custom_components/postnl/sensor.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""Sensor for PostNL packages."""
import logging

from homeassistant.components.sensor import SensorEntity, SensorStateClass
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.helpers.entity_registry import async_get as async_get_entity_registry

Expand All @@ -19,7 +19,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
"""Set up the PostNL sensor platform."""
_LOGGER.debug("Setting up PostNL sensors")

coordinator = PostNLCoordinator(hass)
coordinator = PostNLCoordinator(hass, entry)
await coordinator.async_config_entry_first_refresh()

userinfo = hass.data[DOMAIN][entry.entry_id].get("userinfo", {})
Expand All @@ -46,7 +46,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
])
_LOGGER.debug("PostNL sensors added")

class PostNLDelivery(CoordinatorEntity, Entity):
class PostNLDelivery(CoordinatorEntity, SensorEntity):
_attr_icon = "mdi:package-variant-closed"
_attr_native_unit_of_measurement = "packages"
_attr_state_class = SensorStateClass.MEASUREMENT

def __init__(self, coordinator, postnl_userinfo, unique_id, name, receiver: bool = True):
"""Initialize the PostNL sensor."""
super().__init__(coordinator, context=name)
Expand Down Expand Up @@ -75,6 +79,8 @@ def device_info(self) -> DeviceInfo:
},
name=self.postnl_userinfo.get('email'),
manufacturer="PostNL",
entry_type=DeviceEntryType.SERVICE,
configuration_url="https://jouw.postnl.nl",
)

@property
Expand All @@ -83,25 +89,15 @@ def name(self) -> str:
return self._name

@property
def state(self):
def native_value(self):
"""Return the state of the sensor."""
return self._state

@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return 'packages'

@property
def extra_state_attributes(self):
"""Return the state attributes."""
return self._attributes

@property
def icon(self):
"""Icon to use in the frontend."""
return "mdi:package-variant-closed"

@callback
def _handle_coordinator_update(self) -> None:
_LOGGER.debug('Updating sensor %s', self.name)
Expand All @@ -114,10 +110,13 @@ def handle_coordinator_data(self):
self._attributes['delivered'] = []
self._attributes['enroute'] = []

if not self.coordinator.data:
return

if self.receiver:
coordinator_data = self.coordinator.data['receiver']
coordinator_data = self.coordinator.data.get('receiver', [])
else:
coordinator_data = self.coordinator.data['sender']
coordinator_data = self.coordinator.data.get('sender', [])

for package in coordinator_data:
if package.delivered:
Expand Down