Cool i also do basically the same thing with a pir sensor connected to a raspberry pi.
configuration.yaml:
binary_sensor:
- platform: mqtt
name: "MotionSensor"
state_topic: “movement/motionsensor/motion”
python script: REVISED
import RPi.GPIO as GPIO
import time
import requests
GPIO.setmode(GPIO.BCM)
GPIO.setup(pinnumber, GPIO.IN) #PIR
#GPIO.setup(24, GPIO.OUT) #BUzzer
url = 'http://ipaddress:8123/api/states/binary_sensor.motionsensor'
headers = {'x-ha-access': 'password', 'content-type': 'application/json'}
data = '{"state": "on", "attributes": {"friendly_name": "MotionSensor"}}'
url1 = 'http://ipaddress:8123/api/states/binary_sensor.motionsensor'
headers1 = {'x-ha-access': 'password', 'content-type': 'application/json'}
data1 = '{"state": "off", "attributes": {"friendly_name": "MotionSensor"}}'
def sensor():
try:
time.sleep(2) # to stabilize sensor
while True:
if GPIO.input(pinnumber):
#GPIO.output(24, True)
#time.sleep(0.5) #Buzzer turns on for 0.5 sec
#GPIO.output(24, False)
#print("Motion Detected...")
#localtime = time.asctime( time.localtime(time.time()) )
#print(localtime)
response = requests.post(url, headers=headers, data=data)
#print(response.text)
time.sleep(5) #to avoid multiple detection
response1 = requests.post(url1, headers=headers1, data=data1)
#print(response1.text)
time.sleep(0.1) #loop delay, should be less than detection delay
except:
GPIO.cleanup()
sensor()
sensor()
chmod +x script.py
i do a an autostart using sudo nano ~/.config/lxsession/LXDE-pi/autostart
then add @sudo python script.py
at the bottom of the file.
Also check this out: