receiver.py 1.99 KB
import socket
import select
import os 

def removeAllFile(filePath):
    if os.path.exists(filePath):
        for file in os.scandir(filePath):
            os.remove(file.path)
        return 'Remove All File'
    else:
        return 'Directory Not Found'

print(removeAllFile('/home/pi/capdesign/frames'))

address = ('192.168.50.1', 8080)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(address)

sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
send_address = ('192.168.51.1', 8083)
buf = 1024
finish_msg = "FINISH"

while True:
    data, addr = sock.recvfrom(1024)
    if data:
        print("filename", data)
        file_name = data.strip()
    
    f = open('frames/{}'.format(file_name), 'wb')
    
    while True:
        ready = select.select([sock], [], [], 3)
        if ready[0]:
            data, addr = sock.recvfrom(1024)
            if(data == "FINISH".encode('utf-8')):
                print("Receivin {} FINISH".format(file_name))
                f.close()
                break
            else:
                f.write(data)
        
        # send to uav2 
        try:
            print(file_name)
            sock2.sendto(file_name.encode('utf-8'), send_address)
            print("file name sending success")
            f = open('frames/{}'.format(file_name), 'rb')
            data = f.read(1024)

            print(file_name, "Sending...")
            while(data):
                try:
                    sock2.sendto(data, send_address)
                except:
                    print("sock2 makes problem")
                
                try:
                    data = f.read(1024)
                except:
                    print("data read makes problem")
            print("data sending finished")
            if(sock2.sendto(finish_msg.encode('utf-8'), send_address)):
                print('Finish message send')
            print(file_name, "send finish")
            f.close()
        except:
            print("sending error")
    
sock.close()
sock2.close()