119 lines
3.0 KiB
Python
Executable File
119 lines
3.0 KiB
Python
Executable File
#!/usr/bin/python
|
|
# -*- coding:utf-8 -*-
|
|
import RPi.GPIO as GPIO
|
|
import serial
|
|
import time
|
|
import os
|
|
import csv
|
|
from datetime import datetime
|
|
|
|
|
|
# GPIO configuration
|
|
GPIO.setmode(GPIO.BCM)
|
|
GPIO.setwarnings(False)
|
|
|
|
ser = serial.Serial('/dev/ttyS0', 115200)
|
|
ser.flushInput()
|
|
|
|
rec_buff = ''
|
|
time_count = 0
|
|
|
|
myhost = os.uname()[1]
|
|
|
|
# CSV file settings
|
|
csv_filename = f"gps_data_{myhost}.csv"
|
|
csv_headers = ["Timestamp", "Latitude", "Longitude"]
|
|
|
|
def convert_to_decimal(coord_str):
|
|
coord = coord_str[:-2]
|
|
direction = coord_str[-1]
|
|
|
|
degrees = float(coord[:2] if direction in ['N', 'S'] else coord[:3])
|
|
minutes = float(coord[2:] if direction in ['N', 'S'] else coord[3:])
|
|
|
|
decimal = degrees + (minutes / 60)
|
|
|
|
if direction in ['S', 'W']:
|
|
decimal = -decimal
|
|
|
|
return decimal
|
|
|
|
def parse_gps_data(gps_string):
|
|
parts = gps_string.split(',')
|
|
if len(parts) != 4:
|
|
return "Invalid GPS data"
|
|
|
|
lat = convert_to_decimal(parts[0] + ',' + parts[1])
|
|
lon = convert_to_decimal(parts[2] + ',' + parts[3])
|
|
|
|
return f"{lat:.6f}", f"{lon:.6f}"
|
|
|
|
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):
|
|
rec_buff = ''
|
|
ser.write((command + '\r\n').encode())
|
|
time.sleep(timeout)
|
|
if ser.inWaiting():
|
|
time.sleep(0.01)
|
|
rec_buff = ser.read(ser.inWaiting())
|
|
if rec_buff:
|
|
if back not in rec_buff.decode():
|
|
print(command + ' ERROR')
|
|
print(command + ' back:\t' + rec_buff.decode())
|
|
return 0
|
|
else:
|
|
gps_data = rec_buff.decode()[13:-36]
|
|
print("Raw GPS data:", gps_data)
|
|
lat, lon = parse_gps_data(gps_data)
|
|
converted_gps = f"{lat}, {lon}"
|
|
print("Converted GPS data for Google Maps:", converted_gps)
|
|
current_time = datetime.now()
|
|
write_to_csv(lat, lon)
|
|
return 1
|
|
else:
|
|
print('GPS no está listo')
|
|
return 0
|
|
|
|
def get_gps_position():
|
|
rec_null = True
|
|
answer = 0
|
|
print('Iniciando GPS')
|
|
rec_buff = ''
|
|
send_at('AT+CGPS=1,1', 'OK', 1)
|
|
time.sleep(2)
|
|
while rec_null:
|
|
answer = send_at('AT+CGPSINFO', '+CGPSINFO: ', 1)
|
|
# Handle MQTT publishing here if needed
|
|
if answer == 1:
|
|
if ',,,,,,' in rec_buff:
|
|
print('GPS no está listo')
|
|
rec_null = False
|
|
time.sleep(1)
|
|
else:
|
|
print(f'Error {answer}')
|
|
rec_buff = ''
|
|
send_at('AT+CGPS=0', 'OK', 1)
|
|
return False
|
|
time.sleep(1.5)
|
|
|
|
# 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)
|
|
|
|
try:
|
|
get_gps_position()
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
finally:
|
|
if ser:
|
|
ser.close()
|
|
GPIO.cleanup()
|