So there’re no fancy quotes in the scripts. The MQTT used is the Add-on from HA (Mosquitto broker), and at one point it did work, the Lovelace displaying the state of the MQTT PIR sensor, but now it won’t show the state of the sensor, including when I listen to the topic ha/pir in the MQTT Integration page. Where did it go wrong and what I should fix? Either way, the Python script in the Terminal worked perfectly, but the HA won’t receive its results.
OK, so the first thing that jumps out at me, is that the python script does not seem to use authentication to publish the message to the MQTT server. So check if authentication is actually needed.
Home Assistant will show any and all data flowing on the topic, whether it understands it or not. The fact there is no data flowing on the topic, means it literally is not being published.
EDIT:
You will be able to verify this by opening a terminal on the Pi and sudo apt-get install mosquitto-clients and then running the command mosquitto_sub -h [broker_ip_address] -u [username] -P [password] -t \# that will show you everything flowing through every topic, if it’s very busy and you want to only see the ha/pir topic, change -t \# to -t ha/pir
OK, so far, it seems to be working when I put the Python script in the places that has the folder paho.mqtt.python (I didn’t previously), and when I separated the import part and the GPIO part and added importing paho.mqtt.client, so it’s like this currently:
import RPi.GPIO as GPIO
import time
import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt
GPIO.setmode(GPIO.BCM)
GPIO_PIR = 6
But I’ll stop by again when it stopped working again (hopefully not, obviously).
Seems to be inconsistent, at time it works, at time it doesn’t, and at another time it works but not perfectly (like the indicator of MQTT device PIR will be turned on or off after 2 or 3 times the PIR changed state). What are the factors of the MQTT work here?
And then (though it’s preferable to not use publish.single, as when the user connects to the MQTT server, it’ll send an update and then disconnects. But MQTT is designed for connect and stay connected) add auth=auth on the publish.single part:
publish.single("ha/pir", "false", retain=True, hostname="(my IP address)", auth=auth)