Pyserial文件传输
本想随便找个demo用一下,竟没有搜到文件传输的代码,于是乎写了一个,希望对读者有帮助。简单的数据传输百度可以搜到很多,这里不做累坠了。
client
import serial #pip install pyserial
import struct
import os
#端口,根据自己的端口修改
portx="/dev/ttyUSB0"
#波特率
bps=115200
timex=5
# 打开串口
ser=serial.Serial(portx,bps,timeout=timex)
filepath = "to_uav_end.pt"
if os.path.isfile(filepath):
# 定义文件信息。128s表示文件名为128bytes长,l表示一个int或log文件类型,在此为文件大小
fileinfo_size = struct.calcsize('128sl')
# 定义文件头信息,包含文件名和文件大小
fhead = struct.pack('128sl', os.path.basename(filepath).encode('utf-8'), os.stat(filepath).st_size)
# 发送文件名称与文件大小
ser.write(fhead)
fp = open(filepath, 'rb')
while 1:
data = fp.read(1024)
if not data:
print('{0} file send over...'.format(os.path.basename(filepath)))
break
ser.write(data)
# 关闭ser对象
ser.close()
fp.close()
server
import serial
import struct
import os
#端口自行修改
portx="/dev/ttyUSB2"
#波特率
bps=115200
timex=5
# 打开串口
ser=serial.Serial(portx,bps,timeout=timex)
while 1:
# 申请相同大小的空间存放发送过来的文件名与文件大小信息
fileinfo_size = struct.calcsize('128sl')
# 接收文件名与文件大小信息
buf = ser.read(fileinfo_size)
if buf:
# 获取文件名和文件大小
filename, filesize = struct.unpack('128sl', buf)
fn = filename.strip(b'\00')
fn = fn.decode()
print('file new name is {0}, filesize if {1}'.format(str(fn), filesize))
recvd_size = 0 # 定义已接收文件的大小
# 存储在该脚本所在目录下面
fp = open('./' + "new_uav.pt", 'wb')
print('start receiving...')
# 将分批次传输的二进制流依次写入到文件
while not recvd_size == filesize:
if filesize - recvd_size > 1024:
data = ser.read(1024)
recvd_size += len(data)
else:
data = ser.read(filesize - recvd_size)
recvd_size = filesize
fp.write(data)
fp.close()
print('end receive...')
ser.close()
break