diff --git a/custom_components/saas/__init__.py b/custom_components/saas/__init__.py index 28671be..a9055ff 100644 --- a/custom_components/saas/__init__.py +++ b/custom_components/saas/__init__.py @@ -3,17 +3,16 @@ import logging from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from .const import DOMAIN -from homeassistant.helpers.dispatcher import async_dispatcher_connect from .services import async_setup_services # Import the service setup function _logger = logging.getLogger(__name__) -async def async_setup(hass: HomeAssistant, config: dict): +async def async_setup(hass: HomeAssistant, config: dict) -> bool: """Set up the SAAS - Sleep As Android Status component.""" _logger.info("Starting setup of the SAAS component") return True -async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up a config entry.""" _logger.info(f"Starting setup of config entry with ID: {entry.entry_id}") hass.data.setdefault(DOMAIN, {}) @@ -23,37 +22,30 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): _logger.info(f"hass.data[DOMAIN] after adding entry data: {hass.data[DOMAIN]}") - # Forward the setup to the sensor and button platforms using the new method. - # Note: async_forward_entry_setups must always be awaited. + # Forward the setup to the sensor and button platforms. await hass.config_entries.async_forward_entry_setups(entry, ["sensor", "button"]) _logger.info(f"hass.data[DOMAIN] before async_setup_services: {hass.data[DOMAIN]}") - # Setup the services + # Setup the services. _logger.info("Starting setup of services") await async_setup_services(hass) _logger.info("Finished setup of services") _logger.info(f"hass.data[DOMAIN] after setup of services: {hass.data[DOMAIN]}") - - async def reload_entry(): - _logger.info("Reloading entry") - await hass.config_entries.async_reload(entry.entry_id) - - async_dispatcher_connect(hass, f"{DOMAIN}_reload_{entry.entry_id}", reload_entry) - _logger.info("Finished setup of config entry") return True -async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" _logger.info(f"Starting unload of config entry with ID: {entry.entry_id}") - # Remove the sensor platform - _logger.info("Removing sensor platform") - await hass.config_entries.async_forward_entry_unload(entry, "sensor") + # Unload sensor and button platforms. + unload_ok = await hass.config_entries.async_unload_platforms(entry, ["sensor", "button"]) + if not unload_ok: + _logger.error("Failed to unload platforms for saas") + return False - # Ensure hass.data[DOMAIN] is a dictionary before popping if isinstance(hass.data.get(DOMAIN, {}), dict): hass.data[DOMAIN].pop(entry.entry_id, None) diff --git a/custom_components/saas/config_flow.py b/custom_components/saas/config_flow.py index 9bd25fe..8d6af05 100644 --- a/custom_components/saas/config_flow.py +++ b/custom_components/saas/config_flow.py @@ -1,40 +1,54 @@ import logging -import traceback import voluptuous as vol -from .const import DOMAIN, CONF_NAME, CONF_TOPIC, CONF_QOS, AVAILABLE_STATES, CONF_AWAKE_DURATION, CONF_SLEEP_DURATION, CONF_AWAKE_STATES, CONF_SLEEP_STATES, DEFAULT_AWAKE_DURATION, DEFAULT_SLEEP_DURATION, DEFAULT_AWAKE_STATES, DEFAULT_SLEEP_STATES, CONF_NOTIFY_TARGET +from .const import ( + DOMAIN, + CONF_NAME, + CONF_TOPIC, + CONF_QOS, + AVAILABLE_STATES, + CONF_AWAKE_DURATION, + CONF_SLEEP_DURATION, + CONF_AWAKE_STATES, + CONF_SLEEP_STATES, + DEFAULT_AWAKE_DURATION, + DEFAULT_SLEEP_DURATION, + DEFAULT_AWAKE_STATES, + DEFAULT_SLEEP_STATES, + CONF_NOTIFY_TARGET, +) from homeassistant import config_entries from homeassistant.core import callback from voluptuous import Schema, Required, In, Optional from homeassistant.helpers import config_validation as cv -from homeassistant.helpers.dispatcher import async_dispatcher_send -_logger = logging.getLogger(__name__) +_LOGGER = logging.getLogger(__name__) class MyConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): - VERSION = 1 + """Handle a config flow for SAAS.""" + VERSION = 2 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH async def async_step_user(self, user_input=None): - """Handle a flow initialized by the user.""" + """Handle the initial step.""" errors = {} - - # Get the list of notify targets - notify_services = self.hass.services.async_services().get('notify', {}) - notify_targets = {target.replace('mobile_app_', '').title(): target for target in notify_services.keys() if target.startswith('mobile_app_')} - + + # Build notify targets list + notify_services = self.hass.services.async_services().get("notify", {}) + notify_targets = { + key.replace("mobile_app_", "").title(): key + for key in notify_services.keys() + if key.startswith("mobile_app_") + } + if user_input is not None: - # Map the selected option back to the actual notify target name - user_input[CONF_NOTIFY_TARGET] = notify_targets[user_input[CONF_NOTIFY_TARGET]] - - # Validate the user input here - # If the input is valid, create an entry - # If the input is not valid, add an error message to the 'errors' dictionary - # For example: - if not user_input[CONF_NAME]: + # Map back the chosen label to service name + if user_input.get(CONF_NOTIFY_TARGET): + user_input[CONF_NOTIFY_TARGET] = notify_targets.get(user_input[CONF_NOTIFY_TARGET]) + if not user_input.get(CONF_NAME): errors[CONF_NAME] = "required" if not errors: return self.async_create_entry(title=user_input[CONF_NAME], data=user_input) - + return self.async_show_form( step_id="user", data_schema=Schema( @@ -46,94 +60,86 @@ class MyConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): Required(CONF_SLEEP_DURATION, default=DEFAULT_SLEEP_DURATION): int, Required(CONF_AWAKE_STATES, default=DEFAULT_AWAKE_STATES): cv.multi_select(AVAILABLE_STATES), Required(CONF_SLEEP_STATES, default=DEFAULT_SLEEP_STATES): cv.multi_select(AVAILABLE_STATES), - Optional(CONF_NOTIFY_TARGET): vol.In(list(notify_targets.keys())), + Optional(CONF_NOTIFY_TARGET): vol.In(list(notify_targets.keys())), } ), errors=errors, ) + async def async_migrate_entry(self, hass, entry): + """Migrate old config entries to the new schema.""" + _LOGGER.debug("Migrating config entry %s from version %s", entry.entry_id, entry.version) + data = {**entry.data} + options = {**entry.options} + + # If you renamed keys in entry.data/options, do it here when entry.version == 1 + # e.g.: + # if entry.version == 1: + # data["topic_template"] = data.pop("topic") + # entry.version = 2 + + # For no data changes, just bump the version: + entry.version = self.VERSION + hass.config_entries.async_update_entry(entry, data=data, options=options) + _LOGGER.info("Migrated config entry %s to version %s", entry.entry_id, entry.version) + return True + @staticmethod @callback - def async_get_options_flow(config_entry): - """Get the options flow for this handler.""" - return OptionsFlowHandler(config_entry) + def async_get_options_flow(entry): + """Get the options flow handler.""" + return OptionsFlowHandler(entry) + class OptionsFlowHandler(config_entries.OptionsFlow): - """Handle options.""" - def __init__(self, config_entry): + """Handle SAAS options.""" + + def __init__(self, entry): """Initialize options flow.""" - self.config_entry = config_entry + super().__init__() + self._config_entry = entry # use private attribute async def async_step_init(self, user_input=None): """Manage the options.""" - _logger.debug("Entering async_step_init with user_input: %s", user_input) - - errors = {} # Define errors here - - try: - # Fetch the initial configuration data - current_data = self.hass.data[DOMAIN].get(self.config_entry.entry_id, self.config_entry.options) - _logger.debug("Current data fetched: %s", current_data) - - # Get the list of notify targets - notify_services = self.hass.services.async_services().get('notify', {}) - notify_targets = {target.replace('mobile_app_', '').title(): target for target in notify_services.keys() if target.startswith('mobile_app_')} - - if user_input is not None: - # Validate the user input here - # If the input is valid, create an entry - # If the input is not valid, add an error message to the 'errors' dictionary - # For example: - if not user_input[CONF_NAME]: - errors[CONF_NAME] = "required" - if errors: - return self.async_show_form(step_id="init", data_schema=self.get_data_schema(current_data), errors=errors) # Pass errors to async_show_form - - # Map the selected option back to the actual notify target name - user_input[CONF_NOTIFY_TARGET] = notify_targets[user_input[CONF_NOTIFY_TARGET]] - - # Merge current_data with user_input - updated_data = {**current_data, **user_input} - _logger.debug("User input is not None, updated data: %s", updated_data) - - _logger.debug("Updating entry with updated data: %s", updated_data) - - if updated_data is not None: - self.hass.data[DOMAIN][self.config_entry.entry_id] = updated_data # Save updated data - - # Update the entry data - self.hass.config_entries.async_update_entry(self.config_entry, data=updated_data) - - # Send a signal to reload the integration - async_dispatcher_send(self.hass, f"{DOMAIN}_reload_{self.config_entry.entry_id}") - - return self.async_create_entry(title="", data=updated_data) - - _logger.debug("User input is None, showing form with current_data: %s", current_data) - return self.async_show_form(step_id="init", data_schema=self.get_data_schema(current_data), errors=errors) # Pass errors to async_show_form - - except Exception as e: - _logger.error("Error in async_step_init: %s", str(e)) - return self.async_abort(reason=str(e)) + # Load current options or fall back to data + current = self._config_entry.options.copy() + for key in [ + CONF_NAME, + CONF_TOPIC, + CONF_QOS, + CONF_AWAKE_DURATION, + CONF_SLEEP_DURATION, + CONF_AWAKE_STATES, + CONF_SLEEP_STATES, + CONF_NOTIFY_TARGET, + ]: + if key not in current and key in self._config_entry.data: + current[key] = self._config_entry.data[key] - def get_data_schema(self, current_data): - # Get the list of notify targets - notify_services = self.hass.services.async_services().get('notify', {}) - notify_targets = {target.replace('mobile_app_', '').title(): target for target in notify_services.keys() if target.startswith('mobile_app_')} - - # Extract the part after 'mobile_app_' and capitalize - notify_target = current_data.get(CONF_NOTIFY_TARGET, "") - notify_target = notify_target.replace('mobile_app_', '').title() if notify_target.startswith('mobile_app_') else notify_target - - return Schema( - { - Required(CONF_NAME, default=current_data.get(CONF_NAME, "")): str, - Required(CONF_TOPIC, default=current_data.get(CONF_TOPIC, "")): str, - Required(CONF_QOS, default=current_data.get(CONF_QOS, 0)): In([0, 1, 2]), - Required(CONF_AWAKE_DURATION, default=current_data.get(CONF_AWAKE_DURATION, DEFAULT_AWAKE_DURATION)): int, - Required(CONF_SLEEP_DURATION, default=current_data.get(CONF_SLEEP_DURATION, DEFAULT_SLEEP_DURATION)): int, - Required(CONF_AWAKE_STATES, default=current_data.get(CONF_AWAKE_STATES, DEFAULT_AWAKE_STATES)): cv.multi_select(AVAILABLE_STATES), - Required(CONF_SLEEP_STATES, default=current_data.get(CONF_SLEEP_STATES, DEFAULT_SLEEP_STATES)): cv.multi_select(AVAILABLE_STATES), - Optional(CONF_NOTIFY_TARGET, default=notify_target): vol.In(list(notify_targets.keys())), - } - ) \ No newline at end of file + # Build notify targets list + notify_services = self.hass.services.async_services().get("notify", {}) + notify_targets = { + key.replace("mobile_app_", "").title(): key + for key in notify_services.keys() + if key.startswith("mobile_app_") + } + + if user_input is not None: + return self.async_create_entry(title="", data=user_input) + + return self.async_show_form( + step_id="init", + data_schema=vol.Schema( + { + Required(CONF_NAME, default=current.get(CONF_NAME, "")): str, + Required(CONF_TOPIC, default=current.get(CONF_TOPIC, "")): str, + Required(CONF_QOS, default=current.get(CONF_QOS, 0)): In([0, 1, 2]), + Required(CONF_AWAKE_DURATION, default=current.get(CONF_AWAKE_DURATION, DEFAULT_AWAKE_DURATION)): int, + Required(CONF_SLEEP_DURATION, default=current.get(CONF_SLEEP_DURATION, DEFAULT_SLEEP_DURATION)): int, + Required(CONF_AWAKE_STATES, default=current.get(CONF_AWAKE_STATES, DEFAULT_AWAKE_STATES)): cv.multi_select(AVAILABLE_STATES), + Required(CONF_SLEEP_STATES, default=current.get(CONF_SLEEP_STATES, DEFAULT_SLEEP_STATES)): cv.multi_select(AVAILABLE_STATES), + Optional(CONF_NOTIFY_TARGET, default=current.get(CONF_NOTIFY_TARGET, "")): vol.In(list(notify_targets.keys())), + } + ), + errors={}, + )