Hi, I have a simple python script in rpi which reads distance sensor and send True or False over mqtt depending some criteria
import time
import argparse
import board
import busio
import adafruit_vl53l0x
import settings
i2c = busio.I2C(board.SCL, board.SDA)
vl53 = adafruit_vl53l0x.VL53L0X(i2c)
import paho.mqtt.client as mqtt
# Argument parser setup
parser = argparse.ArgumentParser(description="Distance measurement with MQTT")
parser.add_argument('--verbose', action='store_true', help='Enable verbose mode')
args = parser.parse_args()
# MQTT setup
client = mqtt.Client(client_id=settings.MQTT_CLIENT_ID, protocol=mqtt.MQTTv5)
client.username_pw_set(settings.MQTT_USERNAME, settings.MQTT_PASSWORD)
client.connect(settings.MQTT_BROKER, settings.MQTT_PORT, 60)
# Subscribe to the state topic
client.subscribe(settings.MQTT_TOPIC_SUBSCRIBE)
# Variables to track time and state
start_time = time.time()
state = None
while True:
distance = vl53.range
current_time = time.time()
if args.verbose:
print(f"Measured distance: {distance} mm")
if distance < settings.DISTANCE_THRESHOLD:
if state != "True" and current_time - start_time >= settings.TIME_BELOW_THRESHOLD:
client.publish(settings.MQTT_TOPIC_PUBLISH, "True")
if args.verbose:
print("State changed to True and published to MQTT")
state = "True"
start_time = current_time # Reset start_time when state changes to True
else:
if state != "False" and current_time - start_time >= settings.TIME_ABOVE_THRESHOLD:
client.publish(settings.MQTT_TOPIC_PUBLISH, "False")
if args.verbose:
print("State changed to False and published to MQTT")
state = "False"
start_time = current_time # Reset start_time when state changes to False
time.sleep(0.5)
and
MQTT_TOPIC_SUBSCRIBE = 'homeassistant/sensor/VL53L0Xr/state'
MQTT_TOPIC_PUBLISH = 'homeassistant/sensor/VL53L0Xr/status'
I see from my mqtt broker that it connects to EMQX so I think it should work. I have in my ha config these lines:
mqtt:
- binary_sensor:
name: "Distance Sensor State"
state_topic: "homeassistant/sensor/VL53L0Xr/status"
device_class: "motion"
qos: 0
value_template: "{{ value_json.state }}"
It creates the sensor but state is “unknown”
Any help would be nice!
Thx
Mika