Repository: home-assistant/core
Pull request: Handle alexa invalid climate temp adjustment
<!--
  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.
-->
In cases where a climate entity has not set the target temperature attribute.
Attempts adjust the target temperarture are not supported and should be handled properly.

## 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 #https://github.com/home-assistant/core/issues/99702
- 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.
- [ ] 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:
Uncaught exception processing Alexa
### The problem

Tried to change the temperature today using Alexa. Found this in the logs later on while looking up an unrelated issue.

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

core-2023.8.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

homeassistant.components.alexa.smart_home

### Link to integration documentation on our website

_No response_

### Diagnostics information

2023-09-05 20:32:47.615 ERROR (MainThread) [homeassistant.components.alexa.smart_home] Uncaught exception processing Alexa Alexa.ThermostatController/AdjustTargetTemperature request (climate.family_room)
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/alexa/smart_home.py", line 41, in async_handle_message
    response = await funct_ref(hass, config, directive, context)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/alexa/handlers.py", line 895, in async_api_adjust_target_temp
    target_temp = float(entity.attributes.get(ATTR_TEMPERATURE)) + temp_delta
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: float() argument must be a string or a real number, not 'NoneType'
2023-09-05 20:32:56.564 ERROR (MainThread) [homeassistant.components.alexa.smart_home] Uncaught exception processing Alexa Alexa.ThermostatController/AdjustTargetTemperature request (climate.family_room)
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/alexa/smart_home.py", line 41, in async_handle_message
    response = await funct_ref(hass, config, directive, context)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/alexa/handlers.py", line 895, in async_api_adjust_target_temp
    target_temp = float(entity.attributes.get(ATTR_TEMPERATURE)) + temp_delta
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: float() argument must be a string or a real number, not 'NoneType'

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

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


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

---

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

Commit message: Handle temp adjust when target state not set

Patch to review:
diff --git a/homeassistant/components/alexa/errors.py b/homeassistant/components/alexa/errors.py
index 2c5ced62403a6a..e2a26033d21933 100644
--- a/homeassistant/components/alexa/errors.py
+++ b/homeassistant/components/alexa/errors.py
@@ -90,6 +90,17 @@ class AlexaUnsupportedThermostatModeError(AlexaError):
     error_type = "UNSUPPORTED_THERMOSTAT_MODE"
 
 
+class AlexaUnsupportedThermostatTargetStateError(AlexaError):
+    """Class to represent unsupported climate target state error."""
+
+    namespace = "Alexa.ThermostatController"
+    error_type = "INVALID_TARGET_STATE"
+
+    def __init__(self, msg: str) -> None:
+        """Initialize AlexaUnsupportedThermostatTargetStateError error."""
+        AlexaError.__init__(self, msg)
+
+
 class AlexaTempRangeError(AlexaError):
     """Class to represent TempRange errors."""
 
diff --git a/homeassistant/components/alexa/handlers.py b/homeassistant/components/alexa/handlers.py
index 3e995e9ffe205a..f99b0231e4d4be 100644
--- a/homeassistant/components/alexa/handlers.py
+++ b/homeassistant/components/alexa/handlers.py
@@ -73,6 +73,7 @@
     AlexaSecurityPanelAuthorizationRequired,
     AlexaTempRangeError,
     AlexaUnsupportedThermostatModeError,
+    AlexaUnsupportedThermostatTargetStateError,
     AlexaVideoActionNotPermittedForContentError,
 )
 from .state_report import AlexaDirective, AlexaResponse, async_enable_proactive_mode
@@ -911,7 +912,13 @@ async def async_api_adjust_target_temp(
             }
         )
     else:
-        target_temp = float(entity.attributes[ATTR_TEMPERATURE]) + temp_delta
+        current_target_temp: str | None = entity.attributes.get(ATTR_TEMPERATURE)
+        if current_target_temp is None:
+            raise AlexaUnsupportedThermostatTargetStateError(
+                "The current target temperature is not set, "
+                "cannot adjust target temperature"
+            )
+        target_temp = float(current_target_temp) + temp_delta
 
         if target_temp < min_temp or target_temp > max_temp:
             raise AlexaTempRangeError(hass, target_temp, min_temp, max_temp)
diff --git a/tests/components/alexa/test_smart_home.py b/tests/components/alexa/test_smart_home.py
index c42ea0a0f6a549..bbdf3efeb5fee9 100644
--- a/tests/components/alexa/test_smart_home.py
+++ b/tests/components/alexa/test_smart_home.py
@@ -2471,6 +2471,75 @@ async def test_thermostat(hass: HomeAssistant) -> None:
     assert call.data["preset_mode"] == "eco"
 
 
+async def test_no_current_target_temp_adjusting_temp(hass: HomeAssistant) -> None:
+    """Test thermostat adjusting temp with no initial target temperature."""
+    hass.config.units = US_CUSTOMARY_SYSTEM
+    device = (
+        "climate.test_thermostat",
+        "cool",
+        {
+            "temperature": None,
+            "target_temp_high": None,
+            "target_temp_low": None,
+            "current_temperature": 75.0,
+            "friendly_name": "Test Thermostat",
+            "supported_features": 1 | 2 | 4 | 128,
+            "hvac_modes": ["off", "heat", "cool", "auto", "dry", "fan_only"],
+            "preset_mode": None,
+            "preset_modes": ["eco"],
+            "min_temp": 50,
+            "max_temp": 90,
+        },
+    )
+    appliance = await discovery_test(device, hass)
+
+    assert appliance["endpointId"] == "climate#test_thermostat"
+    assert appliance["displayCategories"][0] == "THERMOSTAT"
+    assert appliance["friendlyName"] == "Test Thermostat"
+
+    capabilities = assert_endpoint_capabilities(
+        appliance,
+        "Alexa.PowerController",
+        "Alexa.ThermostatController",
+        "Alexa.TemperatureSensor",
+        "Alexa.EndpointHealth",
+        "Alexa",
+    )
+
+    properties = await reported_properties(hass, "climate#test_thermostat")
+    properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "COOL")
+    properties.assert_not_has_property(
+        "Alexa.ThermostatController",
+        "targetSetpoint",
+    )
+    properties.assert_equal(
+        "Alexa.TemperatureSensor", "temperature", {"value": 75.0, "scale": "FAHRENHEIT"}
+    )
+
+    thermostat_capability = get_capability(capabilities, "Alexa.ThermostatController")
+    assert thermostat_capability is not None
+    configuration = thermostat_capability["configuration"]
+    assert configuration["supportsScheduling"] is False
+
+    supported_modes = ["OFF", "HEAT", "COOL", "AUTO", "ECO", "CUSTOM"]
+    for mode in supported_modes:
+        assert mode in configuration["supportedModes"]
+
+    # Adjust temperature where target temp is not set
+    msg = await assert_request_fails(
+        "Alexa.ThermostatController",
+        "AdjustTargetTemperature",
+        "climate#test_thermostat",
+        "climate.set_temperature",
+        hass,
+        payload={"targetSetpointDelta": {"value": -5.0, "scale": "KELVIN"}},
+    )
+    assert msg["event"]["payload"]["type"] == "INVALID_TARGET_STATE"
+    assert msg["event"]["payload"]["message"] == (
+        "The current target temperature is not set, cannot adjust target temperature"
+    )
+
+
 async def test_thermostat_dual(hass: HomeAssistant) -> None:
     """Test thermostat discovery with auto mode, with upper and lower target temperatures."""
     hass.config.units = US_CUSTOMARY_SYSTEM


Code review comments:
diff_hunk: @@ -90,6 +90,17 @@ class AlexaUnsupportedThermostatModeError(AlexaError):
     error_type = "UNSUPPORTED_THERMOSTAT_MODE"
 
 
+class AlexaUnsupportedThermostatTargetStateError(AlexaError):
+    """Class to represent unsupported climate target state error."""
+
+    namespace = "Alexa.ThermostatController"
+    error_type = "INVALID_TARGET_STATE"
+
+    def __init__(self, msg: str) -> None:
+        """Initialize AlexaUnsupportedThermostatTargetStateError error."""
+        AlexaError.__init__(self, msg)
path: homeassistant/components/alexa/errors.py
text: @user1:
```suggestion
```

Can be removed