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方便,免费,非常实用。

相关推荐
nice_lcj5202 小时前
【从零理解计算机网络 · 02】分层模型:别背 OSI 七层,看数据怎么被“打包“和“拆包“
java·后端·tcp/ip·计算机网络·面试·osi·分层模型
通信王663 小时前
NBIOT NTN协议整理-TS36.211
网络
kyle~4 小时前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享4 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
光电笑映5 小时前
TCP 为什么可靠?从三次握手、滑动窗口到拥塞控制全面拆解(上)
运维·服务器·网络·udp
梯度下降者5 小时前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信
Vni5 小时前
华三双核心交换机IRF堆叠
网络·交换机·堆叠·华三
MSTcheng.5 小时前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
the局外人6 小时前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
__underline__6 小时前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python