Skip to content

Commit

Permalink
Code cleanup and HACS actions fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
warrior25 committed Jan 26, 2024
1 parent 192f3de commit 5130d5c
Show file tree
Hide file tree
Showing 10 changed files with 79 additions and 42 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from __future__ import annotations

import asyncio

from homeassistant import config_entries, core

from .const import DOMAIN


Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
from typing import Any, Optional

import voluptuous as vol

from homeassistant import config_entries
from .fetch_api import fetch_stop_points, fetch_lines
from homeassistant.helpers.selector import selector
import homeassistant.helpers.config_validation as cv
from homeassistant.core import callback
import voluptuous as vol
import logging
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.selector import selector

from .const import (
CONF_STATION,
CONF_LINES,
CONF_MAX,
DEFAULT_MAX,
CONF_STATION,
CONF_TIMELIMIT,
DEFAULT_MAX,
DEFAULT_TIMELIMIT,
CONF_LINES,
DOMAIN,
)
from .fetch_api import fetch_lines, fetch_stop_points


@config_entries.HANDLERS.register(DOMAIN)
Expand Down Expand Up @@ -73,7 +74,7 @@ async def async_step_options(self, user_input: Optional[dict[str, Any]] = None):

lines = await fetch_lines(self.data[CONF_STATION])
options_schema = {
vol.Required(CONF_LINES): cv.multi_select(lines),
vol.Required(CONF_LINES, default=lines): cv.multi_select(lines),
vol.Optional(CONF_TIMELIMIT, default=DEFAULT_TIMELIMIT): selector(
{
"number": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@
EXPECTED_DEPARTURE_TIME = "expectedDepartureTime"


NYSSE_STOP_URL = "https://data.itsfactory.fi/journeys/api/1/stop-monitoring?stops={0}"
NYSSE_STOP_POINTS_URL = "https://data.itsfactory.fi/journeys/api/1/stop-points/"
NYSSE_JOURNEYS_URL = "https://data.itsfactory.fi/journeys/api/1/journeys?stopPointId={0}&dayTypes={1}&startIndex={2}"
NYSSE_LINES_URL = "https://data.itsfactory.fi/journeys/api/1/lines?stopPointId={0}"
STOP_URL = "https://data.itsfactory.fi/journeys/api/1/stop-monitoring?stops={0}"
STOP_POINTS_URL = "https://data.itsfactory.fi/journeys/api/1/stop-points/"
JOURNEYS_URL = "https://data.itsfactory.fi/journeys/api/1/journeys?stopPointId={0}&dayTypes={1}&startIndex={2}"
LINES_URL = "https://data.itsfactory.fi/journeys/api/1/lines?stopPointId={0}"
SERVICE_ALERTS_URL = (
"https://data.itsfactory.fi/journeys/api/1/gtfs-rt/service-alerts/json"
)
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
from .network import get
from .const import NYSSE_STOP_POINTS_URL, NYSSE_LINES_URL
import logging
import json
import logging

from .const import LINES_URL, STOP_POINTS_URL
from .network import get

_LOGGER = logging.getLogger(__name__)


async def fetch_stop_points(has_id):
"""Fetches stop point names"""
"""Fetch stop point names."""
if not has_id:
stations = {}
else:
stations = []
try:
result = await get(NYSSE_STOP_POINTS_URL)
result = await get(STOP_POINTS_URL)
if not result:
_LOGGER.error("Could not fetch stop points")
return
Expand All @@ -28,30 +29,29 @@ async def fetch_stop_points(has_id):
stations[stop["shortName"]] = stop["name"]

if not has_id:
stations = dict(sorted(stations.items(), key=lambda item: item[1]))
else:
stations = sorted(stations, key=lambda item: item["label"])
return stations
return dict(sorted(stations.items(), key=lambda item: item[1]))

return sorted(stations, key=lambda item: item["label"])

except OSError as err:
except (OSError, KeyError) as err:
_LOGGER.error("Failed to fetch stops: %s", err)
return


async def fetch_lines(stop):
"""Fetches stop point names"""
"""Fetch line point names."""
lines = []
try:
lines_url = NYSSE_LINES_URL.format(stop)
lines_url = LINES_URL.format(stop)
result = await get(lines_url)
if not result:
_LOGGER.error("Could not fetch lines points")
_LOGGER.error("Could not fetch lines")
return
result = json.loads(result)
for line in result["body"]:
lines.append(line["name"])
return lines

except OSError as err:
except (OSError, KeyError) as err:
_LOGGER.error("Failed to fetch lines: %s", err)
return
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import logging

import aiohttp

REQUEST_TIMEOUT = 30
_LOGGER = logging.getLogger(__name__)


async def get(url):
"""Http GET helper."""
timeout = aiohttp.ClientTimeout(total=REQUEST_TIMEOUT)
async with aiohttp.ClientSession(timeout=timeout) as session:
try:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,37 @@
"""Platform for sensor integration."""
from __future__ import annotations
import logging

from datetime import datetime, timedelta
import json
from datetime import timedelta, datetime
import pytz
import logging

from dateutil import parser

from homeassistant import config_entries, core
from homeassistant.components.sensor import SensorEntity
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .network import get
import homeassistant.util.dt as dt_util

from .const import (
AIMED_ARRIVAL_TIME,
AIMED_DEPARTURE_TIME,
DEFAULT_ICON,
DEFAULT_MAX,
DEFAULT_TIMELIMIT,
DEPARTURE,
EXPECTED_ARRIVAL_TIME,
EXPECTED_DEPARTURE_TIME,
JOURNEY,
JOURNEYS_URL,
PLATFORM_NAME,
STOP_URL,
TRAM_LINES,
WEEKDAYS,
)
from .fetch_api import fetch_stop_points
from .const import *
from .network import get

_LOGGER = logging.getLogger(__name__)
# Changing this also affects
SCAN_INTERVAL = timedelta(seconds=30)
PAGE_SIZE = 100

Expand All @@ -23,8 +41,7 @@ async def async_setup_entry(
config_entry: config_entries.ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Setup sensors from a config entry created in the integrations UI."""

"""Setups sensors from a config entry created in the integrations UI."""
sensors = []
if "station" in config_entry.options:
sensors.append(
Expand Down Expand Up @@ -61,7 +78,6 @@ class NysseSensor(SensorEntity):

def __init__(self, stop_code, maximum, timelimit, lines, time_zone) -> None:
"""Initialize the sensor."""

self._unique_id = PLATFORM_NAME + "_" + stop_code
self.stop_code = stop_code
self.max_items = int(maximum)
Expand All @@ -74,17 +90,19 @@ def __init__(self, stop_code, maximum, timelimit, lines, time_zone) -> None:

self._current_weekday_int = -1
self._last_update_time = None
self._time_zone = pytz.timezone(time_zone)
self._time_zone = dt_util.get_time_zone(time_zone)

self._fetch_fail_counter = 0
self._fetch_pause_counter = 0

async def fetch_stops(self, force=False):
"""Fetch stops if not fetched already."""
if len(self._stops) == 0 or force:
_LOGGER.debug("Fetching stops")
self._stops = await fetch_stop_points(False)

def remove_unwanted_data(self, departures, journeys):
"""Remove stale and unwanted data."""
removed_journey_count = 0
removed_departures_count = 0

Expand Down Expand Up @@ -137,7 +155,8 @@ def remove_unwanted_data(self, departures, journeys):
return departures, journeys

async def fetch_departures(self):
url = NYSSE_STOP_URL.format(self.stop_code)
"""Fetch live stop monitoring data."""
url = STOP_URL.format(self.stop_code)
_LOGGER.debug(
"%s: Fectching departures from %s",
self.stop_code,
Expand All @@ -155,13 +174,14 @@ async def fetch_departures(self):
return self.format_departures(unformatted_departures)

async def fetch_journeys(self):
"""Fetch static timetable data."""
journeys = []

async def fetch_data_for_weekday(weekday_index):
journeys_index = 0
weekday_string = WEEKDAYS[weekday_index]
while True:
url = NYSSE_JOURNEYS_URL.format(
url = JOURNEYS_URL.format(
self.stop_code, weekday_string, journeys_index
)
_LOGGER.debug(
Expand Down Expand Up @@ -200,6 +220,7 @@ async def fetch_data_for_weekday(weekday_index):
return journeys

def format_departures(self, departures):
"""Format live stop monitoring data."""
try:
body = departures["body"][self.stop_code]
formatted_data = []
Expand Down Expand Up @@ -227,6 +248,7 @@ def format_departures(self, departures):
return []

def format_journeys(self, journeys, weekday):
"""Format static timetable data."""
formatted_data = []

if weekday == self._current_weekday_int:
Expand Down Expand Up @@ -263,6 +285,7 @@ def format_journeys(self, journeys, weekday):
def get_departure_time(
self, item, item_type, delta=timedelta(seconds=0), time_type=""
):
"""Calculate departure time."""
try:
if item_type == DEPARTURE:
if time_type != "":
Expand Down Expand Up @@ -352,6 +375,7 @@ async def async_update(self) -> None:
_LOGGER.error("%s: Failed to update sensor: %s", self.stop_code, err)

def combine_data(self, departures, journeys):
"""Combine live and static data."""
combined_data = departures[: self.max_items]
i = 0
while len(combined_data) < self.max_items:
Expand All @@ -367,6 +391,7 @@ def combine_data(self, departures, journeys):
return self.data_to_display_format(combined_data)

def data_to_display_format(self, data):
"""Format data to be displayed in sensor attributes."""
formatted_data = []
for item in data:
departure = {
Expand All @@ -381,23 +406,25 @@ def data_to_display_format(self, data):
return formatted_data

def get_line_icon(self, line_no):
if line_no in (TRAM_LINES):
"""Get line icon based on operating vehicle type."""
if line_no in TRAM_LINES:
return "mdi:tram"
return "mdi:bus"

def time_to_station(self, item):
"""Get time until departure"""
"""Get time until departure."""
next_departure_time = (item["departureTime"] - self._last_update_time).seconds
return int(next_departure_time / 60)

@property
def unique_id(self) -> str:
"""Unique id for the sensor."""
return self._unique_id

@property
def name(self) -> str:
"""Return the name of the sensor."""
return "{0} ({1})".format(self._stops[self.stop_code], self.stop_code)
return f"{self._stops[self.stop_code]} ({self.stop_code})"

@property
def icon(self) -> str:
Expand All @@ -413,6 +440,7 @@ def state(self) -> str:

@property
def extra_state_attributes(self):
"""Sensor attributes."""
attributes = {
"last_refresh": self._last_update_time,
"departures": self._all_data,
Expand Down
File renamed without changes.

0 comments on commit 5130d5c

Please sign in to comment.