Quellcode durchsuchen

sensor: Implement new native_precision attribute for HA 2023.2.

As this is an additional attribute, the integration should continue to
work on HA 2022.11 thru 2023.1 by just ignoring it.

Issue #370
Jason Rumney vor 3 Jahren
Ursprung
Commit
f6247d1a01

+ 17 - 0
custom_components/tuya_local/helpers/device_config.py

@@ -454,6 +454,23 @@ class TuyaDpsConfig:
         else:
             return None
 
+    def precision(self, device):
+        if self.type is int:
+            scale = 1
+            mapping = self._find_map_for_dps(device.get_property(self.id))
+            if mapping:
+                scale = mapping.get("scale", 1)
+                cond = self._active_condition(mapping, device)
+                if cond:
+                    scale = cond.get("scale", scale)
+            precision = 0
+            _LOGGER.debug(f"calculating precision of scale {scale}...")
+            while scale > 1.0:
+                scale /= 10.0
+                precision += 1
+            _LOGGER.debug(f"...precision calculated as {precision}")
+            return precision
+
     def step(self, device, scaled=True):
         step = 1
         scale = 1

+ 5 - 0
custom_components/tuya_local/sensor.py

@@ -79,3 +79,8 @@ class TuyaLocalSensor(TuyaLocalEntity, SensorEntity):
             unit = self._unit_dps.get_value(self._device)
 
         return unit_from_ascii(unit)
+
+    @property
+    def native_precision(self):
+        """Return the precision for the sensor"""
+        return self._sensor_dps.precision(self._device)

+ 5 - 0
tests/devices/test_smartplugv2.py

@@ -94,3 +94,8 @@ class TestSwitchV2(
                 "current_power_w": 567.8,
             },
         )
+
+    def test_sensor_precision(self):
+        self.assertEqual(self.multiSensor["sensor_current"].native_precision, 0)
+        self.assertEqual(self.multiSensor["sensor_power"].native_precision, 1)
+        self.assertEqual(self.multiSensor["sensor_voltage"].native_precision, 1)