├── README.md └── raspi-pir-mqtt.py /README.md: -------------------------------------------------------------------------------- 1 | # raspi-pir-mqtt-homeassistant 2 | Simple script to read PIR sensor on Raspberry Pi and publish to MQTT, for use in HomeAssistant. 3 | 4 | Instructions: 5 | * Uses Paho MQTT library & process managed by forever 6 | * Connect PIR sensor to 5v, Ground, and GPIO 4 on the Raspberry Pi 7 | * Edit the script with your MQTT password, username, and host IP. You change the PIR GPIO if you hooked up to a different one 8 | * forever start -c python3 raspi-pir-mqtt.py 9 | 10 | In Home Assistant, using the MQTT Binary Sensor component: 11 | https://home-assistant.io/components/binary_sensor.mqtt/ 12 | 13 | ```yaml 14 | binary_sensor: 15 | - platform: mqtt 16 | state_topic: "CHANNEL/Motion/Switch" 17 | device_class: motion 18 | payload_on: "1" 19 | payload_off: "0" 20 | name: "Motion Sensor" 21 | ``` 22 | -------------------------------------------------------------------------------- /raspi-pir-mqtt.py: -------------------------------------------------------------------------------- 1 | import time 2 | import paho.mqtt.publish as publish 3 | import paho.mqtt.client as mqtt 4 | 5 | # 6 | # Connect to MQTT 7 | # Read PIR sensor 8 | # On motion: send 1 9 | # Wait 4 seconds, turn off 10 | # 11 | # Run with forever 12 | 13 | auth = { 14 | 'username’:”MQTT_USER”, 15 | 'password’:”MQTT_PASS” 16 | } 17 | 18 | from gpiozero import MotionSensor 19 | 20 | 21 | pir = MotionSensor(4) 22 | 23 | while True: 24 | if pir.motion_detected: 25 | # print('Motion On') 26 | publish.single(“CHANNEL/Motion/Switch", 27 | payload="1", 28 | hostname=“MQTT_HOST_IP”, 29 | client_id="pi", 30 | auth=auth, 31 | port=1883, 32 | protocol=mqtt.MQTTv311) 33 | time.sleep(4) 34 | # print('Motion Off') 35 | publish.single(“CHANNEL/Motion/Switch", 36 | payload="0", 37 | hostname=“MQTT_HOST_IP”, 38 | client_id="pi", 39 | auth=auth, 40 | port=1883, 41 | protocol=mqtt.MQTTv311) --------------------------------------------------------------------------------