Using Pyserial to send a file?

11.7k views Asked by At

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

There are 1 answers

2
Joran Beasley On BEST ANSWER

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