Search code examples
pythonmultithreadingtimerraspberry-pimqtt

Thread is blocking the console


I'm currently working on a little MQTT-Projekt where I want to connect a raspberry pi to a windows pc. The connection between those two works perfectly but the problem is that the pc (where the MQTT-Broker is on) starts later than the pi and therefor the connection has to be delayed.

I did a while loop around the client.connect() method so it will try to connect every 2 seconds. But in my case it tries for example 5 times and then stops.

I also implementet a thread that starts a timer that checks if I received a message. The problem with the timer is that it jumps sometimes from 20 seconds to 100 for example.

I guess I misunderstood threads and I made a mistake with it but I don't know where.

My code looks like this:

import threading
import time
import paho.mqtt.client as mqtt

shutdown = 0

def on_connect(client, userdata, flags, rc):
   print("Connected with result code "+str(rc))
   client.subscribe("CoreElectronics/test")
   client.subscribe("CoreElectronics/topic")

def on_message(client, userdata, msg):
   global shutdown
   shutdown = time.time()
   print(msg.topic+" "+str(msg.payload))

def check_connect():
   try:
      client.connect("192.168.xx.xx", 1883, 60)
      return True
   except:
      print("No connection")
      return False

def timer_count():
    global shutdown
    shutdown = time.time()
    elapsed = 0
    while elapsed < 10:
         elapsed = time.time()-shutdown
         print("no Message")
         time.sleep(2)

t1 = threading.Thread(target = timer_count)
t1.start()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

while(True):
    if check_connect():
        break;
    else:
       time.sleep(2)


client.loop_forever()

Running this program prints out:

No Message
No Connection
No Message
No Message
No Message
No Message

But in my case it should print out both things simultaneously all the time. After it doesn't print out No Connection it also doesn't connect to the Broker when it is running...


Solution

  • I made it work by not doing a while loop around the client.connect(xxx). I first checked with the netiface library if the interface was there and then try to connect to it. In this case it waited for the connection and then it worked. Thanks to @JohnAnderson I learned that the client.connect(xxx) is blocking and therefore cause some problems.