I am trying to get a python script to listen in to a topic which is successfully being broadcast from home assistant. I can get MQTT integration to see it but I am struggling to get the python code to work.
HA is on a debian12 machine and in a docker, have checked and everything appears to be running the docker correctly.
appdaemon says: 2025-01-09 14:13:42.292413 CRITICAL MQTT: Could not Complete Connection to Broker, please Ensure Broker at URL 127.0.0.1:1883 is correct and broker is not down and restart Appdaemon
If you have a working mosquitto_broker can you please post the uncommented lines in your mosquitto.config please? Having a hell of a time getting it set up at all.
Here’s a generic guide to getting the MQTT broker add-on working
The best test is to install a MQTT tool like https://mqtt-explorer.com/ and use it to connect to the broker. Try IPv4 addresses first, not hostnames, not IPv6.
The command line tool mosquitto_sub is also useful to extract particular topics - I’ve used it in a simple Bash script before without need for Python (although the paho.mqtt libraries also work well):
thanks, I did go through the guide first, but still could not get anywhere in regards to getting appdaemon to connect to the broker. I can see that my HA script it is creating notifications and I can create another script to react to it, so the broker is working but, I want the python script to then do something with the data it receives and push this into an sql database.
Im sure its either got something to do with using local host, core-broker or the direct ip address that apdaemon config is using or the username/pwd but I have tried everything, I can think of.
As a test, change your Pyton code to subscribe to the wildcard topic of #, or somethingknown/# - you should get a load of callbacks.
I’m guessing you have tested using MQ Explorer and can see the topic? (pressing this point as it is usually the little things you don’t expect that are broken…)
mosquitto_sub is another good test to prove your knowledge and sysadmin - and does work. Here’s a Bash script that subscribes to a MQTT topic, extracts the value, and then logs the result.
#!/bin/bash
# subscribe to a topic waiting for ONE value, print only the payload, use tr to strip " quotes:
LOG_STRING=$(/usr/bin/mosquitto_sub -C 1 -q -d -i "monitor" -h HOST --username 'NAME' --pw "PASS" -v -t 'stat/FOO' -F %p | tr -d '"')
/bin/echo "$LOG_STRING" >> test.log