Ahh. This code needs to run all the time, so its not suitable for a command line sensor, which runs a command every time it wants to get data.
I searched on the site to see if anyone had used this library before, but I couldn’t see anything simple, so you’ll have to do it yourself, which is still relatively straightforward.
What needs to happen is that you create a binary sensor to receive data in HA, and modify this script to send data to the sensor.
I know of two ways to do this, using MQTT and using http. MQTT is more flexible and generic, but also more complex to set up, so for now I suggest you use a http binary sensor.
I have never actually used one, (I use mqtt mostly), but I think the modifications to the script will be something like
#!/usr/bin/env python3
import argparse
import signal
import sys
import time
import logging
import requests ### new
import json ### new
from rpi_rf import RFDevice
rfdevice = None
### new
url = 'http://localhost:8123/api/states/binary_sensor.radio'
header = "{'x-ha-access': 'YOUR_PASSWORD', 'content-type': 'application/json'}"
# I think you can leave aout the x-ha-access section if you don't have a password
# pylint: disable=unused-argument
def exithandler(signal, frame):
rfdevice.cleanup()
sys.exit(0)
logging.basicConfig(level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S',
format='%(asctime)-15s - [%(levelname)s] %(module)s: %(message)s', )
parser = argparse.ArgumentParser(description='Receives a decimal code via a 433/315MHz GPIO device')
parser.add_argument('-g', dest='gpio', type=int, default=27,
help="GPIO pin (Default: 27)")
args = parser.parse_args()
signal.signal(signal.SIGINT, exithandler)
rfdevice = RFDevice(args.gpio)
rfdevice.enable_rx()
timestamp = None
logging.info("Listening for codes on GPIO " + str(args.gpio))
while True:
if rfdevice.rx_code_timestamp != timestamp:
timestamp = rfdevice.rx_code_timestamp
logging.info(str(rfdevice.rx_code) +
" [pulselength " + str(rfdevice.rx_pulselength) +
", protocol " + str(rfdevice.rx_proto) + "]")
### new
if rfdevice.rx_code == oncode: ## you need to determine the code for ON that is returned
requests.post(url, headers=header, data=json.dumps({'state': 'on', 'attributes': {'friendly_name': 'Motion Detector'}}))
elif rfdevice.rx_code == offcode:
requests.post(url, headers=header, data=json.dumps({'state': 'off', 'attributes': {'friendly_name': 'Motion Detector'}}))
time.sleep(0.01)
rfdevice.cleanup()
But this isn’t tested at all, so probably has some errors, which you will have to find. I suggest you use curl to test the binary sensor as suggested in the docs before you try this code.
And eventually, you will need to make this code run at boot, by putting it in /etc/rc.local, but save that for another post.