Files
homeassistantPi/mqtt/motionSensor.py
2022-12-26 02:48:53 -05:00

102 lines
2.6 KiB
Python

import time
import board
import adafruit_dht
import psutil
import random
import RPi.GPIO as GPIO
import time
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()
#12 is the pin number
pir_sensor = 12
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pir_sensor, GPIO.IN)
#Function Definitions
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(pir_sensor):
current_state = 0
try:
while True:
time.sleep(0.1)
current_state = GPIO.input(pir_sensor)
#Condition if motion is detected
if current_state == 1:
print("GPIO pin %s is %s" % (pir_sensor, current_state))
time.sleep(5)
except KeyboardInterrupt:
pass
finally:
return current_state
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}")
while True:
#Run functions
client = connect_mqtt() # Connect to Broker
client.loop_start() #Start loop
current_value = getValues(pir_sensor)
publish(client, current_value)
client.loop_stop() #Stop loop
client.disconnect() # Disconnect
GPIO.cleanup()