Repository: home-assistant/core
Pull request: Return group unit of measurement when device_class is None
<!--
  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.
-->
Allows to return calculated unit of measurement if no device class and all source sensors are same unit of measurement.


## 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 #109969
- 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 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.
- [ ] 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:
Unit of measurements is not correct
### The problem

Unit of measurements is not correct
Unit of measurements °C, °C, °C of input sensors sensor.izone_current_temperature_upstairs, sensor.ble_temperature_upstairs_lounge_ble_climate, sensor.upstairs_climate_display_temperature are not compatible using no device class of sensor group sensor.upstairs_lounge_average_temperature.

Unit of measurements L, L of input sensors sensor.beergarden_garden_tap_total_water_no_cycle_metered, sensor.frontyard_right_side_garden_tap_water_no_cycle_metered are not compatible using no device class of sensor group sensor.total_garden_taps_water_no_cycle_metered.

Please correct the unit of measurements on the source entities or set a proper device class on the sensor group and reload the group sensor to fix this issue.

### What version of Home Assistant Core has the issue?

2024.2.0

### What was the last working version of Home Assistant Core?

2024.1.5

### What type of installation are you running?

Home Assistant OS

### Integration causing the issue

Groups

### 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 @home-assistant/core, mind taking a look at this issue as it has been labeled with an integration (`group`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L516) for? Thanks!

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


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

---

[group documentation](https://www.home-assistant.io/integrations/group)
[group source](https://github.com/home-assistant/core/tree/dev/homeassistant/components/group)
<sub><sup>(message by IssueLinks)</sup></sub>
Occuring, when unit of measurement is defined in the parent sensors and no device_class is available (for example µSv/h for radiation). Unit of measurement is not carried over from parent sensors (all the same unit) to the helper anymore.
When using the old "Combine the state of several sensors" helper, the error message does not appear and the unit of measurement is carried over from the parent sensors to the helper.
Experiencing a similar problem with a different warning in the form of
```
WARNING (MainThread) [homeassistant.components.sensor] Entity sensor.indoor_temperature (<class 'homeassistant.components.group.sensor.SensorGroup'>) is using native unit of measurement 'None' which is not a valid unit for the device class ('temperature') it is using; expected one of ['°F', 'K', '°C'];
```

So in my case it appears the device_class was maintained but the units of measurement were lost. 

~I found that removing and re-adding a group member caused the unit of measurement to be set again.~ Only helped until HA reboots.


Seeing the same error for my cover. I have a sensor how much they are open/closed in % but there is no device class for that.
I did a hard reboot of HA and I think that fixed it, try that everyone
Nothing changed after rebooting.
See @mill1000 and what he did
Negative. Reboot and group re-creation didn't change anything.
Same issue here. I got four different warnings with variations on this, but I was able to fix two by adding a device class for some MQTT temperature sensors in my YAML. It did require a full reboot for them to "take" and the warning to disappear. Still working on the other two.
Issue still present in core 2024.2.1

Commit message: Groups: Return units when device_class is None

Patch to review:
diff --git a/homeassistant/components/group/sensor.py b/homeassistant/components/group/sensor.py
index 8e1a0a242075a..379ccb6cd4c80 100644
--- a/homeassistant/components/group/sensor.py
+++ b/homeassistant/components/group/sensor.py
@@ -602,6 +602,9 @@ def _calculate_unit_of_measurement(
                     "uoms": ", ".join(unit_of_measurements),
                 },
             )
+
+            if all(x == unit_of_measurements[0] for x in unit_of_measurements):
+                return unit_of_measurements[0]
         return None
 
     def _get_valid_units(self) -> set[str | None]:
diff --git a/tests/components/group/test_sensor.py b/tests/components/group/test_sensor.py
index ec6905a500f48..8c9aee362f2a6 100644
--- a/tests/components/group/test_sensor.py
+++ b/tests/components/group/test_sensor.py
@@ -424,6 +424,66 @@ async def test_sensor_calculated_properties(hass: HomeAssistant) -> None:
     assert state.state == str(float(sum(VALUES)))
 
 
+async def test_sensor_calculated_properties_device_class_none(
+    hass: HomeAssistant, issue_registry: ir.IssueRegistry
+) -> None:
+    """Test the sensor calculating device_class, state_class and unit of measurement when device class is None."""
+    config = {
+        SENSOR_DOMAIN: {
+            "platform": GROUP_DOMAIN,
+            "name": "test_last",
+            "type": "last",
+            "entities": ["sensor.test_1", "sensor.test_2", "sensor.test_3"],
+            "unique_id": "very_unique_id_last_sensor",
+        }
+    }
+
+    entity_ids = config["sensor"]["entities"]
+
+    hass.states.async_set(
+        entity_ids[0],
+        VALUES[0],
+        {
+            "device_class": SensorDeviceClass.POWER,
+            "state_class": SensorStateClass.MEASUREMENT,
+            "unit_of_measurement": "W",
+        },
+    )
+    hass.states.async_set(
+        entity_ids[1],
+        VALUES[1],
+        {
+            "device_class": SensorDeviceClass.POWER,
+            "state_class": SensorStateClass.MEASUREMENT,
+            "unit_of_measurement": "W",
+        },
+    )
+    hass.states.async_set(
+        entity_ids[2],
+        VALUES[2],
+        {
+            "device_class": None,
+            "state_class": SensorStateClass.MEASUREMENT,
+            "unit_of_measurement": "W",
+        },
+    )
+
+    await hass.async_block_till_done()
+
+    assert await async_setup_component(hass, "sensor", config)
+    await hass.async_block_till_done()
+
+    state = hass.states.get("sensor.test_last")
+    assert state.state == str(float(VALUES[2]))
+    assert state.attributes.get("device_class") is None
+    assert state.attributes.get("state_class") == SensorStateClass.MEASUREMENT
+    assert state.attributes.get("unit_of_measurement") == "W"
+
+    assert issue_registry.async_get_issue(
+        GROUP_DOMAIN, "sensor.test_last_uoms_not_matching_no_device_class"
+    )
+
+
 async def test_sensor_calculated_properties_not_same(
     hass: HomeAssistant, issue_registry: ir.IssueRegistry
 ) -> None:


Code review comments:
diff_hunk: @@ -602,6 +602,9 @@ def _calculate_unit_of_measurement(
                     "uoms": ", ".join(unit_of_measurements),
                 },
             )
+
path: homeassistant/components/group/sensor.py
text: @user1:
This should go before the repair cases (we shouldn't have those repairs if this is what we want).
Also likely update the description of those repairs to make them more clear and easier to understand.

diff_hunk: @@ -602,6 +602,9 @@ def _calculate_unit_of_measurement(
                     "uoms": ", ".join(unit_of_measurements),
                 },
             )
+
+            if all(x == unit_of_measurements[0] for x in unit_of_measurements):
+                return unit_of_measurements[0]
path: homeassistant/components/group/sensor.py
text: @user1:
Need also to update `_get_valid_units` below