Repository: home-assistant/core
Pull request: Add hvac_modes property to Plugwise
<!--
  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.
-->
Using only static hvac_modes is incorrect: for instance, when a user has a schedule defined for a thermostat and decides to remove it, the HVACMode.AUTO for that thermostat should be removed.

## 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 #102205
- 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.
-->

- [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 Black (`black --fast 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.
- [x] 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:
Plugwise does not adapt to removal of a schedule
### The problem

When a schedule of a thermostat is removed by the user, the `hvac_mode` `auto` should no longer be provided by the integration.
However, `hvac_mode` `auto` is still shown in HA when I remove the schedule of a thermostat.

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

Core 2023.10.3

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

Nonen

### What type of installation are you running?

Home Assistant Supervised

### Integration causing the issue

Plugwise

### 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 @compatech, @frenck, mind taking a look at this issue as it has been labeled with an integration (`plugwise`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L956) for? Thanks!

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


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

---

[plugwise documentation](https://www.home-assistant.io/integrations/plugwise)
[plugwise source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/plugwise)
<sub><sup>(message by IssueLinks)</sup></sub>

Commit message: Implement review comments

Patch to review:
diff --git a/homeassistant/components/plugwise/climate.py b/homeassistant/components/plugwise/climate.py
index 32146c2753ff6a..82ee9b9dc6aeaa 100644
--- a/homeassistant/components/plugwise/climate.py
+++ b/homeassistant/components/plugwise/climate.py
@@ -66,13 +66,6 @@ def __init__(
             self._attr_supported_features |= ClimateEntityFeature.PRESET_MODE
             self._attr_preset_modes = presets
 
-        # Determine hvac modes and current hvac mode
-        self._attr_hvac_modes = [HVACMode.HEAT]
-        if self.coordinator.data.gateway["cooling_present"]:
-            self._attr_hvac_modes = [HVACMode.HEAT_COOL]
-        if self.device["available_schedules"] != ["None"]:
-            self._attr_hvac_modes.append(HVACMode.AUTO)
-
         self._attr_min_temp = self.device["thermostat"]["lower_bound"]
         self._attr_max_temp = self.device["thermostat"]["upper_bound"]
         # Ensure we don't drop below 0.1
@@ -117,6 +110,21 @@ def hvac_mode(self) -> HVACMode:
             return HVACMode.HEAT
         return HVACMode(mode)
 
+    @property
+    def hvac_modes(self) -> list[HVACMode]:
+        """Return the list of available HVACModes."""
+        hvac_modes: list[HVACMode] = [HVACMode.HEAT]
+        if self.coordinator.data.gateway["cooling_present"]:
+            hvac_modes = [HVACMode.HEAT_COOL]
+
+        if self.device["available_schedules"] != ["None"]:
+            if HVACMode.AUTO not in hvac_modes:
+                hvac_modes.append(HVACMode.AUTO)
+        elif HVACMode.AUTO in hvac_modes:
+            hvac_modes.remove(HVACMode.AUTO)
+
+        return hvac_modes
+
     @property
     def hvac_action(self) -> HVACAction | None:
         """Return the current running hvac operation if supported."""
diff --git a/tests/components/plugwise/test_climate.py b/tests/components/plugwise/test_climate.py
index 496eeaae084019..11425cf79da352 100644
--- a/tests/components/plugwise/test_climate.py
+++ b/tests/components/plugwise/test_climate.py
@@ -1,14 +1,17 @@
 """Tests for the Plugwise Climate integration."""
-from unittest.mock import MagicMock
+
+from datetime import timedelta
+from unittest.mock import MagicMock, patch
 
 from plugwise.exceptions import PlugwiseError
 import pytest
 
-from homeassistant.components.climate import HVACMode
+from homeassistant.components.climate.const import HVACMode
 from homeassistant.core import HomeAssistant
 from homeassistant.exceptions import HomeAssistantError
+from homeassistant.util.dt import utcnow
 
-from tests.common import MockConfigEntry
+from tests.common import MockConfigEntry, async_fire_time_changed
 
 
 async def test_adam_climate_entity_attributes(
@@ -87,8 +90,6 @@ async def test_adam_climate_adjust_negative_testing(
     hass: HomeAssistant, mock_smile_adam: MagicMock, init_integration: MockConfigEntry
 ) -> None:
     """Test exceptions of climate entities."""
-    mock_smile_adam.set_preset.side_effect = PlugwiseError
-    mock_smile_adam.set_schedule_state.side_effect = PlugwiseError
     mock_smile_adam.set_temperature.side_effect = PlugwiseError
 
     with pytest.raises(HomeAssistantError):
@@ -99,25 +100,6 @@ async def test_adam_climate_adjust_negative_testing(
             blocking=True,
         )
 
-    with pytest.raises(HomeAssistantError):
-        await hass.services.async_call(
-            "climate",
-            "set_preset_mode",
-            {"entity_id": "climate.zone_thermostat_jessie", "preset_mode": "home"},
-            blocking=True,
-        )
-
-    with pytest.raises(HomeAssistantError):
-        await hass.services.async_call(
-            "climate",
-            "set_hvac_mode",
-            {
-                "entity_id": "climate.zone_thermostat_jessie",
-                "hvac_mode": HVACMode.AUTO,
-            },
-            blocking=True,
-        )
-
 
 async def test_adam_climate_entity_climate_changes(
     hass: HomeAssistant, mock_smile_adam: MagicMock, init_integration: MockConfigEntry
@@ -129,7 +111,6 @@ async def test_adam_climate_entity_climate_changes(
         {"entity_id": "climate.zone_lisa_wk", "temperature": 25},
         blocking=True,
     )
-
     assert mock_smile_adam.set_temperature.call_count == 1
     mock_smile_adam.set_temperature.assert_called_with(
         "c50f167537524366a5af7aa3942feb1e", {"setpoint": 25.0}
@@ -145,7 +126,6 @@ async def test_adam_climate_entity_climate_changes(
         },
         blocking=True,
     )
-
     assert mock_smile_adam.set_temperature.call_count == 2
     mock_smile_adam.set_temperature.assert_called_with(
         "c50f167537524366a5af7aa3942feb1e", {"setpoint": 25.0}
@@ -165,7 +145,6 @@ async def test_adam_climate_entity_climate_changes(
         {"entity_id": "climate.zone_lisa_wk", "preset_mode": "away"},
         blocking=True,
     )
-
     assert mock_smile_adam.set_preset.call_count == 1
     mock_smile_adam.set_preset.assert_called_with(
         "c50f167537524366a5af7aa3942feb1e", "away"
@@ -173,26 +152,13 @@ async def test_adam_climate_entity_climate_changes(
 
     await hass.services.async_call(
         "climate",
-        "set_temperature",
-        {"entity_id": "climate.zone_thermostat_jessie", "temperature": 25},
-        blocking=True,
-    )
-
-    assert mock_smile_adam.set_temperature.call_count == 3
-    mock_smile_adam.set_temperature.assert_called_with(
-        "82fa13f017d240daa0d0ea1775420f24", {"setpoint": 25.0}
-    )
-
-    await hass.services.async_call(
-        "climate",
-        "set_preset_mode",
-        {"entity_id": "climate.zone_thermostat_jessie", "preset_mode": "home"},
+        "set_hvac_mode",
+        {"entity_id": "climate.zone_lisa_wk", "hvac_mode": "heat"},
         blocking=True,
     )
-
-    assert mock_smile_adam.set_preset.call_count == 2
-    mock_smile_adam.set_preset.assert_called_with(
-        "82fa13f017d240daa0d0ea1775420f24", "home"
+    assert mock_smile_adam.set_schedule_state.call_count == 2
+    mock_smile_adam.set_schedule_state.assert_called_with(
+        "c50f167537524366a5af7aa3942feb1e", "GF7  Woonkamer", "off"
     )
 
     with pytest.raises(HomeAssistantError):
@@ -270,7 +236,9 @@ async def test_anna_3_climate_entity_attributes(
 
 
 async def test_anna_climate_entity_climate_changes(
-    hass: HomeAssistant, mock_smile_anna: MagicMock, init_integration: MockConfigEntry
+    hass: HomeAssistant,
+    mock_smile_anna: MagicMock,
+    init_integration: MockConfigEntry,
 ) -> None:
     """Test handling of user requests in anna climate device environment."""
     await hass.services.async_call(
@@ -279,7 +247,6 @@ async def test_anna_climate_entity_climate_changes(
         {"entity_id": "climate.anna", "target_temp_high": 25, "target_temp_low": 20},
         blocking=True,
     )
-
     assert mock_smile_anna.set_temperature.call_count == 1
     mock_smile_anna.set_temperature.assert_called_with(
         "c784ee9fdab44e1395b8dee7d7a497d5",
@@ -292,7 +259,6 @@ async def test_anna_climate_entity_climate_changes(
         {"entity_id": "climate.anna", "preset_mode": "away"},
         blocking=True,
     )
-
     assert mock_smile_anna.set_preset.call_count == 1
     mock_smile_anna.set_preset.assert_called_with(
         "c784ee9fdab44e1395b8dee7d7a497d5", "away"
@@ -301,24 +267,32 @@ async def test_anna_climate_entity_climate_changes(
     await hass.services.async_call(
         "climate",
         "set_hvac_mode",
-        {"entity_id": "climate.anna", "hvac_mode": "heat"},
+        {"entity_id": "climate.anna", "hvac_mode": "auto"},
         blocking=True,
     )
-
-    assert mock_smile_anna.set_temperature.call_count == 1
     assert mock_smile_anna.set_schedule_state.call_count == 1
     mock_smile_anna.set_schedule_state.assert_called_with(
-        "c784ee9fdab44e1395b8dee7d7a497d5", "standaard", "off"
+        "c784ee9fdab44e1395b8dee7d7a497d5", "standaard", "on"
     )
 
     await hass.services.async_call(
         "climate",
         "set_hvac_mode",
-        {"entity_id": "climate.anna", "hvac_mode": "auto"},
+        {"entity_id": "climate.anna", "hvac_mode": "heat"},
         blocking=True,
     )
-
     assert mock_smile_anna.set_schedule_state.call_count == 2
     mock_smile_anna.set_schedule_state.assert_called_with(
-        "c784ee9fdab44e1395b8dee7d7a497d5", "standaard", "on"
+        "c784ee9fdab44e1395b8dee7d7a497d5", "standaard", "off"
     )
+    data = mock_smile_anna.async_update.return_value
+    data.devices["3cb70739631c4d17a86b8b12e8a5161b"]["available_schedules"] = ["None"]
+    with patch(
+        "homeassistant.components.plugwise.coordinator.Smile.async_update",
+        return_value=data,
+    ):
+        async_fire_time_changed(hass, utcnow() + timedelta(minutes=1))
+        await hass.async_block_till_done()
+        state = hass.states.get("climate.anna")
+        assert state.state == HVACMode.HEAT
+        assert state.attributes["hvac_modes"] == [HVACMode.HEAT]


Code review comments:
diff_hunk: @@ -117,6 +110,21 @@ def hvac_mode(self) -> HVACMode:
             return HVACMode.HEAT
         return HVACMode(mode)
 
+    @property
+    def hvac_modes(self) -> list[HVACMode]:
+        """Return the list of available HVACModes."""
+        hvac_modes: list[HVACMode] = [HVACMode.HEAT]
+        if self.coordinator.data.gateway["cooling_present"]:
+            hvac_modes = [HVACMode.HEAT_COOL]
+
+        if self.device["available_schedules"] != ["None"]:
+            if HVACMode.AUTO not in hvac_modes:
+                hvac_modes.append(HVACMode.AUTO)
+        elif HVACMode.AUTO in hvac_modes:
+            hvac_modes.remove(HVACMode.AUTO)
path: homeassistant/components/plugwise/climate.py
text: @user1:
```suggestion
```

@author:
Sorry, this I don't understand. We should not remove HVACMode.AUTO when all the schedules for a thermostat have been removed by the user?

I mean the full logic for these two line reads like:
```
        if self.device["available_schedules"] == ["None"]:
            if HVACMode.AUTO in hvac_modes:
                hvac_modes.remove(HVACMode.AUTO)
```
When the available_schedules-list changes to only "None", meaning there is no schedule defined, then the HVACMode.AUTO is no longer available and should be removed.

This is one half of the main purpose of this PR.

@user1:
Because it is never added in the first place?

Within this method, the removal never happens.

@author:
There are two cases:
1) No schedule was defined before and the user adds at certain point in time one schedule.  "available_schedules" changes from ["None"] to for instance ["Weekschedule"].
These 3 lines cover this case:
```
        if self.device["available_schedules"] != ["None"]:
            if HVACMode.AUTO not in hvac_modes:
                hvac_modes.append(HVACMode.AUTO)
```
2) One or more schedules were define before and the user decides to remove them all. "available_schedules" changes from for instance ["Weekschedule", "Vacation"] to ["None"].
These lines cover this case:
```
        elif HVACMode.AUTO in hvac_modes:
            hvac_modes.remove(HVACMode.AUTO)
```

@user1:
> One or more schedules were define before and the user decides to remove them all.

There is no such case. `havc_modes` is fully created inside this method, the `elif` will never render true.

diff_hunk: @@ -117,6 +110,21 @@ def hvac_mode(self) -> HVACMode:
             return HVACMode.HEAT
         return HVACMode(mode)
 
+    @property
+    def hvac_modes(self) -> list[HVACMode]:
+        """Return the list of available HVACModes."""
+        hvac_modes: list[HVACMode] = [HVACMode.HEAT]
path: homeassistant/components/plugwise/climate.py
text: @user1:
That is already inferred.

```suggestion
        hvac_modes = [HVACMode.HEAT]
```