
import serial
import os

serialport = serial.Serial(port='/dev/ttyACM0', baudrate=115200, timeout=0.1)

def establish_connection():

    serialport.write("\n".encode())
    

    serialport.write("echo off\n".encode())
    while len(serialport.readline())>0:
        continue
    

    serialport.write("test\n".encode())
    response = serialport.readline()
    hrresponse=response.rstrip().decode('ascii')
    if hrresponse != "OK":
        print("Unexpected test response:"+str(response))
        exit()

def get_filenames():

    filenames=[]

    serialport.write("ls\n".encode())
    while True:            
            response = serialport.readline()
            hrresponse=response.rstrip().decode('ascii')
            if(len(response))>0:
                #print(hrresponse)
                filenames.append(hrresponse)
                
            else:
                break

    return filenames


def copy_file(source,destination):
    os.makedirs(os.path.dirname(writefilename), exist_ok=True)
        
    with open(writefilename, 'wb') as writer:
        serialport.write(("cat "+filename+"\n").encode())
                    
        while True:
            
            response = serialport.readline()
            hrresponse=response.rstrip().decode('ascii')
            if(len(response))>0:
                #print(hrresponse)
                writer.write(response)
                
            else:
                break


def log_off():
    serialport.write(("log off\n").encode())
    response = serialport.readline()
    hrresponse=response.rstrip().decode('ascii')
    if (not hrresponse.startswith("Log disabled")):
        print("Unexpected response:"+str(response))
        exit()

def delete_file(filename):       
    
    
    serialport.write(("rm "+filename+"\n").encode())
    response = serialport.readline()
    hrresponse=response.rstrip().decode('ascii')
    if hrresponse != "OK":
        print("Unexpected response:"+str(response))
        exit()


if serialport.isOpen():
    
    establish_connection()
    


    #Get File List
    filenames=get_filenames()


    #Copy all Files    
    for filename in filenames:
        print("Reading file "+filename)
        writefilename='sdcard/'+filename
        copy_file(filename,writefilename)
    

    #Delete all files
    '''
    log_off()
    for filename in filenames:
        delete_file(filename)
    '''

    


serialport.write("echo on\n".encode())


    

serialport.close()