diff --git a/mqtt/motionSensor.py b/mqtt/motionSensor.py index 59a3b78..0cddded 100644 --- a/mqtt/motionSensor.py +++ b/mqtt/motionSensor.py @@ -11,8 +11,7 @@ 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" +motionTopic = "home/office/motion/status" username = 'mqtt' password = 'falrenforbreakfast' @@ -27,7 +26,7 @@ for proc in psutil.process_iter(): #12 is the pin number pir_sensor = 12 -GPIO.setmode(GPIO.BOARD) +GPIO.setmode(GPIO.BMC) GPIO.setup(pir_sensor, GPIO.IN) @@ -50,13 +49,12 @@ 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) + return current_state except KeyboardInterrupt: pass finally: @@ -65,28 +63,18 @@ def getValues(pir_sensor): -def publish(client, temp, humidity): +def publish(client, current_state): #Publish Temp Results - tempMsg = '{{ "temperature": "{}" }}'.format(temp) + motionMsg = '{{ "state": "{}" }}'.format(current_state) #tempMsg = temp - result = client.publish(tempTopic, tempMsg) + 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 {tempTopic}") + print(f"Failed to send message to topic {motionTopic}") - #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}") - @@ -94,8 +82,9 @@ while True: #Run functions client = connect_mqtt() # Connect to Broker client.loop_start() #Start loop - current_value = getValues(pir_sensor) - publish(client, current_value) + current_state = getValues(pir_sensor) + publish(client, current_state) client.loop_stop() #Stop loop client.disconnect() # Disconnect GPIO.cleanup() + time.sleep(5)