99 lines
2.6 KiB
Python
99 lines
2.6 KiB
Python
#!/usr/bin/python
|
|
# -*- coding:utf-8 -*-
|
|
import RPi.GPIO as GPIO
|
|
import serial
|
|
import time
|
|
from datetime import datetime
|
|
import os
|
|
import signal
|
|
from influxdb_client import InfluxDBClient, Point
|
|
from influxdb_client.client.write_api import SYNCHRONOUS
|
|
|
|
# GPIO configuration
|
|
GPIO.setmode(GPIO.BCM)
|
|
GPIO.setwarnings(False)
|
|
|
|
ser = serial.Serial('/dev/ttyUSB3', 115200)
|
|
ser.flushInput()
|
|
|
|
myhost = os.uname()[1]
|
|
|
|
# InfluxDB settings
|
|
INFLUXDB_URL = "http://100.64.0.24:8086"
|
|
INFLUXDB_TOKEN = "IPtqPXbaXuuMHvx_tUOt1cmIZfLHucd-9DcepXTVpQc-fNKBhp6pkhyTsq_XnoGXdxwILy5AFFgZ_QUZCE5Jhg=="
|
|
INFLUXDB_ORG = "juandiego" # Replace with your organization name
|
|
INFLUXDB_BUCKET = "gpsdata"
|
|
|
|
# Initialize InfluxDB client
|
|
client = InfluxDBClient(url=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG)
|
|
write_api = client.write_api(write_options=SYNCHRONOUS)
|
|
|
|
# Global flag for graceful exit
|
|
running = True
|
|
|
|
def signal_handler(sig, frame):
|
|
global running
|
|
print('You pressed Ctrl+C! Stopping GPS tracking...')
|
|
running = False
|
|
|
|
signal.signal(signal.SIGINT, signal_handler)
|
|
|
|
def parse_gps_data(gps_string):
|
|
parts = gps_string.split(',')
|
|
if len(parts) < 4:
|
|
return None
|
|
|
|
lat = float(parts[0][:2]) + float(parts[0][2:]) / 60
|
|
if parts[1] == 'S':
|
|
lat = -lat
|
|
|
|
lon = float(parts[2][:3]) + float(parts[2][3:]) / 60
|
|
if parts[3] == 'W':
|
|
lon = -lon
|
|
|
|
return lat, lon
|
|
|
|
def write_to_influxdb(lat, lon):
|
|
point = Point("gps_location") \
|
|
.tag("host", myhost) \
|
|
.field("latitude", round(lat, 6)) \
|
|
.field("longitude", round(lon, 6))
|
|
|
|
write_api.write(bucket=INFLUXDB_BUCKET, record=point)
|
|
|
|
def send_at(command, back, timeout):
|
|
ser.write((command + '\r\n').encode())
|
|
time.sleep(timeout)
|
|
if ser.inWaiting():
|
|
time.sleep(0.01)
|
|
rec_buff = ser.read(ser.inWaiting()).decode()
|
|
if back in rec_buff:
|
|
gps_data = rec_buff.split('+CGPSINFO: ')[1].split('\r\n')[0]
|
|
parsed_data = parse_gps_data(gps_data)
|
|
if parsed_data:
|
|
lat, lon = parsed_data
|
|
print(f"GPS: Lat: {lat:.6f}, Lon: {lon:.6f}")
|
|
write_to_influxdb(lat, lon)
|
|
return 1
|
|
return 0
|
|
|
|
def get_gps_position():
|
|
send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
|
|
|
|
def initialize_gps():
|
|
print('Starting GPS')
|
|
send_at('AT+CGPS=1', 'OK', 1)
|
|
time.sleep(2)
|
|
|
|
initialize_gps()
|
|
print("Starting continuous GPS tracking. Press Ctrl+C to stop.")
|
|
|
|
while running:
|
|
get_gps_position()
|
|
time.sleep(3) # Wait for 14 seconds before the next reading
|
|
|
|
ser.close()
|
|
GPIO.cleanup()
|
|
client.close()
|
|
print("GPS tracking stopped. Goodbye!")
|