jdz/gps05.py

131 lines
3.5 KiB
Python
Raw Permalink Normal View History

2024-07-22 02:49:33 +00:00
#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import serial
import time, os
import csv
from datetime import datetime
myhost = os.uname()[1]
GPIO.setwarnings(False)
ser = serial.Serial('/dev/ttyS0',115200)
ser.flushInput()
rec_buff = ''
time_count = 0
# CSV file setup
csv_filename = f"gps_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
def convert_to_degrees(raw_value):
decimal_value = float(raw_value)
degrees = int(decimal_value / 100)
d = float(degrees)
m = (decimal_value - (d * 100)) / 60.0
return d + m
def write_to_csv(timestamp, lat, lon):
with open(csv_filename, 'a', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
csv_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(gps_data)
# Parse GPS data
gps_parts = gps_data.split(',')
if len(gps_parts) >= 4 and gps_parts[0] and gps_parts[2]:
lat = convert_to_degrees(gps_parts[0])
lon = convert_to_degrees(gps_parts[2])
if gps_parts[1] == 'S':
lat = -lat
if gps_parts[3] == 'W':
lon = -lon
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
write_to_csv(timestamp, lat, lon)
# Format for Google Maps
maps_url = f"https://www.google.com/maps?q={lat},{lon}"
print(f"Google Maps URL: {maps_url}")
else:
print("Invalid GPS data received")
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)
if 1 == answer:
answer = 0
if ',,,,,,' in rec_buff:
print('GPS no está listo')
rec_null = False
time.sleep(1)
else:
print('error %d'%answer)
rec_buff = ''
send_at('AT+CGPS=0','OK',1)
return False
time.sleep(1.5)
def power_on(power_key):
print('SIM7600X is starting:')
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(power_key,GPIO.OUT)
time.sleep(0.1)
GPIO.output(power_key,GPIO.HIGH)
time.sleep(2)
GPIO.output(power_key,GPIO.LOW)
time.sleep(20)
ser.flushInput()
print('SIM7600X is ready')
def power_down(power_key):
print('SIM7600X is loging off:')
GPIO.output(power_key,GPIO.HIGH)
time.sleep(3)
GPIO.output(power_key,GPIO.LOW)
time.sleep(18)
print('Good bye')
try:
# No need to create CSV file with header anymore
#power_on(power_key)
get_gps_position()
#power_down(power_key)
except:
if ser != None:
ser.close()
#power_down(power_key)
GPIO.cleanup()
if ser != None:
ser.close()
GPIO.cleanup()