2024-07-27 03:14:41 +00:00
|
|
|
#!/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
|
2024-07-27 04:53:29 +00:00
|
|
|
import logging
|
|
|
|
|
|
|
|
# Set up logging
|
|
|
|
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
|
2024-07-27 03:14:41 +00:00
|
|
|
|
|
|
|
# GPIO configuration
|
|
|
|
GPIO.setmode(GPIO.BCM)
|
|
|
|
GPIO.setwarnings(False)
|
|
|
|
|
2024-07-27 04:53:29 +00:00
|
|
|
try:
|
|
|
|
ser = serial.Serial('/dev/ttyUSB3', 115200)
|
|
|
|
ser.flushInput()
|
|
|
|
except serial.SerialException as e:
|
|
|
|
logging.error(f"Failed to open serial port: {e}")
|
|
|
|
exit(1)
|
2024-07-27 03:14:41 +00:00
|
|
|
|
|
|
|
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
|
2024-07-27 04:53:29 +00:00
|
|
|
INFLUXDB_BUCKET = "gpsdata"
|
2024-07-27 03:14:41 +00:00
|
|
|
|
|
|
|
# Initialize InfluxDB client
|
2024-07-27 04:53:29 +00:00
|
|
|
try:
|
|
|
|
client = InfluxDBClient(url=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG)
|
|
|
|
write_api = client.write_api(write_options=SYNCHRONOUS)
|
|
|
|
logging.info("Successfully connected to InfluxDB")
|
|
|
|
except Exception as e:
|
|
|
|
logging.error(f"Failed to connect to InfluxDB: {e}")
|
|
|
|
exit(1)
|
2024-07-27 03:14:41 +00:00
|
|
|
|
|
|
|
# Global flag for graceful exit
|
|
|
|
running = True
|
|
|
|
|
|
|
|
def signal_handler(sig, frame):
|
|
|
|
global running
|
2024-07-27 04:53:29 +00:00
|
|
|
logging.info('You pressed Ctrl+C! Stopping GPS tracking...')
|
2024-07-27 03:14:41 +00:00
|
|
|
running = False
|
|
|
|
|
|
|
|
signal.signal(signal.SIGINT, signal_handler)
|
|
|
|
|
|
|
|
def parse_gps_data(gps_string):
|
|
|
|
parts = gps_string.split(',')
|
|
|
|
if len(parts) < 4:
|
2024-07-27 04:53:29 +00:00
|
|
|
logging.warning(f"Incomplete GPS data: {gps_string}")
|
2024-07-27 03:14:41 +00:00
|
|
|
return None
|
|
|
|
|
2024-07-27 04:53:29 +00:00
|
|
|
try:
|
|
|
|
lat = parts[0]
|
|
|
|
lat_dir = parts[1]
|
|
|
|
lon = parts[2]
|
|
|
|
lon_dir = parts[3]
|
|
|
|
|
|
|
|
# Format latitude and longitude as strings
|
|
|
|
lat_str = f"{lat[:2]}°{lat[2:]}'{lat_dir}"
|
|
|
|
lon_str = f"{lon[:3]}°{lon[3:]}'{lon_dir}"
|
|
|
|
|
|
|
|
return lat_str, lon_str
|
|
|
|
except Exception as e:
|
|
|
|
logging.error(f"Error parsing GPS data: {e}")
|
|
|
|
return None
|
2024-07-27 03:14:41 +00:00
|
|
|
|
|
|
|
def write_to_influxdb(lat, lon):
|
2024-07-27 04:53:29 +00:00
|
|
|
timestamp = int(time.time() * 1000000000) # nanosecond precision
|
2024-07-27 03:14:41 +00:00
|
|
|
|
2024-07-27 04:53:29 +00:00
|
|
|
try:
|
|
|
|
gps_point = Point("gps_location") \
|
|
|
|
.tag("host", myhost) \
|
|
|
|
.field("latitude", lat) \
|
|
|
|
.field("longitude", lon) \
|
|
|
|
.time(timestamp)
|
|
|
|
|
|
|
|
write_api.write(bucket=INFLUXDB_BUCKET, record=gps_point)
|
|
|
|
logging.info(f"Data written to InfluxDB: Lat: {lat}, Lon: {lon}")
|
|
|
|
except Exception as e:
|
|
|
|
logging.error(f"Failed to write to InfluxDB: {e}")
|
2024-07-27 03:14:41 +00:00
|
|
|
|
|
|
|
def send_at(command, back, timeout):
|
2024-07-27 04:53:29 +00:00
|
|
|
try:
|
|
|
|
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]
|
|
|
|
logging.debug(f"Raw GPS data: {gps_data}")
|
|
|
|
parsed_data = parse_gps_data(gps_data)
|
|
|
|
if parsed_data:
|
|
|
|
lat, lon = parsed_data
|
|
|
|
logging.info(f"GPS: Lat: {lat}, Lon: {lon}")
|
|
|
|
write_to_influxdb(lat, lon)
|
|
|
|
return 1
|
|
|
|
else:
|
|
|
|
logging.warning(f"Expected response not found. Received: {rec_buff}")
|
|
|
|
else:
|
|
|
|
logging.warning("No data received from GPS module")
|
|
|
|
except Exception as e:
|
|
|
|
logging.error(f"Error communicating with GPS module: {e}")
|
2024-07-27 03:14:41 +00:00
|
|
|
return 0
|
|
|
|
|
|
|
|
def get_gps_position():
|
2024-07-27 04:53:29 +00:00
|
|
|
return send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
|
2024-07-27 03:14:41 +00:00
|
|
|
|
|
|
|
def initialize_gps():
|
2024-07-27 04:53:29 +00:00
|
|
|
logging.info('Starting GPS')
|
|
|
|
if send_at('AT+CGPS=1', 'OK', 1):
|
|
|
|
logging.info("GPS module initialized successfully")
|
|
|
|
else:
|
|
|
|
logging.error("Failed to initialize GPS module")
|
2024-07-27 03:14:41 +00:00
|
|
|
time.sleep(2)
|
|
|
|
|
|
|
|
initialize_gps()
|
2024-07-27 04:53:29 +00:00
|
|
|
logging.info("Starting continuous GPS tracking. Press Ctrl+C to stop.")
|
2024-07-27 03:14:41 +00:00
|
|
|
|
|
|
|
while running:
|
2024-07-27 04:53:29 +00:00
|
|
|
if not get_gps_position():
|
|
|
|
logging.warning("Failed to get GPS position")
|
2024-07-27 03:14:41 +00:00
|
|
|
time.sleep(14) # Wait for 14 seconds before the next reading
|
|
|
|
|
|
|
|
ser.close()
|
|
|
|
GPIO.cleanup()
|
|
|
|
client.close()
|
2024-07-27 04:53:29 +00:00
|
|
|
logging.info("GPS tracking stopped. Goodbye!")
|