使用 Pyserial 发送文件? [英] Using Pyserial to send a file?

查看:80
本文介绍了使用 Pyserial 发送文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Raspberry Pi 通过两个无线电模块连接到我的 Macbook Pro.到目前为止,我已经成功地使用 pyserial 将字符串和命令从一个设备发送到另一个设备,但是,我找不到发送文本文件的方法.就像在超级终端上一样,您可以选择通过 xmodem 发送文本文件.我已经下载了 xmodem 库并玩了一下,我想我可以发送文件,但我不知道如何在另一端接收它们.有什么帮助吗?

I have a Raspberry Pi connected to my Macbook Pro by two radio modules. I have been successful so far in sending strings and commands from one device to the other using pyserial, however, I cannot find a way to send a text file. Like on HyperTerminal, where you can choose to send a text file over xmodem. I have downloaded the xmodem library and played with it a bit, and I think I am able to send files, but I have no idea how to receive them on the other end. Any help?

推荐答案

这个问题不是很清楚……您只需通过串行端口发送字节……客户端将字节保存到文件中.这是一个简单的实现.

this question is not very clear ... you just send the bytes over the serial port ... where a client saves the bytes to a file. here is a simple implementation.

from serial import Serial
ser = Serial("com4") #or whatever 
readline = lambda : iter(lambda:ser.read(1),"\n")
while "".join(readline()) != "<<SENDFILE>>": #wait for client to request file
    pass #do nothing ... just waiting ... we could time.sleep() if we didnt want to constantly loop
ser.write(open("some_file.txt","rb").read()) #send file
ser.write("\n<<EOF>>\n") #send message indicating file transmission complete

客户端代码

from serial import Serial
ser = Serial("com4") #or whatever 
ser.write("<<SENDFILE>>\n") #tell server we are ready to recieve
readline = lambda : iter(lambda:ser.read(1),"\n")
with open("somefile.txt","wb") as outfile:
   while True:
       line = "".join(readline())
       if line == "<<EOF>>":
           break #done so stop accumulating lines
       print >> outfile,line

这是一个应该有效的过于简化的例子,但它假设 100% 正确传输,这并不总是能够实现......更好的方案是逐行发送校验和以验证正确传输,但基本思想是一样的......校验和将是 OP 的一个练习

this is an overly simplified example that should work, but it assumes 100% correct transmission, this is not always achieved ... a better scheme is to send it line by line with checksums to verify correct transmission, but the underlying idea is the same... the checksum will be an exercsize for OP

这篇关于使用 Pyserial 发送文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆