Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit mqtt forever_loop?

Tags:

python

mqtt

I created a program to receive data, recently.

And I want to break the loop When I receive a specific data.

For example, if I receive "1" to another machine, then my system will regard it as an illegal number, then it will break the loop to stop receiving data.

Here is my code in the below, and you can also see client.loop_stop() in my code. But it not works.

I have also tried sys.exit() in my code.

Although it works in this case, it is not suitable to be utilized in other situation.

So I am wondering about how to break the loop of the client, I don't want to close the whole system by sys.exit().

import paho.mqtt.client as mqtt
# This is the Subscriber
a=""
def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))
  client.subscribe("hello")

def on_message(client, userdata, msg):
    info=msg.payload.decode()
    print info
    if str(info)=='1':
      print "OK"
      client.loop_stop()


client = mqtt.Client()
client.connect("myIp",1883,60)

client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
like image 676
陳俊良 Avatar asked Oct 19 '25 17:10

陳俊良


1 Answers

In order to stop loop_forever, you must use client.disconnect, not loop_stop.

like image 130
N.D.C. Avatar answered Oct 21 '25 07:10

N.D.C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!