Repository: home-assistant/core
Pull request: Add select platform to myuplink
<!--
  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.
-->
Add select platform to myUplink integration.
Select entities will be created for data points with > 2 enum values and writable = True.

## 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 #117942
- This PR is related to issue: 
- Link to documentation pull request: https://github.com/home-assistant/home-assistant.io/pull/33048

## 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:

- [x] 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:

- [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


Problem statement:
Myuplink integration handles enum-controls  incorrect
### The problem

Myuplink integration do not handle writable enum-controls correct.

When the response from Myuplink contains a enum-control that is writable the integration do not handle the response as expected. It should create a writable-control with the enum values. Instead it creates a sensor that can't be used to set any enum-value.
The response below shows the myuplink-swagger-response for the "comfort mode" that have four enum-value for the warmvater comfort-mode.

{
    "category": "VVM 310, 3x400V",
    "parameterId": "47041",
    "parameterName": "comfort mode",
    "parameterUnit": "",
    "writable": true,
    "timestamp": "2024-05-22T15:02:03+00:00",
    "value": 0,
    "strVal": "economy",
    "smartHomeCategories": [],
    "minValue": null,
    "maxValue": null,
    "stepValue": 1,
    "enumValues": [
      {
        "value": "4",
        "text": "smart control",
        "icon": ""
      },
      {
        "value": "0",
        "text": "economy",
        "icon": ""
      },
      {
        "value": "1",
        "text": "normal",
        "icon": ""
      },
      {
        "value": "2",
        "text": "luxury",
        "icon": ""
      }
    ],
    "scaleValue": "1",
    "zoneId": null
  },


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

core-2024.5.3

### 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

Myuplink

### Link to integration documentation on our website

_No response_

### Diagnostics information

_No response_

### Example YAML snippet

_No response_

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

_No response_

### Additional information

_No response_

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

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


Code owners of `myuplink` 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 myuplink` 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>

---

[myuplink documentation](https://www.home-assistant.io/integrations/myuplink)
[myuplink source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/myuplink)
<sub><sup>(message by IssueLinks)</sup></sub>
Thank you for reporting this issue. This is the first example we see where there is an enum datapoint with writable attribute set to true. This entity should probably be implemented with the select platform. We will put it on the to-do list for the integration.
Perfect - looking forward for a release with this implemented. :-)

@hakwest I have now prepared a PR that adds a select entity for data points with multiple enum values. It works in theory (pytest) but I need to verify the functionality in real life before submitting the change. 
Are you comfortable with running a HA development environment? If not, I think the easiest way is if you share access to your device via the myUplink web site. Please contact me on ake@strandberg.eu if you are willing to assist with the final verification.

Commit message: Address more comments

Patch to review:
diff --git a/homeassistant/components/myuplink/__init__.py b/homeassistant/components/myuplink/__init__.py
index a8307cf8c6c8c..d801f27817d59 100644
--- a/homeassistant/components/myuplink/__init__.py
+++ b/homeassistant/components/myuplink/__init__.py
@@ -25,6 +25,7 @@
 PLATFORMS: list[Platform] = [
     Platform.BINARY_SENSOR,
     Platform.NUMBER,
+    Platform.SELECT,
     Platform.SENSOR,
     Platform.SWITCH,
     Platform.UPDATE,
diff --git a/homeassistant/components/myuplink/helpers.py b/homeassistant/components/myuplink/helpers.py
index abe039605d3f1..ac3d2a2d7fa3b 100644
--- a/homeassistant/components/myuplink/helpers.py
+++ b/homeassistant/components/myuplink/helpers.py
@@ -21,6 +21,9 @@ def find_matching_platform(
             return Platform.SWITCH
         return Platform.BINARY_SENSOR
 
+    if len(device_point.enum_values) > 0 and device_point.writable:
+        return Platform.SELECT
+
     if (
         description
         and description.native_unit_of_measurement == "DM"
diff --git a/homeassistant/components/myuplink/select.py b/homeassistant/components/myuplink/select.py
new file mode 100644
index 0000000000000..c0fb66602de1d
--- /dev/null
+++ b/homeassistant/components/myuplink/select.py
@@ -0,0 +1,95 @@
+"""Select entity for myUplink."""
+
+from typing import cast
+
+from aiohttp import ClientError
+from myuplink import DevicePoint
+
+from homeassistant.components.select import SelectEntity, SelectEntityDescription
+from homeassistant.const import Platform
+from homeassistant.core import HomeAssistant
+from homeassistant.exceptions import HomeAssistantError
+from homeassistant.helpers.entity_platform import AddEntitiesCallback
+
+from . import MyUplinkConfigEntry, MyUplinkDataCoordinator
+from .entity import MyUplinkEntity
+from .helpers import find_matching_platform, skip_entity
+
+
+async def async_setup_entry(
+    hass: HomeAssistant,
+    config_entry: MyUplinkConfigEntry,
+    async_add_entities: AddEntitiesCallback,
+) -> None:
+    """Set up myUplink select."""
+    entities: list[SelectEntity] = []
+    coordinator: MyUplinkDataCoordinator = config_entry.runtime_data
+
+    # Setup device point select entities
+    for device_id, point_data in coordinator.data.points.items():
+        for point_id, device_point in point_data.items():
+            if skip_entity(device_point.category, device_point):
+                continue
+            description = None
+            if find_matching_platform(device_point, description) == Platform.SELECT:
+                entities.append(
+                    MyUplinkSelect(
+                        coordinator=coordinator,
+                        device_id=device_id,
+                        device_point=device_point,
+                        entity_description=description,
+                        unique_id_suffix=point_id,
+                    )
+                )
+
+    async_add_entities(entities)
+
+
+class MyUplinkSelect(MyUplinkEntity, SelectEntity):
+    """Representation of a myUplink select entity."""
+
+    def __init__(
+        self,
+        coordinator: MyUplinkDataCoordinator,
+        device_id: str,
+        device_point: DevicePoint,
+        entity_description: SelectEntityDescription | None,
+        unique_id_suffix: str,
+    ) -> None:
+        """Initialize the select."""
+        super().__init__(
+            coordinator=coordinator,
+            device_id=device_id,
+            unique_id_suffix=unique_id_suffix,
+        )
+
+        # Internal properties
+        self.point_id = device_point.parameter_id
+        self._attr_name = device_point.parameter_name
+
+        self._attr_options = [x["text"].capitalize() for x in device_point.enum_values]
+        self.options_map = {
+            str(int(x["value"])): x["text"].capitalize()
+            for x in device_point.enum_values
+        }
+        self.options_rev = {value: key for key, value in self.options_map.items()}
+
+    @property
+    def current_option(self) -> str | None:
+        """Retrieve currently selected option."""
+        device_point = self.coordinator.data.points[self.device_id][self.point_id]
+        value = int(cast(int, device_point.value_t))
+        return self.options_map.get(str(value))
+
+    async def async_select_option(self, option: str) -> None:
+        """Set the current option."""
+        try:
+            await self.coordinator.api.async_set_device_points(
+                self.device_id, data={self.point_id: str(self.options_rev[option])}
+            )
+        except ClientError as err:
+            raise HomeAssistantError(
+                f"Failed to set new option {self.options_rev[option]} for {self.point_id}/{self.entity_id}"
+            ) from err
+
+        await self.coordinator.async_request_refresh()
diff --git a/tests/components/myuplink/fixtures/device_points_nibe_f730.json b/tests/components/myuplink/fixtures/device_points_nibe_f730.json
index 49340bd9e266a..9ec5db0ea3bd3 100644
--- a/tests/components/myuplink/fixtures/device_points_nibe_f730.json
+++ b/tests/components/myuplink/fixtures/device_points_nibe_f730.json
@@ -951,5 +951,43 @@
     ],
     "scaleValue": "1",
     "zoneId": null
+  },
+  {
+    "category": "NIBEF F730 CU 3x400V",
+    "parameterId": "47041",
+    "parameterName": "comfort mode",
+    "parameterUnit": "",
+    "writable": true,
+    "timestamp": "2024-05-22T15:02:03+00:00",
+    "value": 0,
+    "strVal": "economy",
+    "smartHomeCategories": [],
+    "minValue": null,
+    "maxValue": null,
+    "stepValue": 1,
+    "enumValues": [
+      {
+        "value": "4",
+        "text": "smart control",
+        "icon": ""
+      },
+      {
+        "value": "0",
+        "text": "economy",
+        "icon": ""
+      },
+      {
+        "value": "1",
+        "text": "normal",
+        "icon": ""
+      },
+      {
+        "value": "2",
+        "text": "luxury",
+        "icon": ""
+      }
+    ],
+    "scaleValue": "1",
+    "zoneId": null
   }
 ]
diff --git a/tests/components/myuplink/fixtures/device_points_nibe_smo20.json b/tests/components/myuplink/fixtures/device_points_nibe_smo20.json
index b64869c236c5d..9135862d9917a 100644
--- a/tests/components/myuplink/fixtures/device_points_nibe_smo20.json
+++ b/tests/components/myuplink/fixtures/device_points_nibe_smo20.json
@@ -3996,9 +3996,9 @@
     "parameterUnit": "",
     "writable": true,
     "timestamp": "2024-02-14T08:36:05+00:00",
-    "value": 0,
+    "value": 0.0,
     "strVal": "economy",
-    "smartHomeCategories": [],
+    "smartHomeCategories": ["test"],
     "minValue": null,
     "maxValue": null,
     "stepValue": 1,
diff --git a/tests/components/myuplink/snapshots/test_diagnostics.ambr b/tests/components/myuplink/snapshots/test_diagnostics.ambr
index 53664820364c0..9160fd3b365d8 100644
--- a/tests/components/myuplink/snapshots/test_diagnostics.ambr
+++ b/tests/components/myuplink/snapshots/test_diagnostics.ambr
@@ -1012,6 +1012,44 @@
                     ],
                     "scaleValue": "1",
                     "zoneId": null
+                  },
+                  {
+                    "category": "NIBEF F730 CU 3x400V",
+                    "parameterId": "47041",
+                    "parameterName": "comfort mode",
+                    "parameterUnit": "",
+                    "writable": true,
+                    "timestamp": "2024-05-22T15:02:03+00:00",
+                    "value": 0,
+                    "strVal": "economy",
+                    "smartHomeCategories": [],
+                    "minValue": null,
+                    "maxValue": null,
+                    "stepValue": 1,
+                    "enumValues": [
+                      {
+                        "value": "4",
+                        "text": "smart control",
+                        "icon": ""
+                      },
+                      {
+                        "value": "0",
+                        "text": "economy",
+                        "icon": ""
+                      },
+                      {
+                        "value": "1",
+                        "text": "normal",
+                        "icon": ""
+                      },
+                      {
+                        "value": "2",
+                        "text": "luxury",
+                        "icon": ""
+                      }
+                    ],
+                    "scaleValue": "1",
+                    "zoneId": null
                   }
                 ]
   
@@ -2017,6 +2055,44 @@
                     ],
                     "scaleValue": "1",
                     "zoneId": null
+                  },
+                  {
+                    "category": "NIBEF F730 CU 3x400V",
+                    "parameterId": "47041",
+                    "parameterName": "comfort mode",
+                    "parameterUnit": "",
+                    "writable": true,
+                    "timestamp": "2024-05-22T15:02:03+00:00",
+                    "value": 0,
+                    "strVal": "economy",
+                    "smartHomeCategories": [],
+                    "minValue": null,
+                    "maxValue": null,
+                    "stepValue": 1,
+                    "enumValues": [
+                      {
+                        "value": "4",
+                        "text": "smart control",
+                        "icon": ""
+                      },
+                      {
+                        "value": "0",
+                        "text": "economy",
+                        "icon": ""
+                      },
+                      {
+                        "value": "1",
+                        "text": "normal",
+                        "icon": ""
+                      },
+                      {
+                        "value": "2",
+                        "text": "luxury",
+                        "icon": ""
+                      }
+                    ],
+                    "scaleValue": "1",
+                    "zoneId": null
                   }
                 ]
   
diff --git a/tests/components/myuplink/test_select.py b/tests/components/myuplink/test_select.py
new file mode 100644
index 0000000000000..ee97c445c9ef0
--- /dev/null
+++ b/tests/components/myuplink/test_select.py
@@ -0,0 +1,117 @@
+"""Tests for myuplink select module."""
+
+from unittest.mock import MagicMock
+
+from aiohttp import ClientError
+import pytest
+
+from homeassistant.const import (
+    ATTR_ENTITY_ID,
+    ATTR_OPTION,
+    SERVICE_SELECT_OPTION,
+    Platform,
+)
+from homeassistant.core import HomeAssistant
+from homeassistant.exceptions import HomeAssistantError
+from homeassistant.helpers import entity_registry as er
+
+TEST_PLATFORM = Platform.SELECT
+pytestmark = pytest.mark.parametrize("platforms", [(TEST_PLATFORM,)])
+
+ENTITY_ID = "select.gotham_city_comfort_mode"
+ENTITY_FRIENDLY_NAME = "Gotham City comfort mode"
+ENTITY_UID = "robin-r-1234-20240201-123456-aa-bb-cc-dd-ee-ff-47041"
+
+
+async def test_entity_registry(
+    hass: HomeAssistant,
+    entity_registry: er.EntityRegistry,
+    mock_myuplink_client: MagicMock,
+    setup_platform: None,
+) -> None:
+    """Test that the entities are registered in the entity registry."""
+
+    entry = entity_registry.async_get(ENTITY_ID)
+    assert entry.unique_id == ENTITY_UID
+
+
+async def test_attributes(
+    hass: HomeAssistant,
+    mock_myuplink_client: MagicMock,
+    setup_platform: None,
+) -> None:
+    """Test the select attributes are correct."""
+
+    state = hass.states.get(ENTITY_ID)
+    assert state.state == "Economy"
+    assert state.attributes == {
+        "options": ["Smart control", "Economy", "Normal", "Luxury"],
+        "friendly_name": ENTITY_FRIENDLY_NAME,
+    }
+
+
+@pytest.mark.parametrize(
+    ("service", "option"),
+    [
+        (SERVICE_SELECT_OPTION, "Economy"),
+    ],
+)
+async def test_selecting(
+    hass: HomeAssistant,
+    mock_myuplink_client: MagicMock,
+    setup_platform: None,
+    service: str,
+    option: str,
+) -> None:
+    """Test select option service."""
+
+    await hass.services.async_call(
+        TEST_PLATFORM,
+        service,
+        {ATTR_ENTITY_ID: ENTITY_ID, ATTR_OPTION: option},
+        blocking=True,
+    )
+    await hass.async_block_till_done()
+    mock_myuplink_client.async_set_device_points.assert_called_once()
+
+
+@pytest.mark.parametrize(
+    ("service", "option"),
+    [
+        (SERVICE_SELECT_OPTION, "Economy"),
+    ],
+)
+async def test_api_failure(
+    hass: HomeAssistant,
+    mock_myuplink_client: MagicMock,
+    setup_platform: None,
+    service: str,
+    option: str,
+) -> None:
+    """Test handling of exception from API."""
+
+    mock_myuplink_client.async_set_device_points.side_effect = ClientError
+    with pytest.raises(HomeAssistantError):
+        await hass.services.async_call(
+            TEST_PLATFORM,
+            service,
+            {ATTR_ENTITY_ID: ENTITY_ID, ATTR_OPTION: option},
+            blocking=True,
+        )
+    mock_myuplink_client.async_set_device_points.assert_called_once()
+
+
+@pytest.mark.parametrize(
+    "load_device_points_file",
+    ["device_points_nibe_smo20.json"],
+)
+async def test_entity_registry_smo20(
+    hass: HomeAssistant,
+    entity_registry: er.EntityRegistry,
+    mock_myuplink_client: MagicMock,
+    setup_platform: None,
+) -> None:
+    """Test that the entities are registered in the entity registry."""
+
+    entry = entity_registry.async_get("select.gotham_city_all")
+    assert entry.unique_id == "robin-r-1234-20240201-123456-aa-bb-cc-dd-ee-ff-47660"


Code review comments:
diff_hunk: @@ -0,0 +1,117 @@
+"""Tests for myuplink select module."""
+
+from unittest.mock import MagicMock
+
+from aiohttp import ClientError
+import pytest
+
+from homeassistant.const import (
+    ATTR_ENTITY_ID,
+    ATTR_OPTION,
+    SERVICE_SELECT_OPTION,
+    Platform,
+)
+from homeassistant.core import HomeAssistant
+from homeassistant.exceptions import HomeAssistantError
+from homeassistant.helpers import entity_registry as er
+
+TEST_PLATFORM = Platform.SELECT
+pytestmark = pytest.mark.parametrize("platforms", [(TEST_PLATFORM,)])
+
+ENTITY_ID = "select.gotham_city_comfort_mode"
+ENTITY_FRIENDLY_NAME = "Gotham City comfort mode"
+ENTITY_UID = "robin-r-1234-20240201-123456-aa-bb-cc-dd-ee-ff-47041"
+
+
+async def test_entity_registry(
+    hass: HomeAssistant,
+    entity_registry: er.EntityRegistry,
+    mock_myuplink_client: MagicMock,
+    setup_platform: None,
+) -> None:
+    """Test that the entities are registered in the entity registry."""
+
+    entry = entity_registry.async_get(ENTITY_ID)
+    assert entry.unique_id == ENTITY_UID
+
+
+async def test_attributes(
path: tests/components/myuplink/test_select.py
text: @user1:
Let's combine this one with the one above. 

There is no need to separate these (another test will basically reset/set up everything again, which is mostly a waste of CPU cycles at this point 😄)

Alternatively, you could snapshot the state instead of asserting it.

diff_hunk: @@ -0,0 +1,117 @@
+"""Tests for myuplink select module."""
+
+from unittest.mock import MagicMock
+
+from aiohttp import ClientError
+import pytest
+
+from homeassistant.const import (
+    ATTR_ENTITY_ID,
+    ATTR_OPTION,
+    SERVICE_SELECT_OPTION,
+    Platform,
+)
+from homeassistant.core import HomeAssistant
+from homeassistant.exceptions import HomeAssistantError
+from homeassistant.helpers import entity_registry as er
+
+TEST_PLATFORM = Platform.SELECT
+pytestmark = pytest.mark.parametrize("platforms", [(TEST_PLATFORM,)])
+
+ENTITY_ID = "select.gotham_city_comfort_mode"
+ENTITY_FRIENDLY_NAME = "Gotham City comfort mode"
+ENTITY_UID = "robin-r-1234-20240201-123456-aa-bb-cc-dd-ee-ff-47041"
+
+
+async def test_entity_registry(
+    hass: HomeAssistant,
+    entity_registry: er.EntityRegistry,
+    mock_myuplink_client: MagicMock,
+    setup_platform: None,
+) -> None:
+    """Test that the entities are registered in the entity registry."""
+
+    entry = entity_registry.async_get(ENTITY_ID)
+    assert entry.unique_id == ENTITY_UID
+
+
+async def test_attributes(
+    hass: HomeAssistant,
+    mock_myuplink_client: MagicMock,
+    setup_platform: None,
+) -> None:
+    """Test the select attributes are correct."""
+
+    state = hass.states.get(ENTITY_ID)
+    assert state.state == "Economy"
+    assert state.attributes == {
+        "options": ["Smart control", "Economy", "Normal", "Luxury"],
+        "friendly_name": ENTITY_FRIENDLY_NAME,
+    }
+
+
+@pytest.mark.parametrize(
path: tests/components/myuplink/test_select.py
text: @user1:
Parameterize with a single value? Why parameterize in that case?