Repository: home-assistant/core
Pull request: Set and check unique id of config in NUT
<!--
  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.
-->
While the NUT config_flow checks for duplicate alias/hostname/port, the actual device unique_id is generally of the form manufacturer_model_serial.  This PR checks for a duplicate using the standard async_set_unique_id() and _abort_if_unique_id_configured() functions to conform to the integration quality standard.  The NUT configuration's setup function has been update to sets the config_entry's to the unique_id if not already defined.

Add test cases to test for duplicate device unique_id.

It would be great if others could help (1) confirm that async_update_entry should be called to set the config_entry's unique_id in async_setup_entry, and (2) that we wish to retain the alias@host:port check as well.  As to the latter, since the device's unique_id is based on properties of the device itself, it seems as though this could be removed, but I'm uncertain as to its history.

## 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!)
- [X] 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 #141230 
- This PR is related to issue: 
- Link to documentation pull request: 
- Link to developer documentation pull request: 
- Link to frontend 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.
-->

- [X] The code change is tested and works locally.
- [X] Local tests pass. **Your PR cannot be merged unless tests pass**
- [X] There is no commented out code in this PR.
- [X] I have followed the [development checklist][dev-checklist]
- [X] I have followed the [perfect PR recommendations][perfect-pr]
- [X] The code has been formatted using Ruff (`ruff format 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.

<!--
  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/development_checklist/
[manifest-docs]: https://developers.home-assistant.io/docs/creating_integration_manifest/
[quality-scale]: https://developers.home-assistant.io/docs/integration_quality_scale_index/
[docs-repository]: https://github.com/home-assistant/home-assistant.io
[perfect-pr]: https://developers.home-assistant.io/docs/review-process/#creating-the-perfect-pr


Problem statement:
Can't create second NUT instance
### The problem

I have a problem adding a second UPS.

My setup is as follows : 

I have 2 identical UPS's, one is connected to the HA instance, named myups, using the nut add on
The second UPS is connected to a linux box, and named myups3. Both UPS's are connected using USB

In the nut integration I can add myups but when I try to add myups3, myups gets lost. I see these messages iin the debug log :

2025-03-23 18:16:36.554 ERROR (MainThread) [homeassistant.components.sensor] Platform nut does not generate unique IDs. ID KSTAR_UPS HID_HID-C01_ups.status already exists - ignoring sensor.myups_statusgegevens
2025-03-23 18:16:36.562 ERROR (MainThread) [homeassistant.components.sensor] Platform nut does not generate unique IDs. ID KSTAR_UPS HID_HID-C01_ups.load already exists - ignoring sensor.myups_werklast
2025-03-23 18:16:36.563 ERROR (MainThread) [homeassistant.components.sensor] Platform nut does not generate unique IDs. ID KSTAR_UPS HID_HID-C01_battery.charge already exists - ignoring sensor.myups_batterijlading
2025-03-23 18:16:36.567 ERROR (MainThread) [homeassistant.components.sensor] Platform nut does not generate unique IDs. ID KSTAR_UPS HID_HID-C01_input.voltage already exists - ignoring sensor.myups_ingangsspanning
2025-03-23 18:16:36.568 ERROR (MainThread) [homeassistant.components.sensor] Platform nut does not generate unique IDs. ID KSTAR_UPS HID_HID-C01_output.voltage already exists - ignoring sensor.myups_uitgangsspanning
2025-03-23 18:16:36.569 ERROR (MainThread) [homeassistant.components.sensor] Platform nut does not generate unique IDs. ID KSTAR_UPS HID_HID-C01_ups.status.display already exists - ignoring sensor.myups_status


### What version of Home Assistant Core has the issue?

core-2025.3.4

### What was the last working version of Home Assistant Core?

_No response_

### What type of installation are you running?

Home Assistant OS

### Integration causing the issue

_No response_

### Link to integration documentation on our website

_No response_

### Diagnostics information

_No response_

### Example YAML snippet

```yaml

```

### Anything in the logs that might be useful for us?

```txt

```

### Additional information

_No response_

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

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


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

- `@home-assistant close` Closes the issue.
- `@home-assistant rename Awesome new title` Renames the issue.
- `@home-assistant reopen` Reopen the issue.
- `@home-assistant unassign nut` Removes the current integration label and assignees on the issue, add the integration domain after the command.
- `@home-assistant add-label needs-more-information` Add a label (needs-more-information, problem in dependency, problem in custom component) to the issue.
- `@home-assistant remove-label needs-more-information` Remove a label (needs-more-information, problem in dependency, problem in custom component) on the issue.

</details>


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

---

[nut documentation](https://www.home-assistant.io/integrations/nut)
[nut source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/nut)
<sub><sup>(message by IssueLinks)</sup></sub>
It is likely both of your UPS are incorrectly returning the same serial number.  The NUT integration generally uses "manufacturer_model_serial" as the unique ID.

I see other users with what is likely this same model getting these results: the manufacturer of "KSTAR", the model of "UPS HID" and the same serial number of "HID-C01".

You need to get one of these units to return a different serial number.  You may want to look into the NUT Server override setting in ups.conf on the Linux server to see if you can give that unit a different serial number.  See the NUT documentation for more information.
No worries. I actually have 3 of these UPS's. The second one is connected to an old celeron tv box, with an extra instance of HA with NUT addon installed. So no problem there. But for the third one I only have a very old rk3229 android box available. I could get armbian running on it, and I just recompiled the complete NUT suite on it with a custom hack. Now it works as expected...
@home-assistant close

Commit message: Add unique ID check to config flow step for UPS

Patch to review:
diff --git a/homeassistant/components/nut/__init__.py b/homeassistant/components/nut/__init__.py
index dc260dffe9657a..375c38b3e2a398 100644
--- a/homeassistant/components/nut/__init__.py
+++ b/homeassistant/components/nut/__init__.py
@@ -122,6 +122,9 @@ async def async_update_data() -> dict[str, str]:
     if unique_id is None:
         unique_id = entry.entry_id
 
+    if entry.unique_id is None:
+        hass.config_entries.async_update_entry(entry, unique_id=unique_id)
+
     if username is not None and password is not None:
         # Dynamically add outlet integration commands
         additional_integration_commands = set()
diff --git a/homeassistant/components/nut/config_flow.py b/homeassistant/components/nut/config_flow.py
index b1b44966d14586..c110ba4218087a 100644
--- a/homeassistant/components/nut/config_flow.py
+++ b/homeassistant/components/nut/config_flow.py
@@ -28,7 +28,7 @@
 from homeassistant.data_entry_flow import AbortFlow
 from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
 
-from . import PyNUTData
+from . import PyNUTData, _unique_id_from_status
 from .const import DEFAULT_HOST, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN
 
 _LOGGER = logging.getLogger(__name__)
@@ -125,6 +125,11 @@ async def async_step_user(
 
                 if self._host_port_alias_already_configured(nut_config):
                     return self.async_abort(reason="already_configured")
+
+                if unique_id := _unique_id_from_status(info["available_resources"]):
+                    await self.async_set_unique_id(unique_id)
+                    self._abort_if_unique_id_configured()
+
                 title = _format_host_port_alias(nut_config)
                 return self.async_create_entry(title=title, data=nut_config)
 
@@ -147,8 +152,13 @@ async def async_step_ups(
             self.nut_config.update(user_input)
             if self._host_port_alias_already_configured(nut_config):
                 return self.async_abort(reason="already_configured")
-            _, errors, placeholders = await self._async_validate_or_error(nut_config)
+
+            info, errors, placeholders = await self._async_validate_or_error(nut_config)
             if not errors:
+                if unique_id := _unique_id_from_status(info["available_resources"]):
+                    await self.async_set_unique_id(unique_id)
+                    self._abort_if_unique_id_configured()
+
                 title = _format_host_port_alias(nut_config)
                 return self.async_create_entry(title=title, data=nut_config)
 
diff --git a/tests/components/nut/test_config_flow.py b/tests/components/nut/test_config_flow.py
index ed9c87f2f90c01..8eed4b99d94db7 100644
--- a/tests/components/nut/test_config_flow.py
+++ b/tests/components/nut/test_config_flow.py
@@ -21,7 +21,7 @@
 from homeassistant.data_entry_flow import FlowResultType
 from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
 
-from .util import _get_mock_nutclient
+from .util import _get_mock_nutclient, async_init_integration
 
 from tests.common import MockConfigEntry
 
@@ -525,6 +525,108 @@ async def test_abort_if_already_setup(hass: HomeAssistant) -> None:
         assert result2["reason"] == "already_configured"
 
 
+async def test_abort_duplicate_unique_ids(hass: HomeAssistant) -> None:
+    """Test we abort if unique_id is already setup."""
+
+    list_vars = {
+        "device.mfr": "Some manufacturer",
+        "device.model": "Some model",
+        "device.serial": "0000-1",
+    }
+    await async_init_integration(
+        hass,
+        list_ups={"ups1": "UPS 1"},
+        list_vars=list_vars,
+    )
+
+    mock_pynut = _get_mock_nutclient(list_ups={"ups2": "UPS 2"}, list_vars=list_vars)
+
+    result = await hass.config_entries.flow.async_init(
+        DOMAIN, context={"source": config_entries.SOURCE_USER}
+    )
+
+    with patch(
+        "homeassistant.components.nut.AIONUTClient",
+        return_value=mock_pynut,
+    ):
+        result2 = await hass.config_entries.flow.async_configure(
+            result["flow_id"],
+            {
+                CONF_HOST: "1.1.1.1",
+                CONF_PORT: 2222,
+            },
+        )
+        await hass.async_block_till_done()
+
+        assert result2["type"] is FlowResultType.ABORT
+        assert result2["reason"] == "already_configured"
+
+
+async def test_abort_multiple_ups_duplicate_unique_ids(hass: HomeAssistant) -> None:
+    """Test we abort on multiple devices if unique_id is already setup."""
+
+    list_vars = {
+        "device.mfr": "Some manufacturer",
+        "device.model": "Some model",
+        "device.serial": "0000-1",
+    }
+
+    mock_pynut = _get_mock_nutclient(
+        list_ups={"ups2": "UPS 2", "ups3": "UPS 3"}, list_vars=list_vars
+    )
+
+    result = await hass.config_entries.flow.async_init(
+        DOMAIN, context={"source": config_entries.SOURCE_USER}
+    )
+
+    result = await hass.config_entries.flow.async_init(
+        DOMAIN, context={"source": config_entries.SOURCE_USER}
+    )
+    assert result["type"] is FlowResultType.FORM
+    assert result["errors"] == {}
+
+    with patch(
+        "homeassistant.components.nut.AIONUTClient",
+        return_value=mock_pynut,
+    ):
+        result2 = await hass.config_entries.flow.async_configure(
+            result["flow_id"],
+            {
+                CONF_HOST: "1.1.1.1",
+                CONF_PORT: 2222,
+            },
+        )
+        await hass.async_block_till_done()
+
+        assert result2["step_id"] == "ups"
+        assert result2["type"] is FlowResultType.FORM
+
+    await async_init_integration(
+        hass,
+        list_ups={"ups1": "UPS 1"},
+        list_vars=list_vars,
+    )
+
+    with (
+        patch(
+            "homeassistant.components.nut.AIONUTClient",
+            return_value=mock_pynut,
+        ),
+        patch(
+            "homeassistant.components.nut.async_setup_entry",
+            return_value=True,
+        ),
+    ):
+        result3 = await hass.config_entries.flow.async_configure(
+            result["flow_id"],
+            {CONF_ALIAS: "ups2"},
+        )
+        await hass.async_block_till_done()
+
+        assert result3["type"] is FlowResultType.ABORT
+        assert result3["reason"] == "already_configured"
+
+
 async def test_abort_if_already_setup_alias(hass: HomeAssistant) -> None:
     """Test we abort if component is already setup with same alias."""
     config_entry = MockConfigEntry(


Code review comments:
diff_hunk: @@ -122,6 +122,9 @@ async def async_update_data() -> dict[str, str]:
     if unique_id is None:
         unique_id = entry.entry_id
 
+    if entry.unique_id is None:
path: homeassistant/components/nut/__init__.py
text: @user1:
```suggestion
    elif entry.unique_id is None:
```