File Transfer Pc To Raspberry Pi (with Xbee)
Solution 1:
You can't use readline()
with binary data such as images because it is meant for text. It basically looks for linefeed characters to delimit lines of text, but when you have images they are binary and may contain the linefeed character if a pixel happens to have the brightness value of 10 (over-simplified example).
Instead, we need to establish a way for the receiver to know how many bytes of data to expect and it can then just read that many bytes. There are many ways to do that, but I just show below how to send a 4-byte integer, in network order so that the receiver can simply read a fixed number of 4 bytes to get the length of the image, and then read the exact number of bytes that make up the image. I do it in network byte order in case one machine is big-endian and the other little-endian. This allows transmission of up to 2GB images which is enormous when compared to typical JPEG/PNG image sizes.
So, here is the sender:
#!/usr/bin/env python3import serial
import struct
# Open image and slurp entire contentswithopen('image.jpg', 'rb') as f:
image = f.read()
nbytes = len(image)
print(f'DEBUG: Image length={nbytes}')
# Open serial connectionwith serial.Serial('/dev/ttyS0', 9600) as s:
# Send 4-byte network order long with image size
s.write(struct.pack('!L', nbytes))
# Send image itself
s.write(image)
And here is the receiver:
#!/usr/bin/env python3import serial
import struct
# Open serial connectionwith serial.Serial('/dev/ttyS0', 9600) as s:
# Read 4-byte network order long with image sizeprint(f'DEBUG: Waiting for 4-byte header')
nbytes = struct.unpack('!L', s.read(4))[0]
print(f'DEBUG: Image length={nbytes}')
# Read image itself
image = s.read(nbytes)
# Open image and writewithopen('image.jpg', 'wb') as f:
f.write(image)
Keywords: Raspberry Pi, serial, pyserial, send image, receive image, framing protocol.
Post a Comment for "File Transfer Pc To Raspberry Pi (with Xbee)"