Issue publishing via mqtt
hansamann last edited by
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") self.pid += 1 struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid) #print(hex(len(pkt)), hexlify(pkt, ":")) self.sock.write(pkt) self._send_str(topic) self.sock.write(qos.to_bytes(1, sys.byteorder)) while 1: op = self.wait_msg() if op == 0x90: resp = self.sock.read(4) #print(resp) assert resp == pkt and resp == pkt if resp == 0x80: raise MQTTException(resp) return
I had to import sys and change the line
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?
scotlandsimon last edited by scotlandsimon
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 = 'm13.cloudmqtt.com' #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 sleep(2)
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