Repository: home-assistant/core
Pull request: Implement measurement sensor for Sensibo
<!--
  You are amazing! Thanks for contributing to our project!
  Please, DO NOT DELETE ANY TEXT from this template! (unless instructed).
-->
## Breaking change
<!--
  If your PR contains a breaking change for existing users, it is important
  to tell them what breaks, how to make it work again and why we did this.
  This piece of text is published with the release notes, so it helps if you
  write it towards our users, not us.
  Note: Remove this section if this PR is NOT a breaking change.
-->
Users with Sensibo Air devices that has a room sensor active as main measurement sensor will retrieve the temperature and humidity from the room sensor.

## 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.
-->
Implement "mainmeasurementssensor" as the data for temperature and humidity if enabled by the user.
Add room sensor data to coordinator data

## 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)
- [x] 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 #63064
- 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**
- [x] There is no commented out code in this PR.
- [x] I have followed the [development checklist][dev-checklist]
- [x] 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`.

The integration reached or maintains the following [Integration Quality Scale][quality-scale]:
<!--
  The Integration Quality Scale scores an integration on the code quality
  and user experience. Each level of the quality scale consists of a list
  of requirements. We highly recommend getting your integration scored!
-->

- [ ] No score or internal
- [ ] 🥈 Silver
- [ ] 🥇 Gold
- [ ] 🏆 Platinum

<!--
  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/en/development_checklist.html
[manifest-docs]: https://developers.home-assistant.io/docs/en/creating_integration_manifest.html
[quality-scale]: https://developers.home-assistant.io/docs/en/next/integration_quality_scale_index.html
[docs-repository]: https://github.com/home-assistant/home-assistant.io


Problem statement:
Sensibo Air + RoomSensor as a primary sensor
### The problem

The Sensibo integration currently does not consider the RoomSensor (MotionSensor) being configured as the primary temperature/humidity sensor. Temperature and humidity values reported in the climate module/ thermostat are coming from the main Sensibo Air unit.

The values for air + motion sensor should be picked from:

```
mainMeasurementsSensor:
 measurements:
  temperature: foo
  humidity: bar
```

alternatively from:
```
motionSensors:
- id:
  isMainSensor: true
  measurements:
   temperature: foo
   humidity: bar
```


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

core-2021.12.7

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

Sensibo

### Link to integration documentation on our website

_No response_

### Example YAML snippet

```yaml
climate:
  - platform: sensibo
    api_key: !secret sensibo
```


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

```txt
n/a
```


### Additional information

_No response_

Hints from issue discussion:
[sensibo documentation](https://www.home-assistant.io/integrations/sensibo)
[sensibo source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/sensibo)
<sub><sup>(message by IssueLinks)</sup></sub>
Hey there @andrey-git, @gjohansson-st, mind taking a look at this issue as it has been labeled with an integration (`sensibo`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L800) for? Thanks!
<sub><sup>(message by CodeOwnersMention)</sup></sub>
I wonder if it's not best to keep the current setup as the temp for the device itself and add new sensors for those additional devices. I don't have those myself so if you can provide an example json output I can look into creating a PR for those.
@gjohansson-ST there are definitely new measurements that can go as an extra into the climate entity attributes. You effectively have two sensors for temp an humidity and motion. They are certainly "nice to have" for those of us, whose main controller is at a different place to the motion sensor (as they call it). 

In my case I have a ducted system, with the heat pump's thermostat in the corridor, where the temperature is irrelevant to the comfort in the rooms in the rest of the house. Hence having the motion sensor at a room, which is used as the default for temperature measurement and in turn Sensibo controlling the heat pump.

The way I assume the climate entity is setup it uses the current_temperature, as the default for rendering the thermostat card. Which of course is incorrect for use with the motion sensor, as the current_temperture is the main unit's (Sensibo) temp sensor.

Having played around a bit I've noticed that the `mainMeasurementsSensor` cannot be relied for the data at all times, as it is `null` when Sensibo is selected as the Default Sensor. It is only populated when the Motion Sensor is selected as the Default. I've attached a couple of json files to show each scenario.

[SensiboAir_motionSensorDefault.json](https://drive.google.com/file/d/14Rjltejm96swfzbaqA7GTaSK9zzCv9vy/view?usp=sharing)

[SensiboAir_mainUnitDefault.json](https://drive.google.com/file/d/14U4a8v-nBo_c6eANPaDwaw_uVnohJf2M/view?usp=sharing)


For now I've tweaked the current climate.py and used it in custom_components to show what I need, though I notice that you've been working on a new implementation that's on the dev branch. Is that due out in the January release?

It would indeed be nice to take advantage of the room sensor, as this is the reason one would buy the Air model.
Will be done now this month so hopefully then we get it into the 2022.3 release.
Once the PR is made this "issue" will be tagged to the PR so you will see it.

Just for clarity someone also needs to test the PR given that I don't have air and hence can't test this myself.
Are you enough familiar so you can test it?
The Config_flow works with Air, no problem.

On the ground all hvac_modes controls got executed, so did changing the target temperature. I don't have swing on my ac, so couldn't test it. 

Although at a couple of occasions the log filled with a few errors, see below. Hope it helps.

Whilst digging into your code, I can't see any reference to the room sensors. Is that next in the pipeline? We could also do with exposing the battery voltage of the room sensor either as a sensor entity or an attribute.  And lastly, the room sensor also provides presence detection that would be useful as a sensor. Thanks.

```
2022-02-04 21:00:08 DEBUG (MainThread) [homeassistant.components.sensibo] Finished fetching sensibo data in 1.837 seconds (success: True)
2022-02-04 22:59:58 ERROR (MainThread) [homeassistant.components.websocket_api.http.connection] [140266421211248] Failed to set AC state for device Heat pump to Sensibo servers:
Traceback (most recent call last):
File "/workspaces/home-assistant/homeassistant/components/sensibo/climate.py", line 300, in _async_set_ac_state_property
result = await self._client.async_set_ac_state_property(
File "/usr/local/lib/python3.9/site-packages/pysensibo/__init__.py", line 77, in async_set_ac_state_property
resp = yield from self._session.patch(
File "/usr/local/lib/python3.9/site-packages/aiohttp/client.py", line 559, in _request
await resp.start(conn)
File "/usr/local/lib/python3.9/site-packages/aiohttp/client_reqrep.py", line 898, in start
message, payload = await protocol.read() # type: ignore[union-attr]
File "/usr/local/lib/python3.9/site-packages/aiohttp/streams.py", line 616, in read
await self._waiter
asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/workspaces/home-assistant/homeassistant/components/sensibo/climate.py", line 300, in _async_set_ac_state_property
result = await self._client.async_set_ac_state_property(
File "/usr/local/lib/python3.9/site-packages/async_timeout/__init__.py", line 129, in __aexit__
self._do_exit(exc_type)
File "/usr/local/lib/python3.9/site-packages/async_timeout/__init__.py", line 212, in _do_exit
raise asyncio.TimeoutError
asyncio.exceptions.TimeoutError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/workspaces/home-assistant/homeassistant/components/websocket_api/commands.py", line 190, in handle_call_service
await hass.services.async_call(
File "/workspaces/home-assistant/homeassistant/core.py", line 1630, in async_call
task.result()
File "/workspaces/home-assistant/homeassistant/core.py", line 1667, in _execute_service
await cast(Callable[[ServiceCall], Awaitable[None]], handler.job.target)(
File "/workspaces/home-assistant/homeassistant/helpers/entity_component.py", line 204, in handle_service
await self.hass.helpers.service.entity_service_call(
File "/workspaces/home-assistant/homeassistant/helpers/service.py", line 668, in entity_service_call
future.result() # pop exception if have
File "/workspaces/home-assistant/homeassistant/helpers/entity.py", line 921, in async_request_call
await coro
File "/workspaces/home-assistant/homeassistant/helpers/service.py", line 705, in _handle_entity_call
await result
File "/workspaces/home-assistant/homeassistant/components/sensibo/climate.py", line 277, in async_set_hvac_mode
await self._async_set_ac_state_property("on", True)
File "/workspaces/home-assistant/homeassistant/components/sensibo/climate.py", line 312, in _async_set_ac_state_property
raise HomeAssistantError(
homeassistant.exceptions.HomeAssistantError: Failed to set AC state for device Heat pump to Sensibo servers:
2022-02-04 23:00:15 DEBUG (MainThread) [homeassistant.components.sensibo] Result: {'id': 'TTwy5grPES', 'time': {'time': '2022-02-04T23:00:13Z', 'secondsAgo': 0}, 'status': 'Success', 'acState': {'timestamp': {'time': '2022-02-04T23:00:15.199590Z', 'secondsAgo': -2}, 'on': False, 'mode': 'cool', 'targetTemperature': 24, 'temperatureUnit': 'C', 'fanLevel': 'auto', 'swing': 'stopped'}, 'changedProperties': ['on'], 'reason': 'UserRequest', 'failureReason': None}
2022-02-04 23:00:20 DEBUG (MainThread) [homeassistant.components.sensibo] Finished fetching sensibo data in 1.064 seconds (success: True)
2022-02-04 23:00:29 DEBUG (MainThread) [homeassistant.components.sensibo] Result: {'id': 'm9YAoMMBAJ', 'time': {'time': '2022-02-04T23:00:26Z', 'secondsAgo': 0}, 'status': 'Success', 'acState': {'timestamp': {'time': '2022-02-04T23:00:29.150362Z', 'secondsAgo': -3}, 'on': True, 'mode': 'cool', 'targetTemperature': 24, 'temperatureUnit': 'C', 'fanLevel': 'auto', 'swing': 'stopped'}, 'changedProperties': ['on'], 'reason': 'UserRequest', 'failureReason': None}
2022-02-04 23:00:30 DEBUG (MainThread) [homeassistant.components.sensibo] Result: {'id': 'SnVVGMXcwi', 'time': {'time': '2022-02-04T23:00:29Z', 'secondsAgo': 0}, 'status': 'Success', 'acState': {'timestamp': {'time': '2022-02-04T23:00:30.893692Z', 'secondsAgo': -1}, 'on': True, 'mode': 'fan', 'fanLevel': 'auto', 'swing': 'stopped'}, 'changedProperties': ['mode', 'targetTemperature'], 'reason': 'UserRequest', 'failureReason': None}
2022-02-04 23:00:40 ERROR (MainThread) [homeassistant.components.websocket_api.http.connection] [140266421211248] Failed to set AC state for device Heat pump to Sensibo servers: <html><head><title>400 BadRequest - Sensibo</title></head><body><h>400 BadRequest</h><p>parameter &#x27;newValue&#x27; invalid: Invalid targetTemperature in (capabilities: Temperatures: {})</p><body></html>
Traceback (most recent call last):
File "/workspaces/home-assistant/homeassistant/components/sensibo/climate.py", line 300, in _async_set_ac_state_property
result = await self._client.async_set_ac_state_property(
File "/usr/local/lib/python3.9/site-packages/pysensibo/__init__.py", line 86, in async_set_ac_state_property
raise SensiboError((yield from resp.text()))
pysensibo.SensiboError: <html><head><title>400 BadRequest - Sensibo</title></head><body><h>400 BadRequest</h><p>parameter &#x27;newValue&#x27; invalid: Invalid targetTemperature in (capabilities: Temperatures: {})</p><body></html>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/workspaces/home-assistant/homeassistant/components/websocket_api/commands.py", line 190, in handle_call_service
await hass.services.async_call(
File "/workspaces/home-assistant/homeassistant/core.py", line 1630, in async_call
task.result()
File "/workspaces/home-assistant/homeassistant/core.py", line 1667, in _execute_service
await cast(Callable[[ServiceCall], Awaitable[None]], handler.job.target)(
File "/workspaces/home-assistant/homeassistant/helpers/entity_component.py", line 204, in handle_service
await self.hass.helpers.service.entity_service_call(
File "/workspaces/home-assistant/homeassistant/helpers/service.py", line 668, in entity_service_call
future.result() # pop exception if have
File "/workspaces/home-assistant/homeassistant/helpers/entity.py", line 921, in async_request_call
await coro
File "/workspaces/home-assistant/homeassistant/helpers/service.py", line 705, in _handle_entity_call
await result
File "/workspaces/home-assistant/homeassistant/components/climate/__init__.py", line 586, in async_service_temperature_set
await entity.async_set_temperature(**kwargs)
File "/workspaces/home-assistant/homeassistant/components/sensibo/climate.py", line 263, in async_set_temperature
await self._async_set_ac_state_property("targetTemperature", int(temperature))
File "/workspaces/home-assistant/homeassistant/components/sensibo/climate.py", line 312, in _async_set_ac_state_property
raise HomeAssistantError(
homeassistant.exceptions.HomeAssistantError: Failed to set AC state for device Heat pump to Sensibo servers: <html><head><title>400 BadRequest - Sensibo</title></head><body><h>400 BadRequest</h><p>parameter &#x27;newValue&#x27; invalid: Invalid targetTemperature in (capabilities: Temperatures: {})</p><body></html>
2022-02-04 23:00:51 DEBUG (MainThread) [homeassistant.components.sensibo] Result: {'id': 'czTABX3cHg', 'time': {'time': '2022-02-04T23:00:49Z', 'secondsAgo': 0}, 'status': 'Success', 'acState': {'timestamp': {'time': '2022-02-04T23:00:51.194306Z', 'secondsAgo': -2}, 'on': False, 'mode': 'fan', 'fanLevel': 'auto', 'swing': 'stopped'}, 'changedProperties': ['on'], 'reason': 'UserRequest', 'failureReason': None}
```
I've just updated the dev branch and there's a new error that's popping up. This issue causes the integration setup to be in an error stater and unavailable.

```
2022-02-05 03:14:54 ERROR (MainThread) [homeassistant.components.sensibo] Unexpected error fetching sensibo data: list index out of range
Traceback (most recent call last):
  File "/workspaces/home-assistant/homeassistant/helpers/update_coordinator.py", line 187, in _async_refresh
    self.data = await self._async_update_data()
  File "/workspaces/home-assistant/homeassistant/components/sensibo/coordinator.py", line 74, in _async_update_data
    temperature_step = temperatures_list[1] - temperatures_list[0]
IndexError: list index out of range
```
> I've just updated the dev branch and there's a new error that's popping up. This issue causes the integration setup to be in an error stater and unavailable.
> 
Plese report it as a new issue preferably getting an api-output (given I understand you know how to do that).
Will in the meantime create a fix (guard) but need an issue to reference preferably (to get it in as patch for 2022.2)
Thanks

Commit message: Fixes from review

Patch to review:
diff --git a/homeassistant/components/sensibo/coordinator.py b/homeassistant/components/sensibo/coordinator.py
index 926232ef159bc4..f49c58d678ca4f 100644
--- a/homeassistant/components/sensibo/coordinator.py
+++ b/homeassistant/components/sensibo/coordinator.py
@@ -98,6 +98,30 @@ async def _async_update_data(self) -> dict[str, dict[str, Any]]:
             calibration_temp = dev["sensorsCalibration"].get("temperature", 0.0)
             calibration_hum = dev["sensorsCalibration"].get("humidity", 0.0)
 
+            # Sky plus supports functionality to use motion sensor as sensor for temp and humidity
+            if main_sensor := dev["mainMeasurementsSensor"]:
+                measurements = main_sensor["measurements"]
+                temperature = measurements.get("temperature")
+                humidity = measurements.get("humidity")
+
+            motion_sensors = []
+            if dev["motionSensors"]:
+                for motionsensor in dev["motionSensors"]:
+                    sensor = {
+                        "alive": motionsensor["connectionStatus"].get("isAlive"),
+                        "fw_ver": motionsensor.get("firmwareVersion"),
+                        "fw_type": motionsensor.get("firmwareType"),
+                        "id": motionsensor["id"],
+                        "ismainsensor": motionsensor.get("isMainSensor"),
+                        "batteryvoltage": motionsensor["measurements"].get(
+                            "batteryVoltage"
+                        ),
+                        "humidity": motionsensor["measurements"].get("humidity"),
+                        "temperature": motionsensor["measurements"].get("temperature"),
+                        "model": motionsensor.get("productModel"),
+                    }
+                    motion_sensors.append(sensor)
+
             device_data[unique_id] = {
                 "id": unique_id,
                 "mac": mac,
@@ -126,5 +150,6 @@ async def _async_update_data(self) -> dict[str, dict[str, Any]]:
                 "calibration_temp": calibration_temp,
                 "calibration_hum": calibration_hum,
                 "full_capabilities": capabilities,
+                "motion_sensors": motion_sensors,
             }
         return device_data


Code review comments:
diff_hunk: @@ -98,6 +98,30 @@ async def _async_update_data(self) -> dict[str, dict[str, Any]]:
             calibration_temp = dev["sensorsCalibration"].get("temperature", 0.0)
             calibration_hum = dev["sensorsCalibration"].get("humidity", 0.0)
 
+            # Sky plus supports functionality to use motion sensor as sensor for temp and humidity
+            if main_sensor := dev["mainMeasurementsSensor"]:
+                measurements = main_sensor["measurements"]
+                temperature = measurements.get("temperature")
+                humidity = measurements.get("humidity")
+
+            motion_sensors = []
+            if dev["motionSensors"]:
+                for motionsensor in dev["motionSensors"]:
+                    sensor = {
+                        "alive": motionsensor["connectionStatus"].get("isAlive"),
+                        "fw_ver": motionsensor.get("firmwareVersion"),
+                        "fw_type": motionsensor.get("firmwareType"),
+                        "id": motionsensor["id"],
+                        "ismainsensor": motionsensor.get("isMainSensor"),
path: homeassistant/components/sensibo/coordinator.py
text: @user1:
```suggestion
                        "is_main_sensor": motionsensor.get("isMainSensor"),
```

@user1:
You could make each `sensor` a `dataclass`

https://docs.python.org/3/library/dataclasses.html

diff_hunk: @@ -98,6 +98,30 @@ async def _async_update_data(self) -> dict[str, dict[str, Any]]:
             calibration_temp = dev["sensorsCalibration"].get("temperature", 0.0)
             calibration_hum = dev["sensorsCalibration"].get("humidity", 0.0)
 
+            # Sky plus supports functionality to use motion sensor as sensor for temp and humidity
+            if main_sensor := dev["mainMeasurementsSensor"]:
+                measurements = main_sensor["measurements"]
+                temperature = measurements.get("temperature")
+                humidity = measurements.get("humidity")
+
+            motion_sensors = []
+            if dev["motionSensors"]:
+                for motionsensor in dev["motionSensors"]:
+                    sensor = {
+                        "alive": motionsensor["connectionStatus"].get("isAlive"),
+                        "fw_ver": motionsensor.get("firmwareVersion"),
+                        "fw_type": motionsensor.get("firmwareType"),
+                        "id": motionsensor["id"],
+                        "ismainsensor": motionsensor.get("isMainSensor"),
+                        "batteryvoltage": motionsensor["measurements"].get(
path: homeassistant/components/sensibo/coordinator.py
text: @user1:
Please use _s to separate words.  This be easier to type later if you make it a dataclass 

@author:
Can you give me an example as I'm not entirely sure what you mean.