Repository: home-assistant/core
Pull request: Add zwave_js device config file change fix/repair
## Proposed change
Z-Wave JS now has the ability to detect if a device config file changed since the last interview of the node. With this PR, we add an issue and repair flow to trigger a reinterview of a node.

Closes https://github.com/home-assistant-libs/zwave-js-server-python/issues/739


## 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
- [ ] 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 #
- 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]
- [ ] I have followed the [perfect PR recommendations][perfect-pr]
- [ ] 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/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:
Implement hasDeviceConfigChanged
We should call this on startup for every node to see if the device config has changed. Or if we install config updates on the fly like we do once a day in HA? 

If the device config has changed, we can create a repair entry suggesting the user reinterview the device with an automatic action to do so

Hints from issue discussion:

Commit message: Validate that refresh command is called

Patch to review:
diff --git a/homeassistant/components/zwave_js/__init__.py b/homeassistant/components/zwave_js/__init__.py
index 2e6ff4f0b34fd0..268e97c967f4bb 100644
--- a/homeassistant/components/zwave_js/__init__.py
+++ b/homeassistant/components/zwave_js/__init__.py
@@ -550,6 +550,24 @@ async def async_on_node_ready(self, node: ZwaveNode) -> None:
                 node,
             )
 
+        # After ensuring the node is set up in HA, we should check if the node's
+        # device config has changed, and if so, issue a repair registry entry for a
+        # possible reinterview
+        if not node.is_controller_node and await node.async_has_device_config_changed():
+            async_create_issue(
+                self.hass,
+                DOMAIN,
+                f"device_config_file_changed.{device.id}",
+                data={"device_id": device.id},
+                is_fixable=True,
+                is_persistent=False,
+                translation_key="device_config_file_changed",
+                translation_placeholders={
+                    "device_name": device.name_by_user or device.name or ""
+                },
+                severity=IssueSeverity.WARNING,
+            )
+
     async def async_handle_discovery_info(
         self,
         device: dr.DeviceEntry,
diff --git a/homeassistant/components/zwave_js/manifest.json b/homeassistant/components/zwave_js/manifest.json
index 7371a7a88963e8..73fa41a8cca1ec 100644
--- a/homeassistant/components/zwave_js/manifest.json
+++ b/homeassistant/components/zwave_js/manifest.json
@@ -3,7 +3,7 @@
   "name": "Z-Wave",
   "codeowners": ["@home-assistant/z-wave"],
   "config_flow": true,
-  "dependencies": ["usb", "http", "websocket_api"],
+  "dependencies": ["usb", "http", "repairs", "websocket_api"],
   "documentation": "https://www.home-assistant.io/integrations/zwave_js",
   "integration_type": "hub",
   "iot_class": "local_push",
diff --git a/homeassistant/components/zwave_js/repairs.py b/homeassistant/components/zwave_js/repairs.py
new file mode 100644
index 00000000000000..22500b4bfa3431
--- /dev/null
+++ b/homeassistant/components/zwave_js/repairs.py
@@ -0,0 +1,51 @@
+"""Repairs for Z-Wave JS."""
+from __future__ import annotations
+
+from typing import cast
+
+import voluptuous as vol
+from zwave_js_server.model.node import Node
+
+from homeassistant import data_entry_flow
+from homeassistant.components.repairs import ConfirmRepairFlow, RepairsFlow
+from homeassistant.core import HomeAssistant
+
+from .helpers import async_get_node_from_device_id
+
+
+class DeviceConfigFileChangedFlow(RepairsFlow):
+    """Handler for an issue fixing flow."""
+
+    def __init__(self, node: Node) -> None:
+        """Initialize."""
+        self.node = node
+        super().__init__()
+
+    async def async_step_init(
+        self, user_input: dict[str, str] | None = None
+    ) -> data_entry_flow.FlowResult:
+        """Handle the first step of a fix flow."""
+        return await self.async_step_confirm()
+
+    async def async_step_confirm(
+        self, user_input: dict[str, str] | None = None
+    ) -> data_entry_flow.FlowResult:
+        """Handle the confirm step of a fix flow."""
+        if user_input is not None:
+            self.hass.async_create_task(self.node.async_refresh_info())
+            return self.async_create_entry(title="", data={})
+
+        return self.async_show_form(step_id="confirm", data_schema=vol.Schema({}))
+
+
+async def async_create_fix_flow(
+    hass: HomeAssistant,
+    issue_id: str,
+    data: dict[str, str | int | float | None] | None,
+) -> RepairsFlow:
+    """Create flow."""
+    if issue_id.split(".")[0] == "device_config_file_changed":
+        return DeviceConfigFileChangedFlow(
+            async_get_node_from_device_id(hass, cast(dict, data)["device_id"])
+        )
+    return ConfirmRepairFlow()
diff --git a/homeassistant/components/zwave_js/strings.json b/homeassistant/components/zwave_js/strings.json
index 934307947d85d5..863acbb5ddf3c1 100644
--- a/homeassistant/components/zwave_js/strings.json
+++ b/homeassistant/components/zwave_js/strings.json
@@ -161,6 +161,17 @@
           }
         }
       }
+    },
+    "device_config_file_changed": {
+      "title": "Z-Wave device configuration file changed: {device_name}",
+      "fix_flow": {
+        "step": {
+          "confirm": {
+            "title": "Z-Wave device configuration file changed: {device_name}",
+            "description": "Z-Wave JS discovers a lot of device metadata by interviewing the device. However, some of the information has to be loaded from a configuration file. Some of this information is only evaluated once, during the device interview.\n\nWhen a device config file is updated, this information may be stale and and the device must be re-interviewed to pick up the changes.\n\n This is not strictly required and device functionality will be impacted during the re-interview process.\n\nIf you'd like to proceed, click on SUBMIT below. The re-interview will take place in the background."
+          }
+        }
+      }
     }
   },
   "services": {
diff --git a/tests/components/zwave_js/test_repairs.py b/tests/components/zwave_js/test_repairs.py
new file mode 100644
index 00000000000000..1d3c2c7de4d45a
--- /dev/null
+++ b/tests/components/zwave_js/test_repairs.py
@@ -0,0 +1,101 @@
+"""Test the Z-Wave JS repairs module."""
+from copy import deepcopy
+from http import HTTPStatus
+from unittest.mock import patch
+
+from zwave_js_server.event import Event
+from zwave_js_server.model.node import Node
+
+from homeassistant.components.repairs.issue_handler import (
+    async_process_repairs_platforms,
+)
+from homeassistant.components.repairs.websocket_api import (
+    RepairsFlowIndexView,
+    RepairsFlowResourceView,
+)
+from homeassistant.components.zwave_js import DOMAIN
+from homeassistant.components.zwave_js.helpers import get_device_id
+from homeassistant.core import HomeAssistant
+import homeassistant.helpers.device_registry as dr
+
+from tests.typing import ClientSessionGenerator, WebSocketGenerator
+
+
+async def test_device_config_file_changed(
+    hass: HomeAssistant,
+    hass_client: ClientSessionGenerator,
+    hass_ws_client: WebSocketGenerator,
+    client,
+    multisensor_6_state,
+    integration,
+) -> None:
+    """Test the device_config_file_changed issue."""
+    dev_reg = dr.async_get(hass)
+    # Create a node
+    node_state = deepcopy(multisensor_6_state)
+    node = Node(client, node_state)
+    event = Event(
+        "node added",
+        {
+            "source": "controller",
+            "event": "node added",
+            "node": node_state,
+            "result": "",
+        },
+    )
+    with patch(
+        "zwave_js_server.model.node.Node.async_has_device_config_changed",
+        return_value=True,
+    ):
+        client.driver.controller.receive_event(event)
+        await hass.async_block_till_done()
+
+    client.async_send_command_no_wait.reset_mock()
+
+    device = dev_reg.async_get_device(identifiers={get_device_id(client.driver, node)})
+    assert device
+    issue_id = f"device_config_file_changed.{device.id}"
+
+    await async_process_repairs_platforms(hass)
+    ws_client = await hass_ws_client(hass)
+    http_client = await hass_client()
+
+    # Assert the issue is present
+    await ws_client.send_json({"id": 1, "type": "repairs/list_issues"})
+    msg = await ws_client.receive_json()
+    assert msg["success"]
+    assert len(msg["result"]["issues"]) == 1
+    issue = msg["result"]["issues"][0]
+    assert issue["issue_id"] == issue_id
+    assert issue["translation_placeholders"] == {"device_name": device.name}
+
+    url = RepairsFlowIndexView.url
+    resp = await http_client.post(url, json={"handler": DOMAIN, "issue_id": issue_id})
+    assert resp.status == HTTPStatus.OK
+    data = await resp.json()
+
+    flow_id = data["flow_id"]
+    assert data["step_id"] == "confirm"
+
+    # Apply fix
+    url = RepairsFlowResourceView.url.format(flow_id=flow_id)
+    resp = await http_client.post(url)
+
+    assert resp.status == HTTPStatus.OK
+    data = await resp.json()
+
+    assert data["type"] == "create_entry"
+
+    await hass.async_block_till_done()
+
+    assert len(client.async_send_command_no_wait.call_args_list) == 1
+    assert client.async_send_command_no_wait.call_args[0][0] == {
+        "command": "node.refresh_info",
+        "nodeId": node.node_id,
+    }
+
+    # Assert the issue is resolved
+    await ws_client.send_json({"id": 2, "type": "repairs/list_issues"})
+    msg = await ws_client.receive_json()
+    assert msg["success"]
+    assert len(msg["result"]["issues"]) == 0


Code review comments:
diff_hunk: @@ -550,6 +550,24 @@ async def async_on_node_ready(self, node: ZwaveNode) -> None:
                 node,
             )
 
+        # After ensuring the node is set up in HA, we should check if the node's
+        # device config has changed, and if so, issue a repair registry entry for a
+        # possible reinterview
+        if not node.is_controller_node and await node.async_has_device_config_changed():
+            async_create_issue(
+                self.hass,
+                DOMAIN,
+                f"device_config_file_changed.{device.id}",
+                data={"device_id": device.id},
+                is_fixable=True,
+                is_persistent=False,
+                translation_key="device_config_file_changed",
+                translation_placeholders={
+                    "device_name": device.name_by_user or device.name or ""
path: homeassistant/components/zwave_js/__init__.py
text: @user1:
I'd go with "unnamed device" or similar instead of empty string.