Python读取TCP的4字节浮点数

Python4字节浮点数读取

背景

用Python的tkinter开发人机界面。机器是MCU的无线服务器端。Python程序为Client,连接MCU TCP server。client发送21个字节帧。按modbusTCP发送。为提高通讯效率,server端在接到client发送来的8位的数据串后给client发送MCU的运行数据。在server端要解释4个字节的浮点数。

读取4字节的浮点数

在MCU端,用

cpp 复制代码
memcpy(&txBuff[14], &fMeterValue, sizeof(MeterValue));

然后向client发送一串字节。

在python程序侧,一般是要建立一个独立的线程来接收从server发送来的数据。比如,我们从server端读取了下面的一串字节:

cpp 复制代码
b'\x00\x00\x00\x00\x00\x00\x19\x01\x10\x00d\x00\t\x12\x8f\xc2\xd5\xbf\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

其中的msg14, msg15, msg16, msg17是一个浮点数,要在HMI的页面上显示

下面是代码:

cpp 复制代码
def tcp_read(para='hi', sleep=1.0):
    while True:
        global stop_threads
        if stop_threads:
            break
        time.sleep(sleep)
        if ( bConnect == True):
            try:
                msg = tcp_client.recv(512)
                print(len(msg))
                if ( len(msg) > 0 ):
                    vx = bytes([msg[13], msg[14], msg[15], msg[16]])
                    vy = struct.unpack('f', vx)[0]
                    e4.delete(0, END)
                    svy = "%.2f" %vy
                    e4.insert(0, svy)
                    #print(msg)
                    print('The meter = %.2f' %vy)                                 
            except Exception as e:
                print('time out')
                logging.debug(e)
    print('Thread 2 end\r\n')

对程序注释说明:

  1. 可以用bytes来定义8位数据串
  2. struct.unpack('f', struct,pack('4b', *vx))将4字节的浮点数转换成python的浮点数。
  3. 如果在c语言中会使用sprintf(svy, "%.2f", vy); 但是用python就变得非常简单了,只使用一个是svy = %.2f" %vy就可以完成这个转换,方便。
  4. entry的delete的应用。使用(0, END)将entry的内容全部清除

总结

python的tkinter做简单的HMI方便,免费,非常实用。

相关推荐
金銀銅鐵10 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li12 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸17 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学18 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python