104 lines
2.7 KiB
Python
104 lines
2.7 KiB
Python
|
#!/usr/bin/python
|
||
|
# -*- coding:utf-8 -*-
|
||
|
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)
|
||
|
|
||
|
ser = serial.Serial('/dev/ttyUSB3', 115200)
|
||
|
ser.flushInput()
|
||
|
|
||
|
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
|
||
|
|
||
|
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 or not parts[0] or not parts[2]:
|
||
|
return None
|
||
|
|
||
|
try:
|
||
|
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 ValueError:
|
||
|
return 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_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)
|
||
|
return 1
|
||
|
else:
|
||
|
print("Invalid GPS data received")
|
||
|
else:
|
||
|
print("Unexpected response from GPS module")
|
||
|
else:
|
||
|
print("No data received from GPS module")
|
||
|
return 0
|
||
|
|
||
|
def get_gps_position():
|
||
|
send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
|
||
|
|
||
|
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(2) # Wait for 10 seconds before the next reading
|
||
|
|
||
|
ser.close()
|
||
|
GPIO.cleanup()
|
||
|
print("GPS tracking stopped. Goodbye!")
|