BREAKING CHANGES!!!!!

BREAKING CHANGES!!!!!
YOU WILL HAVE TO REMOVE YOUR ORIGINAL ENTRIES AND READD THEM
This commit is contained in:
sudoxnym 2025-04-14 18:43:09 -06:00 committed by GitHub
parent f8f8c7927d
commit e94fe3a72b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 113 additions and 115 deletions

View file

@ -3,17 +3,16 @@ import logging
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from .const import DOMAIN from .const import DOMAIN
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .services import async_setup_services # Import the service setup function from .services import async_setup_services # Import the service setup function
_logger = logging.getLogger(__name__) _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.""" """Set up the SAAS - Sleep As Android Status component."""
_logger.info("Starting setup of the SAAS component") _logger.info("Starting setup of the SAAS component")
return True 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.""" """Set up a config entry."""
_logger.info(f"Starting setup of config entry with ID: {entry.entry_id}") _logger.info(f"Starting setup of config entry with ID: {entry.entry_id}")
hass.data.setdefault(DOMAIN, {}) 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]}") _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. # Forward the setup to the sensor and button platforms.
# Note: async_forward_entry_setups must always be awaited.
await hass.config_entries.async_forward_entry_setups(entry, ["sensor", "button"]) await hass.config_entries.async_forward_entry_setups(entry, ["sensor", "button"])
_logger.info(f"hass.data[DOMAIN] before async_setup_services: {hass.data[DOMAIN]}") _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") _logger.info("Starting setup of services")
await async_setup_services(hass) await async_setup_services(hass)
_logger.info("Finished setup of services") _logger.info("Finished setup of services")
_logger.info(f"hass.data[DOMAIN] after setup of services: {hass.data[DOMAIN]}") _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") _logger.info("Finished setup of config entry")
return True 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.""" """Unload a config entry."""
_logger.info(f"Starting unload of config entry with ID: {entry.entry_id}") _logger.info(f"Starting unload of config entry with ID: {entry.entry_id}")
# Remove the sensor platform # Unload sensor and button platforms.
_logger.info("Removing sensor platform") unload_ok = await hass.config_entries.async_unload_platforms(entry, ["sensor", "button"])
await hass.config_entries.async_forward_entry_unload(entry, "sensor") 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): if isinstance(hass.data.get(DOMAIN, {}), dict):
hass.data[DOMAIN].pop(entry.entry_id, None) hass.data[DOMAIN].pop(entry.entry_id, None)

View file

@ -1,40 +1,54 @@
import logging import logging
import traceback
import voluptuous as vol 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 import config_entries
from homeassistant.core import callback from homeassistant.core import callback
from voluptuous import Schema, Required, In, Optional from voluptuous import Schema, Required, In, Optional
from homeassistant.helpers import config_validation as cv 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): 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 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH
async def async_step_user(self, user_input=None): async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user.""" """Handle the initial step."""
errors = {} errors = {}
# Get the list of notify targets # Build notify targets list
notify_services = self.hass.services.async_services().get('notify', {}) 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_')} 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: if user_input is not None:
# Map the selected option back to the actual notify target name # Map back the chosen label to service name
user_input[CONF_NOTIFY_TARGET] = notify_targets[user_input[CONF_NOTIFY_TARGET]] if user_input.get(CONF_NOTIFY_TARGET):
user_input[CONF_NOTIFY_TARGET] = notify_targets.get(user_input[CONF_NOTIFY_TARGET])
# Validate the user input here if not user_input.get(CONF_NAME):
# 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" errors[CONF_NAME] = "required"
if not errors: if not errors:
return self.async_create_entry(title=user_input[CONF_NAME], data=user_input) return self.async_create_entry(title=user_input[CONF_NAME], data=user_input)
return self.async_show_form( return self.async_show_form(
step_id="user", step_id="user",
data_schema=Schema( 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_SLEEP_DURATION, default=DEFAULT_SLEEP_DURATION): int,
Required(CONF_AWAKE_STATES, default=DEFAULT_AWAKE_STATES): cv.multi_select(AVAILABLE_STATES), 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), 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, 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 @staticmethod
@callback @callback
def async_get_options_flow(config_entry): def async_get_options_flow(entry):
"""Get the options flow for this handler.""" """Get the options flow handler."""
return OptionsFlowHandler(config_entry) return OptionsFlowHandler(entry)
class OptionsFlowHandler(config_entries.OptionsFlow): class OptionsFlowHandler(config_entries.OptionsFlow):
"""Handle options.""" """Handle SAAS options."""
def __init__(self, config_entry):
def __init__(self, entry):
"""Initialize options flow.""" """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): async def async_step_init(self, user_input=None):
"""Manage the options.""" """Manage the options."""
_logger.debug("Entering async_step_init with user_input: %s", user_input) # Load current options or fall back to data
current = self._config_entry.options.copy()
errors = {} # Define errors here for key in [
CONF_NAME,
try: CONF_TOPIC,
# Fetch the initial configuration data CONF_QOS,
current_data = self.hass.data[DOMAIN].get(self.config_entry.entry_id, self.config_entry.options) CONF_AWAKE_DURATION,
_logger.debug("Current data fetched: %s", current_data) CONF_SLEEP_DURATION,
CONF_AWAKE_STATES,
# Get the list of notify targets CONF_SLEEP_STATES,
notify_services = self.hass.services.async_services().get('notify', {}) CONF_NOTIFY_TARGET,
notify_targets = {target.replace('mobile_app_', '').title(): target for target in notify_services.keys() if target.startswith('mobile_app_')} ]:
if key not in current and key in self._config_entry.data:
if user_input is not None: current[key] = self._config_entry.data[key]
# 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))
def get_data_schema(self, current_data): # Build notify targets list
# Get the list of notify targets notify_services = self.hass.services.async_services().get("notify", {})
notify_services = self.hass.services.async_services().get('notify', {}) notify_targets = {
notify_targets = {target.replace('mobile_app_', '').title(): target for target in notify_services.keys() if target.startswith('mobile_app_')} key.replace("mobile_app_", "").title(): key
for key in notify_services.keys()
# Extract the part after 'mobile_app_' and capitalize if key.startswith("mobile_app_")
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
if user_input is not None:
return Schema( return self.async_create_entry(title="", data=user_input)
{
Required(CONF_NAME, default=current_data.get(CONF_NAME, "")): str, return self.async_show_form(
Required(CONF_TOPIC, default=current_data.get(CONF_TOPIC, "")): str, step_id="init",
Required(CONF_QOS, default=current_data.get(CONF_QOS, 0)): In([0, 1, 2]), data_schema=vol.Schema(
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_NAME, default=current.get(CONF_NAME, "")): str,
Required(CONF_AWAKE_STATES, default=current_data.get(CONF_AWAKE_STATES, DEFAULT_AWAKE_STATES)): cv.multi_select(AVAILABLE_STATES), Required(CONF_TOPIC, default=current.get(CONF_TOPIC, "")): str,
Required(CONF_SLEEP_STATES, default=current_data.get(CONF_SLEEP_STATES, DEFAULT_SLEEP_STATES)): cv.multi_select(AVAILABLE_STATES), Required(CONF_QOS, default=current.get(CONF_QOS, 0)): In([0, 1, 2]),
Optional(CONF_NOTIFY_TARGET, default=notify_target): vol.In(list(notify_targets.keys())), 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={},
)