Jelajahi Sumber

feat!(entity): decode JSON extra attributes

Since extra attributes are read-only and have no impact on official
entity APIs, decoding them when marked as JSON is easy, and makes it
easier for users to extract data into template sensors.

Issue #4923
Jason Rumney 2 bulan lalu
induk
melakukan
cc4b0e107c

+ 1 - 1
custom_components/tuya_local/devices/dewall_evcharger.yaml

@@ -34,7 +34,7 @@ entities:
           - dps_val: STOP
             value: charged
       - id: 102
-        type: string
+        type: json
         name: metrics
       - id: 103
         type: string

+ 8 - 0
custom_components/tuya_local/entity.py

@@ -2,6 +2,7 @@
 Common functionality for Tuya Local entities
 """
 
+import json
 import logging
 
 from homeassistant.const import (
@@ -102,6 +103,13 @@ class TuyaLocalEntity:
         for a in self._attr_dps:
             value = a.get_value(self._device)
             if value is not None or not a.optional:
+                // Decode json attributes for user convenience
+                if a.rawtype == "json":
+                    try:
+                        value = json.loads(value)
+                    except json.JSONDecodeError:
+                        if value is not None:
+                            _LOGGER.warning("Failed to decode JSON for attribute %s: %s", a.name, value)
                 attr[a.name] = value
         return attr