Publishing data using MQTT on nRF9160 fails with random message ID

Hello,

I am working on an application that runs on nRF9160 using nRF Connect SDK V2.4.0. This application uses NB-IoT connection and has a stable connection to an MQTT broker. I want to publish data to a topic periodically using a timer every 2 seconds, but I am facing a problem with the publish function.

Code

I have followed the exercise of the cellular course on Nordic Academy  , and I am using the same publish function as in the solution. Here is the code snippet:

int data_publish(struct mqtt_client *c, enum mqtt_qos qos,uint8_t *data, size_t len, uint8_t *topic)
{
	struct mqtt_publish_param param;

	param.message.topic.qos = qos;
	param.message.topic.topic.utf8 = topic;
	param.message.topic.topic.size = strlen(topic);
	param.message.payload.data = data;
	param.message.payload.len = strlen(data);
	param.message_id = sys_rand32_get();
	param.dup_flag = 0;
	param.retain_flag = 0;

	data_print("Publishing: ", data, len);
	LOG_INF("to topic: %s len: %u",
			topic,
			(unsigned int)strlen(topic));

	return mqtt_publish(c, &param);
}

Problem

The problem occurs when I call sys_rand32_get() to generate a random message ID, the board get rebooted without viewing any error message in the logs.

However, when I use a static number instead (e.g. param.message_id = 7;), the publish succeeds but only for the first time. I have enabled these two config parameters:

CONFIG_ENTROPY_GENERATOR=y
CONFIG_TEST_RANDOM_GENERATOR=y

Additional information

I have also subscribed to another topic and the message receiving works fine. Moreover, the publishing using a button works with the same publish function, as shown in the exercise.

I have tried this on NCS V2.5.0 and V2.4.0, and I have also tried changing the implementation following the Zephyr RTOS publisher sample , but the problem persists.

Could anyone please help me with this issue? I appreciate any suggestions or solutions. Thank you very much.

Related