2024-07-26 -

This commit is contained in:
Adolfo Delorenzo 2024-07-26 22:53:29 -06:00
parent fa6fa1390b
commit 09b54f1159
3 changed files with 215 additions and 39 deletions

View File

@ -6531,3 +6531,5 @@ Timestamp,Latitude,Longitude
2024-07-26 22:16:37,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:29:54,9.939918,-84.104902
2024-07-26 22:30:09,9.939918,-84.104902

1 Timestamp Latitude Longitude
6531 2024-07-26 22:16:37 9.939904 -84.104898
6532 2024-07-26 22:16:52 9.939904 -84.104898
6533 2024-07-26 22:17:07 9.939904 -84.104897
6534 2024-07-26 22:29:54 9.939918 -84.104902
6535 2024-07-26 22:30:09 9.939918 -84.104902

View File

@ -8,13 +8,21 @@ 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]
@ -22,18 +30,23 @@ myhost = os.uname()[1]
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 = "gps_data"
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
print('You pressed Ctrl+C! Stopping GPS tracking...')
logging.info('You pressed Ctrl+C! Stopping GPS tracking...')
running = False
signal.signal(signal.SIGINT, signal_handler)
@ -41,27 +54,41 @@ 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
lat = float(parts[0][:2]) + float(parts[0][2:]) / 60
if parts[1] == 'S':
lat = -lat
try:
lat = parts[0]
lat_dir = parts[1]
lon = parts[2]
lon_dir = parts[3]
lon = float(parts[2][:3]) + float(parts[2][3:]) / 60
if parts[3] == 'W':
lon = -lon
# 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 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):
point = Point("gps_location") \
.tag("host", myhost) \
.field("latitude", float(lat)) \
.field("longitude", float(lon))
timestamp = int(time.time() * 1000000000) # nanosecond precision
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):
try:
ser.write((command + '\r\n').encode())
time.sleep(timeout)
if ser.inWaiting():
@ -69,30 +96,41 @@ def send_at(command, back, timeout):
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
print(f"GPS: Lat: {lat}, Lon: {lon}")
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}")
return 0
def get_gps_position():
send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
return send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
def initialize_gps():
print('Starting GPS')
send_at('AT+CGPS=1', 'OK', 1)
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()
print("Starting continuous GPS tracking. Press Ctrl+C to stop.")
logging.info("Starting continuous GPS tracking. Press Ctrl+C to stop.")
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
ser.close()
GPIO.cleanup()
client.close()
print("GPS tracking stopped. Goodbye!")
logging.info("GPS tracking stopped. Goodbye!")

136
gpsinflux01.py Normal file
View 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!")