pythonmqttmosquittopaho

Python MQTT on_subscribes fires an extra time


I am using loop_start and loop. I subscribe to 1 topic in the on_connection callback. However, the on_subscribe callback is fired 2 times. Then the second comes, the next loop() gets an error

loop: bad char in struct format

Here is the main section of the code, minus the callbacks (which are just print statements.

    self.client.connect(self.broker, self.port, 60)
    self.client.loop_start()

    self.client.on_connect = self.onConnect
    self.client.on_publish = self.onPublish
    self.client.on_subscribe = self.on_subscribe

 
  def run(self):
    while not self.client.is_connected():
      time.sleep(1)

    self.running = True
    while(self.running):
      row = self.db.getMessage()
      if(row != None):
        message = row[2]
        topic = 'data'
        timestamp = strftime("%Y-%m-%d %H:%M:%S", localtime())
        try:
          ret = self.client.publish(topic, message, 0)
          pass
        except Exception as ex:
          print(str(ex))
      try:
        self.client.loop(0.1)
      except Exception as ex:
        print('loop:', str(ex))

Any suggestions as to how to prevent the subscribe callback and more importantly the bad char in struct format error?


Solution

  • As per the docs "Do not mix the different loop functions".

    You are calling self.client.loop_start() which "runs a thread in the background to call loop() automatically"; you then call self.client.loop(0.1) within the loop in your code. This will lead to unpredictable results (loop is not designed to be run multiple times concurrently, so does not employ synchronization).

    As the docs say "Using loop() on it's own is no longer recommended" I'd suggest replacing the self.client.loop(0.1) with a time.sleep() or equivalent.