eclipse / paho.mqtt.python

paho.mqtt.python
Other
2.17k stars 723 forks source link

How to call publish function independently #699

Open lgeuder opened 1 year ago

lgeuder commented 1 year ago

Hi, I have created a class that should handle my mqtt publish dynamically (I used the class example:) )

import paho.mqtt.client as mqtt

class MQTTClient(mqtt.Client):

   def on_connect(self, mqttc, obj, flags, rc):
      print("rc: "+str(rc))

   def on_connect_fail(self, mqttc, obj):
      print("Connect failed")

   def on_message(self, mqttc, obj, msg):
      print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

   def on_publish(self, mqttc, obj, mid):
      print("mid: "+str(mid))

   def on_subscribe(self, mqttc, obj, mid, granted_qos):
      print("Subscribed: "+str(mid)+" "+str(granted_qos))

   def on_log(self, mqttc, obj, level, string):
      print(string)

   def run(self):
      self.connect("localhost", 1883, 60)
      self.subscribe("state", 0)
      rc = 0
      while rc == 0:
         rc = self.loop()
      return rc

   def publish(self, channel="state", payload="payload"):
      #self.connect("localhost", 1883, 60)
      self.publish(channel, payload=payload)

I have added this publish function in hope that i can call mqttc.publish() from whereever I want. As this is not working at all I am beginning to think that I haven't understood way mqtt works... Is there a way I can open a connection (in a Thread - it should not block my script where I call publish()) and just pass channel and payload an this gets published to the localhost which I can connect?

ralight commented 1 year ago

I would suggest using loop_start() instead of the while loop that calls self.loop() - this creates a background thread that doesn't block your code and will reconnect for you in case of a connection failure. I would also suggest putting your call to subscribe() in your on_connect callback - that means it will be recreated on a reconnect.

Finally, in your publish() function you should call super.publish() to access the publish function of the base class.

I hope that helps.