2024-07-24 -

This commit is contained in:
Adolfo Delorenzo 2024-07-24 20:08:38 -06:00
parent 1c52539c35
commit 2c3588be81
7 changed files with 692 additions and 0 deletions

93
gps002.py Normal file
View File

@ -0,0 +1,93 @@
#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import serial
import time
import os
import csv
from datetime import datetime
import pynmea2
# GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
ser = serial.Serial('/dev/ttyUSB3', 115200)
ser.flushInput()
myhost = os.uname()[1]
# CSV file settings
csv_filename = f"gps_data_{myhost}.csv"
csv_headers = ["Timestamp", "Latitude", "Longitude"]
def parse_gps_data(gps_string):
try:
msg = pynmea2.parse(gps_string)
if isinstance(msg, pynmea2.GGA):
if msg.latitude and msg.longitude:
return f"{msg.latitude:.6f}", f"{msg.longitude:.6f}"
except pynmea2.ParseError as e:
print(f"Parse error: {e}")
return None, None
def write_to_csv(lat, lon):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(csv_filename, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([timestamp, lat, lon])
time.sleep(12)
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 not in rec_buff:
print(command + ' ERROR')
print(command + ' back:\t' + rec_buff)
return 0
else:
print("Raw GPS data:", rec_buff)
gps_sentences = rec_buff.split('\r\n')
for sentence in gps_sentences:
if sentence.startswith('$'):
lat, lon = parse_gps_data(sentence)
if lat and lon:
print(f"Parsed GPS data: {lat}, {lon}")
write_to_csv(lat, lon)
return 1
print('No valid GPS data found')
return 0
else:
print('GPS is not ready')
return 0
def get_gps_position():
print('Starting GPS')
send_at('AT+CGPS=1,1', 'OK', 1)
time.sleep(2)
while True:
answer = send_at('AT+CGPSINFO', '+CGPSINFO: ', 1)
if answer == 1:
break
else:
print('Waiting for GPS fix...')
time.sleep(2)
# Create CSV file with headers if it doesn't exist
if not os.path.exists(csv_filename):
with open(csv_filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(csv_headers)
try:
get_gps_position()
except Exception as e:
print(f"Error: {e}")
finally:
if ser:
ser.close()
GPIO.cleanup()

106
gps003.py Normal file
View File

@ -0,0 +1,106 @@
#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import serial
import time
import os
import csv
from datetime import datetime
import pynmea2
# GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
ser = serial.Serial('/dev/ttyUSB3', 115200)
ser.flushInput()
myhost = os.uname()[1]
# CSV file settings
csv_filename = f"gps_data_{myhost}.csv"
csv_headers = ["Timestamp", "Latitude", "Longitude"]
def parse_gps_data(gps_string):
try:
msg = pynmea2.parse(gps_string)
print(f"Parsed message type: {type(msg).__name__}")
if hasattr(msg, 'latitude') and hasattr(msg, 'longitude'):
return f"{msg.latitude:.6f}", f"{msg.longitude:.6f}"
else:
print(f"Message doesn't contain lat/lon. Available attributes: {msg.fields}")
except pynmea2.ParseError as e:
print(f"Parse error: {e}")
return None, None
def write_to_csv(lat, lon):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(csv_filename, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([timestamp, lat, lon])
time.sleep(12)
def send_at(command, back, timeout):
print(f"Sending command: {command}")
ser.write((command + '\r\n').encode())
time.sleep(timeout)
if ser.inWaiting():
time.sleep(0.01)
rec_buff = ser.read(ser.inWaiting()).decode()
print(f"Received data: {rec_buff}")
if back not in rec_buff:
print(command + ' ERROR')
print(command + ' back:\t' + rec_buff)
return 0
else:
print("Raw GPS data:", rec_buff)
gps_sentences = rec_buff.split('\r\n')
for sentence in gps_sentences:
print(f"Processing sentence: {sentence}")
if sentence.startswith('$'):
lat, lon = parse_gps_data(sentence)
if lat and lon:
print(f"Valid GPS data found: {lat}, {lon}")
write_to_csv(lat, lon)
return 1
print('No valid GPS data found in this response')
return 0
else:
print('No data received from GPS')
return 0
def get_gps_position():
print('Starting GPS')
send_at('AT+CGPS=1,1', 'OK', 1)
time.sleep(2)
attempts = 0
max_attempts = 10
while attempts < max_attempts:
print(f"Attempt {attempts + 1} of {max_attempts}")
answer = send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
if answer == 1:
print("Valid GPS data received and processed")
break
else:
print('Waiting for GPS fix...')
attempts += 1
time.sleep(2)
if attempts == max_attempts:
print("Max attempts reached. GPS fix not obtained.")
# Create CSV file with headers if it doesn't exist
if not os.path.exists(csv_filename):
with open(csv_filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(csv_headers)
try:
get_gps_position()
except Exception as e:
print(f"Error: {e}")
finally:
if ser:
ser.close()
GPIO.cleanup()

119
gps004.py Normal file
View File

@ -0,0 +1,119 @@
#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import serial
import time
from datetime import datetime
import os
import csv
# GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
ser = serial.Serial('/dev/ttyUSB3', 115200)
ser.flushInput()
myhost = os.uname()[1]
# CSV file settings
csv_filename = f"gps_data_{myhost}.csv"
csv_headers = ["Timestamp", "Latitude", "Longitude", "Date", "Time", "Altitude", "Speed"]
def parse_gps_data(gps_string):
parts = gps_string.split(',')
if len(parts) < 8 or all(part == '' for part in parts):
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
date = parts[4]
gps_time = parts[5] # Renamed to avoid conflict with time module
altitude = parts[6]
speed = parts[7]
return f"{lat:.6f}", f"{lon:.6f}", date, gps_time, altitude, speed
except ValueError as e:
print(f"Error parsing GPS data: {e}")
return None
def write_to_csv(lat, lon, date, gps_time, altitude, speed):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(csv_filename, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([timestamp, lat, lon, date, gps_time, altitude, speed])
def send_at(command, back, timeout):
print(f"Sending command: {command}")
ser.write((command + '\r\n').encode())
time.sleep(timeout)
if ser.inWaiting():
time.sleep(0.01)
rec_buff = ser.read(ser.inWaiting()).decode()
print(f"Received data: {rec_buff}")
if back not in rec_buff:
print(command + ' ERROR')
print(command + ' back:\t' + rec_buff)
return 0
else:
try:
gps_data = rec_buff.split('+CGPSINFO: ')[1].split('\r\n')[0]
print(f"Extracted GPS data: {gps_data}")
parsed_data = parse_gps_data(gps_data)
if parsed_data:
lat, lon, date, gps_time, altitude, speed = parsed_data
print(f"Parsed GPS data: Lat: {lat}, Lon: {lon}, Date: {date}, Time: {gps_time}, Altitude: {altitude}, Speed: {speed}")
write_to_csv(lat, lon, date, gps_time, altitude, speed)
return 1
else:
print("No valid GPS data found in this response")
return 0
except IndexError:
print("Unexpected response format")
return 0
else:
print('No data received from GPS')
return 0
def get_gps_position():
print('Starting GPS')
send_at('AT+CGPS=1,1', 'OK', 1)
time.sleep(2)
attempts = 0
max_attempts = 10
while attempts < max_attempts:
print(f"Attempt {attempts + 1} of {max_attempts}")
answer = send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
if answer == 1:
print("Valid GPS data received and processed")
break
else:
print('Waiting for GPS fix...')
attempts += 1
time.sleep(2)
if attempts == max_attempts:
print("Max attempts reached. GPS fix not obtained.")
# Create CSV file with headers if it doesn't exist
if not os.path.exists(csv_filename):
with open(csv_filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(csv_headers)
try:
get_gps_position()
except Exception as e:
print(f"Error: {e}")
finally:
if ser:
ser.close()
GPIO.cleanup()

142
gps005.py Normal file
View File

@ -0,0 +1,142 @@
#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import serial
import time
from datetime import datetime
import os
import csv
import signal
import sys
# GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
ser = serial.Serial('/dev/ttyUSB3', 115200)
ser.flushInput()
myhost = os.uname()[1]
# CSV file settings
csv_filename = f"gps_data_{myhost}.csv"
csv_headers = ["Timestamp", "Latitude", "Longitude", "Date", "Time", "Altitude", "Speed"]
# 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) < 8 or all(part == '' for part in parts):
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
date = parts[4]
gps_time = parts[5]
altitude = parts[6]
speed = parts[7]
return f"{lat:.6f}", f"{lon:.6f}", date, gps_time, altitude, speed
except ValueError as e:
print(f"Error parsing GPS data: {e}")
return None
def write_to_csv(lat, lon, date, gps_time, altitude, speed):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(csv_filename, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([timestamp, lat, lon, date, gps_time, altitude, speed])
def send_at(command, back, timeout):
print(f"Sending command: {command}")
ser.write((command + '\r\n').encode())
time.sleep(timeout)
if ser.inWaiting():
time.sleep(0.01)
rec_buff = ser.read(ser.inWaiting()).decode()
print(f"Received data: {rec_buff}")
if back not in rec_buff:
print(command + ' ERROR')
print(command + ' back:\t' + rec_buff)
return 0
else:
try:
gps_data = rec_buff.split('+CGPSINFO: ')[1].split('\r\n')[0]
print(f"Extracted GPS data: {gps_data}")
parsed_data = parse_gps_data(gps_data)
if parsed_data:
lat, lon, date, gps_time, altitude, speed = parsed_data
print(f"Parsed GPS data: Lat: {lat}, Lon: {lon}, Date: {date}, Time: {gps_time}, Altitude: {altitude}, Speed: {speed}")
write_to_csv(lat, lon, date, gps_time, altitude, speed)
return 1
else:
print("No valid GPS data found in this response")
return 0
except IndexError:
print("Unexpected response format")
return 0
else:
print('No data received from GPS')
return 0
def get_gps_position():
answer = send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
if answer == 1:
print("Valid GPS data received and processed")
else:
print('Waiting for GPS fix...')
def initialize_gps():
print('Starting GPS')
send_at('AT+CGPS=1,1', 'OK', 1)
time.sleep(2)
attempts = 0
max_attempts = 10
while attempts < max_attempts:
print(f"Initialization attempt {attempts + 1} of {max_attempts}")
if get_gps_position() == 1:
print("GPS initialized successfully")
return True
attempts += 1
time.sleep(2)
print("Failed to initialize GPS after maximum attempts")
return False
# Create CSV file with headers if it doesn't exist
if not os.path.exists(csv_filename):
with open(csv_filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(csv_headers)
try:
if initialize_gps():
print("Starting continuous GPS tracking. Press Ctrl+C to stop.")
while running:
get_gps_position()
time.sleep(10) # Wait for 10 seconds before the next reading
else:
print("GPS initialization failed. Exiting.")
except Exception as e:
print(f"Error: {e}")
finally:
if ser:
ser.close()
GPIO.cleanup()
print("GPS tracking stopped. Goodbye!")

94
gps006.py Normal file
View File

@ -0,0 +1,94 @@
#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import serial
import time
from datetime import datetime
import os
import csv
import signal
# GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
ser = serial.Serial('/dev/ttyUSB3', 115200)
ser.flushInput()
myhost = os.uname()[1]
# CSV file settings
csv_filename = f"gps_data_{myhost}.csv"
csv_headers = ["Timestamp", "Latitude", "Longitude"]
# 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 f"{lat:.6f}", f"{lon:.6f}"
def write_to_csv(lat, lon):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(csv_filename, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([timestamp, lat, lon])
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}, Lon: {lon}")
write_to_csv(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,1', 'OK', 1)
time.sleep(2)
# Create CSV file with headers if it doesn't exist
if not os.path.exists(csv_filename):
with open(csv_filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(csv_headers)
initialize_gps()
print("Starting continuous GPS tracking. Press Ctrl+C to stop.")
while running:
get_gps_position()
time.sleep(10) # Wait for 10 seconds before the next reading
ser.close()
GPIO.cleanup()
print("GPS tracking stopped. Goodbye!")

103
gps007.py Normal file
View File

@ -0,0 +1,103 @@
#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import serial
import time
from datetime import datetime
import os
import csv
import signal
# GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
ser = serial.Serial('/dev/ttyUSB3', 115200)
ser.flushInput()
myhost = os.uname()[1]
# CSV file settings
csv_filename = f"gps_data_{myhost}.csv"
csv_headers = ["Timestamp", "Latitude", "Longitude"]
# 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 or not parts[0] or not parts[2]:
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 f"{lat:.6f}", f"{lon:.6f}"
except ValueError:
return None
def write_to_csv(lat, lon):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(csv_filename, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([timestamp, lat, lon])
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}, Lon: {lon}")
write_to_csv(lat, lon)
return 1
else:
print("Invalid GPS data received")
else:
print("Unexpected response from GPS module")
else:
print("No data received from GPS module")
return 0
def get_gps_position():
send_at('AT+CGPSINFO', '+CGPSINFO:', 1)
def initialize_gps():
print('Starting GPS')
send_at('AT+CGPS=1,1', 'OK', 1)
time.sleep(2)
# Create CSV file with headers if it doesn't exist
if not os.path.exists(csv_filename):
with open(csv_filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(csv_headers)
initialize_gps()
print("Starting continuous GPS tracking. Press Ctrl+C to stop.")
while running:
get_gps_position()
time.sleep(2) # Wait for 10 seconds before the next reading
ser.close()
GPIO.cleanup()
print("GPS tracking stopped. Goodbye!")

View File

@ -9844,3 +9844,38 @@ Timestamp,Latitude,Longitude
2024-07-24 19:33:34,9.939922,-84.104880
2024-07-24 19:33:49,9.939921,-84.104880
2024-07-24 19:34:04,9.939921,-84.104879
2024-07-24 19:54:56,9.939955,-84.104903
2024-07-24 19:55:21,9.939954,-84.104904
2024-07-24 19:56:50,9.939957,-84.104904
2024-07-24 20:00:54,9.939958,-84.104903
2024-07-24 20:01:16,9.939958,-84.104903
2024-07-24 20:03:54,9.939959,-84.104901
2024-07-24 20:03:58,9.939959,-84.104901
2024-07-24 20:04:10,9.939957,-84.104902
2024-07-24 20:04:14,9.939957,-84.104902
2024-07-24 20:04:20,9.939958,-84.104902
2024-07-24 20:04:48,9.939958,-84.104901
2024-07-24 20:04:54,9.939958,-84.104901
2024-07-24 20:05:00,9.939958,-84.104901
2024-07-24 20:05:12,9.939960,-84.104901
2024-07-24 20:05:18,9.939961,-84.104901
2024-07-24 20:05:30,9.939964,-84.104901
2024-07-24 20:05:36,9.939964,-84.104901
2024-07-24 20:05:48,9.939962,-84.104902
2024-07-24 20:05:54,9.939965,-84.104902
2024-07-24 20:06:03,9.939965,-84.104902
2024-07-24 20:06:14,9.939965,-84.104902
2024-07-24 20:06:23,9.939965,-84.104902
2024-07-24 20:06:29,9.939965,-84.104902
2024-07-24 20:06:47,9.939968,-84.104902
2024-07-24 20:06:53,9.939968,-84.104902
2024-07-24 20:07:17,9.939969,-84.104905
2024-07-24 20:07:23,9.939971,-84.104905
2024-07-24 20:07:29,9.939971,-84.104906
2024-07-24 20:07:35,9.939971,-84.104906
2024-07-24 20:07:41,9.939971,-84.104906
2024-07-24 20:07:50,9.939971,-84.104906
2024-07-24 20:07:56,9.939971,-84.104906
2024-07-24 20:08:02,9.939971,-84.104906
2024-07-24 20:08:14,9.939970,-84.104906
2024-07-24 20:08:20,9.939970,-84.104906

1 Timestamp Latitude Longitude
9844 2024-07-24 19:33:34 9.939922 -84.104880
9845 2024-07-24 19:33:49 9.939921 -84.104880
9846 2024-07-24 19:34:04 9.939921 -84.104879
9847 2024-07-24 19:54:56 9.939955 -84.104903
9848 2024-07-24 19:55:21 9.939954 -84.104904
9849 2024-07-24 19:56:50 9.939957 -84.104904
9850 2024-07-24 20:00:54 9.939958 -84.104903
9851 2024-07-24 20:01:16 9.939958 -84.104903
9852 2024-07-24 20:03:54 9.939959 -84.104901
9853 2024-07-24 20:03:58 9.939959 -84.104901
9854 2024-07-24 20:04:10 9.939957 -84.104902
9855 2024-07-24 20:04:14 9.939957 -84.104902
9856 2024-07-24 20:04:20 9.939958 -84.104902
9857 2024-07-24 20:04:48 9.939958 -84.104901
9858 2024-07-24 20:04:54 9.939958 -84.104901
9859 2024-07-24 20:05:00 9.939958 -84.104901
9860 2024-07-24 20:05:12 9.939960 -84.104901
9861 2024-07-24 20:05:18 9.939961 -84.104901
9862 2024-07-24 20:05:30 9.939964 -84.104901
9863 2024-07-24 20:05:36 9.939964 -84.104901
9864 2024-07-24 20:05:48 9.939962 -84.104902
9865 2024-07-24 20:05:54 9.939965 -84.104902
9866 2024-07-24 20:06:03 9.939965 -84.104902
9867 2024-07-24 20:06:14 9.939965 -84.104902
9868 2024-07-24 20:06:23 9.939965 -84.104902
9869 2024-07-24 20:06:29 9.939965 -84.104902
9870 2024-07-24 20:06:47 9.939968 -84.104902
9871 2024-07-24 20:06:53 9.939968 -84.104902
9872 2024-07-24 20:07:17 9.939969 -84.104905
9873 2024-07-24 20:07:23 9.939971 -84.104905
9874 2024-07-24 20:07:29 9.939971 -84.104906
9875 2024-07-24 20:07:35 9.939971 -84.104906
9876 2024-07-24 20:07:41 9.939971 -84.104906
9877 2024-07-24 20:07:50 9.939971 -84.104906
9878 2024-07-24 20:07:56 9.939971 -84.104906
9879 2024-07-24 20:08:02 9.939971 -84.104906
9880 2024-07-24 20:08:14 9.939970 -84.104906
9881 2024-07-24 20:08:20 9.939970 -84.104906