utf-8 编码,奇怪的字符,GUI 不起作用

问题描述 投票:0回答:2

我正在开发一个 MQTT 应用程序,它通过板获取一些值并将其带到 GUI。所以我也用 C 和 python(用于 GUI)进行编程。 我在 UTF-8 编码方面遇到问题。 我用C写的:

   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上的经纪人的命令提示符上看到了该消息,但我不明白为什么,添加了一些奇怪的字符:

我编写了一个应用程序,将这个值带到图形界面上: 客户端 = 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')
    

它适用于普通的字符字符串,但对于我上面提到的字符串,它不起作用,出现此错误: 问题的原因可能是编纂吗?有人可以帮助我理解我错在哪里吗? 任何帮助将不胜感激, 凯文

python c user-interface tkinter utf-8
2个回答
0
投票

先生,有人在 mangOH 黄板上工作过,我有一些疑问,如果有人可以帮助请告诉我,这将是一个很大的帮助

谢谢


-1
投票

问题之一是

size_t payloadLen = sizeof(diagnostic_payload);

您正在获取缓冲区的大小,而不是字符串的大小。注意:Python 允许您使用任何 Unicode 字符,也可以在文本中使用

\0
。这在过去用于填充,或者只是作为指定速度的终端上的“非字符”,但数据尚未准备好。

因此,您发送带有脏尾部字节的数据,Python 尝试打印这些数据,但由于它们是随机数并且不是有效的 UTF-8 序列,因此会出现错误。

© www.soinside.com 2019 - 2024. All rights reserved.