93 lines
2.5 KiB
Python
93 lines
2.5 KiB
Python
import time
|
|
import board
|
|
import adafruit_dht
|
|
import psutil
|
|
import random
|
|
|
|
from paho.mqtt import client as mqtt_client
|
|
|
|
name = 'test'
|
|
broker = '192.168.0.196'
|
|
port = 1883
|
|
tempTopic = "home/office/climate/temp"
|
|
humidTopic = "home/office/climate/humid"
|
|
username = 'mqtt'
|
|
password = 'falrenforbreakfast'
|
|
|
|
client_id = f'python-mqtt-office-{random.randint(0, 1000)}'
|
|
|
|
#We first check if a libgpiod process is running. If yes, we kill it!
|
|
for proc in psutil.process_iter():
|
|
if proc.name() == 'libgpiod_pulsein' or proc.name() == 'libgpiod_pulsei':
|
|
proc.kill()
|
|
|
|
#D20 is the pin number, DHT11 is the sensor type
|
|
sensor = adafruit_dht.DHT11(board.D20)
|
|
|
|
def connect_mqtt():
|
|
def on_connect(client, userdata, flags, rc):
|
|
if rc == 0:
|
|
print("Connected to MQTT Broker!")
|
|
else:
|
|
print("Failed to connect, return code %d\n", rc)
|
|
|
|
client = mqtt_client.Client(client_id)
|
|
client.username_pw_set(username, password)
|
|
client.on_connect = on_connect
|
|
client.connect(broker, port)
|
|
return client
|
|
|
|
|
|
def getValues(sensor):
|
|
try:
|
|
temp = sensor.temperature
|
|
humidity = sensor.humidity
|
|
|
|
#convert to Farenheit
|
|
temp = (temp * 1.8) + 32
|
|
#Round the decimals
|
|
temp = round(temp, 2)
|
|
#print("Temperature: {}*F Humidity: {}% ".format(temp, humidity))
|
|
except RuntimeError as error:
|
|
print(error.args[0])
|
|
time.sleep(2.0)
|
|
except Exception as error:
|
|
sensor.exit()
|
|
raise error
|
|
return temp, humidity
|
|
|
|
|
|
def publish(client, temp, humidity):
|
|
#Publish Temp Results
|
|
tempMsg = '{{ "temperature": "{}" }}'.format(temp)
|
|
#tempMsg = temp
|
|
result = client.publish(tempTopic, tempMsg)
|
|
status = result[0]
|
|
if status == 0:
|
|
#print(f"Send `{tempMsg}` to topic `{tempTopic}`")
|
|
pass
|
|
else:
|
|
print(f"Failed to send message to topic {tempTopic}")
|
|
|
|
#Publish Humid Results
|
|
humidMsg = '{{ "humidity": "{}" }}'.format(humidity)
|
|
result = client.publish(humidTopic, humidMsg)
|
|
status = result[0]
|
|
if status == 0:
|
|
#print(f"Send `{humidMsg}` to topic `{humidTopic}`")
|
|
pass
|
|
else:
|
|
print(f"Failed to send message to topic {humidTopic}")
|
|
|
|
time.sleep(5.0)
|
|
|
|
|
|
while True:
|
|
client = connect_mqtt()
|
|
client.loop_start()
|
|
temp, humidity = getValues(sensor)
|
|
publish(client, temp, humidity)
|
|
time.sleep (5.0)
|
|
client.loop_stop() #Stop loop
|
|
client.disconnect() # disconnect
|