From ad1c7797245e869c955ec46621e16dde722e466d Mon Sep 17 00:00:00 2001 From: Adolfo Delorenzo Date: Sun, 21 Jul 2024 20:49:33 -0600 Subject: [PATCH] 2024-07-21 - --- gps.py | 2 +- gps01.py | 15 ++--- gps03.py | 142 +++++++++++++++++++++++++++++++++++++++ gps04.py | 113 +++++++++++++++++++++++++++++++ gps05.py | 130 +++++++++++++++++++++++++++++++++++ gps06.py | 128 +++++++++++++++++++++++++++++++++++ gps07.py | 89 ++++++++++++++++++++++++ gps_data_raspberrypi.csv | 1 - 8 files changed, 608 insertions(+), 12 deletions(-) create mode 100644 gps03.py create mode 100644 gps04.py create mode 100644 gps05.py create mode 100644 gps06.py create mode 100755 gps07.py diff --git a/gps.py b/gps.py index 02c212a..322cbf8 100755 --- a/gps.py +++ b/gps.py @@ -96,4 +96,4 @@ except: GPIO.cleanup() if ser != None: ser.close() - GPIO.cleanup() + GPIO.cleanup() diff --git a/gps01.py b/gps01.py index c4b50f6..6978ce9 100755 --- a/gps01.py +++ b/gps01.py @@ -1,7 +1,6 @@ #!/usr/bin/python # -*- coding:utf-8 -*- import RPi.GPIO as GPIO -import paho.mqtt.client as mqtt import serial import time, os import csv @@ -11,17 +10,14 @@ from datetime import datetime GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) -# MQTT Broker settings -mqttBroker ="65.108.199.212" -myhost = os.uname()[1] -client = mqtt.Client(myhost) -# client.connect(mqttBroker, 1883) ser = serial.Serial('/dev/ttyS0',115200) ser.flushInput() rec_buff = '' time_count = 0 +myhost = os.uname()[1] + # CSV file settings csv_filename = f"gps_data_{myhost}.csv" csv_headers = ["Timestamp", "Latitude", "Longitude"] @@ -29,7 +25,7 @@ csv_headers = ["Timestamp", "Latitude", "Longitude"] def convert_to_decimal(coord_str): coord = coord_str[:-2] direction = coord_str[-1] - + degrees = float(coord[:2] if direction in ['N', 'S'] else coord[:3]) minutes = float(coord[2:] if direction in ['N', 'S'] else coord[3:]) @@ -75,7 +71,6 @@ def send_at(command,back,timeout): lat, lon = parse_gps_data(gps_data) converted_gps = f"{lat}, {lon}" print("Converted GPS data for Google Maps:", converted_gps) - client.publish("iiot/"+ myhost +"/gps", converted_gps) current_time = datetime.datetime.now() write_to_csv(current_time, lat, lon) return 1 @@ -89,7 +84,6 @@ def get_gps_position(): print('Iniciando GPS') rec_buff = '' send_at('AT+CGPS=1,1','OK',1) - send_at("AT+CNTP=\"pool.ntp.org\",52") time.sleep(2) while rec_null: answer = send_at('AT+CGPSINFO','+CGPSINFO: ',1) @@ -112,7 +106,8 @@ def get_gps_position(): if not os.path.exists(csv_filename): with open(csv_filename, mode='w', newline='') as file: writer = csv.writer(file) - writer.writerow(csv_headers) + writer.writerow([timestamp, lat, lon]) +# writer.writerow(csv_headers) try: get_gps_position() diff --git a/gps03.py b/gps03.py new file mode 100644 index 0000000..6607aed --- /dev/null +++ b/gps03.py @@ -0,0 +1,142 @@ +#!/usr/bin/python +# -*- coding:utf-8 -*- +import RPi.GPIO as GPIO +import paho.mqtt.client as mqtt +import serial +import time, os +import csv +from datetime import datetime + +# MQTT Broker settings +mqttBroker ="65.108.199.212" +myhost = os.uname()[1] +client = mqtt.Client(myhost) +# client.connect(mqttBroker, 1883) + +ser = serial.Serial('/dev/ttyS0',115200) +ser.flushInput() + +rec_buff = '' +time_count = 0 + +# CSV file settings +csv_filename = f"gps_data_{myhost}.csv" +csv_headers = ["Timestamp", "Latitude", "Longitude"] + +def convert_to_decimal(coord_str): + coord = coord_str[:-2] + direction = coord_str[-1] + + degrees = float(coord[:2] if direction in ['N', 'S'] else coord[:3]) + minutes = float(coord[2:] if direction in ['N', 'S'] else coord[3:]) + + decimal = degrees + (minutes / 60) + + if direction in ['S', 'W']: + decimal = -decimal + + return decimal + +def parse_gps_data(gps_string): + parts = gps_string.split(',') + if len(parts) != 4: + return "Invalid GPS data" + + lat = convert_to_decimal(parts[0] + ',' + parts[1]) + lon = convert_to_decimal(parts[2] + ',' + parts[3]) + + 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): + rec_buff = '' + ser.write((command+'\r\n').encode()) + time.sleep(timeout) + if ser.inWaiting(): + time.sleep(0.01) + rec_buff = ser.read(ser.inWaiting()) + if rec_buff != '': + if back not in rec_buff.decode(): + print(command + ' ERROR') + print(command + ' back:\t' + rec_buff.decode()) + return 0 + else: + gps_data = rec_buff.decode()[13:-36] + print("Raw GPS data:", gps_data) + lat, lon = parse_gps_data(gps_data) + converted_gps = f"{lat}, {lon}" + print("Converted GPS data for Google Maps:", converted_gps) + client.publish("iiot/"+ myhost +"/gps", converted_gps) + write_to_csv(lat, lon) + return 1 + else: + print('GPS no está listo') + return 0 + +def get_gps_position(): + rec_null = True + answer = 0 + print('Iniciando GPS') + rec_buff = '' + send_at('AT+CGPS=1,1','OK',1) + time.sleep(2) + while rec_null: + answer = send_at('AT+CGPSINFO','+CGPSINFO: ',1) + client.publish("iiot/"+ myhost +"/gps", rec_buff, 0) + if 1 == answer: + answer = 0 + if ',,,,,,' in rec_buff: + print('GPS no está listo') + rec_null = False + time.sleep(1) + else: + print('error %d'%answer) + rec_buff = '' + send_at('AT+CGPS=0','OK',1) + return False + time.sleep(1.5) + +def power_on(power_key): + print('SIM7600X is starting:') + GPIO.setmode(GPIO.BCM) + GPIO.setwarnings(False) + GPIO.setup(power_key,GPIO.OUT) + time.sleep(0.1) + GPIO.output(power_key,GPIO.HIGH) + time.sleep(2) + GPIO.output(power_key,GPIO.LOW) + time.sleep(20) + ser.flushInput() + print('SIM7600X is ready') + +def power_down(power_key): + print('SIM7600X is loging off:') + GPIO.output(power_key,GPIO.HIGH) + time.sleep(3) + GPIO.output(power_key,GPIO.LOW) + time.sleep(18) + print('Good bye') + +# 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: + #power_on(power_key) + get_gps_position() + #power_down(power_key) +except: + if ser != None: + ser.close() + #power_down(power_key) + GPIO.cleanup() +if ser != None: + ser.close() + GPIO.cleanup() diff --git a/gps04.py b/gps04.py new file mode 100644 index 0000000..9d3b9c6 --- /dev/null +++ b/gps04.py @@ -0,0 +1,113 @@ +#!/usr/bin/python +# -*- coding:utf-8 -*- +import RPi.GPIO as GPIO +import paho.mqtt.client as mqtt +import serial +import time, os +import csv +from datetime import datetime + +# MQTT Broker settings +mqttBroker ="65.108.199.212" +myhost = os.uname()[1] +client = mqtt.Client(myhost) +# client.connect(mqttBroker, 1883) + +ser = serial.Serial('/dev/ttyS0',115200) +ser.flushInput() + +rec_buff = '' +time_count = 0 + +# CSV file setup +csv_filename = f"gps_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv" +csv_header = ['Timestamp', 'GPS Data'] + +def write_to_csv(data): + with open(csv_filename, 'a', newline='') as csvfile: + csv_writer = csv.writer(csvfile) + csv_writer.writerow([datetime.now().strftime('%Y-%m-%d %H:%M:%S'), data]) + +def send_at(command,back,timeout): + rec_buff = '' + ser.write((command+'\r\n').encode()) + time.sleep(timeout) + if ser.inWaiting(): + time.sleep(0.01) + rec_buff = ser.read(ser.inWaiting()) + if rec_buff != '': + if back not in rec_buff.decode(): + print(command + ' ERROR') + print(command + ' back:\t' + rec_buff.decode()) + return 0 + else: + gps_data = rec_buff.decode()[13:-36] + print(gps_data) + client.publish("iiot/"+ myhost +"/gps", gps_data) + write_to_csv(gps_data) # Write GPS data to CSV + return 1 + else: + print('GPS no está listo') + return 0 + +def get_gps_position(): + rec_null = True + answer = 0 + print('Iniciando GPS') + rec_buff = '' + send_at('AT+CGPS=1,1','OK',1) + time.sleep(2) + while rec_null: + answer = send_at('AT+CGPSINFO','+CGPSINFO: ',1) + client.publish("iiot/"+ myhost +"/gps", rec_buff, 0) + if 1 == answer: + answer = 0 + if ',,,,,,' in rec_buff: + print('GPS no está listo') + rec_null = False + time.sleep(1) + else: + print('error %d'%answer) + rec_buff = '' + send_at('AT+CGPS=0','OK',1) + return False + time.sleep(1.5) + +def power_on(power_key): + print('SIM7600X is starting:') + GPIO.setmode(GPIO.BCM) + GPIO.setwarnings(False) + GPIO.setup(power_key,GPIO.OUT) + time.sleep(0.1) + GPIO.output(power_key,GPIO.HIGH) + time.sleep(2) + GPIO.output(power_key,GPIO.LOW) + time.sleep(20) + ser.flushInput() + print('SIM7600X is ready') + +def power_down(power_key): + print('SIM7600X is loging off:') + GPIO.output(power_key,GPIO.HIGH) + time.sleep(3) + GPIO.output(power_key,GPIO.LOW) + time.sleep(18) + print('Good bye') + +try: + # Create CSV file with header + with open(csv_filename, 'w', newline='') as csvfile: + csv_writer = csv.writer(csvfile) + csv_writer.writerow(csv_header) + + #power_on(power_key) + get_gps_position() + #power_down(power_key) +except: + if ser != None: + ser.close() + #power_down(power_key) + GPIO.cleanup() +if ser != None: + ser.close() + GPIO.cleanup() diff --git a/gps05.py b/gps05.py new file mode 100644 index 0000000..4e686da --- /dev/null +++ b/gps05.py @@ -0,0 +1,130 @@ +#!/usr/bin/python +# -*- coding:utf-8 -*- +import RPi.GPIO as GPIO +import serial +import time, os +import csv +from datetime import datetime + +myhost = os.uname()[1] + +GPIO.setwarnings(False) + +ser = serial.Serial('/dev/ttyS0',115200) +ser.flushInput() + +rec_buff = '' +time_count = 0 + +# CSV file setup +csv_filename = f"gps_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv" + +def convert_to_degrees(raw_value): + decimal_value = float(raw_value) + degrees = int(decimal_value / 100) + d = float(degrees) + m = (decimal_value - (d * 100)) / 60.0 + return d + m + +def write_to_csv(timestamp, lat, lon): + with open(csv_filename, 'a', newline='') as csvfile: + csv_writer = csv.writer(csvfile) + csv_writer.writerow([timestamp, lat, lon]) + +def send_at(command,back,timeout): + rec_buff = '' + ser.write((command+'\r\n').encode()) + time.sleep(timeout) + if ser.inWaiting(): + time.sleep(0.01) + rec_buff = ser.read(ser.inWaiting()) + if rec_buff != '': + if back not in rec_buff.decode(): + print(command + ' ERROR') + print(command + ' back:\t' + rec_buff.decode()) + return 0 + else: + gps_data = rec_buff.decode()[13:-36] + print(gps_data) + + # Parse GPS data + gps_parts = gps_data.split(',') + if len(gps_parts) >= 4 and gps_parts[0] and gps_parts[2]: + lat = convert_to_degrees(gps_parts[0]) + lon = convert_to_degrees(gps_parts[2]) + if gps_parts[1] == 'S': + lat = -lat + if gps_parts[3] == 'W': + lon = -lon + + timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + write_to_csv(timestamp, lat, lon) + + # Format for Google Maps + maps_url = f"https://www.google.com/maps?q={lat},{lon}" + print(f"Google Maps URL: {maps_url}") + + else: + print("Invalid GPS data received") + + return 1 + else: + print('GPS no está listo') + return 0 + +def get_gps_position(): + rec_null = True + answer = 0 + print('Iniciando GPS') + rec_buff = '' + send_at('AT+CGPS=1,1','OK',1) + time.sleep(2) + while rec_null: + answer = send_at('AT+CGPSINFO','+CGPSINFO: ',1) + if 1 == answer: + answer = 0 + if ',,,,,,' in rec_buff: + print('GPS no está listo') + rec_null = False + time.sleep(1) + else: + print('error %d'%answer) + rec_buff = '' + send_at('AT+CGPS=0','OK',1) + return False + time.sleep(1.5) + +def power_on(power_key): + print('SIM7600X is starting:') + GPIO.setmode(GPIO.BCM) + GPIO.setwarnings(False) + GPIO.setup(power_key,GPIO.OUT) + time.sleep(0.1) + GPIO.output(power_key,GPIO.HIGH) + time.sleep(2) + GPIO.output(power_key,GPIO.LOW) + time.sleep(20) + ser.flushInput() + print('SIM7600X is ready') + +def power_down(power_key): + print('SIM7600X is loging off:') + GPIO.output(power_key,GPIO.HIGH) + time.sleep(3) + GPIO.output(power_key,GPIO.LOW) + time.sleep(18) + print('Good bye') + +try: + # No need to create CSV file with header anymore + #power_on(power_key) + get_gps_position() + #power_down(power_key) +except: + if ser != None: + ser.close() + #power_down(power_key) + GPIO.cleanup() +if ser != None: + ser.close() + GPIO.cleanup() diff --git a/gps06.py b/gps06.py new file mode 100644 index 0000000..4a31ac7 --- /dev/null +++ b/gps06.py @@ -0,0 +1,128 @@ +#!/usr/bin/python +# -*- coding:utf-8 -*- +import RPi.GPIO as GPIO +import serial +import time +import os +import csv +from datetime import datetime + +myhost = os.uname()[1] + +# GPIO setup +GPIO.setmode(GPIO.BCM) +GPIO.setwarnings(False) +gpio_initialized = False + +ser = serial.Serial('/dev/ttyS0', 115200) +ser.flushInput() + +rec_buff = '' +time_count = 0 + +# CSV file setup +csv_filename = 'gps_coordinates.csv' +csv_header = ['Timestamp', 'Latitude', 'Longitude'] + +def write_to_csv(lat, lon): + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + with open(csv_filename, 'a', newline='') as csvfile: + csv_writer = csv.writer(csvfile) + if os.stat(csv_filename).st_size == 0: + csv_writer.writerow(csv_header) + csv_writer.writerow([timestamp, lat, lon]) + +def parse_gps_data(gps_data): + parts = gps_data.split(',') + if len(parts) >= 4: + lat = convert_to_decimal(parts[0], parts[1]) + lon = convert_to_decimal(parts[2], parts[3]) + return lat, lon + return None, None + +def convert_to_decimal(coord, direction): + degrees = float(coord[:2]) + minutes = float(coord[2:]) + decimal = degrees + (minutes / 60) + if direction in ['S', 'W']: + decimal = -decimal + return round(decimal, 6) + +def send_at(command, back, timeout): + rec_buff = '' + ser.write((command+'\r\n').encode()) + time.sleep(timeout) + if ser.inWaiting(): + time.sleep(0.01) + rec_buff = ser.read(ser.inWaiting()) + if rec_buff != '': + if back not in rec_buff.decode(): + print(command + ' ERROR') + print(command + ' back:\t' + rec_buff.decode()) + return 0 + else: + gps_data = rec_buff.decode()[13:-36] + print(gps_data) + lat, lon = parse_gps_data(gps_data) + if lat is not None and lon is not None: + write_to_csv(lat, lon) + return 1 + else: + print('GPS is not ready') + return 0 + +def get_gps_position(): + rec_null = True + answer = 0 + print('Starting GPS') + rec_buff = '' + send_at('AT+CGPS=1,1','OK',1) + time.sleep(2) + while rec_null: + answer = send_at('AT+CGPSINFO','+CGPSINFO: ',1) + if 1 == answer: + answer = 0 + if ',,,,,,' in rec_buff: + print('GPS is not ready') + rec_null = False + time.sleep(1) + else: + print('error %d'%answer) + rec_buff = '' + send_at('AT+CGPS=0','OK',1) + return False + time.sleep(1.5) + +def power_on(power_key): + print('SIM7600X is starting:') + GPIO.setmode(GPIO.BCM) + GPIO.setwarnings(False) + GPIO.setup(power_key,GPIO.OUT) + time.sleep(0.1) + GPIO.output(power_key,GPIO.HIGH) + time.sleep(2) + GPIO.output(power_key,GPIO.LOW) + time.sleep(20) + ser.flushInput() + print('SIM7600X is ready') + +def power_down(power_key): + print('SIM7600X is logging off:') + GPIO.output(power_key,GPIO.HIGH) + time.sleep(3) + GPIO.output(power_key,GPIO.LOW) + time.sleep(18) + print('Good bye') + +try: + #power_on(power_key) + get_gps_position() + #power_down(power_key) +except: + if ser != None: + ser.close() + #power_down(power_key) + GPIO.cleanup() +if ser != None: + ser.close() + GPIO.cleanup() diff --git a/gps07.py b/gps07.py new file mode 100755 index 0000000..ef5dccb --- /dev/null +++ b/gps07.py @@ -0,0 +1,89 @@ +#!/usr/bin/python +# -*- coding:utf-8 -*- +import RPi.GPIO as GPIO +import serial +import time, os + +ser = serial.Serial('/dev/ttyS0',115200) +ser.flushInput() + +rec_buff = '' +time_count = 0 + +def send_at(command,back,timeout): + rec_buff = '' + ser.write((command+'\r\n').encode()) + time.sleep(timeout) + if ser.inWaiting(): + time.sleep(0.01 ) + rec_buff = ser.read(ser.inWaiting()) + if rec_buff != '': + if back not in rec_buff.decode(): + print(command + ' ERROR') + print(command + ' back:\t' + rec_buff.decode()) + return 0 + else: + gps_data = rec_buff.decode()[13:-36] + print(gps_data) + return 1 + else: + print('GPS no está listo') + return 0 + +def get_gps_position(): + rec_null = True + answer = 0 + print('Iniciando GPS') + rec_buff = '' + send_at('AT+CGPS=1,1','OK',1) + time.sleep(2) + while rec_null: + answer = send_at('AT+CGPSINFO','+CGPSINFO: ',1) + client.publish("iiot/"+ myhost +"/gps", rec_buff, 0) + if 1 == answer: + answer = 0 + if ',,,,,,' in rec_buff: + print('GPS no está listo') + rec_null = False + time.sleep(1) + else: + print('error %d'%answer) + rec_buff = '' + send_at('AT+CGPS=0','OK',1) + return False + time.sleep(1.5) + + +def power_on(power_key): + print('SIM7600X is starting:') + GPIO.setmode(GPIO.BCM) + GPIO.setwarnings(False) + GPIO.setup(power_key,GPIO.OUT) + time.sleep(0.1) + GPIO.output(power_key,GPIO.HIGH) + time.sleep(2) + GPIO.output(power_key,GPIO.LOW) + time.sleep(20) + ser.flushInput() + print('SIM7600X is ready') + +def power_down(power_key): + print('SIM7600X is loging off:') + GPIO.output(power_key,GPIO.HIGH) + time.sleep(3) + GPIO.output(power_key,GPIO.LOW) + time.sleep(18) + print('Good bye') + +try: + #power_on(power_key) + get_gps_position() + #power_down(power_key) +except: + if ser != None: + ser.close() + #power_down(power_key) + GPIO.cleanup() +if ser != None: + ser.close() + GPIO.cleanup() diff --git a/gps_data_raspberrypi.csv b/gps_data_raspberrypi.csv index f8ae912..e69de29 100644 --- a/gps_data_raspberrypi.csv +++ b/gps_data_raspberrypi.csv @@ -1 +0,0 @@ -Timestamp,Latitude,Longitude