Adjustment post move to WS in Traccar Server (#111337)

* Adjustment post move to WS in Traccar Server

* Use entry.async_create_background_task
This commit is contained in:
Joakim Sørensen 2024-02-25 16:04:09 +01:00 committed by GitHub
parent 23cf418807
commit a6a0a0c901
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 18 additions and 35 deletions

View File

@ -75,6 +75,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
) )
) )
entry.async_create_background_task(
hass=hass,
target=coordinator.subscribe(),
name="Traccar Server subscription",
)
return True return True

View File

@ -15,9 +15,8 @@ from pytraccar import (
) )
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import dispatcher_send from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
@ -66,7 +65,6 @@ class TraccarServerCoordinator(DataUpdateCoordinator[TraccarServerCoordinatorDat
self.skip_accuracy_filter_for = skip_accuracy_filter_for self.skip_accuracy_filter_for = skip_accuracy_filter_for
self._geofences: list[GeofenceModel] = [] self._geofences: list[GeofenceModel] = []
self._last_event_import: datetime | None = None self._last_event_import: datetime | None = None
self._subscription: asyncio.Task | None = None
self._should_log_subscription_error: bool = True self._should_log_subscription_error: bool = True
async def _async_update_data(self) -> TraccarServerCoordinatorData: async def _async_update_data(self) -> TraccarServerCoordinatorData:
@ -115,8 +113,6 @@ class TraccarServerCoordinator(DataUpdateCoordinator[TraccarServerCoordinatorDat
"attributes": attr, "attributes": attr,
} }
await self.subscribe()
return data return data
async def handle_subscription_data(self, data: SubscriptionData) -> None: async def handle_subscription_data(self, data: SubscriptionData) -> None:
@ -163,7 +159,7 @@ class TraccarServerCoordinator(DataUpdateCoordinator[TraccarServerCoordinatorDat
update_devices.add(device_id) update_devices.add(device_id)
for device_id in update_devices: for device_id in update_devices:
dispatcher_send(self.hass, f"{DOMAIN}_{device_id}") async_dispatcher_send(self.hass, f"{DOMAIN}_{device_id}")
async def import_events(self, _: datetime) -> None: async def import_events(self, _: datetime) -> None:
"""Import events from Traccar.""" """Import events from Traccar."""
@ -203,33 +199,17 @@ class TraccarServerCoordinator(DataUpdateCoordinator[TraccarServerCoordinatorDat
}, },
) )
async def unsubscribe(self, *args) -> None:
"""Unsubscribe from Traccar Server."""
if self._subscription is None:
return
self._should_log_subscription_error = False
self._subscription.cancel()
self._subscription = None
async def subscribe(self) -> None: async def subscribe(self) -> None:
"""Subscribe to events.""" """Subscribe to events."""
if self._subscription is not None: try:
return await self.client.subscribe(self.handle_subscription_data)
except TraccarException as ex:
async def _subscriber(): if self._should_log_subscription_error:
try: self._should_log_subscription_error = False
await self.client.subscribe(self.handle_subscription_data) LOGGER.error("Error while subscribing to Traccar: %s", ex)
except TraccarException as ex: # Retry after 10 seconds
if self._should_log_subscription_error: await asyncio.sleep(10)
self._should_log_subscription_error = False await self.subscribe()
LOGGER.error("Error while subscribing to Traccar: %s", ex)
# Retry after 10 seconds
await asyncio.sleep(10)
await _subscriber()
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.unsubscribe)
self.config_entry.async_on_unload(self.unsubscribe)
self._subscription = asyncio.create_task(_subscriber())
def _return_custom_attributes_if_not_filtered_by_accuracy_configuration( def _return_custom_attributes_if_not_filtered_by_accuracy_configuration(
self, self,

View File

@ -34,10 +34,7 @@ class TraccarServerEntity(CoordinatorEntity[TraccarServerCoordinator]):
@property @property
def available(self) -> bool: def available(self) -> bool:
"""Return True if entity is available.""" """Return True if entity is available."""
return ( return bool(self.coordinator.data and self.device_id in self.coordinator.data)
self.coordinator.last_update_success
and self.device_id in self.coordinator.data
)
@property @property
def traccar_device(self) -> DeviceModel: def traccar_device(self) -> DeviceModel: