Repository: home-assistant/core
File: homeassistant/components/tuya/sensor.py (Python)

Code before:
        device: CustomerDevice,
        device_manager: Manager,
        description: TuyaSensorEntityDescription,
        dpcode_wrapper: DeviceWrapper[StateType],
    ) -> None:
        """Init Tuya sensor."""
        super().__init__(device, device_manager)
        self.entity_description = description
        self._attr_unique_id = f"{super().unique_id}{description.key}"
        self._dpcode_wrapper = dpcode_wrapper

        if description.native_unit_of_measurement is None:
            self._attr_native_unit_of_measurement = dpcode_wrapper.native_unit
        if description.suggested_unit_of_measurement is None:
            self._attr_suggested_unit_of_measurement = dpcode_wrapper.suggested_unit

        self._apply_report_type_state_class(dpcode_wrapper, description)
        self._validate_device_class_unit()

    async def async_added_to_hass(self) -> None:
        """Handle entity added to Home Assistant."""
        await super().async_added_to_hass()

        # Initialize delta wrapper if applicable
        if isinstance(self._dpcode_wrapper, DPCodeDeltaIntegerWrapper):
            self._dpcode_wrapper.initialize_accumulated_value(self.device)

    async def _handle_state_update(
        self,
        updated_status_properties: list[str] | None,
        dp_timestamps: dict | None = None,
    ) -> None:
        """Handle state update from device."""
        if self._dpcode_wrapper.skip_update(self.device, updated_status_properties):
            return

        # Process delta update if applicable
        if isinstance(self._dpcode_wrapper, DPCodeDeltaIntegerWrapper):
            self._dpcode_wrapper.process_delta_update(self.device, dp_timestamps)

        self.async_write_ha_state()

    def _apply_report_type_state_class(
        self, dpcode_wrapper: DeviceWrapper, description: TuyaSensorEntityDescription
    ) -> None:
        """Apply state class based on wrapper's report_type.

        This will override the state_class from entity description
        if the wrapper indicates a delta or cumulative report type.
        """
        # Check if this is a delta integer wrapper with report_type info

Review comment (suggestion):
Can this be made a standard function of `DeviceWrapper` (which does nothing), and be overriden inside `DPCodeDeltaIntegerWrapper`?
Then it would be called all the time by `TuyaSensorEntity` - and the logic for what to do would be only inside `DPCodeDeltaIntegerWrapper`

Code after:
        self._dpcode_wrapper = dpcode_wrapper

        if description.native_unit_of_measurement is None:
            self._attr_native_unit_of_measurement = dpcode_wrapper.native_unit
        if description.suggested_unit_of_measurement is None:
            self._attr_suggested_unit_of_measurement = dpcode_wrapper.suggested_unit
        if description.state_class is None:
            self._attr_state_class = dpcode_wrapper.state_class

        self._validate_device_class_unit()

    def _validate_device_class_unit(self) -> None:
        """Validate device class unit compatibility."""

        # Logic to ensure the set device class and API received Unit Of Measurement
        # match Home Assistants requirements.
        if (
            self.device_class is not None
            and not self.device_class.startswith(DOMAIN)
            and self.entity_description.native_unit_of_measurement is None
            # we do not need to check mappings if the API UOM is allowed
            and self.native_unit_of_measurement
            not in SENSOR_DEVICE_CLASS_UNITS[self.device_class]
        ):
            # We cannot have a device class, if the UOM isn't set or the
            # device class cannot be found in the validation mapping.
            if (
                self.native_unit_of_measurement is None
                or self.device_class not in DEVICE_CLASS_UNITS
            ):
                LOGGER.debug(
                    "Device class %s ignored for incompatible unit %s in sensor entity %s",
                    self.device_class,
                    self.native_unit_of_measurement,
                    self.unique_id,
                )
                self._attr_device_class = None
                self._attr_suggested_unit_of_measurement = None
                return

            uoms = DEVICE_CLASS_UNITS[self.device_class]
            uom = uoms.get(self.native_unit_of_measurement) or uoms.get(
                self.native_unit_of_measurement.lower()
            )

            # Unknown unit of measurement, device class should not be used.
            if uom is None:
                self._attr_device_class = None
                self._attr_suggested_unit_of_measurement = None
                return