使用Pyserial发送文件?

时间:2013-12-19 00:35:49

标签: python radio pyserial xmodem

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

1 个答案:

答案 0 :(得分:0)

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

服务器代码

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的练习