diff --git a/gps.py b/gps.py index 322cbf8..cc6b748 100755 --- a/gps.py +++ b/gps.py @@ -45,7 +45,7 @@ def get_gps_position(): answer = 0 print('Iniciando GPS') rec_buff = '' - send_at('AT+CGPS=1,1','OK',1) + send_at('AT+CGPS=1','OK',1) time.sleep(2) while rec_null: answer = send_at('AT+CGPSINFO','+CGPSINFO: ',1) diff --git a/gps006.py b/gps006.py index 1ab2daa..0862535 100755 --- a/gps006.py +++ b/gps006.py @@ -73,7 +73,7 @@ def get_gps_position(): def initialize_gps(): print('Starting GPS') - send_at('AT+CGPS=1,1', 'OK', 1) + send_at('AT+CGPS=1', 'OK', 1) time.sleep(2) # Create CSV file with headers if it doesn't exist diff --git a/gps007.py b/gps007.py old mode 100644 new mode 100755 diff --git a/gps008.py b/gps008.py index 48e1df7..63bb5ee 100644 --- a/gps008.py +++ b/gps008.py @@ -12,7 +12,7 @@ GPIO.setwarnings(False) # Initialize serial port try: - ser = serial.Serial('/dev/ttyUSB3', 115200) + ser = serial.Serial('/dev/ttyUSB3', 9600) ser.flushInput() except serial.SerialException as e: print(f"Error initializing serial port: {e}") @@ -38,8 +38,19 @@ def signal_handler(sig, frame): signal.signal(signal.SIGINT, signal_handler) def parse_gps_data(gps_string): - # Implement GPS data parsing logic here - pass + 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(data): file_exists = os.path.isfile(csv_filename) @@ -49,9 +60,21 @@ def write_to_csv(data): writer.writerow(csv_headers) writer.writerow(data) -def send_data(data): - # Implement data sending logic here - pass +def send_data(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 main(): while running: diff --git a/gps010.py b/gps010.py new file mode 100644 index 0000000..fa19908 --- /dev/null +++ b/gps010.py @@ -0,0 +1,136 @@ +import RPi.GPIO as GPIO +import serial +import time +from datetime import datetime +import os +import csv +import requests +import signal + +# GPIO configuration +GPIO.setmode(GPIO.BCM) +GPIO.setwarnings(False) + +# Initialize serial port +try: + ser = serial.Serial('/dev/ttyUSB3', 115200) + ser.flushInput() +except serial.SerialException as e: + print(f"Error initializing serial port: {e}") + exit(1) + +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 + +# List to store pending data +pending_data = [] + +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): + try: + parts = gps_string.split(',') + 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 (IndexError, ValueError) as e: + print(f"Error parsing GPS data: {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]) + +def send_data_to_influxdb(lat, lon): + url = "http://100.64.0.24:8086/write?db=telegraf" # Reemplaza con tu URL + data = f"gps_data,host={myhost} latitude={lat},longitude={lon} {int(time.time() * 1e9)}" + try: + response = requests.post(url, data=data) + response.raise_for_status() + print(f"Data sent successfully to InfluxDB: {response.status_code}") + except requests.RequestException as e: + print(f"Error sending data to InfluxDB: {e}") + pending_data.append((lat, lon)) + +def send_pending_data(): + global pending_data + for data in pending_data[:]: # Iterate over a copy of the list + try: + send_data_to_influxdb(data[0], data[1]) + pending_data.remove(data) + except Exception as e: + print(f"Error sending data: {e}") + break # Exit loop if sending fails + +def check_internet_connection(): + try: + requests.get('http://www.google.com', timeout=3) + return True + except requests.ConnectionError: + return False + +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) + if check_internet_connection(): + send_data_to_influxdb(lat, lon) + else: + pending_data.append((lat, lon)) + return 1 + return 0 + +def get_gps_position(): + send_at('AT+CGPSINFO', '+CGPSINFO:', 1) + if check_internet_connection(): + send_pending_data() + +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(14) # Wait for 14 seconds before the next reading + +ser.close() +GPIO.cleanup() +print("GPS tracking stopped. Goodbye!") \ No newline at end of file diff --git a/gps011.py b/gps011.py new file mode 100644 index 0000000..3028722 --- /dev/null +++ b/gps011.py @@ -0,0 +1,37 @@ +import csv +from datetime import datetime +from influxdb_client import InfluxDBClient, Point +from influxdb_client.client.write_api import SYNCHRONOUS + +# InfluxDB connection parameters +url = "http://100.64.0.24:8086" +token = "IPtqPXbaXuuMHvx_tUOt1cmIZfLHucd-9DcepXTVpQc-fNKBhp6pkhyTsq_XnoGXdxwILy5AFFgZ_QUZCE5Jhg==" +org = "juandiego" +bucket = "gps_data" + +# Connect to InfluxDB +client = InfluxDBClient(url=url, token=token, org=org) +write_api = client.write_api(write_options=SYNCHRONOUS) + +# Read CSV file +with open('gps_data_raspberrypi.csv', 'r') as csvfile: + csvreader = csv.DictReader(csvfile) + + for row in csvreader: + # Assuming your CSV has 'timestamp', 'measurement', and 'value' columns + timestamp = datetime.fromisoformat(row['timestamp']) + measurement = row['measurement'] + value = float(row['value']) + + # Create a Point + point = Point(measurement) \ + .time(timestamp) \ + .field("value", value) + + # Write the point to InfluxDB + write_api.write(bucket=bucket, org=org, record=point) + +print("Data import completed") + +# Close the client +client.close() diff --git a/gps_data_raspberrypi.csv b/gps_data_raspberrypi.csv index 45baf09..1291a1b 100644 --- a/gps_data_raspberrypi.csv +++ b/gps_data_raspberrypi.csv @@ -5954,3 +5954,84 @@ Timestamp,Latitude,Longitude 2024-07-26 17:24:33,9.939789,-84.105024 2024-07-26 17:24:48,9.939788,-84.105025 2024-07-26 17:25:03,9.939787,-84.105025 +2024-07-26 18:04:44,, +2024-07-26 18:05:16,, +2024-07-26 18:05:20,, +2024-07-26 18:39:59,, +2024-07-26 18:40:18,, +2024-07-26 18:40:37,, +2024-07-26 18:52:54,9.940134,-84.105023 +2024-07-26 18:53:09,9.939868,-84.104842 +2024-07-26 18:53:24,9.939948,-84.104932 +2024-07-26 18:53:39,9.940019,-84.104949 +2024-07-26 18:53:54,9.940023,-84.104955 +2024-07-26 18:54:09,9.940023,-84.104955 +2024-07-26 18:54:24,9.940023,-84.104956 +2024-07-26 18:54:39,9.940023,-84.104955 +2024-07-26 18:54:54,9.940022,-84.104954 +2024-07-26 18:55:09,9.940022,-84.104954 +2024-07-26 18:55:24,9.940022,-84.104954 +2024-07-26 18:55:39,9.940023,-84.104954 +2024-07-26 18:55:54,9.940023,-84.104953 +2024-07-26 18:56:09,9.940023,-84.104953 +2024-07-26 18:56:24,9.940024,-84.104953 +2024-07-26 18:56:39,9.940024,-84.104953 +2024-07-26 18:56:54,9.940023,-84.104952 +2024-07-26 18:57:09,9.940033,-84.104945 +2024-07-26 18:57:24,9.939985,-84.104922 +2024-07-26 18:57:39,9.939985,-84.104921 +2024-07-26 18:57:54,9.939985,-84.104921 +2024-07-26 18:58:09,9.939977,-84.104905 +2024-07-26 18:58:24,9.939955,-84.104910 +2024-07-26 18:58:39,9.939955,-84.104910 +2024-07-26 18:58:54,9.939956,-84.104909 +2024-07-26 18:59:09,9.939955,-84.104909 +2024-07-26 18:59:24,9.939956,-84.104909 +2024-07-26 18:59:39,9.939959,-84.104906 +2024-07-26 18:59:54,9.939965,-84.104901 +2024-07-26 19:00:09,9.939965,-84.104901 +2024-07-26 19:00:24,9.939965,-84.104901 +2024-07-26 19:00:39,9.939965,-84.104901 +2024-07-26 19:00:54,9.939965,-84.104901 +2024-07-26 19:01:09,9.939965,-84.104901 +2024-07-26 19:01:24,9.939965,-84.104901 +2024-07-26 19:01:39,9.939965,-84.104901 +2024-07-26 19:01:54,9.939965,-84.104901 +2024-07-26 19:02:09,9.939965,-84.104901 +2024-07-26 19:02:24,9.939964,-84.104902 +2024-07-26 19:02:39,9.939964,-84.104902 +2024-07-26 19:02:54,9.939964,-84.104902 +2024-07-26 19:03:09,9.939963,-84.104902 +2024-07-26 19:03:24,9.939963,-84.104903 +2024-07-26 19:03:39,9.939964,-84.104903 +2024-07-26 19:03:54,9.939964,-84.104904 +2024-07-26 19:04:10,9.939964,-84.104904 +2024-07-26 19:04:25,9.939964,-84.104904 +2024-07-26 19:04:40,9.939965,-84.104904 +2024-07-26 19:04:55,9.939965,-84.104904 +2024-07-26 19:05:10,9.939966,-84.104904 +2024-07-26 19:05:25,9.939966,-84.104904 +2024-07-26 19:05:40,9.939966,-84.104904 +2024-07-26 19:05:55,9.939966,-84.104904 +2024-07-26 19:06:10,9.939988,-84.104884 +2024-07-26 19:06:25,9.939988,-84.104883 +2024-07-26 19:06:40,9.939987,-84.104881 +2024-07-26 19:06:55,9.939988,-84.104883 +2024-07-26 19:07:10,9.939988,-84.104882 +2024-07-26 19:07:42,9.939988,-84.104882 +2024-07-26 19:07:57,9.939988,-84.104882 +2024-07-26 19:08:12,9.939988,-84.104882 +2024-07-26 19:08:27,9.939988,-84.104882 +2024-07-26 19:08:42,9.939988,-84.104882 +2024-07-26 19:08:57,9.939988,-84.104882 +2024-07-26 19:09:12,9.939989,-84.104882 +2024-07-26 19:09:27,9.939989,-84.104881 +2024-07-26 19:09:42,9.939989,-84.104882 +2024-07-26 19:09:57,9.939989,-84.104881 +2024-07-26 19:10:12,9.939989,-84.104881 +2024-07-26 19:10:27,9.939989,-84.104881 +2024-07-26 19:10:42,9.939989,-84.104883 +2024-07-26 19:10:57,9.939989,-84.104886 +2024-07-26 19:11:12,9.939990,-84.104887 +2024-07-26 19:11:27,9.939989,-84.104886 +2024-07-26 19:11:42,9.939991,-84.104889 diff --git a/gpssend.py b/gpssend.py new file mode 100644 index 0000000..0e8c008 --- /dev/null +++ b/gpssend.py @@ -0,0 +1,64 @@ +import csv +from datetime import datetime +from influxdb_client import InfluxDBClient, Point +from influxdb_client.client.write_api import SYNCHRONOUS + +# InfluxDB connection parameters +url = "http://100.64.0.24:8086" +token = "IPtqPXbaXuuMHvx_tUOt1cmIZfLHucd-9DcepXTVpQc-fNKBhp6pkhyTsq_XnoGXdxwILy5AFFgZ_QUZCE5Jhg==" +org = "juandiego" +bucket = "gps_data" + +# Authentication credentials +#username = "your-username" +#password = "your-password" + +# Connect to InfluxDB with authentication +client = InfluxDBClient(url=url, token=token, org=org) +write_api = client.write_api(write_options=SYNCHRONOUS) + +# Read CSV file +with open('gps_data_raspberrypi.csv', 'r') as csvfile: + csvreader = csv.DictReader(csvfile) + + # Print column names for debugging + print("CSV columns:", csvreader.fieldnames) + + for row in csvreader: + # Flexible handling of columns + timestamp = None + measurement = "default_measurement" + fields = {} + + for key, value in row.items(): + if key.lower() == 'timestamp' and value: + timestamp = datetime.fromisoformat(value) + elif key.lower() == 'measurement': + measurement = value + else: + # Try to convert to float, if not possible, store as string + try: + fields[key] = float(value) + except ValueError: + fields[key] = value + + # If no timestamp found, use current time + if timestamp is None: + timestamp = datetime.utcnow() + + # Create a Point + point = Point(measurement).time(timestamp) + + # Add all fields to the point + for key, value in fields.items(): + point = point.field(key, value) + + # Write the point to InfluxDB + write_api.write(bucket=bucket, org=org, record=point) + + print(f"Wrote point: {measurement} at {timestamp} with fields {fields}") + +print("Data import completed") + +# Close the client +client.close() diff --git a/modbus_door.py b/modbus_door.py index 02331c4..2c25690 100644 --- a/modbus_door.py +++ b/modbus_door.py @@ -6,6 +6,7 @@ import time # Limpiar configuraciĆ³n previa de GPIO GPIO.setmode(GPIO.BCM) +GPIO.setwarnings(False) GPIO.cleanup() # MQTT Broker settings @@ -38,7 +39,7 @@ sensy_boi.close_port_after_each_call = True PIN_17 = 17 LuzPuerta = 18 LuzEncendido = 23 -GPIO.setup(PIN_17, GPIO.IN, pull_up_down=GPIO.PUD_UP) +GPIO.setup(PIN_17, GPIO.IN) GPIO.setup(LuzPuerta, GPIO.OUT) GPIO.setup(LuzEncendido, GPIO.OUT)