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', 9600) 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): parts = gps_string.split(',') if len(parts) < 4: return None lat = float(parts[0][:2]) + float(parts[0][2:]) / 60 if parts[1] == 'S': lat = -lat lon = float(parts[2][:3]) + float(parts[2][3:]) / 60 if parts[3] == 'W': lon = -lon return f"{lat:.6f}", f"{lon:.6f}" 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(command, back, timeout): ser.write((command + '\r\n').encode()) time.sleep(timeout) if ser.inWaiting(): time.sleep(0.01) rec_buff = ser.read(ser.inWaiting()).decode() if back in rec_buff: gps_data = rec_buff.split('+CGPSINFO: ')[1].split('\r\n')[0] parsed_data = parse_gps_data(gps_data) if parsed_data: lat, lon = parsed_data print(f"GPS: Lat: {lat}, Lon: {lon}") write_to_csv(lat, lon) return 1 return 0 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()