Skip to content

Commit

Permalink
Refactoring Services for the Camera and improving init
Browse files Browse the repository at this point in the history
  • Loading branch information
sca075 committed Nov 17, 2024
1 parent 0b5584c commit 09400e6
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 47 deletions.
47 changes: 12 additions & 35 deletions custom_components/mqtt_vacuum_camera/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
DOMAIN,
)
from .coordinator import MQTTVacuumCoordinator
from .utils.camera.camera_services import reset_trims, reload_config
from .utils.files_operations import (
async_clean_up_all_auto_crop_files,
async_get_translations_vacuum_id,
Expand All @@ -50,35 +51,6 @@ async def options_update_listener(hass: core.HomeAssistant, config_entry: Config
async def async_setup_entry(hass: core.HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up platform from a ConfigEntry."""

async def _reload_config(call: ServiceCall) -> None:
"""Reload the camera platform for all entities in the integration."""
_LOGGER.debug(f"Reloading the config entry for all {DOMAIN} entities")
# Retrieve all config entries associated with the DOMAIN
camera_entries = hass.config_entries.async_entries(DOMAIN)

# Iterate over each config entry and check if it's LOADED
for camera_entry in camera_entries:
if camera_entry.state == ConfigEntryState.LOADED:
_LOGGER.debug(f"Unloading entry: {camera_entry.entry_id}")
await async_unload_entry(hass, camera_entry)

_LOGGER.debug(f"Reloading entry: {camera_entry.entry_id}")
await async_setup_entry(hass, camera_entry)
else:
_LOGGER.debug(
f"Skipping entry {camera_entry.entry_id} as it is NOT_LOADED"
)

# Optionally, trigger other reinitialization steps if needed
hass.bus.async_fire(f"event_{DOMAIN}_reloaded", context=call.context)

async def reset_trims(call: ServiceCall) -> None:
"""Action Reset Map Trims."""
_LOGGER.debug(f"Resetting trims for {DOMAIN}")
await async_clean_up_all_auto_crop_files(hass)
await hass.services.async_call(DOMAIN, "reload")
hass.bus.async_fire(f"event_{DOMAIN}_reset_trims", context=call.context)

hass.data.setdefault(DOMAIN, {})
hass_data = dict(entry.data)

Expand Down Expand Up @@ -109,10 +81,14 @@ async def reset_trims(call: ServiceCall) -> None:
}
)
# Register Services
hass.services.async_register(DOMAIN, "reset_trims", reset_trims)
if not hass.services.has_service(DOMAIN, SERVICE_RELOAD):
async_register_admin_service(hass, DOMAIN, SERVICE_RELOAD, _reload_config)
await async_register_vacuums_services(hass, data_coordinator)
async_register_admin_service(
hass, DOMAIN, SERVICE_RELOAD, lambda call: reload_config(hass, DOMAIN)
)
hass.services.async_register(
DOMAIN, "reset_trims", lambda call: reset_trims(hass, call, DOMAIN)
)
await async_register_vacuums_services(hass, data_coordinator)
# Registers update listener to update config entry when options are updated.
unsub_options_update_listener = entry.add_update_listener(options_update_listener)
# Store a reference to the unsubscribe function to clean up if an entry is unloaded.
Expand Down Expand Up @@ -146,9 +122,10 @@ async def async_unload_entry(
entry_data = hass.data[DOMAIN].pop(entry.entry_id)
entry_data["unsub_options_update_listener"]()
# Remove services
hass.services.async_remove(DOMAIN, "reset_trims")
hass.services.async_remove(DOMAIN, SERVICE_RELOAD)
await async_remove_vacuums_services(hass)
if not hass.data[DOMAIN]:
hass.services.async_remove(DOMAIN, "reset_trims")
hass.services.async_remove(DOMAIN, SERVICE_RELOAD)
await async_remove_vacuums_services(hass)
return unload_ok


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""Camera-related services for the MQTT Vacuum Camera integration."""

import logging


from homeassistant.core import ServiceCall, HomeAssistant
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import SERVICE_RELOAD

from ...utils.files_operations import async_clean_up_all_auto_crop_files

_LOGGER = logging.getLogger(__name__)

async def reset_trims(hass: HomeAssistant, call: ServiceCall, domain: str) -> None:
"""Action Reset Map Trims."""
_LOGGER.debug(f"Resetting trims for {domain}")
await async_clean_up_all_auto_crop_files(hass)
await hass.services.async_call(domain, SERVICE_RELOAD)
hass.bus.async_fire(f"event_{domain}_reset_trims", context=call.context)


async def reload_config(hass: HomeAssistant, domain: str) -> None:
"""Reload the camera platform for all entities in the integration."""
_LOGGER.debug(f"Reloading the config entry for all {domain} entities")
camera_entries = hass.config_entries.async_entries(domain)

for camera_entry in camera_entries:
if camera_entry.state == ConfigEntryState.LOADED:
_LOGGER.debug(f"Unloading entry: {camera_entry.entry_id}")
await hass.config_entries.async_unload(camera_entry.entry_id)

_LOGGER.debug(f"Reloading entry: {camera_entry.entry_id}")
await hass.config_entries.async_setup(camera_entry.entry_id)
else:
_LOGGER.debug(
f"Skipping entry {camera_entry.entry_id} as it is NOT_LOADED"
)

hass.bus.async_fire(f"event_{domain}_reloaded")
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.exceptions import ServiceValidationError

from custom_components.mqtt_vacuum_camera.common import (
from ...common import (
get_device_info_from_entity_id,
get_entity_id,
get_vacuum_mqtt_topic,
is_rand256_vacuum,
)
from custom_components.mqtt_vacuum_camera.const import DOMAIN
from ...const import DOMAIN

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -50,7 +50,7 @@ async def vacuum_clean_segments(call: ServiceCall, coordinator) -> None:
service_data["payload"],
)
except Exception as e:
raise ServiceValidationError(f"Error sending command to vacuum: {e}")
raise ServiceValidationError(f"Error sending command to vacuum: {e}") from e

coordinator.hass.bus.async_fire(
f"event_{DOMAIN}.vacuum_clean_zone",
Expand All @@ -62,7 +62,7 @@ async def vacuum_clean_segments(call: ServiceCall, coordinator) -> None:
context=call.context,
)
except KeyError as e:
raise ServiceValidationError(f"Missing required parameter: {e}")
raise ServiceValidationError(f"Missing required parameter: {e}") from e


async def vacuum_clean_zone(call: ServiceCall, coordinator) -> None:
Expand Down Expand Up @@ -95,7 +95,7 @@ async def vacuum_clean_zone(call: ServiceCall, coordinator) -> None:
service_data["payload"],
)
except Exception as e:
raise ServiceValidationError(f"Error sending command to vacuum: {e}")
raise ServiceValidationError(f"Error sending command to vacuum: {e}") from e
coordinator.hass.bus.async_fire(
f"event_{DOMAIN}.vacuum_clean_zone",
{
Expand All @@ -106,7 +106,7 @@ async def vacuum_clean_zone(call: ServiceCall, coordinator) -> None:
context=call.context,
)
except KeyError as e:
raise ServiceValidationError(f"Missing required parameter: {e}")
raise ServiceValidationError(f"Missing required parameter: {e}") from e


async def vacuum_goto(call: ServiceCall, coordinator) -> None:
Expand Down Expand Up @@ -138,15 +138,15 @@ async def vacuum_goto(call: ServiceCall, coordinator) -> None:
service_data["payload"],
)
except Exception as e:
raise ServiceValidationError(f"Error sending command to vacuum: {e}")
raise ServiceValidationError(f"Error sending command to vacuum: {e}") from e

coordinator.hass.bus.async_fire(
f"event_{DOMAIN}.vacuum_go_to",
{"topic": service_data["topic"], "x": x_coord, "y": y_coord},
context=call.context,
)
except KeyError as e:
raise ServiceValidationError(f"Missing required parameter: {e}")
raise ServiceValidationError(f"Missing required parameter: {e}") from e


async def vacuum_map_save(call: ServiceCall, coordinator) -> None:
Expand Down Expand Up @@ -181,15 +181,15 @@ async def vacuum_map_save(call: ServiceCall, coordinator) -> None:
service_data["payload"],
)
except Exception as e:
raise ServiceValidationError(f"Error sending command to vacuum: {e}")
raise ServiceValidationError(f"Error sending command to vacuum: {e}") from e

coordinator.hass.bus.async_fire(
f"event_{DOMAIN}.vacuum_map_save",
{"topic": service_data["topic"]},
context=call.context,
)
except KeyError as e:
raise ServiceValidationError(f"Missing required parameter: {e}")
raise ServiceValidationError(f"Missing required parameter: {e}") from e


async def vacuum_map_load(call: ServiceCall, coordinator) -> None:
Expand Down Expand Up @@ -224,7 +224,7 @@ async def vacuum_map_load(call: ServiceCall, coordinator) -> None:
service_data["payload"],
)
except Exception as e:
raise ServiceValidationError(f"Error sending command to vacuum: {e}")
raise ServiceValidationError(f"Error sending command to vacuum: {e}") from e

coordinator.hass.bus.async_fire(
f"event_{DOMAIN}.vacuum_map_load",
Expand All @@ -233,7 +233,7 @@ async def vacuum_map_load(call: ServiceCall, coordinator) -> None:
)
await coordinator.hass.services.async_call(DOMAIN, "reset_trims")
except KeyError as e:
raise ServiceValidationError(f"Missing required parameter: {e}")
raise ServiceValidationError(f"Missing required parameter: {e}") from e


def resolve_datas(
Expand Down

0 comments on commit 09400e6

Please sign in to comment.