Issue publishing via mqtt

  • I seem to narrow down the issues I have with the mqtt lib that I found here;

    I am now able to connect and also publish messages, currently to adafruit io every two seconds. The problem with the subscription remains, I would hope someone has a clue.

    My current subscribe method looks liek this

        def subscribe(self, topic, qos=0):
            assert self.cb is not None, "Subscribe callback is not set"
            pkt = bytearray(b"\x82\0\0\0")
   += 1
            struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1,
            #print(hex(len(pkt)), hexlify(pkt, ":"))
            self.sock.write(qos.to_bytes(1, sys.byteorder))
            while 1:
                op = self.wait_msg()
                if op == 0x90:
                    resp =
                    assert resp[1] == pkt[2] and resp[2] == pkt[3]
                    if resp[3] == 0x80:
                        raise MQTTException(resp[3])

    I had to import sys and change the line



    self.sock.write(qos.to_bytes(1, sys.byteorder))

    I otherwise cannot call the qos.to_bytes method as it expects the byteorder on the micropython lopy that I have. Unfortunately I cannot see messages that I send to the topic - I've verified that messages are sent using another mqtt client that subscribed.

    Can anyone help? What is the correct code for subscribing?


  • You have to set a callback to the subscribe, in easier words, the subscribe function need to know what to do with the msg it will get back from the server.

    so you have to write a callback function before start using the subscribe function.

    The correct code for subscribing should be like that:

    from time import sleep
    from umqtt.simple import MQTTClient
    CLIENT_ID = 'Board_Name'       #name your board any name you want
    SERVER = ''   #info from servce provider
    Port=14250					   #info from servce provider
    User='kaeugs'                #info from servce provider
    Password='Euif_Ehf674qi'        #info from servce provider
    def sub_cb(topic, msg): #the action you want to happen, when you receive a msg
        print((topic, msg))
    client = MQTTClient(CLIENT_ID, SERVER, Port, User, Password)
    client.connect()   # Connect to MQTT broker
    while True:
    	client.set_callback(sub_cb)          #callback function 
            client.subscribe(b'Proportional')    #b'Proportional is just a topic 

    following this code, you should be able to subscribe to a topic and print the msg in the python console.

    A very helpful examples could be found here, take care these examples is for Micropython on
    esp8266, but the main idea is the same

Log in to reply

Pycom on Twitter