jdz/GPS2.py

75 lines
2.2 KiB
Python
Raw Normal View History

2024-07-12 01:13:29 +00:00
#!/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 ',,,,,,' not in rec_buff:
# Extract GPS information from rec_buff and store it in the database
gps_info = extract_gps_info(rec_buff) # Implement this function based on the format of rec_buff
store_gps_coordinates(gps_info)
return True
else:
print('GPS is not ready')
time.sleep(1)
else:
print('error %d' % answer)
rec_buff = ''
send_at('AT+CGPS=0','OK',1)
return False
time.sleep(1.5)
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()