MQTT connect: clean_seesion True and False

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Posts: 22
Joined: Sat Oct 29, 2016 2:29 pm

MQTT connect: clean_seesion True and False

Post by BigMan » Mon Jan 15, 2018 8:43 pm


With my Sonoff's, I want to turn on/off my lamps.
I believe, for that it is not necessary to store mqtt messages at the mqtt-broker.
Hence, I connect to the broker with connect(clean_session=False) ... but this doesn't work.
But, when I do connect(session=True), it works at least for many hours (but it seems to be unstable, because after one day, the connection is lost. I assume because my router reboots each night and Wlan-connection is lost ... but this is another story.)

Following, the code for establishing mqtt-connection:

Code: Select all

class Mqtt:
    global status_flag
    def __init__(self, client_id, broker_ip, broker_port, topic):
        self.connect_with_broker(client_id, broker_ip, broker_port, topic)

    def connect_with_broker(self, client_id, broker_ip, broker_port, topic):
        self.c = MQTTClient(client_id, broker_ip, broker_port)
        self.c.set_last_will("last_will", client_id + " said good-bye")
        print("Trying to establish connection to MQTT-Broker ...") # <-- this message I always see
        if not self.c.connect(clean_session=True):  #<-- True works, False doesn't work
            print("Successfully established connection with MQTT-broker") <-- in case of True, I see this, but never in case of false
As a mqtt-broker, I am runing mosquitto on a raspberry pi (wheezy). There the file /etc/mosquitto/mosquitto.conf contains the lines

Code: Select all

persistence true
persistence_location /var/lib/mosquitto
It also seems, that no entry is made at all in /var/log/mosquitto/mosquitto.log in case of clean_session=False

User avatar
Posts: 4476
Joined: Fri Jul 18, 2014 8:01 am
Location: UK

Re: MQTT connect: clean_seesion True and False

Post by pythoncoder » Tue Jan 16, 2018 11:03 am

I have used clean_session False but it needs to be handled with care on the ESP8266 at least. The reason is that if you disconnect a session with clean-session False the broker will queue up any qos 1 messages (and possibly qos 0 ones) for when the session is re-established. The resulting backlog can fill the buffers on the ESP8266 and crash it. I recommend using clean sessions if possible.

You might be interested in my take on MQTT on the ESP8266. tl;dr the official drivers, the ESPx and WiFi all have limitations which make long term running problematic unless various precautions are adopted.
Peter Hinch

Post Reply