当前位置: 首页 > news >正文

通过python读取并发送二进制文件到串口

代码

#!python.exe
"""
@filename       send_bin.py
@brief          According to the user's input, read bin file, subpackage and send the file by UART.
@HowToUse       send_bin.py -h
@author         shadowThreeD@gmail.com
@data           20220224
"""
from asyncio.windows_events import NULL
from importlib.metadata import files
from socket import timeout
import sys
import os
from time import sleep
import serial
import crcmodglobal fileName;
global fileSize;
global pkgSize;
global needAck;
global pkgInterval;def main(argv):global fileName;        # 将需要使用的 global 变量引入,不然默认使用局部变量,即使变量名相同global fileSize;global pkgSize;global needAck;global pkgInterval;checkParams(argv);crc32_func = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0, xorOut=0x0000)try:pFile = open(fileName, "rb");#tempFile = open("temp.bin", "wb");except:print('bin file read error...');port = 'COM3';baudRate = 115200;try:com = serial.Serial(port, baudRate, timeout=2);     # 设置超时时间为 5sexcept:print(port + ' open failed...');sys.exit();else:print(port + ' open succ, baudrate is ' + str(baudRate));# 发送字符串#subFile = "ABCD\r\n".encode();      # 将 str 编码成 Bytes#com.write(subFile);#print(com.read_until(b'\r\n').decode());    # 将 Bytes 解码成 str# 发送二进制indexFile = 0;isEnd = 0;curPkgSize = pkgSize-4;MAC_addr = bytes([0x5a, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);      # start and MACwhile isEnd == 0 :if indexFile != 0:subFile = pFile.read(pkgSize-4);curPkgSize = len(subFile);if curPkgSize != pkgSize-4 :isEnd = 1;print('curPkgSize: ' + str(curPkgSize));curSend = MAC_addr;         # start + MACif indexFile == 0:CRC_part = int(14).to_bytes(4, 'little');       # RS485 Lengthelse:CRC_part = (curPkgSize+10).to_bytes(4, 'little');       #CRC_part += int(5).to_bytes(1, 'little');               # Msg type:CRC_part += int(4).to_bytes(1, 'little');               # Sensor type: NTCCRC_part += indexFile.to_bytes(2, 'little');            # pkg IDif indexFile == 0:CRC_part += (4<<2 | needAck<<1 | isEnd).to_bytes(2, 'little');      # 4 is sizeof(uint32_t) for fileSize lengthCRC_part += fileSize.to_bytes(4, 'little');else:CRC_part += (curPkgSize<<2 | needAck<<1 | isEnd).to_bytes(2, 'little');CRC_part += subFile;curSend += CRC_part;     curSend += crc32_func(CRC_part).to_bytes(2, 'big');print(curSend.hex());com.write(curSend);curRecv = com.read_until(b'\r\n');#if curRecv is not NULL:if len(curRecv) == 20 and curRecv[17] == 0:print(curRecv.decode());indexFile += 1;else:print(len(curRecv));#tempFile.write(curSend);pFile.close();#tempFile.close();return;def checkParams(argv):global fileName;global fileSize;global pkgSize;global needAck;global pkgInterval;try:fileName = argv[1];if fileName == '-h':showHelp();raise SystemExit;         # 导致程序触发 SystemExit 异常。这里也可以用 sys.exit();pkgSize = int(argv[2]);if argv[3] != '1':needAck = 0;pkgInterval = int(argv[4]);else:needAck = 1;except SystemExit:sys.exit();except:print('Params error...');showHelp();sys.exit();else:fileSize = os.path.getsize(fileName);print('fileName:    ' + fileName);print('fileSize:    ' + str(fileSize));print('pkgSize:     ' + str(pkgSize));print('needAck:     ' + str(needAck));if needAck == 'false':print('pkgInterval: ' + str(pkgInterval));return;def showHelp():print("""Usage:1. send_bin.py test.bin 1500 12. send_bin.py test.bin 1500 0 1000- test.bin:     the file name of bin file.- 1500:         is the package size, unit in Bytes.- 0:            whether need ack after send eack package; 1 meaning need, 0 meaning NO need.- 1000:         if last param is true, this is ignored; otherwise meaning the interval of two package, unit in ms.""");return;if __name__ == "__main__":main(sys.argv);
http://www.lryc.cn/news/351149.html

相关文章:

  • 前端笔记-day07
  • 【MySQL精通之路】INFORMATION_SCHEMA库-INNODB_METRICS表
  • React Native 之 定义全局状态管理库(九)
  • java线程池实战应用总结
  • 部署 harbor 创建私有项目
  • 在Linux系统中解决Java生成海报文字乱码和缺少字体文件的问题
  • 升级版网创教程wordpress插件自动采集并发布
  • MySQL 视图(1)
  • 在排序数组中查找元素的一个位置和最后一个位置-力扣
  • 系统分析师-案例分析-数据库
  • 【RabbitMQ】使用SpringAMQP的消息队列(Hello Word)和工作队列(Work Queue)
  • 项目集成SkyWalking,基于k8s搭建
  • mysql-差异备份流程
  • 基于动态规划算法的DNA序列比对函数,给出两条序列(v和w)的打分矩阵
  • Tailwind CSS快速入门
  • Postman使用技巧
  • sqli-labs靶场
  • 基于springboot的大创管理系统
  • 常用torch.nn
  • 力扣226.翻转二叉树101.对称二叉树
  • word如何按照原本页面审阅文档
  • 前端基础入门三大核心之HTML篇:探索WebAssembly —— 开启网页高性能应用新时代
  • NDIS小端口驱动(四)
  • 用户态网络缓冲区设计
  • Linux运维工程师基础面试题整理(三)
  • 基于单片机与传感器技术的汽车起动线路设计
  • C#如何通过反射获取外部dll的函数
  • 从零开始傅里叶变换
  • 解决1万条数据前端渲染不卡的问题
  • 如何编写一个API——Python代码示例及拓展