paho.mqtt.python
paho.mqtt.python copied to clipboard
on_pre_connect not optional?
Hi,
I just migrated a ( rather large) script to 1.6.1, and for some reason I had to add something like this
self.client.on_pre_connect = self.on_pre_connect
def on_pre_connect(self, *args):
"""This seems to be needed due to a bug in paho-1-6-1"""
self.logger.debug('running on_pre_connect, apparently paho needs this now')
for it to connect. Otherwise it would complain about the missing overwrite above. After quickly glancing at the code this seems to be meant as optional, which for me it apparently is not.
KR, Moritz
I stay trying this: https://www.newtoncbraga.com.br/index.php/microcontroladores/54-dicas-de-pic/16748-primeiro-programa-phyton-com-mqtt-na-raspberry-pi-introducao.html
I have same issue:
AttributeError: 'Client' object has no attribute '_on_pre_connect'
I try with "mqtt.eclipseprojects.io" and/Or “test.mosquitto.org”
But not Solved yet
I am just trying to run the example but i got the issue as shown below:
vivek@vivek-zs:/mnt/d/Softwares/MQTT/paho.mqtt.python/examples$ python3 loop_select.py
Using client_id / topic: paho-mqtt-python/issue72/6ddb7a35-0916-457d-b288-ea22697ffb84
Starting
Traceback (most recent call last):
File "/mnt/d/Softwares/MQTT/paho.mqtt.python/examples/loop_select.py", line 89, in
Could anyone please help me resolving this issue?
Echoing above observations but will dig in further in the coming weeks. Something has changed!
Preamble I used to get satisfactory responses with an utility from https://github.com/jpmens/check-mqtt but had to stop using it for nearly two years. I tried to reuse the, check_mqtt, with a fresh install from /usr/local/lib/python3.9/dist-packages/paho_mqtt-1.6.1-py3.9.egg but the following error message was generated:
./check-mqtt.py -H localhost -t nagios/ListenForPing -s nagios/PublishPongTo -l ping -v pong
OK - message from nagios/PublishPongTo at localhost in 0.05s | response_time=0.05 value=pong
CRITICAL - Connection to localhost:1883 failed: 'Client' object has no attribute '_on_pre_connect'
-bash: OK: command not found
Issue I don't need help with the Nagios Remote Executor Plugin (viz. check_mqtt). I need some explanation on how to workaround the message as a general rule if at all possible:
Pardon my ignorance in these matters but I'm simply trying to monitor if broker is alive. Thanks for your understanding.
'Client' object has no attribute '_on_pre_connect'. Did you mean: 'on_pre_connect'
Regards.
Hello
I have the same issue with following: `import glob import time import paho.mqtt.client as mqtt import paho.mqtt.publish as publish import ConfigParser import json
clientname = "Pellmon" hostname = 'x.x.x.x' port = 1883 timeout = 60
Connect MQTT
MQTT Start
callback for CONNACK response from the server.
def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc))
callback for received messages
def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload))
client = mqtt.Client(clientname) client.on_connect = on_connect client.on_message = on_message
client.username_pw_set("MqttBroker", "mqtt") client.connect(hostname, port, timeout)
client.loop_start()
while True:
for sensor in glob.glob("/sys/bus/w1/devices/28-00000016f2f6/w1_slave"): id = sensor.split("/")[5]
try:
f = open(sensor, "r")
data = f.read()
f.close()
if "YES" in data:
(discard, sep, reading) = data.partition(' t=')
t = float(reading) / 1000.0
print("{} {:.1f}".format(id, t))
if t > 1:
#Gem data til HA via MQTT
data = round(t,1)
topic = "home-assistant/pillefyr/temperatur"
client.publish(topic, data)
else:
print("Gemmes ikke")
else:
print("999.9")
except:
pass
time.sleep(2.0) `
@Nomisdk86, I wish I had the expertise to submit a pull request! :)
I was receiving this:
Traceback (most recent call last): File "/home/alexandrosferent/mqttSubTest.py", line 13, in <module> client.connect(broker_address, broker_port, 60) File "/usr/local/lib/python3.9/dist-packages/paho_mqtt-1.6.1-py3.9.egg/paho/mqtt/client.py", line 914, in connect return self.reconnect() File "/usr/local/lib/python3.9/dist-packages/paho_mqtt-1.6.1-py3.9.egg/paho/mqtt/client.py", line 1045, in reconnect on_pre_connect = self.on_pre_connect File "/usr/local/lib/python3.9/dist-packages/paho_mqtt-1.6.1-py3.9.egg/paho/mqtt/client.py", line 1863, in on_pre_connect return self._on_pre_connect AttributeError: 'Client' object has no attribute '_on_pre_connect'
I run :
pip3 uninstall paho-mqtt pip3 install paho-mqtt sudo apt-get update sudo apt-get upgrade
And it stopped giving me the traceback. I am running this on a raspbian so I guess, adjust to your operating system?
Any news about this issue ?? Im having the same...
AttributeError: 'Client' object has no attribute '_on_pre_connect'
, im using the publish.single() function
The "on_pre_connect callback" function is not an option, you have to add the callback even if you are not using it. So add the function: def on_pre_connect(client,data): return
and you create the callback with: client.on_pre_connect=on_pre_connect
Thanks, @termic1!
Regards.
Has this issue been resolved or not? If yes, what should I do to resolve it? (my details are at the beginning of this issue)
Has this issue been resolved or not? If yes, what should I do to resolve it? (my details are at the beginning of this issue)
Did you try what OP wrote in their first post? What's the result then?
Tested using the code linked in the first comment without issue (well did need to fix the broker and brackets in print
).
As such it appears this is fixed. However the error mentions python 2.7 which is no longer supported (in the upcoming release) so I'm guessing it may still be an issue with older python releases. Flagging as "More Info Needed" so anyone still seeing this can provide input.
import paho.mqtt.client as mqtt
import sys
#definicoes do MQTT
Broker = "mqtt.eclipseprojects.io" #broker publico utilizado.
porta_broker = 1883 #porta utilizada para comunicacao com o broker MQTT
#utilize a porta 1883 para comunicacao com conexao nao segura
keep_alive_broker = 60 #tempo (em segundos) do keep-alive
topico_subscribe = "MQTTRaspPiINCB" #topico MQTT que o programa ira "ouvir" (fazer subscribe)
#dica: troque o nome do topico por algo "unico",
#Dessa maneira, ninguem ira saber seu topico de
#subscribe e interferir em seus testes
#Callback - conexao ao broker realizada
def on_connect(client, userdata, flags, rc):
print("[STATUS] Conectado ao Broker.")
#faz subscribe automatico no topico
client.subscribe(topico_subscribe)
#Callback - mensagem recebida do broker
#toda vez que uma mensagem for recebida do broker, esta funcao sera chamada
def on_message(client, userdata, msg):
MensagemRecebida = str(msg.payload)
print("[MSG RECEBIDA] Topico: "+msg.topic+" / Mensagem: "+MensagemRecebida)
#programa principal:
try:
print("[STATUS] Inicializando MQTT...")
#inicializa MQTT:
#cria client MQTT e define funcoes de callback de conexao (client.on_connect)
#e recepcao de dados recebidos (client.on_message)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
#faz a conexao ao broker MQTT
client.connect(Broker, porta_broker, keep_alive_broker)
#mantem o MQTT funcionando por tempo indeterminado, sendo que todas as
#mensagens recebidas vao fazer a funcao de callback de dados recebidos
#(on_message) ser chamada
client.loop_forever()
except KeyboardInterrupt:
print ("\nCtrl+C pressionado, encerrando aplicacao e saindo...")
sys.exit(0)
Note: This is part of an exercise to clean up old issues so that the project can move forwards.