Hi,
I have been trying for a few days to get a small MQTT Pyscript to work. Locally and through the console, the script works fine (connects, reads messages, etc.), but in the end, I want to set some Home Assistant input templates or template status.
For this reason, I put the code into a Pyscript file and set it as a service. When the service is run, I can see in the MQTT broker that it connects as it should. The input_number
is set to 0 and 1. However, I cannot get it to work where a log output is created or an input_template
is set to 2 in the onConnect
method.
It seems like the entire onConnect
(and following the onMessage, onDisconnect,…) method is not being called. There is no error in the log output. I have no idea where the issue could be. How can I, for example, create a log output or set the value?
I tried async/await as well, but it didn’t work either.
import paho.mqtt.client as mqttClient
import random
entityName = "input_number.statustester"
def connectLocalMQTT():
def onLocalMQTTConnect(client, userdata, flags, rc):
state.set(entityName, 2, attributes)
if rc == 0:
log.error("Connected to MQTT Broker!")
else:
log.error("Failed to connect, return code %d\n", rc)
localMQTTClient = mqttClient.Client(LOCAL_MQTT_CLIENT+str(random.randint(0, 100)))
localMQTTClient.username_pw_set(LOCAL_MQTT_USER, LOCAL_MQTT_PWD)
localMQTTClient.on_connect = onLocalMQTTConnect
localMQTTClient.connect(LOCAL_MQTT_HOST, LOCAL_MQTT_PORT)
@service
def mqttConnectTest():
global attributes
attributes = state.getattr(entityName)
state.set(entityName, 0, attributes)
state.set(entityName, 1, attributes)
connectLocalMQTT()