Using Pyserial to send a file?

大憨熊 提交于 2019-12-08 01:56:47

问题


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?


回答1:


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.

server code

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

client code

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

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



来源:https://stackoverflow.com/questions/20671412/using-pyserial-to-send-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!