Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move tankerkoenig to new aiotankerkoenig package #108913

Merged
merged 4 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 2 additions & 2 deletions CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -1330,8 +1330,8 @@ build.json @home-assistant/supervisor
/tests/components/tailwind/ @frenck
/homeassistant/components/tami4/ @Guy293
/tests/components/tami4/ @Guy293
/homeassistant/components/tankerkoenig/ @guillempages @mib1185
/tests/components/tankerkoenig/ @guillempages @mib1185
/homeassistant/components/tankerkoenig/ @guillempages @mib1185 @jpbede
/tests/components/tankerkoenig/ @guillempages @mib1185 @jpbede
/homeassistant/components/tapsaff/ @bazwilliams
/homeassistant/components/tasmota/ @emontnemery
/tests/components/tasmota/ @emontnemery
Expand Down
27 changes: 5 additions & 22 deletions homeassistant/components/tankerkoenig/__init__.py
Original file line number Diff line number Diff line change
@@ -1,48 +1,31 @@
"""Ask tankerkoenig.de for petrol price information."""
from __future__ import annotations

import logging

from requests.exceptions import RequestException

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
import homeassistant.helpers.config_validation as cv

from .const import DEFAULT_SCAN_INTERVAL, DOMAIN
from .coordinator import TankerkoenigDataUpdateCoordinator

_LOGGER = logging.getLogger(__name__)


PLATFORMS = [Platform.BINARY_SENSOR, Platform.SENSOR]

CONFIG_SCHEMA = cv.removed(DOMAIN, raise_if_present=False)
jpbede marked this conversation as resolved.
Show resolved Hide resolved


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set a tankerkoenig configuration entry up."""
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator = TankerkoenigDataUpdateCoordinator(

coordinator = TankerkoenigDataUpdateCoordinator(
hass,
entry,
_LOGGER,
name=entry.unique_id or DOMAIN,
update_interval=DEFAULT_SCAN_INTERVAL,
)

try:
setup_ok = await hass.async_add_executor_job(coordinator.setup)
except RequestException as err:
raise ConfigEntryNotReady from err
if not setup_ok:
_LOGGER.error("Could not setup integration")
return False

await coordinator.async_setup()
await coordinator.async_config_entry_first_refresh()

hass.data[DOMAIN][entry.entry_id] = coordinator

entry.async_on_unload(entry.add_update_listener(_async_update_listener))

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
Expand Down
33 changes: 14 additions & 19 deletions homeassistant/components/tankerkoenig/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

import logging

from aiotankerkoenig import PriceInfo, Station, Status

from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
Expand All @@ -23,21 +25,15 @@ async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the tankerkoenig binary sensors."""

coordinator: TankerkoenigDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]

stations = coordinator.stations.values()
entities = []
for station in stations:
sensor = StationOpenBinarySensorEntity(
async_add_entities(
StationOpenBinarySensorEntity(
station,
coordinator,
coordinator.show_on_map,
)
entities.append(sensor)
_LOGGER.debug("Added sensors %s", entities)

async_add_entities(entities)
for station in coordinator.stations.values()
)


class StationOpenBinarySensorEntity(TankerkoenigCoordinatorEntity, BinarySensorEntity):
Expand All @@ -48,22 +44,21 @@ class StationOpenBinarySensorEntity(TankerkoenigCoordinatorEntity, BinarySensorE

def __init__(
self,
station: dict,
station: Station,
coordinator: TankerkoenigDataUpdateCoordinator,
show_on_map: bool,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator, station)
self._station_id = station["id"]
self._attr_unique_id = f"{station['id']}_status"
if show_on_map:
self._station_id = station.id
self._attr_unique_id = f"{station.id}_status"
if coordinator.show_on_map:
self._attr_extra_state_attributes = {
ATTR_LATITUDE: station["lat"],
ATTR_LONGITUDE: station["lng"],
ATTR_LATITUDE: station.lat,
ATTR_LONGITUDE: station.lng,
}

@property
def is_on(self) -> bool | None:
"""Return true if the station is open."""
data: dict = self.coordinator.data[self._station_id]
return data is not None and data.get("status") == "open"
data: PriceInfo = self.coordinator.data[self._station_id]
return data is not None and data.status == Status.OPEN
89 changes: 56 additions & 33 deletions homeassistant/components/tankerkoenig/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@
from collections.abc import Mapping
from typing import Any

from pytankerkoenig import customException, getNearbyStations
from aiotankerkoenig import (
GasType,
Sort,
Station,
Tankerkoenig,
TankerkoenigInvalidKeyError,
)
import voluptuous as vol

from homeassistant import config_entries
Expand All @@ -18,8 +24,9 @@
CONF_SHOW_ON_MAP,
UnitOfLength,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.selector import (
LocationSelector,
Expand All @@ -31,33 +38,27 @@


async def async_get_nearby_stations(
hass: HomeAssistant, data: Mapping[str, Any]
) -> dict[str, Any]:
tankerkoenig: Tankerkoenig, data: Mapping[str, Any]
) -> list[Station]:
"""Fetch nearby stations."""
try:
return await hass.async_add_executor_job(
getNearbyStations,
data[CONF_API_KEY],
return await tankerkoenig.nearby_stations(
coordinates=(
data[CONF_LOCATION][CONF_LATITUDE],
data[CONF_LOCATION][CONF_LONGITUDE],
data[CONF_RADIUS],
"all",
"dist",
)
except customException as err:
return {"ok": False, "message": err, "exception": True}
),
radius=data[CONF_RADIUS],
gas_type=GasType.ALL,
sort=Sort.DISTANCE,
)


class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow."""

VERSION = 1

def __init__(self) -> None:
"""Init the FlowHandler."""
super().__init__()
self._data: dict[str, Any] = {}
self._stations: dict[str, str] = {}
_data: dict[str, Any] = {}
_stations: dict[str, str] = {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't initialize class attributes to mutable objects unless explicitly required. It's very error prone. Use an init method to set instance attributes.


@staticmethod
@callback
Expand All @@ -79,17 +80,25 @@ async def async_step_user(
)
self._abort_if_unique_id_configured()

data = await async_get_nearby_stations(self.hass, user_input)
if not data.get("ok"):
tankerkoenig = Tankerkoenig(
api_key=user_input[CONF_API_KEY],
session=async_get_clientsession(self.hass),
)
try:
stations = await async_get_nearby_stations(tankerkoenig, user_input)
except TankerkoenigInvalidKeyError:
return self._show_form_user(
user_input, errors={CONF_API_KEY: "invalid_auth"}
)
if len(stations := data.get("stations", [])) == 0:

# no stations found
if len(stations) == 0:
return self._show_form_user(user_input, errors={CONF_RADIUS: "no_stations"})

for station in stations:
self._stations[station["id"]] = (
f"{station['brand']} {station['street']} {station['houseNumber']} -"
f" ({station['dist']}km)"
self._stations[station.id] = (
f"{station.brand} {station.street} {station.house_number} -"
f" ({station.distance}km)"
)

self._data = user_input
Expand Down Expand Up @@ -128,8 +137,14 @@ async def async_step_reauth_confirm(
entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
assert entry
user_input = {**entry.data, **user_input}
data = await async_get_nearby_stations(self.hass, user_input)
if not data.get("ok"):

tankerkoenig = Tankerkoenig(
api_key=user_input[CONF_API_KEY],
session=async_get_clientsession(self.hass),
)
try:
await async_get_nearby_stations(tankerkoenig, user_input)
except TankerkoenigInvalidKeyError:
return self._show_form_reauth(user_input, {CONF_API_KEY: "invalid_auth"})

self.hass.config_entries.async_update_entry(entry, data=user_input)
Expand Down Expand Up @@ -233,14 +248,22 @@ async def async_step_init(
)
return self.async_create_entry(title="", data=user_input)

nearby_stations = await async_get_nearby_stations(
self.hass, self.config_entry.data
tankerkoenig = Tankerkoenig(
api_key=self.config_entry.data[CONF_API_KEY],
session=async_get_clientsession(self.hass),
)
if stations := nearby_stations.get("stations"):
try:
stations = await async_get_nearby_stations(
tankerkoenig, self.config_entry.data
)
except TankerkoenigInvalidKeyError:
return self.async_show_form(step_id="init", errors={"base": "invalid_auth"})

if stations:
for station in stations:
self._stations[station["id"]] = (
f"{station['brand']} {station['street']} {station['houseNumber']} -"
f" ({station['dist']}km)"
self._stations[station.id] = (
f"{station.brand} {station.street} {station.house_number} -"
f" ({station.distance}km)"
)

# add possible extra selected stations from import
Expand Down
Loading
Loading