Skip to content

Commit

Permalink
Merge pull request #12 from HAEdwin/Use-config_flow-settings-and-exte…
Browse files Browse the repository at this point in the history
…nded-error-handling

Use config flow settings and extended error handling
  • Loading branch information
HAEdwin authored Nov 17, 2024
2 parents e5bb7e2 + 9187f86 commit b4c49ab
Show file tree
Hide file tree
Showing 7 changed files with 169 additions and 7 deletions.
37 changes: 34 additions & 3 deletions custom_components/apsystems_ecu_proxy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
"""Initialise Module for ECU Proxy."""

from datetime import datetime, timedelta
import logging
from typing import Any
Expand Down Expand Up @@ -37,15 +35,48 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry):

hass.data.setdefault(DOMAIN, {})

# Initialize the API manager
api_handler = APIManager(hass, config_entry)
await api_handler.setup_socket_servers()

# Save the API handler in hass.data for later use
hass.data[DOMAIN][config_entry.entry_id] = {"api_handler": api_handler}

# Forward any configured platforms (e.g., sensors)
await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)

# Add an update listener to listen for config entry changes
config_entry.add_update_listener(update_listener)

return True


async def update_listener(hass: HomeAssistant, config_entry: ConfigEntry):
"""Handle configuration entry updates."""
_LOGGER.debug("Config entry updated: %s", config_entry.data)

# Get updated data from the config entry
new_timeout = int(config_entry.data.get("no_update_timeout"))
# Update the configuration for the relevant API handler(s)
api_handler = hass.data[DOMAIN][config_entry.entry_id]["api_handler"]

if api_handler:
if new_timeout != api_handler.no_update_timeout:
_LOGGER.debug("no_update_timeout has changed. Updating API manager.")
api_handler.no_update_timeout = new_timeout

# Reset the existing no_update_timer.
if api_handler.no_update_timer_unregister:
api_handler.no_update_timer_unregister()
api_handler.no_update_timer_unregister = async_call_later(
hass, timedelta(seconds=new_timeout), api_handler.fire_no_update
)

# Update config values in api module.
for socket_server in api_handler.socket_servers:
socket_server.update_config(config_entry)


async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Unload a config entry."""

Expand Down Expand Up @@ -98,7 +129,7 @@ def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
hass, self.midnight_reset, "0", "0", "0", local=True
)

# Get configuration. If initial data else options.
# Get configuration
self.no_update_timeout = int(self.config_entry.data.get("no_update_timeout"))

# Add listener for 0 or None if no update.
Expand Down
17 changes: 14 additions & 3 deletions custom_components/apsystems_ecu_proxy/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,13 @@ def get_config_value(self, key, default_type):
"""Get config value."""
return default_type(self.config_entry.data.get(key))

def update_config(self, new_config_entry: ConfigEntry):
"""Update configuration values based on a new config entry."""
_LOGGER.debug("Updating config for API on port %s", self.port)
self.send_to_ema = self.get_config_value("send_to_ema", bool)
self.message_ignore_age = self.get_config_value("message_ignore_age", int)
self.ema_host = self.get_config_value("ema_host", str)

async def start(self) -> bool:
"""Start listening socket server."""
try:
Expand Down Expand Up @@ -172,9 +179,13 @@ async def data_received(
self.callback(ecu)
except ConnectionResetError:
_LOGGER.warning("Error: Connection was reset")
except Exception: # noqa: BLE001
_LOGGER.warning("Exception error with %s", traceback.format_exc())

except Exception:
_LOGGER.warning(
"Exception error with %s where data is: %s",
traceback.format_exc(),
data,
)

def get_model(self, model_code: str) -> str:
"""Get model from model code."""
if model := ECU_MODELS_216.get(model_code) or ECU_MODELS_215.get(
Expand Down
2 changes: 1 addition & 1 deletion custom_components/apsystems_ecu_proxy/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@
],
"requirements": [],
"single_config_entry": true,
"version": "v1.1.0"
"version": "v1.2.0"
}
30 changes: 30 additions & 0 deletions custom_components/apsystems_ecu_proxy/translations/de.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"options": {
"step": {
"init": {
"data": {
"ema_host": "EMA Host (3.67.1.32)",
"message_ignore_age": "Alte Nachrichten ignorieren (Standard 1800 Sekunden)",
"max_stub_interval": "Maximales Stub-Intervall (Standard 300 Sekunden)",
"no_update_timeout": "Zeitüberschreitung beim Zurücksetzen der Werte (Standard 660 Sekunden)",
"send_to_ema": "An EMA versenden"
},
"title": "Konfiguration"
}
}
},
"config": {
"step": {
"user": {
"data": {
"ema_host": "EMA Host (3.67.1.32)",
"message_ignore_age": "Alte Nachrichten ignorieren (Standard 1800 Sekunden)",
"max_stub_interval": "Maximales Stub-Intervall (Standard 300 Sekunden)",
"no_update_timeout": "Zeitüberschreitung beim Zurücksetzen der Werte (Standard 660 Sekunden)",
"send_to_ema": "An EMA versenden"
},
"title": "Konfiguration"
}
}
}
}
30 changes: 30 additions & 0 deletions custom_components/apsystems_ecu_proxy/translations/es.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"options": {
"step": {
"init": {
"data": {
"ema_host": "EMA Host (3.67.1.32)",
"message_ignore_age": "Ignorar mensajes antiguos (predeterminado 1800 segundos)",
"max_stub_interval": "Intervalo máximo de código auxiliar (predeterminado 300 segundos)",
"no_update_timeout": "Restablecer el tiempo de espera de los valores (predeterminado 660 segundos)",
"send_to_ema": "Enviar a EMA"
},
"title": "Configuración"
}
}
},
"config": {
"step": {
"user": {
"data": {
"ema_host": "EMA Host (3.67.1.32)",
"message_ignore_age": "Ignorar mensajes antiguos (predeterminado 1800 segundos)",
"max_stub_interval": "Intervalo máximo de código auxiliar (predeterminado 300 segundos)",
"no_update_timeout": "Restablecer el tiempo de espera de los valores (predeterminado 660 segundos)",
"send_to_ema": "Enviar a EMA"
},
"title": "Configuración"
}
}
}
}
30 changes: 30 additions & 0 deletions custom_components/apsystems_ecu_proxy/translations/fr.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"options": {
"step": {
"init": {
"data": {
"ema_host": "EMA Host (3.67.1.32)",
"message_ignore_age": "Ignorer les anciens messages (1 800 secondes par défaut)",
"max_stub_interval": "Intervalle de stub maximum (300 secondes par défaut)",
"no_update_timeout": "Délai d'expiration des valeurs de réinitialisation (660 secondes par défaut)",
"send_to_ema": "Expédier vers l'EMA"
},
"title": "configuration"
}
}
},
"config": {
"step": {
"user": {
"data": {
"ema_host": "EMA Host (3.67.1.32)",
"message_ignore_age": "Ignorer les anciens messages (1 800 secondes par défaut)",
"max_stub_interval": "Intervalle de stub maximum (300 secondes par défaut)",
"no_update_timeout": "Délai d'expiration des valeurs de réinitialisation (660 secondes par défaut)",
"send_to_ema": "Expédier vers l'EMA"
},
"title": "configuration"
}
}
}
}
30 changes: 30 additions & 0 deletions custom_components/apsystems_ecu_proxy/translations/nl.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"options": {
"step": {
"init": {
"data": {
"ema_host": "EMA Host (3.67.1.32)",
"message_ignore_age": "Negeer oude berichten (standaard 1800 seconden)",
"max_stub_interval": "Maximale stub interval (standaard 300 seconden)",
"no_update_timeout": "Reset waarden timeout (standaard 660 seconden)",
"send_to_ema": "Verzend naar EMA"
},
"title": "Configuratie"
}
}
},
"config": {
"step": {
"user": {
"data": {
"ema_host": "EMA Host (3.67.1.32)",
"message_ignore_age": "Negeer oude berichten (standaard 1800 seconden)",
"max_stub_interval": "Maximale stub interval (standaard 300 seconden)",
"no_update_timeout": "Reset waarden timeout (standaard 660 seconden)",
"send_to_ema": "Verzend naar EMA"
},
"title": "Configuratie"
}
}
}
}

0 comments on commit b4c49ab

Please sign in to comment.