import RPi.GPIO as GPIO import serial import time from datetime import datetime import os import csv import signal # GPIO configuration GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Initialize serial port try: ser = serial.Serial('/dev/ttyUSB3', 115200) ser.flushInput() except serial.SerialException as e: print(f"Error initializing serial port: {e}") exit(1) myhost = os.uname()[1] # CSV file settings csv_filename = f"gps_data_{myhost}.csv" csv_headers = ["Timestamp", "Latitude", "Longitude"] # Global flag for graceful exit running = True # List to store pending data pending_data = [] def signal_handler(sig, frame): global running print('You pressed Ctrl+C! Stopping GPS tracking...') running = False signal.signal(signal.SIGINT, signal_handler) def parse_gps_data(gps_string): # Implement GPS data parsing logic here pass def write_to_csv(data): file_exists = os.path.isfile(csv_filename) with open(csv_filename, mode='a', newline='') as file: writer = csv.writer(file) if not file_exists: writer.writerow(csv_headers) writer.writerow(data) def send_data(data): # Implement data sending logic here pass def main(): while running: try: if ser.in_waiting > 0: gps_data = ser.readline().decode('utf-8').strip() parsed_data = parse_gps_data(gps_data) if parsed_data: timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') latitude, longitude = parsed_data data = [timestamp, latitude, longitude] write_to_csv(data) pending_data.append(data) print(f"Logged data: {timestamp}, {latitude}, {longitude}") # Try to send pending data for data in pending_data: try: send_data(data) pending_data.remove(data) except Exception as e: print(f"Error sending data: {e}") break # Exit loop if sending fails time.sleep(1) except Exception as e: print(f"Error during GPS tracking: {e}") ser.close() GPIO.cleanup() print("Program terminated gracefully") if __name__ == "__main__": main()