pythonmqttpaho

mqtt not send data when qos 2


I am creating class for connect and send the data throw mqtt. when the qos 0 or 1, it works fine. but in qos 2, its not send the data.

from paho.mqtt import client as mqtt


class MqttClient:
    """ Manage connection """

    def __init__(self, clientId, port, ip) -> None:
        self.clientId = clientId
        self.port = port
        self.broker = ip
        self.connect()

    def connect(self):
        """ Connects to an mqtt client """
        client = mqtt.Client(client_id=self.clientId)
        client.connect(self.broker, self.port)
        self._client = client

    def pub(self, topic: str, payload: str):
        self.client.publish(topic, payload, qos=2)

    def disconnect(self):
        self.client.disconnect()

    @property
    def client(self):
        return self._client

this is my class. I send the data and check by mqtt explorer. qos 0 or 1 data recived, but not in 2


Solution

  • QOS 2 messages require sending multiple packets back and forth to the broker. The Paho client can only process these multiple packets if the network loop is running.

    https://eclipse.dev/paho/files/paho.mqtt.python/html/index.html#network-loop

    You are not starting the network loop anywhere in your code.

    Simplest fix is to add client.loop_start() to the end of your connect function

        def connect(self):
            """ Connects to an mqtt client """
            client = mqtt.Client(client_id=self.clientId)
            client.connect(self.broker, self.port)
            self._client = client
            client.loop_start()
    
    ...
    
    
        def disconnect(self):
            self.client.disconnect()
            self.client.loop_stop()