2024-07-26 -

This commit is contained in:
Adolfo Delorenzo 2024-07-26 17:37:36 -06:00
parent 4052a233b9
commit 8943d559d8
4 changed files with 4547 additions and 48 deletions

View File

@ -87,7 +87,7 @@ print("Starting continuous GPS tracking. Press Ctrl+C to stop.")
while running:
get_gps_position()
time.sleep(15) # Wait for 10 seconds before the next reading
time.sleep(14) # Wait for 10 seconds before the next reading
ser.close()
GPIO.cleanup()

88
gps008.py Normal file
View File

@ -0,0 +1,88 @@
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)
# 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):
# Implement GPS data parsing logic here
pass
def write_to_csv(data):
file_exists = os.path.isfile(csv_filename)
with open(csv_filename, mode='a', newline='') as file:
writer = csv.writer(file)
if not file_exists:
writer.writerow(csv_headers)
writer.writerow(data)
def send_data(data):
# Implement data sending logic here
pass
def main():
while running:
try:
if ser.in_waiting > 0:
gps_data = ser.readline().decode('utf-8').strip()
parsed_data = parse_gps_data(gps_data)
if parsed_data:
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
latitude, longitude = parsed_data
data = [timestamp, latitude, longitude]
write_to_csv(data)
pending_data.append(data)
print(f"Logged data: {timestamp}, {latitude}, {longitude}")
# Try to send pending data
for data in pending_data:
try:
send_data(data)
pending_data.remove(data)
except Exception as e:
print(f"Error sending data: {e}")
break # Exit loop if sending fails
time.sleep(1)
except Exception as e:
print(f"Error during GPS tracking: {e}")
ser.close()
GPIO.cleanup()
print("Program terminated gracefully")
if __name__ == "__main__":
main()

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,14 @@
import minimalmodbus
import time, os
import serial
import RPi.GPIO as GPIO
import subprocess
import paho.mqtt.client as mqtt
import os
import minimalmodbus
import time
# Limpiar configuración previa de GPIO
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
# MQTT Broker settings
mqttBroker = "65.108.199.212"
myhost = os.uname()[1]
client = mqtt.Client(myhost)
@ -20,9 +22,7 @@ modbus_device = '/dev/modbus'
# Modbus configuration
mb_address = 1 # Modbus address
#sensy_boi = minimalmodbus.Instrument(device_path, mb_address)
sensy_boi = minimalmodbus.Instrument(modbus_device, mb_address)
#sensy_boi = minimalmodbus.Instrument(preferred_device, mb_address)
sensy_boi.serial.baudrate = 9600
sensy_boi.serial.bytesize = 8
sensy_boi.serial.parity = minimalmodbus.serial.PARITY_NONE
@ -35,55 +35,69 @@ sensy_boi.clear_buffers_before_each_transaction = True
sensy_boi.close_port_after_each_call = True
# GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Define pin numbers
PIN_17 = 17
PIN_23 = 23
LuzPuerta = 18
LuzEncendido = 25
# Set GPIO
GPIO.setup(PIN_17, GPIO.IN)
GPIO.setup(PIN_23, GPIO.IN)
LuzEncendido = 23
GPIO.setup(PIN_17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(LuzPuerta, GPIO.OUT)
GPIO.setup(LuzEncendido, GPIO.OUT)
# Mantener LuzEncendido en HIGH mientras el programa esté corriendo
GPIO.output(LuzEncendido, GPIO.HIGH)
try:
while True:
# Lista para almacenar los datos pendientes
pending_data = []
def control_gpio():
status_17 = GPIO.input(PIN_17)
if GPIO.input(23) == GPIO.HIGH:
print("Adquiriendo datos...")
# Read data from multiple registers
data = sensy_boi.read_registers(0, 2, 3)
print("")
print(f"Datos crudos {data}")
# Process the raw data
hum = data[0] / 10
temp = data[1] / 10
client.publish("iiot/"+ myhost +"/temperature", temp)
client.publish("iiot/"+ myhost +"/humidity", hum)
client.publish(f"iiot/{myhost}/door/pin17", str(status_17))
# Print the processed data
print("-------------------------------------")
print(f"Temperatura = {temp}\u00B0C")
print(f"Humedad relativa = {hum}%")
print("-------------------------------------")
print("")
time.sleep(15)
if GPIO.input(PIN_17) == GPIO.LOW:
if status_17 == GPIO.LOW:
GPIO.output(LuzPuerta, GPIO.HIGH) # Luz Roja encendida
else:
GPIO.output(LuzPuerta, GPIO.LOW)
GPIO.output(LuzEncendido, GPIO.HIGH)
return status_17
try:
while True:
# Controlar GPIO sin retraso
status_17 = control_gpio()
# Leer datos del sensor Modbus
data = sensy_boi.read_registers(0, 2)
hum = data[0] / 10
temp = data[1] / 10
# Datos a publicar
payload = {
"temperature": temp,
"humidity": hum,
"door_status": str(status_17)
}
try:
# Intentar publicar los datos actuales
client.publish(f"iiot/{myhost}/temperature", temp)
client.publish(f"iiot/{myhost}/humidity", hum)
client.publish(f"iiot/{myhost}/door/pin17", str(status_17))
# Intentar publicar los datos pendientes
for item in pending_data:
client.publish(f"iiot/{myhost}/temperature", item["temperature"])
client.publish(f"iiot/{myhost}/humidity", item["humidity"])
client.publish(f"iiot/{myhost}/door/pin17", item["door_status"])
pending_data.clear() # Limpiar la lista si se publicaron todos los datos
except Exception as e:
print(f"Error al publicar datos: {str(e)}")
pending_data.append(payload) # Guardar los datos en memoria
# Imprimir los datos procesados
print("-------------------------------------")
print(f"Temperatura = {temp}\u00B0C")
print(f"Humedad relativa = {hum}%")
print(f"Estado de la puerta (PIN 17) = {status_17}")
print("-------------------------------------\n")
time.sleep(30)
except Exception as e:
print(f"Error: {str(e)}")