55 lines
1.6 KiB
Python
55 lines
1.6 KiB
Python
from flask import Flask, jsonify
|
|
import gps
|
|
import threading
|
|
import time
|
|
|
|
app = Flask(__name__)
|
|
|
|
# GPS data container
|
|
current_gps_data = {
|
|
"latitude": None,
|
|
"longitude": None,
|
|
"altitude": None,
|
|
"speed": None,
|
|
"timestamp": None
|
|
}
|
|
|
|
# Global gps session object
|
|
session = gps.gps(mode=gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
|
|
|
|
def gps_monitor():
|
|
global current_gps_data
|
|
while True:
|
|
try:
|
|
# Wait for new data from the GPS device
|
|
report = session.next()
|
|
if report['class'] == 'TPV':
|
|
current_gps_data = {
|
|
"latitude": report.get('lat', None),
|
|
"longitude": report.get('lon', None),
|
|
"altitude": report.get('alt', None),
|
|
"speed": report.get('speed', None),
|
|
"timestamp": report.get('time', None)
|
|
}
|
|
except gps.GPSException as e:
|
|
print(f"GPS Error: {e}")
|
|
except KeyError as e:
|
|
print(f"Missing Key: {e}")
|
|
time.sleep(1)
|
|
|
|
@app.route('/gps', methods=['GET'])
|
|
def get_gps_data():
|
|
"""API endpoint to fetch current GPS data"""
|
|
if None in current_gps_data.values():
|
|
return jsonify({"error": "No GPS data available yet"}), 404
|
|
return jsonify(current_gps_data)
|
|
|
|
if __name__ == '__main__':
|
|
# Start GPS monitoring in a separate thread
|
|
gps_thread = threading.Thread(target=gps_monitor)
|
|
gps_thread.daemon = True # This makes the thread exit when the program does
|
|
gps_thread.start()
|
|
|
|
# Run the Flask web service
|
|
app.run(host='0.0.0.0', port=5000)
|