This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

nrf9160: MQTT - scan for topics

HI,

I am trying to connect to our cloudmqtt account where the topics are dynamically created because of which is it not possible to pre-program a specific topic. 

I would like to be able to scan for topics by subscribing to '#' and seeing all the messages on all the topics. I am able to receive messages but i am not sure how to read the topic name that message was published on.

I tried reading the p->message.topic.topic.utf8 but it is just returning the topic that set as publish.

/**@brief MQTT client event handler
 */
void mqtt_evt_handler(struct mqtt_client *const c,
		      const struct mqtt_evt *evt)
{
	int err;

	switch (evt->type) {
	case MQTT_EVT_CONNACK:
		if (evt->result != 0) {
			printk("MQTT connect failed %d\n", evt->result);
			break;
		}

		connected = true;
		printk("[%s:%d] MQTT client connected!\n", __func__, __LINE__);
		subscribe();
		break;

	case MQTT_EVT_DISCONNECT:
		printk("[%s:%d] MQTT client disconnected %d\n", __func__,
		       __LINE__, evt->result);

		connected = false;
		break;

	case MQTT_EVT_PUBLISH: {
		const struct mqtt_publish_param *p = &evt->param.publish;

                evt->param.
            
		printk("[%s:%d] MQTT PUBLISH result=%d len=%d\n", __func__,
		       __LINE__, evt->result, p->message.payload.len);
		err = publish_get_payload(c, p->message.payload.len);
		if (err >= 0) {
			data_print("Received: ", payload_buf,
				p->message.payload.len);
                              
                        data_print("Topic: ", 
                        p->message.topic.topic.utf8, p->message.topic.topic.size);

thank you!

Related