Skip to content

Commit

Permalink
Ensured entities are being updated once added.
Browse files Browse the repository at this point in the history
  • Loading branch information
jampez77 committed Sep 23, 2024
1 parent b99d7ea commit 935fc94
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 67 deletions.
45 changes: 22 additions & 23 deletions custom_components/premierinn/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,39 @@

from datetime import timedelta
import logging
from homeassistant.const import CONTENT_TYPE_JSON
from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator,
UpdateFailed,
)

import aiohttp

from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import (
DOMAIN,
HOST,
BOOKING_CONF_POST_BODY,
CONF_ARRIVAL_DATE,
CONF_ARRIVALDATE,
CONF_BASKET_REFERENCE,
CONF_BOOKING_CONFIRMATION,
CONF_COUNTRY,
CONF_DATA,
CONF_DE,
CONF_FIND_BOOKING,
CONF_FIND_BOOKING_CRITERIA,
CONF_GB,
CONF_GERMANY,
CONF_HOTEL_ID,
CONF_HOTEL_INFORMATION,
CONF_LAST_NAME,
CONF_LASTNAME,
CONF_POST,
CONF_RES_NO,
CONF_RESNO,
CONF_VARIABLES,
DOMAIN,
FIND_BOOKING_POST_BODY,
BOOKING_CONF_POST_BODY,
HOST,
HOTEL_INFORMATION_POST_BODY,
REQUEST_HEADER,
CONF_VARIABLES,
CONF_FIND_BOOKING,
CONF_FIND_BOOKING_CRITERIA,
CONF_DATA,
CONF_POST,
CONF_BASKET_REFERENCE,
CONF_BOOKING_CONFIRMATION,
CONF_HOTEL_INFORMATION,
CONF_HOTEL_ID,
CONF_COUNTRY,
CONF_GERMANY,
CONF_GB,
CONF_DE,
)

_LOGGER = logging.getLogger(__name__)
Expand Down
2 changes: 1 addition & 1 deletion custom_components/premierinn/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@
"issue_tracker": "https://github.com/jampez77/PremierInn/issues",
"requirements": ["beautifulsoup4==4.12.3"],
"ssdp": [],
"version": "2024.9.4",
"version": "2024.9.5",
"zeroconf": []
}
122 changes: 79 additions & 43 deletions custom_components/premierinn/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
SensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
Expand Down Expand Up @@ -133,6 +133,83 @@ def __init__(
self.entity_id = f"sensor.{DOMAIN}_{name}_{description.key}".lower()
self.attrs: dict[str, Any] = {}
self.entity_description = description
self.name = name
self._state = None

def update_from_coordinator(self):
"""Update sensor state and attributes from coordinator data."""
room_stay = self.data.get(CONF_BOOKING_CONFIRMATION)["reservationByIdList"][0][
"roomStay"
]

check_out_time = f"{room_stay['departureDate']}T{room_stay['checkOutTime']}:00"

if hasBookingExpired(self.hass, check_out_time):
self.hass.async_add_job(removeBooking(self.hass, self.name))
else:
value = self.data.get(self.entity_description.key)

if self.entity_description.key == "roomStay":
room_stay = self.data.get(CONF_BOOKING_CONFIRMATION)[
"reservationByIdList"
][0]["roomStay"]

value = room_stay["roomExtraInfo"]["roomName"]

if self.entity_description.key == "hotelInformation":
value = self.data.get(CONF_HOTEL_INFORMATION)["name"]

if self.entity_description.device_class == SensorDeviceClass.TIMESTAMP:
room_stay = self.data.get(CONF_BOOKING_CONFIRMATION)[
"reservationByIdList"
][0]["roomStay"]

if self.entity_description.key == "checkInTime":
value = f"{room_stay['arrivalDate']}T{room_stay['checkInTime']}:00"
elif self.entity_description.key == "checkOutTime":
value = (
f"{room_stay['departureDate']}T{room_stay['checkOutTime']}:00"
)

user_timezone = dt_util.get_time_zone(self.hass.config.time_zone)

dt_utc = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S").replace(
tzinfo=user_timezone
)
# Convert the datetime to the default timezone
value = dt_utc.astimezone(user_timezone)

self._state = value

if self.entity_description.key == "roomStay":
value = self.data.get(CONF_BOOKING_CONFIRMATION)
else:
value = self.data.get(self.entity_description.key)

if isinstance(value, (dict, list)):
for index, attribute in enumerate(value):
if isinstance(attribute, (dict, list)):
for attr in attribute:
self.attrs[str(attr) + str(index)] = attribute[attr]
else:
self.attrs[attribute] = value[attribute]

@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
self.update_from_coordinator()
self.async_write_ha_state()

async def async_added_to_hass(self) -> None:
"""Handle adding to Home Assistant."""
await super().async_added_to_hass()
await self.async_update()

async def async_remove(self) -> None:
"""Handle the removal of the entity."""
# If you have any specific cleanup logic, add it here
if self.hass is not None:
await super().async_remove()

@property
def available(self) -> bool:
Expand All @@ -142,50 +219,9 @@ def available(self) -> bool:
@property
def native_value(self) -> str | date | None:
"""Native value."""
value = self.data.get(self.entity_description.key)

if self.entity_description.key == "roomStay":
room_stay = self.data.get(CONF_BOOKING_CONFIRMATION)["reservationByIdList"][
0
]["roomStay"]

value = room_stay["roomExtraInfo"]["roomName"]

if self.entity_description.key == "hotelInformation":
value = self.data.get(CONF_HOTEL_INFORMATION)["name"]

if self.entity_description.device_class == SensorDeviceClass.TIMESTAMP:
room_stay = self.data.get(CONF_BOOKING_CONFIRMATION)["reservationByIdList"][
0
]["roomStay"]

if self.entity_description.key == "checkInTime":
value = f"{room_stay['arrivalDate']}T{room_stay['checkInTime']}:00"
elif self.entity_description.key == "checkOutTime":
value = f"{room_stay['departureDate']}T{room_stay['checkOutTime']}:00"

user_timezone = dt_util.get_time_zone(self.hass.config.time_zone)

dt_utc = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S").replace(
tzinfo=user_timezone
)
# Convert the datetime to the default timezone
value = dt_utc.astimezone(user_timezone)
return value
return self._state

@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Define entity attributes."""
if self.entity_description.key == "roomStay":
value = self.data.get(CONF_BOOKING_CONFIRMATION)
else:
value = self.data.get(self.entity_description.key)
if isinstance(value, (dict, list)):
for index, attribute in enumerate(value):
if isinstance(attribute, (dict, list)):
for attr in attribute:
self.attrs[str(attr) + str(index)] = attribute[attr]
else:
self.attrs[attribute] = value[attribute]

return self.attrs

0 comments on commit 935fc94

Please sign in to comment.