From 55f9c8f5196882ec4dfe8af76e8b77e2195c5a77 Mon Sep 17 00:00:00 2001 From: Zhong Jianxin Date: Mon, 15 Jun 2020 17:44:58 +0800 Subject: [PATCH] Huami: Avoid cutting multibyte chars in half --- .../service/devices/huami/HuamiSupport.java | 3 +++ .../gadgetbridge/util/StringUtils.java | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/huami/HuamiSupport.java b/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/huami/HuamiSupport.java index 99a30fc02..532fb5bac 100644 --- a/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/huami/HuamiSupport.java +++ b/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/huami/HuamiSupport.java @@ -673,6 +673,9 @@ public class HuamiSupport extends AbstractBTLEDeviceSupport { byte[] rawmessage = message.getBytes(); int length = Math.min(rawmessage.length, maxLength - prefixlength); + if (length < rawmessage.length) { + length = StringUtils.utf8ByteLength(message, length); + } byte[] command = new byte[length + prefixlength + suffixlength]; int pos = 0; diff --git a/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/util/StringUtils.java b/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/util/StringUtils.java index 0495dae01..5d5b923e7 100644 --- a/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/util/StringUtils.java +++ b/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/util/StringUtils.java @@ -17,6 +17,10 @@ along with this program. If not, see . */ package nodomain.freeyourgadget.gadgetbridge.util; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.StandardCharsets; + import androidx.annotation.NonNull; public class StringUtils { @@ -37,6 +41,16 @@ public class StringUtils { return s.substring(0, length); } + public static int utf8ByteLength(String string, int length) { + if (string == null) { + return 0; + } + ByteBuffer outBuf = ByteBuffer.allocate(length); + CharBuffer inBuf = CharBuffer.wrap(string.toCharArray()); + StandardCharsets.UTF_8.newEncoder().encode(inBuf, outBuf, true); + return outBuf.position(); + } + public static String pad(String s, int length){ return pad(s, length, ' '); }