jdz/minimalmodbus.py
2024-07-05 09:05:28 -06:00

71 lines
1.9 KiB
Python

import minimalmodbus
import time, os
import serial
import RPi.GPIO as GPIO
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)
# Modbus configuration
mb_address = 1 # Modbus address
sensy_boi = minimalmodbus.Instrument('/dev/ttyUSB0', 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.setup(17, GPIO.IN)
try:
while True:
if GPIO.input(17) == 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("iiot/"+ myhost +"/door", door)
# Print the processed data
print("-------------------------------------")
print(f"Temperatura = {temp}\u00B0C")
print(f"Humedad relativa = {hum}%")
print("-------------------------------------")
print("")
time.sleep(1)
except KeyboardInterrupt:
print("Programa terminado por el usuario")
except Exception as e:
print(f"Error: {str(e)}")
finally:
GPIO.cleanup()
print("Programa finalizado")