jdz/GPS2.py
2024-07-12 01:25:33 +00:00

90 lines
2.6 KiB
Python

#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import sqlite3
import serial
import time, os
# SQLite Database settings
db_file = "gps_coordinates.db"
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
ser = serial.Serial('/dev/ttyS0',115200)
ser.flushInput()
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:
print(rec_buff.decode())
return 1
else:
print('GPS is not ready')
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:
# Extract GPS coordinates from the response
gps_data = rec_buff.split(',')
latitude = gps_data[2]
longitude = gps_data[3]
# Connect to the SQLite database
conn = sqlite3.connect('gps_coordinates.db')
c = conn.cursor()
# Insert the GPS coordinates into the database
c.execute("INSERT INTO gps_coordinates (latitude, longitude) VALUES (?, ?)", (latitude, longitude))
# Commit and close the connection
conn.commit()
conn.close()
else:
print('error %d'%answer)
rec_buff = ''
send_at('AT+CGPS=0','OK',1)
return False
time.sleep(1.5)
return True
def extract_gps_info(rec_buff):
# Implement this function based on the format of rec_buff
# Example: gps_info = rec_buff.split(',')[2]
return gps_info
def store_gps_coordinates(gps_info):
cursor.execute("INSERT INTO coordinates (latitude, longitude) VALUES (?, ?)", gps_info)
conn.commit()
# Main program
if __name__ == '__main__':
# Create the SQLite table if it doesn't exist
cursor.execute('''CREATE TABLE IF NOT EXISTS coordinates (id INTEGER PRIMARY KEY AUTOINCREMENT, latitude REAL, longitude REAL)''')
while True:
get_gps_position()