91 lines
2.2 KiB
Python
91 lines
2.2 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
|
|
motionTopic = "home/office/motion/status"
|
|
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.BCM)
|
|
|
|
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(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))
|
|
return current_state
|
|
else:
|
|
return current_state
|
|
except KeyboardInterrupt:
|
|
pass
|
|
finally:
|
|
return current_state
|
|
|
|
|
|
|
|
|
|
def publish(client, current_state):
|
|
#Publish Temp Results
|
|
motionMsg = '{{ "state": "{}" }}'.format(current_state)
|
|
#tempMsg = temp
|
|
result = client.publish(motionTopic, motionMsg)
|
|
status = result[0]
|
|
if status == 0:
|
|
#print(f"Send `{tempMsg}` to topic `{tempTopic}`")
|
|
pass
|
|
else:
|
|
print(f"Failed to send message to topic {motionTopic}")
|
|
|
|
#Run functions
|
|
client = connect_mqtt() # Connect to Broker
|
|
client.loop_start() #Start loop
|
|
while True:
|
|
current_state = getValues(pir_sensor)
|
|
publish(client, current_state)
|
|
# print(current_state)
|
|
|
|
client.loop_stop() #Stop loop
|
|
client.disconnect() # Disconnect
|
|
# GPIO.cleanup()
|