Skip to content

Commit

Permalink
Added flight device_tracker
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexandrErohin committed Oct 8, 2024
1 parent fe69bbc commit fe78a02
Show file tree
Hide file tree
Showing 19 changed files with 128 additions and 3 deletions.
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

<img src="https://raw.githubusercontent.com/AlexandrErohin/home-assistant-flightradar24/master/docs/media/map.png" width="48%"><img src="https://raw.githubusercontent.com/AlexandrErohin/home-assistant-flightradar24/master/docs/media/sensors.png" width="48%">
<p align="center"><img src="https://raw.githubusercontent.com/AlexandrErohin/home-assistant-flightradar24/master/docs/media/lovelace.png" width="50%"></p>
Expand All @@ -31,6 +32,15 @@ It allows you:
- Additional tracked
- Most tracked flights (You may disable it via configuration)

### <a id="device-tracker">Device Tracker</a>
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
Expand Down Expand Up @@ -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
### <a id="edit-configuration">Edit Configuration</a>
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:

Expand Down
4 changes: 4 additions & 0 deletions custom_components/flightradar24/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,16 @@
CONF_MAX_ALTITUDE,
CONF_MOST_TRACKED,
CONF_MOST_TRACKED_DEFAULT,
CONF_ENABLE_TRACKER,
CONF_ENABLE_TRACKER_DEFAULT,
MIN_ALTITUDE,
MAX_ALTITUDE,
)
from FlightRadar24 import FlightRadar24API, Entity
from .sensor import SENSOR_TYPES

PLATFORMS: list[Platform] = [
Platform.DEVICE_TRACKER,
Platform.SENSOR,
Platform.TEXT,
]
Expand Down Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions custom_components/flightradar24/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -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,
})
Expand Down
2 changes: 2 additions & 0 deletions custom_components/flightradar24/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)},
Expand Down
88 changes: 88 additions & 0 deletions custom_components/flightradar24/device_tracker.py
Original file line number Diff line number Diff line change
@@ -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']
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/be.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"min_altitude": "Мінімальная вышыня ў футах, вышэй за якую будуць адсочвацца ўсе самалёты.",
"max_altitude": "Максімальная вышыня ў футах, ніжэй за якую будуць адсочвацца ўсе самалёты.",
"most_tracked": "Уключыць спіс найбольш адсочваемых рэйсаў",
"enable_tracker": "Уключыце device_tracker для дадатковага адсочвання рэйсаў",
"username": "НЕАБАВЯЗКОВА! Імя карыстальніка Flightradar24",
"password": "НЕАБАВЯЗКОВА! Пароль Flightradar24"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/bg.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"min_altitude": "Минималната надморска височина във футове, над която всички самолети ще бъдат проследявани.",
"max_altitude": "Максималната надморска височина във футове, под която всички самолети ще бъдат проследявани.",
"most_tracked": "Активирайте списъка с най-проследяваните полети",
"enable_tracker": "Активирайте device_tracker за допълнителни полети за проследяване",
"username": "ПО ИЗБОР! Потребителско име в Flightradar24",
"password": "ПО ИЗБОР! Парола за Flightradar24"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/cs.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"min_altitude": "Минимальная высота в футах, выше которой будут отслеживаться все самолеты.",
"max_altitude": "Максимальная высота в футах, ниже которой будут отслеживаться все самолеты.",
"most_tracked": "Включить список наиболее отслеживаемых рейсов",
"enable_tracker": "Включить device_tracker для дополнительно отслеживаемых рейсов",
"username": "НЕОБЯЗАТЕЛЬНО! Имя пользователя Flightradar24",
"password": "НЕОБЯЗАТЕЛЬНО! Пароль Flightradar24"
}
Expand Down
1 change: 1 addition & 0 deletions custom_components/flightradar24/translations/sk.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down

0 comments on commit fe78a02

Please sign in to comment.