Skip to content

Commit

Permalink
Adjustment post move to WS in Traccar Server (home-assistant#111337)
Browse files Browse the repository at this point in the history
* Adjustment post move to WS in Traccar Server

* Use entry.async_create_background_task
  • Loading branch information
ludeeus authored Feb 25, 2024
1 parent 23cf418 commit a6a0a0c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 35 deletions.
6 changes: 6 additions & 0 deletions homeassistant/components/traccar_server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
42 changes: 11 additions & 31 deletions homeassistant/components/traccar_server/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@
)

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
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.util import dt as dt_util

Expand Down Expand Up @@ -66,7 +65,6 @@ def __init__(
self.skip_accuracy_filter_for = skip_accuracy_filter_for
self._geofences: list[GeofenceModel] = []
self._last_event_import: datetime | None = None
self._subscription: asyncio.Task | None = None
self._should_log_subscription_error: bool = True

async def _async_update_data(self) -> TraccarServerCoordinatorData:
Expand Down Expand Up @@ -115,8 +113,6 @@ async def _async_update_data(self) -> TraccarServerCoordinatorData:
"attributes": attr,
}

await self.subscribe()

return data

async def handle_subscription_data(self, data: SubscriptionData) -> None:
Expand Down Expand Up @@ -163,7 +159,7 @@ async def handle_subscription_data(self, data: SubscriptionData) -> None:
update_devices.add(device_id)

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:
"""Import events from Traccar."""
Expand Down Expand Up @@ -203,33 +199,17 @@ async def import_events(self, _: datetime) -> None:
},
)

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:
"""Subscribe to events."""
if self._subscription is not None:
return

async def _subscriber():
try:
await self.client.subscribe(self.handle_subscription_data)
except TraccarException as ex:
if self._should_log_subscription_error:
self._should_log_subscription_error = False
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())
try:
await self.client.subscribe(self.handle_subscription_data)
except TraccarException as ex:
if self._should_log_subscription_error:
self._should_log_subscription_error = False
LOGGER.error("Error while subscribing to Traccar: %s", ex)
# Retry after 10 seconds
await asyncio.sleep(10)
await self.subscribe()

def _return_custom_attributes_if_not_filtered_by_accuracy_configuration(
self,
Expand Down
5 changes: 1 addition & 4 deletions homeassistant/components/traccar_server/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,7 @@ def __init__(
@property
def available(self) -> bool:
"""Return True if entity is available."""
return (
self.coordinator.last_update_success
and self.device_id in self.coordinator.data
)
return bool(self.coordinator.data and self.device_id in self.coordinator.data)

@property
def traccar_device(self) -> DeviceModel:
Expand Down

0 comments on commit a6a0a0c

Please sign in to comment.