2024-07-26 -
This commit is contained in:
parent
fa6fa1390b
commit
09b54f1159
@ -6531,3 +6531,5 @@ Timestamp,Latitude,Longitude
|
|||||||
2024-07-26 22:16:37,9.939904,-84.104898
|
2024-07-26 22:16:37,9.939904,-84.104898
|
||||||
2024-07-26 22:16:52,9.939904,-84.104898
|
2024-07-26 22:16:52,9.939904,-84.104898
|
||||||
2024-07-26 22:17:07,9.939904,-84.104897
|
2024-07-26 22:17:07,9.939904,-84.104897
|
||||||
|
2024-07-26 22:29:54,9.939918,-84.104902
|
||||||
|
2024-07-26 22:30:09,9.939918,-84.104902
|
||||||
|
|
80
gpsinflux.py
80
gpsinflux.py
@ -8,13 +8,21 @@ import os
|
|||||||
import signal
|
import signal
|
||||||
from influxdb_client import InfluxDBClient, Point
|
from influxdb_client import InfluxDBClient, Point
|
||||||
from influxdb_client.client.write_api import SYNCHRONOUS
|
from influxdb_client.client.write_api import SYNCHRONOUS
|
||||||
|
import logging
|
||||||
|
|
||||||
|
# Set up logging
|
||||||
|
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||||
|
|
||||||
# GPIO configuration
|
# GPIO configuration
|
||||||
GPIO.setmode(GPIO.BCM)
|
GPIO.setmode(GPIO.BCM)
|
||||||
GPIO.setwarnings(False)
|
GPIO.setwarnings(False)
|
||||||
|
|
||||||
|
try:
|
||||||
ser = serial.Serial('/dev/ttyUSB3', 115200)
|
ser = serial.Serial('/dev/ttyUSB3', 115200)
|
||||||
ser.flushInput()
|
ser.flushInput()
|
||||||
|
except serial.SerialException as e:
|
||||||
|
logging.error(f"Failed to open serial port: {e}")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
myhost = os.uname()[1]
|
myhost = os.uname()[1]
|
||||||
|
|
||||||
@ -22,18 +30,23 @@ myhost = os.uname()[1]
|
|||||||
INFLUXDB_URL = "http://100.64.0.24:8086"
|
INFLUXDB_URL = "http://100.64.0.24:8086"
|
||||||
INFLUXDB_TOKEN = "IPtqPXbaXuuMHvx_tUOt1cmIZfLHucd-9DcepXTVpQc-fNKBhp6pkhyTsq_XnoGXdxwILy5AFFgZ_QUZCE5Jhg=="
|
INFLUXDB_TOKEN = "IPtqPXbaXuuMHvx_tUOt1cmIZfLHucd-9DcepXTVpQc-fNKBhp6pkhyTsq_XnoGXdxwILy5AFFgZ_QUZCE5Jhg=="
|
||||||
INFLUXDB_ORG = "juandiego" # Replace with your organization name
|
INFLUXDB_ORG = "juandiego" # Replace with your organization name
|
||||||
INFLUXDB_BUCKET = "gps_data"
|
INFLUXDB_BUCKET = "gpsdata"
|
||||||
|
|
||||||
# Initialize InfluxDB client
|
# Initialize InfluxDB client
|
||||||
|
try:
|
||||||
client = InfluxDBClient(url=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG)
|
client = InfluxDBClient(url=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG)
|
||||||
write_api = client.write_api(write_options=SYNCHRONOUS)
|
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)
|
||||||
|
|
||||||
# Global flag for graceful exit
|
# Global flag for graceful exit
|
||||||
running = True
|
running = True
|
||||||
|
|
||||||
def signal_handler(sig, frame):
|
def signal_handler(sig, frame):
|
||||||
global running
|
global running
|
||||||
print('You pressed Ctrl+C! Stopping GPS tracking...')
|
logging.info('You pressed Ctrl+C! Stopping GPS tracking...')
|
||||||
running = False
|
running = False
|
||||||
|
|
||||||
signal.signal(signal.SIGINT, signal_handler)
|
signal.signal(signal.SIGINT, signal_handler)
|
||||||
@ -41,27 +54,41 @@ signal.signal(signal.SIGINT, signal_handler)
|
|||||||
def parse_gps_data(gps_string):
|
def parse_gps_data(gps_string):
|
||||||
parts = gps_string.split(',')
|
parts = gps_string.split(',')
|
||||||
if len(parts) < 4:
|
if len(parts) < 4:
|
||||||
|
logging.warning(f"Incomplete GPS data: {gps_string}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
lat = float(parts[0][:2]) + float(parts[0][2:]) / 60
|
try:
|
||||||
if parts[1] == 'S':
|
lat = parts[0]
|
||||||
lat = -lat
|
lat_dir = parts[1]
|
||||||
|
lon = parts[2]
|
||||||
|
lon_dir = parts[3]
|
||||||
|
|
||||||
lon = float(parts[2][:3]) + float(parts[2][3:]) / 60
|
# Format latitude and longitude as strings
|
||||||
if parts[3] == 'W':
|
lat_str = f"{lat[:2]}°{lat[2:]}'{lat_dir}"
|
||||||
lon = -lon
|
lon_str = f"{lon[:3]}°{lon[3:]}'{lon_dir}"
|
||||||
|
|
||||||
return f"{lat:.6f}", f"{lon:.6f}"
|
return lat_str, lon_str
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Error parsing GPS data: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
def write_to_influxdb(lat, lon):
|
def write_to_influxdb(lat, lon):
|
||||||
point = Point("gps_location") \
|
timestamp = int(time.time() * 1000000000) # nanosecond precision
|
||||||
.tag("host", myhost) \
|
|
||||||
.field("latitude", float(lat)) \
|
|
||||||
.field("longitude", float(lon))
|
|
||||||
|
|
||||||
write_api.write(bucket=INFLUXDB_BUCKET, record=point)
|
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}")
|
||||||
|
|
||||||
def send_at(command, back, timeout):
|
def send_at(command, back, timeout):
|
||||||
|
try:
|
||||||
ser.write((command + '\r\n').encode())
|
ser.write((command + '\r\n').encode())
|
||||||
time.sleep(timeout)
|
time.sleep(timeout)
|
||||||
if ser.inWaiting():
|
if ser.inWaiting():
|
||||||
@ -69,30 +96,41 @@ def send_at(command, back, timeout):
|
|||||||
rec_buff = ser.read(ser.inWaiting()).decode()
|
rec_buff = ser.read(ser.inWaiting()).decode()
|
||||||
if back in rec_buff:
|
if back in rec_buff:
|
||||||
gps_data = rec_buff.split('+CGPSINFO: ')[1].split('\r\n')[0]
|
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)
|
parsed_data = parse_gps_data(gps_data)
|
||||||
if parsed_data:
|
if parsed_data:
|
||||||
lat, lon = parsed_data
|
lat, lon = parsed_data
|
||||||
print(f"GPS: Lat: {lat}, Lon: {lon}")
|
logging.info(f"GPS: Lat: {lat}, Lon: {lon}")
|
||||||
write_to_influxdb(lat, lon)
|
write_to_influxdb(lat, lon)
|
||||||
return 1
|
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}")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
def get_gps_position():
|
def get_gps_position():
|
||||||
send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
|
return send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
|
||||||
|
|
||||||
def initialize_gps():
|
def initialize_gps():
|
||||||
print('Starting GPS')
|
logging.info('Starting GPS')
|
||||||
send_at('AT+CGPS=1', 'OK', 1)
|
if send_at('AT+CGPS=1', 'OK', 1):
|
||||||
|
logging.info("GPS module initialized successfully")
|
||||||
|
else:
|
||||||
|
logging.error("Failed to initialize GPS module")
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
|
|
||||||
initialize_gps()
|
initialize_gps()
|
||||||
print("Starting continuous GPS tracking. Press Ctrl+C to stop.")
|
logging.info("Starting continuous GPS tracking. Press Ctrl+C to stop.")
|
||||||
|
|
||||||
while running:
|
while running:
|
||||||
get_gps_position()
|
if not get_gps_position():
|
||||||
|
logging.warning("Failed to get GPS position")
|
||||||
time.sleep(14) # Wait for 14 seconds before the next reading
|
time.sleep(14) # Wait for 14 seconds before the next reading
|
||||||
|
|
||||||
ser.close()
|
ser.close()
|
||||||
GPIO.cleanup()
|
GPIO.cleanup()
|
||||||
client.close()
|
client.close()
|
||||||
print("GPS tracking stopped. Goodbye!")
|
logging.info("GPS tracking stopped. Goodbye!")
|
||||||
|
136
gpsinflux01.py
Normal file
136
gpsinflux01.py
Normal file
@ -0,0 +1,136 @@
|
|||||||
|
#!/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
|
||||||
|
import logging
|
||||||
|
|
||||||
|
# Set up logging
|
||||||
|
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||||
|
|
||||||
|
# GPIO configuration
|
||||||
|
GPIO.setmode(GPIO.BCM)
|
||||||
|
GPIO.setwarnings(False)
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
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
|
||||||
|
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)
|
||||||
|
|
||||||
|
# Global flag for graceful exit
|
||||||
|
running = True
|
||||||
|
|
||||||
|
def signal_handler(sig, frame):
|
||||||
|
global running
|
||||||
|
logging.info('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:
|
||||||
|
logging.warning(f"Incomplete GPS data: {gps_string}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
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
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Error parsing GPS data: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def write_to_influxdb(lat, lon):
|
||||||
|
timestamp = int(time.time() * 1000000000) # nanosecond precision
|
||||||
|
|
||||||
|
try:
|
||||||
|
gps_point = Point("gps_location") \
|
||||||
|
.tag("host", myhost) \
|
||||||
|
.field("latitude", lat) \
|
||||||
|
.field("longitude", lon) \
|
||||||
|
.field("geolocation", f"{lat},{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}")
|
||||||
|
|
||||||
|
def send_at(command, back, timeout):
|
||||||
|
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:.6f}, Lon: {lon:.6f}")
|
||||||
|
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}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def get_gps_position():
|
||||||
|
return send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
|
||||||
|
|
||||||
|
def initialize_gps():
|
||||||
|
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")
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
initialize_gps()
|
||||||
|
logging.info("Starting continuous GPS tracking. Press Ctrl+C to stop.")
|
||||||
|
|
||||||
|
while running:
|
||||||
|
if not get_gps_position():
|
||||||
|
logging.warning("Failed to get GPS position")
|
||||||
|
time.sleep(14) # Wait for 14 seconds before the next reading
|
||||||
|
|
||||||
|
ser.close()
|
||||||
|
GPIO.cleanup()
|
||||||
|
client.close()
|
||||||
|
logging.info("GPS tracking stopped. Goodbye!")
|
Loading…
Reference in New Issue
Block a user