首页 > 解决方案 > utf-8 编码,奇怪的字符,GUI 不起作用

问题描述

我正在开发一个 MQTT 应用程序,它通过电路板获取一些值并将其带到 GUI。所以我也用C和python(用于GUI)编程。我对 UTF-8 编码有疑问。在 CI 中写道:

   sprintf((char*)diagnostic_payload, "{\"Diagnostic response: \%X %X %X %X %X %X %X %X %X}", frameRead.can_id, frameRead.data[0], frameRead.data[1], frameRead.data[2], frameRead.data[3]
, frameRead.data[4], frameRead.data[5], frameRead.data[6], frameRead.data[7]);
            
            size_t payloadLen = sizeof(diagnostic_payload);

            const le_result_t publishResult = mqtt_Publish(
            MQTTSession,
            newTopic,
            diagnostic_payload,
            payloadLen,
            MQTT_QOS0_TRANSMIT_ONCE,
            retain);
            if (publishResult == LE_OK)
            LE_INFO(
                "Message published");

效果很好,我在 Windows 上的 broker 的命令提示符下看到消息,但我不明白为什么,添加了一些奇怪的字符:

在此处输入图像描述 我写了一个在图形界面上带来这个值的应用程序:client = mqtt.Client("Prova")

m_decode = ''




def on_log(client, userdata, level, buf):
    print("log: "+buf)

def on_connect(client, userdata, flags, rc):
    if rc==0:
        print("Connected OK")
        connection_status.config(text="Connection status: CONNECTED")
    else:
        print("Bad connection Returned code = ", rc)
        connection_status.config(text="Connection status: BAD CONNECTION with error" + rc)

def on_disconnect(client, userdata, flags, rc=0):
    print("DisConnected result code "+str(rc))
    connection_status.config(text="Connection status: DISCONNECTED" + rc)

def on_message(client, userdata, msg):
    topic=msg.topic
    global m_decode
    m_decode=str(msg.payload.decode("utf-8"))
    print("message received", m_decode)
    testo_receive.configure(text=m_decode)
    #testo_receive.config(text="Messaggio ricevuto on diag_response: " + (m_decode))
    #Le righe sotto vanno aggiunte se vuoi memorizzare i dati su file di testo
    file = open("documento_test_diagnosi.txt", 'a')
    file.write(m_decode)
    file.write("\n")
    file.close()
    

#questa funzione, tramite il tasto send, invia un messaggio su un certo topic (in esempio, mangoh)
def publish_message(client, msg_entry):
    msg=msg_entry.get()
    msg_entry.delete('0', 'end')
    

它适用于普通的char字符串,但是对于我上面提到的字符串它不起作用,得到这个错误: 在此处输入图像描述 问题的原因可能是编码吗?有人可以帮我理解我哪里错了吗?任何帮助将不胜感激,凯文

标签: pythoncuser-interfacetkinterutf-8

解决方案


问题之一是

size_t payloadLen = sizeof(diagnostic_payload);

您正在获取缓冲区的大小,而不是字符串的大小。注意:Python 允许您使用任何 Unicode 字符,包括\0文本。这在过去用于填充,或者在指定速度但数据未准备好的终端上用作“非字符”。

因此,您发送带有脏尾随字节的数据,python 尝试打印这些字节,但是因为它们是随机数并且不是有效的 UTF-8 序列,所以您遇到了错误。


推荐阅读