Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
21 changes: 12 additions & 9 deletions homeassistant/components/trafikverket_ferry/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util.dt import UTC, as_utc, parse_time
from homeassistant.util import dt

from .const import CONF_FROM, CONF_TIME, CONF_TO, DOMAIN

Expand Down Expand Up @@ -58,21 +58,23 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
)
self._from: str = entry.data[CONF_FROM]
self._to: str = entry.data[CONF_TO]
self._time: time | None = parse_time(entry.data[CONF_TIME])
self._time: time | None = dt.parse_time(entry.data[CONF_TIME])
self._weekdays: list[str] = entry.data[CONF_WEEKDAY]

async def _async_update_data(self) -> dict[str, Any]:
"""Fetch data from Trafikverket."""

departure_day = next_departuredate(self._weekdays)
currenttime = datetime.now()
current_time = dt.now(dt.get_time_zone(self.hass.config.time_zone))
Comment thread
gjohansson-ST marked this conversation as resolved.
Outdated
when = (
datetime.combine(departure_day, self._time)
datetime.combine(
departure_day, self._time, dt.get_time_zone(self.hass.config.time_zone)
)
if self._time
else datetime.now()
else datetime.now(dt.get_time_zone(self.hass.config.time_zone))
Comment thread
gjohansson-ST marked this conversation as resolved.
Outdated
)
if currenttime > when:
when = currenttime
if current_time > when:
when = current_time

try:
routedata: FerryStop = await self._ferry_api.async_get_next_ferry_stop(
Expand All @@ -84,10 +86,11 @@ async def _async_update_data(self) -> dict[str, Any]:
) from error

states = {
"departure_time": routedata.departure_time.replace(tzinfo=UTC),
"departure_time": routedata.departure_time,
"departure_from": routedata.from_harbor_name,
"departure_to": routedata.to_harbor_name,
"departure_modified": as_utc(routedata.modified_time.replace(tzinfo=UTC)),
"departure_modified": routedata.modified_time,
"departure_information": routedata.other_information,
}
_LOGGER.debug("States: %s", states)
return states
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"domain": "trafikverket_ferry",
"name": "Trafikverket Ferry",
"documentation": "https://www.home-assistant.io/integrations/trafikverket_ferry",
"requirements": ["pytrafikverket==0.1.6.2"],
"requirements": ["pytrafikverket==0.2.0.1"],
"codeowners": ["@gjohansson-ST"],
"config_flow": true,
"iot_class": "cloud_polling",
Expand Down
15 changes: 7 additions & 8 deletions homeassistant/components/trafikverket_ferry/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@

from collections.abc import Callable
from dataclasses import dataclass
from datetime import timedelta
import logging
from datetime import datetime, timedelta
from typing import Any

from homeassistant.components.sensor import (
Expand All @@ -20,12 +19,11 @@
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util.dt import as_utc

from .const import ATTRIBUTION, DOMAIN
from .coordinator import TVDataUpdateCoordinator

_LOGGER = logging.getLogger(__name__)

ATTR_FROM = "from_harbour"
ATTR_TO = "to_harbour"
ATTR_MODIFIED_TIME = "modified_time"
Expand All @@ -39,7 +37,7 @@
class TrafikverketRequiredKeysMixin:
"""Mixin for required keys."""

value_fn: Callable[[dict[str, Any]], StateType]
value_fn: Callable[[dict[str, Any]], StateType | datetime]
info_fn: Callable[[dict[str, Any]], StateType | list]


Expand All @@ -56,7 +54,7 @@ class TrafikverketSensorEntityDescription(
name="Departure Time",
icon="mdi:clock",
device_class=SensorDeviceClass.TIMESTAMP,
value_fn=lambda data: data["departure_time"],
value_fn=lambda data: as_utc(data["departure_time"]),
info_fn=lambda data: data["departure_information"],
),
TrafikverketSensorEntityDescription(
Expand All @@ -78,7 +76,7 @@ class TrafikverketSensorEntityDescription(
name="Departure Modified",
icon="mdi:clock",
device_class=SensorDeviceClass.TIMESTAMP,
value_fn=lambda data: data["departure_modified"],
value_fn=lambda data: as_utc(data["departure_modified"]),
info_fn=lambda data: data["departure_information"],
entity_registry_enabled_default=False,
),
Expand Down Expand Up @@ -122,7 +120,7 @@ def __init__(
entry_type=DeviceEntryType.SERVICE,
identifiers={(DOMAIN, entry_id)},
manufacturer="Trafikverket",
model="v1.2",
model="v2.0",
name=name,
configuration_url="https://api.trafikinfo.trafikverket.se/",
)
Expand All @@ -133,6 +131,7 @@ def _update_attr(self) -> None:
self._attr_native_value = self.entity_description.value_fn(
self.coordinator.data
)

self._attr_extra_state_attributes = {
"other_information": self.entity_description.info_fn(self.coordinator.data),
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"domain": "trafikverket_train",
"name": "Trafikverket Train",
"documentation": "https://www.home-assistant.io/integrations/trafikverket_train",
"requirements": ["pytrafikverket==0.1.6.2"],
"requirements": ["pytrafikverket==0.2.0.1"],
"codeowners": ["@endor-force", "@gjohansson-ST"],
"config_flow": true,
"iot_class": "cloud_polling",
Expand Down
23 changes: 8 additions & 15 deletions homeassistant/components/trafikverket_train/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@

ICON = "mdi:train"
SCAN_INTERVAL = timedelta(minutes=5)
STOCKHOLM_TIMEZONE = get_time_zone("Europe/Stockholm")

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
Expand Down Expand Up @@ -153,7 +152,7 @@ def next_departuredate(departure: list[str]) -> date:

def _to_iso_format(traintime: datetime) -> str:
"""Return isoformatted utc time."""
return as_utc(traintime.replace(tzinfo=STOCKHOLM_TIMEZONE)).isoformat()
return as_utc(traintime).isoformat()


class TrainSensor(SensorEntity):
Expand Down Expand Up @@ -183,7 +182,7 @@ def __init__(
entry_type=DeviceEntryType.SERVICE,
identifiers={(DOMAIN, entry_id)},
manufacturer="Trafikverket",
model="v1.2",
model="v2.0",
name=name,
configuration_url="https://api.trafikinfo.trafikverket.se/",
)
Expand All @@ -193,12 +192,12 @@ def __init__(

async def async_update(self) -> None:
"""Retrieve latest state."""
when = datetime.now()
when = datetime.now(get_time_zone(self.hass.config.time_zone))
Comment thread
gjohansson-ST marked this conversation as resolved.
Outdated
_state: TrainStop | None = None
if self._time:
departure_day = next_departuredate(self._weekday)
when = datetime.combine(departure_day, self._time).replace(
tzinfo=STOCKHOLM_TIMEZONE
when = datetime.combine(
departure_day, self._time, get_time_zone(self.hass.config.time_zone)
)
try:
if self._time:
Expand All @@ -222,17 +221,11 @@ async def async_update(self) -> None:
self._attr_available = True

# The original datetime doesn't provide a timezone so therefore attaching it here.
self._attr_native_value = _state.advertised_time_at_location.replace(
tzinfo=STOCKHOLM_TIMEZONE
)
self._attr_native_value = as_utc(_state.advertised_time_at_location)
if _state.time_at_location:
self._attr_native_value = _state.time_at_location.replace(
tzinfo=STOCKHOLM_TIMEZONE
)
self._attr_native_value = as_utc(_state.time_at_location)
if _state.estimated_time_at_location:
self._attr_native_value = _state.estimated_time_at_location.replace(
tzinfo=STOCKHOLM_TIMEZONE
)
self._attr_native_value = as_utc(_state.estimated_time_at_location)

self._update_attributes(_state)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"domain": "trafikverket_weatherstation",
"name": "Trafikverket Weather Station",
"documentation": "https://www.home-assistant.io/integrations/trafikverket_weatherstation",
"requirements": ["pytrafikverket==0.1.6.2"],
"requirements": ["pytrafikverket==0.2.0.1"],
"codeowners": ["@endor-force", "@gjohansson-ST"],
"config_flow": true,
"iot_class": "cloud_polling",
Expand Down
10 changes: 4 additions & 6 deletions homeassistant/components/trafikverket_weatherstation/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,11 @@
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util.dt import as_utc, get_time_zone
from homeassistant.util.dt import as_utc

from .const import ATTRIBUTION, CONF_STATION, DOMAIN, NONE_IS_ZERO_SENSORS
from .coordinator import TVDataUpdateCoordinator

STOCKHOLM_TIMEZONE = get_time_zone("Europe/Stockholm")


@dataclass
class TrafikverketRequiredKeysMixin:
Expand Down Expand Up @@ -156,8 +154,8 @@ async def async_setup_entry(

def _to_datetime(measuretime: str) -> datetime:
"""Return isoformatted utc time."""
time_obj = datetime.strptime(measuretime, "%Y-%m-%dT%H:%M:%S")
return as_utc(time_obj.replace(tzinfo=STOCKHOLM_TIMEZONE))
time_obj = datetime.strptime(measuretime, "%Y-%m-%dT%H:%M:%S.%f%z")
return as_utc(time_obj)


class TrafikverketWeatherStation(
Expand All @@ -184,7 +182,7 @@ def __init__(
entry_type=DeviceEntryType.SERVICE,
identifiers={(DOMAIN, entry_id)},
manufacturer="Trafikverket",
model="v1.2",
model="v2.0",
name=sensor_station,
configuration_url="https://api.trafikinfo.trafikverket.se/",
)
Expand Down
2 changes: 1 addition & 1 deletion requirements_all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1978,7 +1978,7 @@ pytradfri[async]==9.0.0
# homeassistant.components.trafikverket_ferry
# homeassistant.components.trafikverket_train
# homeassistant.components.trafikverket_weatherstation
pytrafikverket==0.1.6.2
pytrafikverket==0.2.0.1

# homeassistant.components.usb
pyudev==0.22.0
Expand Down
2 changes: 1 addition & 1 deletion requirements_test_all.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1301,7 +1301,7 @@ pytradfri[async]==9.0.0
# homeassistant.components.trafikverket_ferry
# homeassistant.components.trafikverket_train
# homeassistant.components.trafikverket_weatherstation
pytrafikverket==0.1.6.2
pytrafikverket==0.2.0.1

# homeassistant.components.usb
pyudev==0.22.0
Expand Down