Explorar o código

Add utf16b64 type.

This type represents a UTF-16-BE string encoded in base64.
This encoding is used by some devices "raw" encoding type to pass
textual messages often containing Chinese characters or punctuation,
or user supplied messages that may be in any language.
I guess there is a fear that utf-8 may sometimes encode to problematic
bytes, or when they test with Chinese strings, this encoding is more
efficient than utf-8.

To support the encoding found in PR #2388
Jason Rumney hai 1 ano
pai
achega
d321baa6b2
Modificáronse 1 ficheiros con 10 adicións e 0 borrados
  1. 10 0
      custom_components/tuya_local/helpers/device_config.py

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

@@ -348,6 +348,7 @@ class TuyaDpsConfig:
             "bitfield": int,
             "json": str,
             "base64": str,
+            "utf16b64": str,
             "hex": str,
             "unixtime": int,
         }
@@ -667,6 +668,8 @@ class TuyaDpsConfig:
             result = float(result)
         elif self.type is str:
             result = str(result)
+            if self.rawtype == "utf16b64":
+                result = b64encode(result.encode("utf-16-be")).decode("utf-8")
 
         if self.stringify:
             result = str(result)
@@ -683,6 +686,13 @@ class TuyaDpsConfig:
         else:
             self.stringify = False
 
+        # decode utf-16 base64 strings first, so normal strings can be matched
+        if self.rawtype == "utf16b64" and isinstance(val, str):
+            try:
+                val = b64decode(val).decode("utf-16-be")
+            except ValueError:
+                _LOGGER.warning("Invalid utf16b64 %s", val)
+
         result = val
         scale = self.scale(device)
         replaced = False