diff --git a/README.md b/README.md index b508e84..ec23f15 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ It allows you: 4. Create notifications (example - [Get a notification when a flight enters or exits your area](#notification-enters), [Get a notification when a tracked scheduled flight takes off](#notification-scheduled)) 5. Create automations (example - [Automatically track a flight by your needs](#automation)) 6. Add flights table to your [Home Assistant dashboard](https://www.home-assistant.io/dashboards/) by [Lovelace Card](#lovelace)) +7. Track your flight as [Device Tracker](#device-tracker)

@@ -31,6 +32,15 @@ It allows you: - Additional tracked - Most tracked flights (You may disable it via configuration) +### Device Tracker +Track flights as device_tracker with flight information. To use it - you need to activate this feature +in [Edit Configuration](edit-configuration). When it is enabled - this integration creates device_tracker +for every additional tracked flight from `sensor.flightradar24_additional_tracked`. + +To create device_tracker for a flight: +1. Add a flight to Additional tracked by flight number +2. Use device_tracker `device_tracker.FLIGHT_NUMBER`. + ### Configuration - Add to track - Remove from track @@ -73,14 +83,15 @@ The default data is preset already 3. You may change the default values for Radius, Latitude and Longitude 4. Click `SUBMIT` -### Edit Configuration +### Edit Configuration You may edit configuration data like: 1. Latitude and longitude of your point 2. Radius of your zone 3. Scan interval for updates in seconds 4. The minimum and maximum altitudes in foots between which the aircraft will be tracked -5. Enable/Disable [top 10 most tracked flights on FlightRadar24](#most-tracked) -6. Username and password if you have FlightRadar24 subscription +5. Enable/Disable [top 10 most tracked flights on FlightRadar24](#most-tracked) +6. Enable/Disable [device_tracker for flights](#device-tracker) +7. Username and password if you have FlightRadar24 subscription To do that: diff --git a/custom_components/flightradar24/__init__.py b/custom_components/flightradar24/__init__.py index fdbd67d..174040e 100644 --- a/custom_components/flightradar24/__init__.py +++ b/custom_components/flightradar24/__init__.py @@ -18,6 +18,8 @@ CONF_MAX_ALTITUDE, CONF_MOST_TRACKED, CONF_MOST_TRACKED_DEFAULT, + CONF_ENABLE_TRACKER, + CONF_ENABLE_TRACKER_DEFAULT, MIN_ALTITUDE, MAX_ALTITUDE, ) @@ -25,6 +27,7 @@ from .sensor import SENSOR_TYPES PLATFORMS: list[Platform] = [ + Platform.DEVICE_TRACKER, Platform.SENSOR, Platform.TEXT, ] @@ -58,6 +61,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: ) coordinator.most_tracked = {} if entry.data.get(CONF_MOST_TRACKED, CONF_MOST_TRACKED_DEFAULT) else None + coordinator.enable_tracker = entry.data.get(CONF_ENABLE_TRACKER, CONF_ENABLE_TRACKER_DEFAULT) await coordinator.async_config_entry_first_refresh() hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator diff --git a/custom_components/flightradar24/config_flow.py b/custom_components/flightradar24/config_flow.py index 4301931..c60a7e0 100644 --- a/custom_components/flightradar24/config_flow.py +++ b/custom_components/flightradar24/config_flow.py @@ -13,7 +13,9 @@ CONF_MIN_ALTITUDE, CONF_MAX_ALTITUDE, CONF_MOST_TRACKED, + CONF_ENABLE_TRACKER, CONF_MOST_TRACKED_DEFAULT, + CONF_ENABLE_TRACKER_DEFAULT, MIN_ALTITUDE, MAX_ALTITUDE, ) @@ -97,6 +99,10 @@ async def async_step_init(self, user_input: dict[str, Any] | None = None) -> Flo vol.Optional(CONF_MOST_TRACKED, description={ "suggested_value": data.get(CONF_MOST_TRACKED, CONF_MOST_TRACKED_DEFAULT)}): cv.boolean, + vol.Optional(CONF_ENABLE_TRACKER, + description={ + "suggested_value": data.get(CONF_ENABLE_TRACKER, + CONF_ENABLE_TRACKER_DEFAULT)}): cv.boolean, vol.Optional(CONF_USERNAME, description={"suggested_value": data.get(CONF_USERNAME, '')}): cv.string, vol.Optional(CONF_PASSWORD, description={"suggested_value": data.get(CONF_PASSWORD, '')}): cv.string, }) diff --git a/custom_components/flightradar24/const.py b/custom_components/flightradar24/const.py index 8cf9edc..56dd443 100644 --- a/custom_components/flightradar24/const.py +++ b/custom_components/flightradar24/const.py @@ -5,7 +5,9 @@ CONF_MIN_ALTITUDE = "min_altitude" CONF_MAX_ALTITUDE = "max_altitude" CONF_MOST_TRACKED = "most_tracked" +CONF_ENABLE_TRACKER = "enable_tracker" CONF_MOST_TRACKED_DEFAULT = True +CONF_ENABLE_TRACKER_DEFAULT = False EVENT_ENTRY = f"{DOMAIN}_entry" EVENT_EXIT = f"{DOMAIN}_exit" diff --git a/custom_components/flightradar24/coordinator.py b/custom_components/flightradar24/coordinator.py index 2b223c2..589207c 100644 --- a/custom_components/flightradar24/coordinator.py +++ b/custom_components/flightradar24/coordinator.py @@ -53,6 +53,7 @@ def __init__( self.min_altitude = min_altitude self.max_altitude = max_altitude self.point = point + self.enable_tracker: bool = False self.device_info = DeviceInfo( configuration_url=URL, identifiers={(DOMAIN, self.unique_id)}, diff --git a/custom_components/flightradar24/device_tracker.py b/custom_components/flightradar24/device_tracker.py new file mode 100644 index 0000000..6c5c6ae --- /dev/null +++ b/custom_components/flightradar24/device_tracker.py @@ -0,0 +1,88 @@ +from __future__ import annotations +from homeassistant.components.device_tracker.config_entry import TrackerEntity +from homeassistant.components.device_tracker.const import SourceType +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.update_coordinator import CoordinatorEntity +from .coordinator import FlightRadar24Coordinator +from .const import DOMAIN + + +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + coordinator = hass.data[DOMAIN][entry.entry_id] + tracked: dict[str, FlightRadar24Tracker] = {} + + @callback + def coordinator_updated(): + """Update the status of the device.""" + update_items(coordinator, async_add_entities, tracked) + + entry.async_on_unload(coordinator.async_add_listener(coordinator_updated)) + coordinator_updated() + + +@callback +def update_items( + coordinator: FlightRadar24Coordinator, + async_add_entities: AddEntitiesCallback, + tracked: dict[str, FlightRadar24Tracker], +) -> None: + if not coordinator.enable_tracker: + return + + new_tracked: list[FlightRadar24Tracker] = [] + active: list[str] = [] + for flight in coordinator.tracked.values(): + active.append(flight['flight_number']) + if flight['flight_number'] not in tracked: + tracked[flight['flight_number']] = FlightRadar24Tracker(coordinator, flight) + new_tracked.append(tracked[flight['flight_number']]) + else: + tracked[flight['flight_number']].info = flight + + if new_tracked: + async_add_entities(new_tracked) + + +class FlightRadar24Tracker(CoordinatorEntity, TrackerEntity): + def __init__( + self, + coordinator: FlightRadar24Coordinator, + data: dict, + ) -> None: + self.info = data + + super().__init__(coordinator) + + @property + def source_type(self) -> SourceType: + return SourceType.GPS + + @property + def unique_id(self) -> str: + return f"{self.coordinator.unique_id}_{DOMAIN}_{self.info['flight_number']}" + + @property + def extra_state_attributes(self) -> dict[str, str]: + return self.info + + @property + def latitude(self) -> float | None: + return self.info.get('latitude') + + @property + def longitude(self) -> float | None: + return self.info.get('longitude') + + @property + def icon(self) -> str: + return "mdi:airplane" + + @property + def name(self) -> str: + return self.info['flight_number'] diff --git a/custom_components/flightradar24/translations/be.json b/custom_components/flightradar24/translations/be.json index 7f6cada..06b51c4 100644 --- a/custom_components/flightradar24/translations/be.json +++ b/custom_components/flightradar24/translations/be.json @@ -24,6 +24,7 @@ "min_altitude": "Мінімальная вышыня ў футах, вышэй за якую будуць адсочвацца ўсе самалёты.", "max_altitude": "Максімальная вышыня ў футах, ніжэй за якую будуць адсочвацца ўсе самалёты.", "most_tracked": "Уключыць спіс найбольш адсочваемых рэйсаў", + "enable_tracker": "Уключыце device_tracker для дадатковага адсочвання рэйсаў", "username": "НЕАБАВЯЗКОВА! Імя карыстальніка Flightradar24", "password": "НЕАБАВЯЗКОВА! Пароль Flightradar24" } diff --git a/custom_components/flightradar24/translations/bg.json b/custom_components/flightradar24/translations/bg.json index 772d5cc..ef0eec7 100644 --- a/custom_components/flightradar24/translations/bg.json +++ b/custom_components/flightradar24/translations/bg.json @@ -24,6 +24,7 @@ "min_altitude": "Минималната надморска височина във футове, над която всички самолети ще бъдат проследявани.", "max_altitude": "Максималната надморска височина във футове, под която всички самолети ще бъдат проследявани.", "most_tracked": "Активирайте списъка с най-проследяваните полети", + "enable_tracker": "Активирайте device_tracker за допълнителни полети за проследяване", "username": "ПО ИЗБОР! Потребителско име в Flightradar24", "password": "ПО ИЗБОР! Парола за Flightradar24" } diff --git a/custom_components/flightradar24/translations/cs.json b/custom_components/flightradar24/translations/cs.json index 8c2ff80..9c6a591 100644 --- a/custom_components/flightradar24/translations/cs.json +++ b/custom_components/flightradar24/translations/cs.json @@ -24,6 +24,7 @@ "min_altitude":"Minimální nadmořská výška ve stopách, nad kterou budou všechna letadla sledována.", "max_altitude":"Maximální nadmořská výška ve stopách, pod kterou budou všechna letadla sledována.", "most_tracked":"Povolit seznam nejvíce sledovaných letů", + "enable_tracker": "Povolte device_tracker pro další sledování letů", "username":"VOLITELNÉ! Uživatelské jméno Flightradar24", "password":"VOLITELNÉ! Heslo Flightradar24" } diff --git a/custom_components/flightradar24/translations/de.json b/custom_components/flightradar24/translations/de.json index 7f8aa8b..7164308 100644 --- a/custom_components/flightradar24/translations/de.json +++ b/custom_components/flightradar24/translations/de.json @@ -24,6 +24,7 @@ "min_altitude": "Die minimale Höhe in Fuß über dem Flugzeuge verfolgt werden.", "max_altitude": "Die maximale Höhe in Fuß unter dem Flugzeug verfolgt werden.", "most_tracked": "Aktiviere die Liste der am häufigsten verfolgten Flüge", + "enable_tracker": "Aktivieren Sie device_tracker für zusätzliche Tracking-Flüge", "username": "OPTIONAL! Flightradar24 Benutzername", "password": "OPTIONAL! Flightradar24 Passwort" } diff --git a/custom_components/flightradar24/translations/en.json b/custom_components/flightradar24/translations/en.json index cbebefe..3bc2858 100644 --- a/custom_components/flightradar24/translations/en.json +++ b/custom_components/flightradar24/translations/en.json @@ -24,6 +24,7 @@ "min_altitude": "The minimum altitude in feet above which all aircraft will be tracked.", "max_altitude": "The maximum altitude in feet below which all aircraft will be tracked.", "most_tracked": "Enable most tracked flights list", + "enable_tracker": "Enable device_tracker for additional tracking flights", "username": "OPTIONAL! Flightradar24 username", "password": "OPTIONAL! Flightradar24 password" } diff --git a/custom_components/flightradar24/translations/es.json b/custom_components/flightradar24/translations/es.json index a20b883..87c4d1d 100644 --- a/custom_components/flightradar24/translations/es.json +++ b/custom_components/flightradar24/translations/es.json @@ -24,6 +24,7 @@ "min_altitude": "La altitud mínima en pies por debajo de la cual se rastreará la aeronave.", "max_altitude": "La altitud máxima en pies por encima de la cual se rastreará la aeronave.", "most_tracked": "Activar la lista de vuelos más seguidos", + "enable_tracker": "Habilitar device_tracker para seguimiento adicional de vuelos", "username": "OPCIONAL! Nombre de usuario de Flightradar24", "password": "OPCIONAL! Contraseña de Flightradar24" } diff --git a/custom_components/flightradar24/translations/fr.json b/custom_components/flightradar24/translations/fr.json index 2058aa8..4235bb7 100644 --- a/custom_components/flightradar24/translations/fr.json +++ b/custom_components/flightradar24/translations/fr.json @@ -24,6 +24,7 @@ "min_altitude": "L'altitude minimale en pieds au-dessus de laquelle l'avion sera suivie.", "max_altitude": "L'altitude maximale en pieds à l'avion sera suivi.", "most_tracked": "Activer la liste des vols les plus suivis", + "enable_tracker": "Activer device_tracker pour des vols de suivi supplémentaires", "username": "FACULTATIF! Nom d'utilisateur Flightradar24", "password": "FACULTATIF! Mot de passe Flightradar24" } diff --git a/custom_components/flightradar24/translations/nl.json b/custom_components/flightradar24/translations/nl.json index 1de319f..b19e6bc 100644 --- a/custom_components/flightradar24/translations/nl.json +++ b/custom_components/flightradar24/translations/nl.json @@ -24,6 +24,7 @@ "min_altitude": "Minimum hoogte in feet waarboven alle vliegverkeer gevolgd wordt.", "max_altitude": "Maximum hoogte in feet waaronder alle vliegverkeer gevolgd wordt.", "most_tracked": "Activeer meest gevolgde vluchtlijst", + "enable_tracker": "Device_tracker inschakelen voor extra trackingvluchten", "username": "OPTIONEEL! Flightradar24 gebruikersnaam", "password": "OPTIONEEL! Flightradar24 wachtwoord" } diff --git a/custom_components/flightradar24/translations/pl.json b/custom_components/flightradar24/translations/pl.json index 7f4b2b0..301d713 100644 --- a/custom_components/flightradar24/translations/pl.json +++ b/custom_components/flightradar24/translations/pl.json @@ -24,6 +24,7 @@ "min_altitude": "Wysokość, powyżej której samoloty będą śledzone (w stopach)", "max_altitude": "Wysokość, poniżej której samoloty będą śledzone (w stopach)", "most_tracked": "Włącz listę najczęściej śledzonych samolotów", + "enable_tracker": "Włącz device_tracker, aby dodatkowo śledzić loty", "username": "OPCJONALNE! Login do Flightradar24", "password": "OPCJONALNE! Hasło do Flightradar24" } diff --git a/custom_components/flightradar24/translations/pt-BR.json b/custom_components/flightradar24/translations/pt-BR.json index 3689999..1c4382d 100644 --- a/custom_components/flightradar24/translations/pt-BR.json +++ b/custom_components/flightradar24/translations/pt-BR.json @@ -24,6 +24,7 @@ "min_altitude": "A altitude mínima, em pés, acima da qual todos os aviões serão monitorados.", "max_altitude": "A altitude máxima, em pés, abaixo da qual todos os aviões serão monitorados.", "most_tracked": "Ativar lista de voos mais monitorados", + "enable_tracker": "Habilitar device_tracker para voos de rastreamento adicionais", "username": "OPCIONAL! Nome de usuário do Flightradar24", "password": "OPCIONAL! Senha do Flightradar24" } diff --git a/custom_components/flightradar24/translations/pt.json b/custom_components/flightradar24/translations/pt.json index 320125e..7d896ad 100644 --- a/custom_components/flightradar24/translations/pt.json +++ b/custom_components/flightradar24/translations/pt.json @@ -24,6 +24,7 @@ "min_altitude": "A altitude mínima em pés acima da qual todos os aviões serão rastreados.", "max_altitude": "A altitude máxima em pés abaixo da qual todos os aviões serão rastreados.", "most_tracked": "Ativar lista de voos mais rastreados", + "enable_tracker": "Ative o device_tracker para voos de seguimento adicionais", "username": "Opcional! Nome de utilizador Flightradar24", "password": "Opcional! Palavra-passe Flightradar24" } diff --git a/custom_components/flightradar24/translations/ru.json b/custom_components/flightradar24/translations/ru.json index c8f0c31..77cdbee 100644 --- a/custom_components/flightradar24/translations/ru.json +++ b/custom_components/flightradar24/translations/ru.json @@ -24,6 +24,7 @@ "min_altitude": "Минимальная высота в футах, выше которой будут отслеживаться все самолеты.", "max_altitude": "Максимальная высота в футах, ниже которой будут отслеживаться все самолеты.", "most_tracked": "Включить список наиболее отслеживаемых рейсов", + "enable_tracker": "Включить device_tracker для дополнительно отслеживаемых рейсов", "username": "НЕОБЯЗАТЕЛЬНО! Имя пользователя Flightradar24", "password": "НЕОБЯЗАТЕЛЬНО! Пароль Flightradar24" } diff --git a/custom_components/flightradar24/translations/sk.json b/custom_components/flightradar24/translations/sk.json index aea2030..78d3d3b 100644 --- a/custom_components/flightradar24/translations/sk.json +++ b/custom_components/flightradar24/translations/sk.json @@ -24,6 +24,7 @@ "min_altitude": "Minimálna výška v stopách, nad ktorou budú všetky lietadlá sledované.", "max_altitude": "Maximálna výška v stopách, pod ktorou budú všetky lietadlá sledované.", "most_tracked": "Povoliť zoznam najviac sledovaných letov", + "enable_tracker": "Povoľte device_tracker pre ďalšie sledovanie letov", "username": "VOLITEĽNÉ! Používateľské meno Flightradar24", "password": "VOLITEĽNÉ! Heslo Flightradar24" }