jdz/modbus_door.py

108 lines
3.2 KiB
Python
Raw Normal View History

2024-07-19 20:19:01 +00:00
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
2024-07-26 23:37:36 +00:00
import os
import minimalmodbus
import time
2024-07-19 20:19:01 +00:00
2024-07-26 23:37:36 +00:00
# Limpiar configuración previa de GPIO
GPIO.setmode(GPIO.BCM)
2024-07-27 01:11:44 +00:00
GPIO.setwarnings(False)
2024-07-26 23:37:36 +00:00
GPIO.cleanup()
2024-07-19 20:19:01 +00:00
2024-07-26 23:37:36 +00:00
# MQTT Broker settings
mqttBroker = "65.108.199.212"
2024-07-19 20:19:01 +00:00
myhost = os.uname()[1]
client = mqtt.Client(myhost)
client.connect(mqttBroker, 1883)
2024-07-25 19:28:42 +00:00
preferred_device = '/dev/ttyUSB0'
fallback_device = '/dev/ttyUSB5'
2024-07-23 03:02:56 +00:00
device_path = preferred_device if os.path.exists(preferred_device) else fallback_device
2024-07-25 19:28:42 +00:00
modbus_device = '/dev/modbus'
2024-07-23 03:02:56 +00:00
2024-07-19 20:19:01 +00:00
# Modbus configuration
mb_address = 1 # Modbus address
2024-07-25 19:28:42 +00:00
sensy_boi = minimalmodbus.Instrument(modbus_device, mb_address)
2024-07-19 20:19:01 +00:00
sensy_boi.serial.baudrate = 9600
sensy_boi.serial.bytesize = 8
sensy_boi.serial.parity = minimalmodbus.serial.PARITY_NONE
sensy_boi.serial.stopbits = 1
sensy_boi.serial.timeout = 0.5
sensy_boi.mode = minimalmodbus.MODE_RTU
# Configure buffer clearing and port closing settings
sensy_boi.clear_buffers_before_each_transaction = True
sensy_boi.close_port_after_each_call = True
# GPIO configuration
2024-07-19 20:29:45 +00:00
PIN_17 = 17
2024-07-22 01:55:14 +00:00
LuzPuerta = 18
2024-07-26 23:37:36 +00:00
LuzEncendido = 23
2024-07-27 01:11:44 +00:00
GPIO.setup(PIN_17, GPIO.IN)
2024-07-22 01:55:14 +00:00
GPIO.setup(LuzPuerta, GPIO.OUT)
GPIO.setup(LuzEncendido, GPIO.OUT)
2024-07-26 23:37:36 +00:00
# Mantener LuzEncendido en HIGH mientras el programa esté corriendo
GPIO.output(LuzEncendido, GPIO.HIGH)
# Lista para almacenar los datos pendientes
pending_data = []
2024-07-19 20:19:01 +00:00
2024-07-26 23:37:36 +00:00
def control_gpio():
status_17 = GPIO.input(PIN_17)
if status_17 == GPIO.LOW:
GPIO.output(LuzPuerta, GPIO.HIGH) # Luz Roja encendida
else:
GPIO.output(LuzPuerta, GPIO.LOW)
return status_17
try:
2024-07-19 20:19:01 +00:00
while True:
2024-07-26 23:37:36 +00:00
# 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)
2024-07-19 20:19:01 +00:00
except Exception as e:
print(f"Error: {str(e)}")
2024-07-26 23:37:36 +00:00
2024-07-19 20:19:01 +00:00
finally:
GPIO.cleanup()
2024-07-26 23:37:36 +00:00
print("Programa finalizado")