diff --git a/homeassistant/components/sensor/__init__.py b/homeassistant/components/sensor/__init__.py index 0268bd8b207..419c4df4f84 100644 --- a/homeassistant/components/sensor/__init__.py +++ b/homeassistant/components/sensor/__init__.py @@ -361,25 +361,30 @@ class SensorEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_): def _is_valid_suggested_unit(self, suggested_unit_of_measurement: str) -> bool: """Validate the suggested unit. - Validate that a unit converter exists for the sensor's device class and that the - unit converter supports both the native and the suggested units of measurement. + Validate that the native unit of measurement can be converted to the + suggested unit of measurement, either because they are the same or + because a unit converter supports both. """ - # Make sure we can convert the units - if self.native_unit_of_measurement != suggested_unit_of_measurement and ( - (unit_converter := UNIT_CONVERTERS.get(self.device_class)) is None - or self.__native_unit_of_measurement_compat - not in unit_converter.VALID_UNITS - or suggested_unit_of_measurement not in unit_converter.VALID_UNITS - ): - if not self._invalid_suggested_unit_of_measurement_reported: - self._invalid_suggested_unit_of_measurement_reported = True - raise ValueError( - f"Entity {type(self)} suggest an incorrect " - f"unit of measurement: {suggested_unit_of_measurement}." - ) - return False + # No need to check the unit converter if the units are the same + if self.native_unit_of_measurement == suggested_unit_of_measurement: + return True - return True + # Make sure there is a unit converter and it supports both units + if ( + (unit_converter := UNIT_CONVERTERS.get(self.device_class)) + and self.__native_unit_of_measurement_compat in unit_converter.VALID_UNITS + and suggested_unit_of_measurement in unit_converter.VALID_UNITS + ): + return True + + # Report invalid suggested unit only once per entity + if not self._invalid_suggested_unit_of_measurement_reported: + self._invalid_suggested_unit_of_measurement_reported = True + raise ValueError( + f"Entity {type(self)} suggest an incorrect " + f"unit of measurement: {suggested_unit_of_measurement}." + ) + return False def _get_initial_suggested_unit(self) -> str | UndefinedType: """Return the initial unit."""