import minimalmodbus import time, os import serial import RPi.GPIO as GPIO import subprocess import paho.mqtt.client as mqtt # MQTT Broker settings mqttBroker ="65.108.199.212" myhost = os.uname()[1] client = mqtt.Client(myhost) client.connect(mqttBroker, 1883) preferred_device = '/dev/ttyUSB5' fallback_device = '/dev/ttyUSB0' device_path = preferred_device if os.path.exists(preferred_device) else fallback_device # Modbus configuration mb_address = 1 # Modbus address sensy_boi = minimalmodbus.Instrument(device_path, mb_address) 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 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) GPIO.setup(LuzPuerta, GPIO.OUT) GPIO.setup(LuzEncendido, GPIO.OUT) try: while True: status_17 = GPIO.input(PIN_17) if GPIO.input(23) == GPIO.HIGH: print("Adquiriendo datos...") # subprocess.run(['python3', '/home/pi/jdz/gps001.py']) # 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(5) if GPIO.input(PIN_17) == GPIO.LOW: GPIO.output(LuzPuerta, GPIO.HIGH) # Luz Roja encendida else: GPIO.output(LuzPuerta, GPIO.LOW) GPIO.output(LuzEncendido, GPIO.HIGH) time.sleep(15) except Exception as e: print(f"Error: {str(e)}") finally: GPIO.cleanup() print("Programa finalizado")