Skip to content

Commit

Permalink
Merge branch 'master' into patch
Browse files Browse the repository at this point in the history
  • Loading branch information
Kolbi authored Apr 3, 2024
2 parents 7e5beec + 0148751 commit 03bc355
Show file tree
Hide file tree
Showing 9 changed files with 157 additions and 24 deletions.
21 changes: 21 additions & 0 deletions custom_components/audiconnect/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

from datetime import timedelta
import voluptuous as vol
import logging

import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import device_registry as dr
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.util.dt import utcnow
from homeassistant import config_entries
from homeassistant.const import (
Expand All @@ -33,6 +35,8 @@
COMPONENTS,
)

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
Expand Down Expand Up @@ -96,6 +100,14 @@ async def async_setup_entry(hass, config_entry):
"""Set up the Audi Connect component."""
hass.data[DOMAIN]["devices"] = set()

# Attempt to retrieve the scan interval from options, then fall back to data, or use default
scan_interval = timedelta(
minutes=config_entry.options.get(
CONF_SCAN_INTERVAL,
config_entry.data.get(CONF_SCAN_INTERVAL, DEFAULT_UPDATE_INTERVAL),
)
)

account = config_entry.data.get(CONF_USERNAME)

unit_system = "metric"
Expand All @@ -110,6 +122,15 @@ async def async_setup_entry(hass, config_entry):
else:
data = hass.data[DOMAIN][account]

async def update_data(now):
"""Update the data with the latest information."""
_LOGGER.info("Running cloud update at set interval...")
await data.update(utcnow())

_LOGGER.info("Scheduling update at every %s interval", scan_interval)
async_track_time_interval(hass, update_data, scan_interval)

# Initially update the data
return await data.update(utcnow())


Expand Down
47 changes: 23 additions & 24 deletions custom_components/audiconnect/audi_account.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import logging
from datetime import timedelta
import voluptuous as vol

from homeassistant.helpers import config_validation as cv, device_registry as dr
from homeassistant.helpers.dispatcher import (
async_dispatcher_send,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_track_point_in_utc_time
from homeassistant.util.dt import utcnow
from homeassistant.const import (
CONF_PASSWORD,
CONF_SCAN_INTERVAL,
CONF_USERNAME,
)

Expand Down Expand Up @@ -39,6 +36,7 @@

REFRESH_VEHICLE_DATA_FAILED_EVENT = "refresh_failed"
REFRESH_VEHICLE_DATA_COMPLETED_EVENT = "refresh_completed"

SERVICE_REFRESH_VEHICLE_DATA = "refresh_vehicle_data"
SERVICE_REFRESH_VEHICLE_DATA_SCHEMA = vol.Schema(
{
Expand Down Expand Up @@ -75,7 +73,6 @@ def __init__(self, hass, config_entry, unit_system: str):
self.config_entry = config_entry
self.config_vehicles = set()
self.vehicles = set()
self.interval = config_entry.data.get(CONF_SCAN_INTERVAL)
self.unit_system = unit_system

def init_connection(self):
Expand Down Expand Up @@ -173,26 +170,28 @@ def discover_vehicles(self, vehicles):
)

async def update(self, now):
"""Update status from the online service."""
try:
if not await self.connection.update(None):
return False

self.discover_vehicles(
[x for x in self.connection._vehicles if x.vin not in self.vehicles]
)

async_dispatcher_send(self.hass, SIGNAL_STATE_UPDATED)

for config_vehicle in self.config_vehicles:
for instrument in config_vehicle.device_trackers:
async_dispatcher_send(self.hass, TRACKER_UPDATE, instrument)

return True
finally:
async_track_point_in_utc_time(
self.hass, self.update, utcnow() + timedelta(minutes=self.interval)
)
"""Update status from the cloud."""
_LOGGER.info("Running update for Audi Connect service at %s", now)
if not await self.connection.update(None):
_LOGGER.warning("Failed to update from Audi Connect service")
return False

# Discover new vehicles that have not been added yet
new_vehicles = [
x for x in self.connection._vehicles if x.vin not in self.vehicles
]
if new_vehicles:
_LOGGER.info("Discovered %d vehicle(s)", len(new_vehicles))
self.discover_vehicles(new_vehicles)

async_dispatcher_send(self.hass, SIGNAL_STATE_UPDATED)

for config_vehicle in self.config_vehicles:
for instrument in config_vehicle.device_trackers:
async_dispatcher_send(self.hass, TRACKER_UPDATE, instrument)

_LOGGER.info("Successfully updated Audi Connect service")
return True

async def execute_vehicle_action(self, service):
device_id = service.data.get(CONF_VIN).lower()
Expand Down
35 changes: 35 additions & 0 deletions custom_components/audiconnect/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,3 +146,38 @@ async def async_step_import(self, user_input):
CONF_SCAN_INTERVAL: scan_interval,
},
)

@staticmethod
@callback
def async_get_options_flow(config_entry):
"""Get the options flow for this handler."""
return OptionsFlowHandler(config_entry)


class OptionsFlowHandler(config_entries.OptionsFlow):
def __init__(self, config_entry):
self.config_entry: config_entries.ConfigEntry = config_entry
_LOGGER.debug("Initializing options flow for %s", config_entry.title)

async def async_step_init(self, user_input=None):
_LOGGER.debug("Options flow initiated")
if user_input is not None:
_LOGGER.debug("Received user input for options: %s", user_input)
return self.async_create_entry(title="", data=user_input)

current_scan_interval = self.config_entry.options.get(
CONF_SCAN_INTERVAL,
self.config_entry.data.get(CONF_SCAN_INTERVAL, DEFAULT_UPDATE_INTERVAL),
)
_LOGGER.debug("Current scan interval: %s minutes", current_scan_interval)

return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Optional(
CONF_SCAN_INTERVAL, default=current_scan_interval
): vol.All(vol.Coerce(int), vol.Clamp(min=MIN_UPDATE_INTERVAL)),
}
),
)
13 changes: 13 additions & 0 deletions custom_components/audiconnect/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,19 @@
}
}
},
"options": {
"step": {
"init": {
"data": {
"scan_interval": "Scan Interval"
},
"title": "Audi Connect Options",
"data_description": {
"scan_interval": "(Minutes) Restart required for new scan interval to take effect."
}
}
}
},
"selector": {
"vehicle_actions": {
"options": {
Expand Down
13 changes: 13 additions & 0 deletions custom_components/audiconnect/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,19 @@
}
}
},
"options": {
"step": {
"init": {
"data": {
"scan_interval": "Abfrageintervall"
},
"title": "Audi Connect-Optionen",
"data_description": {
"scan_interval": "(Minuten) Damit das neue Scanintervall wirksam wird, ist ein Neustart erforderlich."
}
}
}
},
"selector": {
"vehicle_actions": {
"options": {
Expand Down
13 changes: 13 additions & 0 deletions custom_components/audiconnect/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,19 @@
}
}
},
"options": {
"step": {
"init": {
"data": {
"scan_interval": "Scan Interval"
},
"title": "Audi Connect Options",
"data_description": {
"scan_interval": "(Minutes) Restart required for new scan interval to take effect."
}
}
}
},
"selector": {
"vehicle_actions": {
"options": {
Expand Down
13 changes: 13 additions & 0 deletions custom_components/audiconnect/translations/nb.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,18 @@
"title": "Audi Connect kontoinformasjon"
}
}
},
"options": {
"step": {
"init": {
"data": {
"scan_interval": "Skanneintervall"
},
"title": "Audi Connect-alternativer",
"data_description": {
"scan_interval": "(Minutter) Omstart kreves for at nytt skanneintervall skal tre i kraft."
}
}
}
}
}
13 changes: 13 additions & 0 deletions custom_components/audiconnect/translations/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,18 @@
"title": "Audi Connect accountgegevens"
}
}
},
"options": {
"step": {
"init": {
"data": {
"scan_interval": "Scaninterval"
},
"title": "Audi Connect-opties",
"data_description": {
"scan_interval": "(Minuten) Opnieuw opstarten vereist om het nieuwe scaninterval van kracht te laten worden."
}
}
}
}
}
13 changes: 13 additions & 0 deletions custom_components/audiconnect/translations/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,18 @@
"title": "Informações da conta Audi Connect "
}
}
},
"options": {
"step": {
"init": {
"data": {
"scan_interval": "Intervalo de escaneamento"
},
"title": "Opções Audi Connect",
"data_description": {
"scan_interval": "(Minutos) É necessário reiniciar para que o novo intervalo de verificação entre em vigor."
}
}
}
}
}

0 comments on commit 03bc355

Please sign in to comment.