Repository: home-assistant/core
Pull request: Remove sky connect config entry if USB stick is not plugged in
<!--
  You are amazing! Thanks for contributing to our project!
  Please, DO NOT DELETE ANY TEXT from this template! (unless instructed).
-->
## Proposed change
<!--
  Describe the big picture of your changes here to communicate to the
  maintainers why we should accept this pull request. If it fixes a bug
  or resolves a feature request, be sure to link to that issue in the
  additional information section.
-->
Remove sky connect config entry if USB stick is not plugged in

~~Third~~Fourth time's the charm?

All iterations:
 1. https://github.com/home-assistant/core/pull/84975 💥 
 2. https://github.com/home-assistant/core/pull/85225 💥 
 3. https://github.com/home-assistant/core/pull/85758 💥
 4. This PR 🥉

## Type of change
<!--
  What type of change does your PR introduce to Home Assistant?
  NOTE: Please, check only 1! box!
  If your PR requires multiple boxes to be checked, you'll most likely need to
  split it into multiple PRs. This makes things easier and faster to code review.
-->

- [ ] Dependency upgrade
- [x] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [ ] New feature (which adds functionality to an existing integration)
- [ ] Deprecation (breaking change to happen in the future)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests

## Additional information
<!--
  Details are important, and help maintainers processing your PR.
  Please be sure to fill out additional details, if applicable.
-->

- This PR fixes or closes issue: fixes https://github.com/home-assistant/core/issues/83725
- This PR is related to issue: 
- Link to documentation pull request: 

## Checklist
<!--
  Put an `x` in the boxes that apply. You can also fill these out after
  creating the PR. If you're unsure about any of them, don't hesitate to ask.
  We're here to help! This is simply a reminder of what we are going to look
  for before merging your code.
-->

- [ ] The code change is tested and works locally.
- [ ] Local tests pass. **Your PR cannot be merged unless tests pass**
- [ ] There is no commented out code in this PR.
- [ ] I have followed the [development checklist][dev-checklist]
- [ ] The code has been formatted using Black (`black --fast homeassistant tests`)
- [ ] Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

- [ ] Documentation added/updated for [www.home-assistant.io][docs-repository]

If the code communicates with devices, web services, or third-party tools:

- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.  
      Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.  
      Updated by running `python3 -m script.gen_requirements_all`.
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.
- [ ] Untested files have been added to `.coveragerc`.

<!--
  This project is very active and we have a high turnover of pull requests.

  Unfortunately, the number of incoming pull requests is higher than what our
  reviewers can review and merge so there is a long backlog of pull requests
  waiting for review. You can help here!
  
  By reviewing another pull request, you will help raise the code quality of
  that pull request and the final review will be faster. This way the general
  pace of pull request reviews will go up and your wait time will go down.
  
  When picking a pull request to review, try to choose one that hasn't yet
  been reviewed.

  Thanks for helping out!
-->

To help with the load of incoming pull requests:

- [ ] I have reviewed two other [open pull requests][prs] in this repository.

[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure

<!--
  Thank you for contributing <3

  Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/en/development_checklist.html
[manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html
[quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html
[docs-repository]: https://github.com/home-assistant/home-assistant.io


Problem statement:
When removing integration "Sky Connect USB" from Raspberry Pi it keeps trying to find it.
### The problem

Hi,

As the title suggest: I disabled the Home Assistant Sky Connect integration. Then removed the USB stick from the Pi. And then deleted the integration. Rebooted. But in the log this keeps popping up:

```
Logger: homeassistant.config_entries
Source: config_entries.py:412
First occurred: 18:25:46 (1 occurrences)
Last logged: 18:25:46

Config entry 'Home Assistant Sky Connect' for homeassistant_sky_connect integration not ready yet: None; Retrying in background
```

### What version of Home Assistant Core has the issue?

2022.12.1

### What was the last working version of Home Assistant Core?

2022.12.1

### What type of installation are you running?

Home Assistant OS

### Integration causing the issue

New Sky Connect USB stick from Nabu Casa

### Link to integration documentation on our website

_No response_

### Diagnostics information

_No response_

### Example YAML snippet

```yaml
Config flow
```


### Anything in the logs that might be useful for us?

_No response_

### Additional information

Reboot doesn't help. I don't have anything to remove because allready removed it, so nothing I can do about it.

Hints from issue discussion:
Hey there @home-assistant/core, mind taking a look at this issue as it has been labeled with an integration (`homeassistant_sky_connect`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L488) for? Thanks!

<details>
<summary>Code owner commands</summary>


Code owners of `homeassistant_sky_connect` can trigger bot actions by commenting:

- `@home-assistant close` Closes the issue.
- `@home-assistant rename Awesome new title` Change the title of the issue.
- `@home-assistant reopen` Reopen the issue.
- `@home-assistant unassign homeassistant_sky_connect` Removes the current integration label and assignees on the issue, add the integration domain after the command.

</details>


<sub><sup>(message by CodeOwnersMention)</sup></sub>

---

[homeassistant_sky_connect documentation](https://www.home-assistant.io/integrations/homeassistant_sky_connect)
[homeassistant_sky_connect source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/homeassistant_sky_connect)
<sub><sup>(message by IssueLinks)</sup></sub>
@balloob Seems important error about new Sky Connect product. Anyone interested? If not I can close my case... 
What you have removed is the ZHA config entry; the `homeassistant_sky_connect` config entry is still there.
It's not nice that there are never ending warnings when the USB stick is removed, we should maybe let the config entry either disable itself, or remove itself, if the USB stick is not plugged in, or lower the log severity from warning to debug or info.

The solution in #84975 was not working well and has been reverted

Commit message: Remove sky connect config entry if USB stick is not plugged in

Patch to review:
diff --git a/homeassistant/components/homeassistant_sky_connect/__init__.py b/homeassistant/components/homeassistant_sky_connect/__init__.py
index 08d54bdef1283f..42bde2d38241cd 100644
--- a/homeassistant/components/homeassistant_sky_connect/__init__.py
+++ b/homeassistant/components/homeassistant_sky_connect/__init__.py
@@ -16,7 +16,7 @@
     get_zigbee_socket,
 )
 from homeassistant.config_entries import ConfigEntry
-from homeassistant.core import HomeAssistant
+from homeassistant.core import HomeAssistant, callback
 from homeassistant.exceptions import ConfigEntryNotReady
 
 from .const import DOMAIN
@@ -25,12 +25,10 @@
 _LOGGER = logging.getLogger(__name__)
 
 
-async def _multi_pan_addon_info(
-    hass: HomeAssistant, entry: ConfigEntry
-) -> AddonInfo | None:
-    """Return AddonInfo if the multi-PAN addon is enabled for our SkyConnect."""
+async def _wait_multi_pan_addon(hass: HomeAssistant, entry: ConfigEntry) -> None:
+    """Wait for multi-PAN info to be available."""
     if not is_hassio(hass):
-        return None
+        return
 
     addon_manager: AddonManager = get_addon_manager(hass)
     try:
@@ -50,7 +48,18 @@ async def _multi_pan_addon_info(
         )
         raise ConfigEntryNotReady
 
-    if addon_info.state == AddonState.NOT_INSTALLED:
+
+async def _multi_pan_addon_info(
+    hass: HomeAssistant, entry: ConfigEntry
+) -> AddonInfo | None:
+    """Return AddonInfo if the multi-PAN addon is enabled for our SkyConnect."""
+    if not is_hassio(hass):
+        return None
+
+    addon_manager: AddonManager = get_addon_manager(hass)
+    addon_info: AddonInfo = await addon_manager.async_get_addon_info()
+
+    if addon_info.state != AddonState.RUNNING:
         return None
 
     usb_dev = entry.data["device"]
@@ -62,7 +71,7 @@ async def _multi_pan_addon_info(
     return addon_info
 
 
-async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
+async def _async_usb_discovery_started(hass: HomeAssistant, entry: ConfigEntry) -> None:
     """Set up a Home Assistant Sky Connect config entry."""
     matcher = usb.USBCallbackMatcher(
         domain=DOMAIN,
@@ -74,8 +83,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
     )
 
     if not usb.async_is_plugged_in(hass, matcher):
-        # The USB dongle is not plugged in
-        raise ConfigEntryNotReady
+        # The USB dongle is not plugged in, remove the config entry
+        hass.async_create_task(hass.config_entries.async_remove(entry.entry_id))
 
     addon_info = await _multi_pan_addon_info(hass, entry)
 
@@ -86,7 +95,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
             context={"source": "usb"},
             data=usb_info,
         )
-        return True
+        return
 
     hw_discovery_data = {
         "name": "Sky Connect Multi-PAN",
@@ -101,6 +110,22 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
         data=hw_discovery_data,
     )
 
+
+async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
+    """Set up a Home Assistant Sky Connect config entry."""
+
+    await _wait_multi_pan_addon(hass, entry)
+
+    @callback
+    def async_usb_discovery_started() -> None:
+        """Handle usb discovery started."""
+        hass.async_add_job(_async_usb_discovery_started, hass, entry)
+
+    unsub_usb = usb.async_register_discovery_started_callback(
+        hass, async_usb_discovery_started
+    )
+    entry.async_on_unload(unsub_usb)
+
     return True
 
 
diff --git a/homeassistant/components/usb/__init__.py b/homeassistant/components/usb/__init__.py
index 0f81d2e42d6714..d030e3f45507db 100644
--- a/homeassistant/components/usb/__init__.py
+++ b/homeassistant/components/usb/__init__.py
@@ -61,6 +61,18 @@ def async_register_scan_request_callback(
     return discovery.async_register_scan_request_callback(callback)
 
 
+@hass_callback
+def async_register_discovery_started_callback(
+    hass: HomeAssistant, callback: CALLBACK_TYPE
+) -> CALLBACK_TYPE:
+    """Register to receive a callback when USB discovery has started.
+
+    If USB discovery is already started, the callback is called immediately.
+    """
+    discovery: USBDiscovery = hass.data[DOMAIN]
+    return discovery.async_register_discovery_started_callback(callback)
+
+
 @hass_callback
 def async_is_plugged_in(hass: HomeAssistant, matcher: USBCallbackMatcher) -> bool:
     """Return True is a USB device is present."""
@@ -186,6 +198,8 @@ def __init__(
         self.observer_active = False
         self._request_debouncer: Debouncer[Coroutine[Any, Any, None]] | None = None
         self._request_callbacks: list[CALLBACK_TYPE] = []
+        self.discovery_started = False
+        self._discovery_started_callbacks: list[CALLBACK_TYPE] = []
 
     async def async_setup(self) -> None:
         """Set up USB Discovery."""
@@ -195,6 +209,9 @@ async def async_setup(self) -> None:
     async def async_start(self, event: Event) -> None:
         """Start USB Discovery and run a manual scan."""
         await self._async_scan_serial()
+        for callback in self._discovery_started_callbacks:
+            callback()
+        self.discovery_started = True
 
     async def _async_start_monitor(self) -> None:
         """Start monitoring hardware with pyudev."""
@@ -249,7 +266,7 @@ def async_register_scan_request_callback(
         self,
         _callback: CALLBACK_TYPE,
     ) -> CALLBACK_TYPE:
-        """Register a callback."""
+        """Register a scan request callback."""
         self._request_callbacks.append(_callback)
 
         @hass_callback
@@ -258,6 +275,26 @@ def _async_remove_callback() -> None:
 
         return _async_remove_callback
 
+    @hass_callback
+    def async_register_discovery_started_callback(
+        self,
+        callback: CALLBACK_TYPE,
+    ) -> CALLBACK_TYPE:
+        """Register a discovery started callback."""
+        if self.discovery_started:
+            callback()
+            return lambda: None
+
+        self._discovery_started_callbacks.append(callback)
+
+        @hass_callback
+        def _async_remove_callback() -> None:
+            if callback not in self._discovery_started_callbacks:
+                return
+            self._discovery_started_callbacks.remove(callback)
+
+        return _async_remove_callback
+
     @hass_callback
     def _async_process_discovered_usb_device(self, device: USBDevice) -> None:
         """Process a USB discovery."""
diff --git a/tests/components/homeassistant_sky_connect/test_hardware.py b/tests/components/homeassistant_sky_connect/test_hardware.py
index 01f0e6ac5d760a..09e650388c5a40 100644
--- a/tests/components/homeassistant_sky_connect/test_hardware.py
+++ b/tests/components/homeassistant_sky_connect/test_hardware.py
@@ -2,9 +2,10 @@
 from unittest.mock import patch
 
 from homeassistant.components.homeassistant_sky_connect.const import DOMAIN
-from homeassistant.core import HomeAssistant
+from homeassistant.core import EVENT_HOMEASSISTANT_STARTED, HomeAssistant
+from homeassistant.setup import async_setup_component
 
-from tests.common import MockConfigEntry, MockModule, mock_integration
+from tests.common import MockConfigEntry
 
 CONFIG_ENTRY_DATA = {
     "device": "bla_device",
@@ -29,7 +30,8 @@ async def test_hardware_info(
     hass: HomeAssistant, hass_ws_client, addon_store_info
 ) -> None:
     """Test we can get the board info."""
-    mock_integration(hass, MockModule("usb"))
+    assert await async_setup_component(hass, "usb", {})
+    hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
 
     # Setup the config entry
     config_entry = MockConfigEntry(
diff --git a/tests/components/homeassistant_sky_connect/test_init.py b/tests/components/homeassistant_sky_connect/test_init.py
index ebf1c74d9e0735..c47066e8bc9209 100644
--- a/tests/components/homeassistant_sky_connect/test_init.py
+++ b/tests/components/homeassistant_sky_connect/test_init.py
@@ -9,7 +9,8 @@
 from homeassistant.components.hassio.handler import HassioAPIError
 from homeassistant.components.homeassistant_sky_connect.const import DOMAIN
 from homeassistant.config_entries import ConfigEntryState
-from homeassistant.core import HomeAssistant
+from homeassistant.core import EVENT_HOMEASSISTANT_STARTED, HomeAssistant
+from homeassistant.setup import async_setup_component
 
 from tests.common import MockConfigEntry
 
@@ -55,6 +56,9 @@ async def test_setup_entry(
     num_flows,
 ) -> None:
     """Test setup of a config entry, including setup of zha."""
+    assert await async_setup_component(hass, "usb", {})
+    hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
+
     # Setup the config entry
     config_entry = MockConfigEntry(
         data=CONFIG_ENTRY_DATA,
@@ -100,6 +104,9 @@ async def test_setup_zha(
     mock_zha_config_flow_setup, hass: HomeAssistant, addon_store_info
 ) -> None:
     """Test zha gets the right config."""
+    assert await async_setup_component(hass, "usb", {})
+    hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
+
     # Setup the config entry
     config_entry = MockConfigEntry(
         data=CONFIG_ENTRY_DATA,
@@ -146,6 +153,9 @@ async def test_setup_zha_multipan(
     hass: HomeAssistant, addon_info, addon_running
 ) -> None:
     """Test zha gets the right config."""
+    assert await async_setup_component(hass, "usb", {})
+    hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
+
     addon_info.return_value["options"]["device"] = CONFIG_ENTRY_DATA["device"]
 
     # Setup the config entry
@@ -197,6 +207,9 @@ async def test_setup_zha_multipan_other_device(
     mock_zha_config_flow_setup, hass: HomeAssistant, addon_info, addon_running
 ) -> None:
     """Test zha gets the right config."""
+    assert await async_setup_component(hass, "usb", {})
+    hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
+
     addon_info.return_value["options"]["device"] = "/dev/not_our_sky_connect"
 
     # Setup the config entry
@@ -258,16 +271,23 @@ async def test_setup_entry_wait_usb(hass: HomeAssistant) -> None:
         "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
         return_value=False,
     ) as mock_is_plugged_in:
-        assert not await hass.config_entries.async_setup(config_entry.entry_id)
+        await hass.config_entries.async_setup(config_entry.entry_id)
+        assert config_entry.state == ConfigEntryState.LOADED
+        assert len(hass.config_entries.async_entries(DOMAIN)) == 1
+        # USB discovery starts, config entry should be removed
+        hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
         await hass.async_block_till_done()
         assert len(mock_is_plugged_in.mock_calls) == 1
-        assert config_entry.state == ConfigEntryState.SETUP_RETRY
+        assert len(hass.config_entries.async_entries(DOMAIN)) == 0
 
 
 async def test_setup_entry_addon_info_fails(
     hass: HomeAssistant, addon_store_info
 ) -> None:
     """Test setup of a config entry when fetching addon info fails."""
+    assert await async_setup_component(hass, "usb", {})
+    hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
+
     addon_store_info.side_effect = HassioAPIError("Boom")
 
     # Setup the config entry
@@ -296,6 +316,9 @@ async def test_setup_entry_addon_not_running(
     hass: HomeAssistant, addon_installed, start_addon
 ) -> None:
     """Test the addon is started if it is not running."""
+    assert await async_setup_component(hass, "usb", {})
+    hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
+
     # Setup the config entry
     config_entry = MockConfigEntry(
         data=CONFIG_ENTRY_DATA,


Code review comments:
diff_hunk: @@ -101,6 +110,22 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
         data=hw_discovery_data,
     )
 
+
+async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
+    """Set up a Home Assistant Sky Connect config entry."""
+
+    await _wait_multi_pan_addon(hass, entry)
+
+    @callback
+    def async_usb_discovery_started() -> None:
+        """Handle usb discovery started."""
+        hass.async_add_job(_async_usb_discovery_started, hass, entry)
path: homeassistant/components/homeassistant_sky_connect/__init__.py
text: @user1:
```suggestion
        hass.async_create_task(_async_usb_discovery_started, hass, entry)
```