Repository: home-assistant/core
Pull request: Disable 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.
-->
Disable sky connect config entry if USB stick is not plugged in when Home Assistant start.
The config entry will be re-enabled if the USB stick is plugged in again.

## 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.

Commit message: Disable 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..4315862e523b77 100644
--- a/homeassistant/components/homeassistant_sky_connect/__init__.py
+++ b/homeassistant/components/homeassistant_sky_connect/__init__.py
@@ -15,7 +15,7 @@
     get_addon_manager,
     get_zigbee_socket,
 )
-from homeassistant.config_entries import ConfigEntry
+from homeassistant.config_entries import ConfigEntry, ConfigEntryDisabler
 from homeassistant.core import HomeAssistant
 from homeassistant.exceptions import ConfigEntryNotReady
 
@@ -75,7 +75,12 @@ 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
+        hass.async_create_task(
+            hass.config_entries.async_set_disabled_by(
+                entry.entry_id, ConfigEntryDisabler.INTEGRATION
+            )
+        )
+        return False
 
     addon_info = await _multi_pan_addon_info(hass, entry)
 
diff --git a/homeassistant/components/homeassistant_sky_connect/config_flow.py b/homeassistant/components/homeassistant_sky_connect/config_flow.py
index 1e4fd8701cd3a0..076a093e5b0dd3 100644
--- a/homeassistant/components/homeassistant_sky_connect/config_flow.py
+++ b/homeassistant/components/homeassistant_sky_connect/config_flow.py
@@ -5,7 +5,7 @@
 
 from homeassistant.components import usb
 from homeassistant.components.homeassistant_hardware import silabs_multiprotocol_addon
-from homeassistant.config_entries import ConfigEntry, ConfigFlow
+from homeassistant.config_entries import ConfigEntry, ConfigEntryDisabler, ConfigFlow
 from homeassistant.core import callback
 from homeassistant.data_entry_flow import FlowResult
 
@@ -35,7 +35,12 @@ async def async_step_usb(self, discovery_info: usb.UsbServiceInfo) -> FlowResult
         manufacturer = discovery_info.manufacturer
         description = discovery_info.description
         unique_id = f"{vid}:{pid}_{serial_number}_{manufacturer}_{description}"
-        if await self.async_set_unique_id(unique_id):
+        if existing_entry := await self.async_set_unique_id(unique_id):
+            # Re-enable existing config entry which was disabled by USB unplug
+            if existing_entry.disabled_by == ConfigEntryDisabler.INTEGRATION:
+                await self.hass.config_entries.async_set_disabled_by(
+                    existing_entry.entry_id, None
+                )
             self._abort_if_unique_id_configured(updates={"device": device})
         return self.async_create_entry(
             title="Home Assistant Sky Connect",
diff --git a/homeassistant/config_entries.py b/homeassistant/config_entries.py
index 0f3fb0a3aea6cc..df8091d15d156a 100644
--- a/homeassistant/config_entries.py
+++ b/homeassistant/config_entries.py
@@ -158,6 +158,7 @@ class ConfigEntryChange(StrEnum):
 class ConfigEntryDisabler(StrEnum):
     """What disabled a config entry."""
 
+    INTEGRATION = "integration"
     USER = "user"
 
 
diff --git a/tests/components/homeassistant_sky_connect/test_init.py b/tests/components/homeassistant_sky_connect/test_init.py
index ebf1c74d9e0735..6b5668d0d24d4f 100644
--- a/tests/components/homeassistant_sky_connect/test_init.py
+++ b/tests/components/homeassistant_sky_connect/test_init.py
@@ -5,11 +5,12 @@
 
 import pytest
 
-from homeassistant.components import zha
+from homeassistant.components import usb, zha
 from homeassistant.components.hassio.handler import HassioAPIError
 from homeassistant.components.homeassistant_sky_connect.const import DOMAIN
-from homeassistant.config_entries import ConfigEntryState
+from homeassistant.config_entries import ConfigEntryDisabler, ConfigEntryState
 from homeassistant.core import HomeAssistant
+from homeassistant.data_entry_flow import FlowResultType
 
 from tests.common import MockConfigEntry
 
@@ -244,14 +245,22 @@ async def test_setup_zha_multipan_other_device(
     assert config_entry.title == CONFIG_ENTRY_DATA["description"]
 
 
-async def test_setup_entry_wait_usb(hass: HomeAssistant) -> None:
+async def test_setup_entry_wait_usb(
+    mock_zha_config_flow_setup, hass: HomeAssistant
+) -> None:
     """Test setup of a config entry when the dongle is not plugged in."""
     # Setup the config entry
+    vid = CONFIG_ENTRY_DATA["vid"]
+    pid = CONFIG_ENTRY_DATA["device"]
+    serial_number = CONFIG_ENTRY_DATA["serial_number"]
+    manufacturer = CONFIG_ENTRY_DATA["manufacturer"]
+    description = CONFIG_ENTRY_DATA["description"]
     config_entry = MockConfigEntry(
         data=CONFIG_ENTRY_DATA,
         domain=DOMAIN,
         options={},
         title="Home Assistant Sky Connect",
+        unique_id=f"{vid}:{pid}_{serial_number}_{manufacturer}_{description}",
     )
     config_entry.add_to_hass(hass)
     with patch(
@@ -261,7 +270,33 @@ async def test_setup_entry_wait_usb(hass: HomeAssistant) -> None:
         assert not await hass.config_entries.async_setup(config_entry.entry_id)
         await hass.async_block_till_done()
         assert len(mock_is_plugged_in.mock_calls) == 1
-        assert config_entry.state == ConfigEntryState.SETUP_RETRY
+        assert config_entry.disabled_by == ConfigEntryDisabler.INTEGRATION
+        assert config_entry.state == ConfigEntryState.NOT_LOADED
+
+    # USB dongle plugged in
+    usb_data = usb.UsbServiceInfo(
+        device=CONFIG_ENTRY_DATA["device"],
+        vid=CONFIG_ENTRY_DATA["vid"],
+        pid=CONFIG_ENTRY_DATA["device"],
+        serial_number=CONFIG_ENTRY_DATA["serial_number"],
+        manufacturer=CONFIG_ENTRY_DATA["manufacturer"],
+        description=CONFIG_ENTRY_DATA["description"],
+    )
+    with patch(
+        "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
+        return_value=True,
+    ) as mock_is_plugged_in, patch(
+        "homeassistant.components.onboarding.async_is_onboarded", return_value=True
+    ):
+        result = await hass.config_entries.flow.async_init(
+            DOMAIN, context={"source": "usb"}, data=usb_data
+        )
+        assert result["type"] == FlowResultType.ABORT
+
+        assert config_entry.disabled_by is None
+        assert config_entry.state == ConfigEntryState.LOADED
+
+        assert 1 == 2
 
 
 async def test_setup_entry_addon_info_fails(


Code review comments:
diff_hunk: @@ -261,7 +270,33 @@ async def test_setup_entry_wait_usb(hass: HomeAssistant) -> None:
         assert not await hass.config_entries.async_setup(config_entry.entry_id)
         await hass.async_block_till_done()
         assert len(mock_is_plugged_in.mock_calls) == 1
-        assert config_entry.state == ConfigEntryState.SETUP_RETRY
+        assert config_entry.disabled_by == ConfigEntryDisabler.INTEGRATION
+        assert config_entry.state == ConfigEntryState.NOT_LOADED
+
+    # USB dongle plugged in
+    usb_data = usb.UsbServiceInfo(
+        device=CONFIG_ENTRY_DATA["device"],
+        vid=CONFIG_ENTRY_DATA["vid"],
+        pid=CONFIG_ENTRY_DATA["device"],
+        serial_number=CONFIG_ENTRY_DATA["serial_number"],
+        manufacturer=CONFIG_ENTRY_DATA["manufacturer"],
+        description=CONFIG_ENTRY_DATA["description"],
+    )
+    with patch(
+        "homeassistant.components.homeassistant_sky_connect.usb.async_is_plugged_in",
+        return_value=True,
+    ) as mock_is_plugged_in, patch(
+        "homeassistant.components.onboarding.async_is_onboarded", return_value=True
+    ):
+        result = await hass.config_entries.flow.async_init(
+            DOMAIN, context={"source": "usb"}, data=usb_data
+        )
+        assert result["type"] == FlowResultType.ABORT
+
+        assert config_entry.disabled_by is None
+        assert config_entry.state == ConfigEntryState.LOADED
+
+        assert 1 == 2
path: tests/components/homeassistant_sky_connect/test_init.py
text: @user1:
Debug leftover?