import RPi.GPIO as GPIO import serial import time from datetime import datetime import os import csv import requests 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): try: parts = gps_string.split(',') 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}" except (IndexError, ValueError) as e: print(f"Error parsing GPS data: {e}") return None, None def write_to_csv(lat, lon): timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open(csv_filename, mode='a', newline='') as file: writer = csv.writer(file) writer.writerow([timestamp, lat, lon]) def send_data_to_influxdb(lat, lon): url = "http://100.64.0.24:8086/write?db=telegraf" # Reemplaza con tu URL data = f"gps_data,host={myhost} latitude={lat},longitude={lon} {int(time.time() * 1e9)}" try: response = requests.post(url, data=data) response.raise_for_status() print(f"Data sent successfully to InfluxDB: {response.status_code}") except requests.RequestException as e: print(f"Error sending data to InfluxDB: {e}") pending_data.append((lat, lon)) def send_pending_data(): global pending_data for data in pending_data[:]: # Iterate over a copy of the list try: send_data_to_influxdb(data[0], data[1]) pending_data.remove(data) except Exception as e: print(f"Error sending data: {e}") break # Exit loop if sending fails def check_internet_connection(): try: requests.get('http://www.google.com', timeout=3) return True except requests.ConnectionError: return False def send_at(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) if check_internet_connection(): send_data_to_influxdb(lat, lon) else: pending_data.append((lat, lon)) return 1 return 0 def get_gps_position(): send_at('AT+CGPSINFO', '+CGPSINFO:', 1) if check_internet_connection(): send_pending_data() def initialize_gps(): print('Starting GPS') send_at('AT+CGPS=1,1', 'OK', 1) time.sleep(2) # Create CSV file with headers if it doesn't exist if not os.path.exists(csv_filename): with open(csv_filename, mode='w', newline='') as file: writer = csv.writer(file) writer.writerow(csv_headers) initialize_gps() print("Starting continuous GPS tracking. Press Ctrl+C to stop.") while running: get_gps_position() time.sleep(14) # Wait for 14 seconds before the next reading ser.close() GPIO.cleanup() print("GPS tracking stopped. Goodbye!")