Просмотр исходного кода

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 1 год назад
Родитель
Сommit
d321baa6b2
1 измененных файлов с 10 добавлено и 0 удалено
  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,
             "bitfield": int,
             "json": str,
             "json": str,
             "base64": str,
             "base64": str,
+            "utf16b64": str,
             "hex": str,
             "hex": str,
             "unixtime": int,
             "unixtime": int,
         }
         }
@@ -667,6 +668,8 @@ class TuyaDpsConfig:
             result = float(result)
             result = float(result)
         elif self.type is str:
         elif self.type is str:
             result = str(result)
             result = str(result)
+            if self.rawtype == "utf16b64":
+                result = b64encode(result.encode("utf-16-be")).decode("utf-8")
 
 
         if self.stringify:
         if self.stringify:
             result = str(result)
             result = str(result)
@@ -683,6 +686,13 @@ class TuyaDpsConfig:
         else:
         else:
             self.stringify = False
             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
         result = val
         scale = self.scale(device)
         scale = self.scale(device)
         replaced = False
         replaced = False