Repository: home-assistant/core
Pull request #140802: Add Z-Wave JS lookup_device API
Author: login: MindFreeze
Labels: name: cla-signed
name: new-feature
name: has-tests
name: integration: zwave_js
name: Quality Scale: No score
Created: 2025-03-17T14:05:52Z | Merged: 2025-03-18T11:05:10Z

<!--
  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.
-->
Needed for the new add device flow to set a default device name. I would prefer not to wait for frontend for this one because more changes will be needed and this one is pretty standalone as is.

Frontend PR: https://github.com/home-assistant/frontend/pull/24667

## 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: 
- 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`)
- [x] 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:

- [x] 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



Diff:
diff --git a/homeassistant/components/zwave_js/api.py b/homeassistant/components/zwave_js/api.py
index a3d1416962e97..ec164e2b505ad 100644
--- a/homeassistant/components/zwave_js/api.py
+++ b/homeassistant/components/zwave_js/api.py
@@ -405,6 +405,7 @@ def async_register_api(hass: HomeAssistant) -> None:
     websocket_api.async_register_command(
         hass, websocket_try_parse_dsk_from_qr_code_string
     )
+    websocket_api.async_register_command(hass, websocket_lookup_device)
     websocket_api.async_register_command(hass, websocket_supports_feature)
     websocket_api.async_register_command(hass, websocket_stop_inclusion)
     websocket_api.async_register_command(hass, websocket_stop_exclusion)
@@ -1138,6 +1139,41 @@ async def websocket_try_parse_dsk_from_qr_code_string(
     )
 
 
+@websocket_api.require_admin
+@websocket_api.websocket_command(
+    {
+        vol.Required(TYPE): "zwave_js/lookup_device",
+        vol.Required(ENTRY_ID): str,
+        vol.Required(MANUFACTURER_ID): int,
+        vol.Required(PRODUCT_TYPE): int,
+        vol.Required(PRODUCT_ID): int,
+        vol.Optional(APPLICATION_VERSION): str,
+    }
+)
+@websocket_api.async_response
+@async_handle_failed_command
+@async_get_entry
+async def websocket_lookup_device(
+    hass: HomeAssistant,
+    connection: ActiveConnection,
+    msg: dict[str, Any],
+    entry: ConfigEntry,
+    client: Client,
+    driver: Driver,
+) -> None:
+    """Look up the definition of a given device in the configuration DB."""
+    device = await driver.config_manager.lookup_device(
+        msg[MANUFACTURER_ID],
+        msg[PRODUCT_TYPE],
+        msg[PRODUCT_ID],
+        msg.get(APPLICATION_VERSION),
+    )
+    if device is None:
+        connection.send_error(msg[ID], ERR_NOT_FOUND, "Device not found")
+    else:
+        connection.send_result(msg[ID], device.to_dict())
+
+
 @websocket_api.require_admin
 @websocket_api.websocket_command(
     {
diff --git a/tests/components/zwave_js/test_api.py b/tests/components/zwave_js/test_api.py
index 07c874197b6b2..b2741a53a9258 100644
--- a/tests/components/zwave_js/test_api.py
+++ b/tests/components/zwave_js/test_api.py
@@ -5,7 +5,7 @@
 from io import BytesIO
 import json
 from typing import Any
-from unittest.mock import MagicMock, PropertyMock, patch
+from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
 
 import pytest
 from zwave_js_server.const import (
@@ -5577,3 +5577,127 @@ async def test_subscribe_s2_inclusion(
     msg = await ws_client.receive_json()
     assert not msg["success"]
     assert msg["error"]["code"] == ERR_NOT_FOUND
+
+
+async def test_lookup_device(
+    hass: HomeAssistant,
+    integration: MockConfigEntry,
+    client: MagicMock,
+    hass_ws_client: WebSocketGenerator,
+) -> None:
+    """Test lookup_device websocket command."""
+    entry = integration
+    ws_client = await hass_ws_client(hass)
+
+    # Create mock device response
+    mock_device = MagicMock()
+    mock_device.to_dict.return_value = {
+        "manufacturer": "Test Manufacturer",
+        "label": "Test Device",
+        "description": "Test Device Description",
+        "devices": [{"productType": 1, "productId": 2}],
+        "firmwareVersion": {"min": "1.0", "max": "2.0"},
+    }
+
+    # Test successful lookup
+    client.driver.config_manager.lookup_device = AsyncMock(return_value=mock_device)
+
+    await ws_client.send_json_auto_id(
+        {
+            TYPE: "zwave_js/lookup_device",
+            ENTRY_ID: entry.entry_id,
+            MANUFACTURER_ID: 1,
+            PRODUCT_TYPE: 2,
+            PRODUCT_ID: 3,
+            APPLICATION_VERSION: "1.5",
+        }
+    )
+    msg = await ws_client.receive_json()
+
+    assert msg["success"]
+    assert msg["result"] == mock_device.to_dict.return_value
+
+    client.driver.config_manager.lookup_device.assert_called_once_with(1, 2, 3, "1.5")
+
+    # Reset mock
+    client.driver.config_manager.lookup_device.reset_mock()
+
+    # Test lookup without optional application_version
+    await ws_client.send_json_auto_id(
+        {
+            TYPE: "zwave_js/lookup_device",
+            ENTRY_ID: entry.entry_id,
+            MANUFACTURER_ID: 4,
+            PRODUCT_TYPE: 5,
+            PRODUCT_ID: 6,
+        }
+    )
+    msg = await ws_client.receive_json()
+
+    assert msg["success"]
+    assert msg["result"] == mock_device.to_dict.return_value
+
+    client.driver.config_manager.lookup_device.assert_called_once_with(4, 5, 6, None)
+
+    # Test device not found
+    with patch.object(
+        client.driver.config_manager,
+        "lookup_device",
+        return_value=None,
+    ):
+        await ws_client.send_json_auto_id(
+            {
+                TYPE: "zwave_js/lookup_device",
+                ENTRY_ID: entry.entry_id,
+                MANUFACTURER_ID: 99,
+                PRODUCT_TYPE: 99,
+                PRODUCT_ID: 99,
+                APPLICATION_VERSION: "9.9",
+            }
+        )
+        msg = await ws_client.receive_json()
+
+        assert not msg["success"]
+        assert msg["error"]["code"] == ERR_NOT_FOUND
+        assert msg["error"]["message"] == "Device not found"
+
+    # Test sending command with improper entry ID fails
+    await ws_client.send_json_auto_id(
+        {
+            TYPE: "zwave_js/lookup_device",
+            ENTRY_ID: "invalid_entry_id",
+            MANUFACTURER_ID: 1,
+            PRODUCT_TYPE: 1,
+            PRODUCT_ID: 1,
+            APPLICATION_VERSION: "1.0",
+        }
+    )
+    msg = await ws_client.receive_json()
+    assert not msg["success"]
+    assert msg["error"]["code"] == ERR_NOT_FOUND
+    assert msg["error"]["message"] == "Config entry invalid_entry_id not found"
+
+    # Test FailedCommand exception
+    error_message = "Failed to execute lookup_device command"
+    with patch.object(
+        client.driver.config_manager,
+        "lookup_device",
+        side_effect=FailedCommand("lookup_device", error_message),
+    ):
+        # Send the subscription request
+        await ws_client.send_json_auto_id(
+            {
+                TYPE: "zwave_js/lookup_device",
+                ENTRY_ID: entry.entry_id,
+                MANUFACTURER_ID: 1,
+                PRODUCT_TYPE: 2,
+                PRODUCT_ID: 3,
+                APPLICATION_VERSION: "1.0",
+            }
+        )
+
+        # Verify error response
+        msg = await ws_client.receive_json()
+        assert not msg["success"]
+        assert msg["error"]["code"] == error_message
+        assert msg["error"]["message"] == f"Command failed: {error_message}"


Reviews:
user: login: MartinHjelmare
state: CHANGES_REQUESTED
author_association: MEMBER
submitted_at: 2025-03-17T16:46:20Z
user: login: MartinHjelmare
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-03-17T20:42:00Z
user: login: MartinHjelmare
body: Thanks!
state: APPROVED
author_association: MEMBER
submitted_at: 2025-03-18T11:04:17Z

Review comments:
diff_hunk: @@ -5577,3 +5577,127 @@ async def test_subscribe_s2_inclusion(
     msg = await ws_client.receive_json()
     assert not msg["success"]
     assert msg["error"]["code"] == ERR_NOT_FOUND
+
+
+async def test_lookup_device(
+    hass: HomeAssistant,
+    integration: MockConfigEntry,
+    client: MagicMock,
+    hass_ws_client: WebSocketGenerator,
+) -> None:
+    """Test lookup_device websocket command."""
+    entry = integration
+    ws_client = await hass_ws_client(hass)
+
+    # Create mock device response
+    mock_device = MagicMock()
+    mock_device.to_dict.return_value = {
+        "manufacturer": "Test Manufacturer",
+        "label": "Test Device",
+        "description": "Test Device Description",
+        "devices": [{"productType": 1, "productId": 2}],
+        "firmwareVersion": {"min": "1.0", "max": "2.0"},
+    }
+
+    # Test successful lookup
+    client.driver.config_manager.lookup_device = AsyncMock(return_value=mock_device)
+
+    await ws_client.send_json_auto_id(
+        {
+            TYPE: "zwave_js/lookup_device",
+            ENTRY_ID: entry.entry_id,
+            MANUFACTURER_ID: 1,
+            PRODUCT_TYPE: 2,
+            PRODUCT_ID: 3,
+            APPLICATION_VERSION: "1.5",
+        }
+    )
+    msg = await ws_client.receive_json()
+
+    assert msg["success"]
+    assert msg["result"] == mock_device.to_dict.return_value
+
+    client.driver.config_manager.lookup_device.assert_called_once_with(1, 2, 3, "1.5")
+
+    # Reset mock
+    client.driver.config_manager.lookup_device.reset_mock()
+
+    # Test lookup without optional application_version
+    await ws_client.send_json_auto_id(
+        {
+            TYPE: "zwave_js/lookup_device",
+            ENTRY_ID: entry.entry_id,
+            MANUFACTURER_ID: 4,
+            PRODUCT_TYPE: 5,
+            PRODUCT_ID: 6,
+        }
+    )
+    msg = await ws_client.receive_json()
+
+    assert msg["success"]
+    assert msg["result"] == mock_device.to_dict.return_value
+
+    client.driver.config_manager.lookup_device.assert_called_once_with(4, 5, 6, None)
+
+
+async def test_lookup_device_not_found(
+    hass: HomeAssistant,
+    integration: MockConfigEntry,
+    client: MagicMock,
+    hass_ws_client: WebSocketGenerator,
+) -> None:
+    """Test lookup_device websocket command when device is not found."""
+    entry = integration
+    ws_client = await hass_ws_client(hass)
+
+    # Test device not found
+    client.driver.config_manager.lookup_device = AsyncMock(return_value=None)
+
+    await ws_client.send_json_auto_id(
+        {
+            TYPE: "zwave_js/lookup_device",
+            ENTRY_ID: entry.entry_id,
+            MANUFACTURER_ID: 99,
+            PRODUCT_TYPE: 99,
+            PRODUCT_ID: 99,
+            APPLICATION_VERSION: "9.9",
+        }
+    )
+    msg = await ws_client.receive_json()
+
+    assert not msg["success"]
+    assert msg["error"]["code"] == ERR_NOT_FOUND
+    assert msg["error"]["message"] == "Device not found"
+
+    # Test sending command with improper entry ID fails
+    await ws_client.send_json_auto_id(
+        {
+            TYPE: "zwave_js/lookup_device",
+            ENTRY_ID: "invalid_entry_id",
+            MANUFACTURER_ID: 1,
+            PRODUCT_TYPE: 1,
+            PRODUCT_ID: 1,
+            APPLICATION_VERSION: "1.0",
+        }
+    )
+    msg = await ws_client.receive_json()
+    assert not msg["success"]
+    assert msg["error"]["code"] == ERR_NOT_FOUND
+
+    # Test sending command with not loaded entry fails
+    await hass.config_entries.async_unload(entry.entry_id)
+    await hass.async_block_till_done()
+
+    await ws_client.send_json_auto_id(
+        {
+            TYPE: "zwave_js/lookup_device",
+            ENTRY_ID: entry.entry_id,
+            MANUFACTURER_ID: 1,
+            PRODUCT_TYPE: 1,
+            PRODUCT_ID: 1,
+            APPLICATION_VERSION: "1.0",
+        }
+    )
+    msg = await ws_client.receive_json()
+    assert not msg["success"]
+    assert msg["error"]["code"] == ERR_NOT_LOADED
path: tests/components/zwave_js/test_api.py
user: login: MartinHjelmare
body: Please test the FailedCommand case too.
created_at: 2025-03-17T16:45:42Z
author_association: MEMBER
diff_hunk: @@ -5577,3 +5577,127 @@ async def test_subscribe_s2_inclusion(
     msg = await ws_client.receive_json()
     assert not msg["success"]
     assert msg["error"]["code"] == ERR_NOT_FOUND
+
+
+async def test_lookup_device(
+    hass: HomeAssistant,
+    integration: MockConfigEntry,
+    client: MagicMock,
+    hass_ws_client: WebSocketGenerator,
+) -> None:
+    """Test lookup_device websocket command."""
+    entry = integration
+    ws_client = await hass_ws_client(hass)
+
+    # Create mock device response
+    mock_device = MagicMock()
+    mock_device.to_dict.return_value = {
+        "manufacturer": "Test Manufacturer",
+        "label": "Test Device",
+        "description": "Test Device Description",
+        "devices": [{"productType": 1, "productId": 2}],
+        "firmwareVersion": {"min": "1.0", "max": "2.0"},
+    }
+
+    # Test successful lookup
+    client.driver.config_manager.lookup_device = AsyncMock(return_value=mock_device)
+
+    await ws_client.send_json_auto_id(
+        {
+            TYPE: "zwave_js/lookup_device",
+            ENTRY_ID: entry.entry_id,
+            MANUFACTURER_ID: 1,
+            PRODUCT_TYPE: 2,
+            PRODUCT_ID: 3,
+            APPLICATION_VERSION: "1.5",
+        }
+    )
+    msg = await ws_client.receive_json()
+
+    assert msg["success"]
+    assert msg["result"] == mock_device.to_dict.return_value
+
+    client.driver.config_manager.lookup_device.assert_called_once_with(1, 2, 3, "1.5")
+
+    # Reset mock
+    client.driver.config_manager.lookup_device.reset_mock()
+
+    # Test lookup without optional application_version
+    await ws_client.send_json_auto_id(
+        {
+            TYPE: "zwave_js/lookup_device",
+            ENTRY_ID: entry.entry_id,
+            MANUFACTURER_ID: 4,
+            PRODUCT_TYPE: 5,
+            PRODUCT_ID: 6,
+        }
+    )
+    msg = await ws_client.receive_json()
+
+    assert msg["success"]
+    assert msg["result"] == mock_device.to_dict.return_value
+
+    client.driver.config_manager.lookup_device.assert_called_once_with(4, 5, 6, None)
+
+    # Test device not found
+    with patch.object(
+        client.driver.config_manager,
+        "lookup_device",
+        return_value=None,
+    ):
+        await ws_client.send_json_auto_id(
+            {
+                TYPE: "zwave_js/lookup_device",
+                ENTRY_ID: entry.entry_id,
+                MANUFACTURER_ID: 99,
+                PRODUCT_TYPE: 99,
+                PRODUCT_ID: 99,
+                APPLICATION_VERSION: "9.9",
+            }
+        )
+        msg = await ws_client.receive_json()
+
+        assert not msg["success"]
+        assert msg["error"]["code"] == ERR_NOT_FOUND
+        assert msg["error"]["message"] == "Device not found"
+
+        # Test sending command with improper entry ID fails
+        await ws_client.send_json_auto_id(
+            {
+                TYPE: "zwave_js/lookup_device",
+                ENTRY_ID: "invalid_entry_id",
+                MANUFACTURER_ID: 1,
+                PRODUCT_TYPE: 1,
+                PRODUCT_ID: 1,
+                APPLICATION_VERSION: "1.0",
+            }
+        )
+        msg = await ws_client.receive_json()
+        assert not msg["success"]
+        assert msg["error"]["code"] == ERR_NOT_FOUND
+        assert msg["error"]["message"] == "Config entry invalid_entry_id not found"
path: tests/components/zwave_js/test_api.py
user: login: MartinHjelmare
body: Can we outdent this block, that tests improper entry ID? It doesn't need the patch above and is not related to that, right?
created_at: 2025-03-17T20:41:29Z
author_association: MEMBER

PR comments:
user: login: home-assistant[bot]
created_at: 2025-03-17T14:05:58Z
body: 
Hey there @home-assistant/z-wave, mind taking a look at this pull request as it has been labeled with an integration (`zwave_js`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L1794) for? Thanks!

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


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

- `@home-assistant close` Closes the pull request.
- `@home-assistant rename Awesome new title` Renames the pull request.
- `@home-assistant reopen` Reopen the pull request.
- `@home-assistant unassign zwave_js` Removes the current integration label and assignees on the pull request, 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 pull request.
- `@home-assistant remove-label needs-more-information` Remove a label (needs-more-information, problem in dependency, problem in custom component) on the pull request.

</details>


author_association: CONTRIBUTOR
user: login: wendevlin
created_at: 2025-03-17T16:07:46Z
body: - Frontend PR: https://github.com/home-assistant/frontend/pull/24667
author_association: MEMBER
user: login: home-assistant[bot]
created_at: 2025-03-17T16:46:22Z
body: <!-- ReviewDrafterComment -->
Please take a look at the requested changes, and use the **Ready for review** button when you are done, thanks :+1:

[_Learn more about our pull request process._](https://developers.home-assistant.io/docs/review-process#prs-are-being-drafted-when-changes-are-needed)

author_association: CONTRIBUTOR