arduino-photometrics/exec/download_csv.py

88 lines
3 KiB
Python

import serial
import time
import os
ARDUINO_PORT = '/dev/ttyACM0'
BAUD_RATE = 9600
FILE_PREFIX = 'arduino_data_package'
OUTPUT_DIR = "../data"
LISTENING_TIME = 1000
START_PACKAGE_FLAG = "START_PACKAGE"
END_PACKAGE_FLAG = "END_PACKAGE"
CLOSE_TRANSFERT_FLAG = "END_TRANSFERT"
def download_data():
try:
ser = serial.Serial(ARDUINO_PORT, BAUD_RATE)
time.sleep(2)
except serial.SerialException as e:
print(f"Error : failure to open {ARDUINO_PORT}: {e}")
return
print(f"Connected to {ARDUINO_PORT}.")
dowload_cmd = 'D\n'
ser.write(dowload_cmd.encode())
print(f"-> Cmd sent: {dowload_cmd.strip()}")
print("-> Waiting for data...")
current_file_handle = None
start_download = time.time()
while True:
if LISTENING_TIME > 0 and time.time() - start_download > LISTENING_TIME:
print("\nElapsed time, session closed.")
break
if ser.in_waiting > 0:
raw_line = ser.readline()
str_line = raw_line.decode('utf-8').strip()
if str_line.startswith(START_PACKAGE_FLAG):
print("Get starting package word.")
if current_file_handle:
print(f"Unsignaled end file, closure of : {current_file_handle.name}")
current_file_handle.close()
try:
unique_part = str_line.split(':', 1)[1]
file_name = f"{FILE_PREFIX}_{unique_part}.csv"
except IndexError:
file_name = f"{FILE_PREFIX}_auto_{time.strftime('%Y%m%d_%H%M%S')}.csv"
print(f"\n*** New package detected, opening the new package : {file_name} ***")
os.makedirs(OUTPUT_DIR, exist_ok=True)
file_name = os.path.join(OUTPUT_DIR, file_name)
current_file_handle = open(file_name, 'w')
continue
elif str_line == END_PACKAGE_FLAG:
if current_file_handle:
print(f"-> Flag '{END_PACKAGE_FLAG}' detected. File closure : {current_file_handle.name}")
current_file_handle.close()
current_file_handle = None
else:
print(f"-> Flag '{END_PACKAGE_FLAG}' Ignored.")
continue
elif str_line == CLOSE_TRANSFERT_FLAG:
print(f"\n*** Flag '{CLOSE_TRANSFERT_FLAG}' detected. End of the download. ***")
break
if current_file_handle:
current_file_handle.write(str_line + '\n')
# else:
# print(f"Ignored data : {str_line}")
if current_file_handle:
print(f"\nClosure of the opened file : {current_file_handle.name}")
current_file_handle.close()
ser.close()
print("\nConnection closed. Download done.")
if __name__ == "__main__":
download_data()