python - 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字符串,但是对于我上面提到的字符串它不起作用,得到这个错误: 问题的原因可能是编码吗?有人可以帮我理解我哪里错了吗?任何帮助将不胜感激,凯文
解决方案
问题之一是
size_t payloadLen = sizeof(diagnostic_payload);
您正在获取缓冲区的大小,而不是字符串的大小。注意:Python 允许您使用任何 Unicode 字符,包括\0
文本。这在过去用于填充,或者在指定速度但数据未准备好的终端上用作“非字符”。
因此,您发送带有脏尾随字节的数据,python 尝试打印这些字节,但是因为它们是随机数并且不是有效的 UTF-8 序列,所以您遇到了错误。
推荐阅读
- javascript - 如何重新安排日程安排到午夜?
- c - 如何从 CSV 文件(用 C 语言)读取和写入寄存器?
- javascript - 小滑块点击监听器注册太晚
- excel - 是否有方法或属性(与 PivotCache / PivotCaches 相关)来确定无法创建数据透视缓存的原因?
- angular - 从 Angular 5 中的 http.get 返回单个项目的 Observable
- javascript - 如何将一位整数数组转换为 2 位或更多位
- windows - 在批处理 FOR /F 命令中使用空格
- highcharts - 如何将数据动态添加到钻取图?
- html - 水平放置带有浮动文本的段落
- c# - 将 JSON 作为资源加载到对象