MQTT publishing results in either a buffer overflow or in a network disconnect

Hi,

I am trying to upload a firmware update status via MQTT shortly after a nrf9160 reboot because of the firmware update.

To be able to mimic this behavior I have implemented a section in my main loop which is supposed to send the firmware update right after the nrf9160 has a stable connection with our MQTT server. To be able to tell if the MQTT connection is established i implemented a bool variable in the following software piece:

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

		LOG_INF("MQTT client connected");
                enable_led_system();
                mqtt_client_connected = true;
		subscribe();
		break;

As can be seen in the code above the bool "mqtt_client_connected" is set after the MQTT event is triggered and this bool also governs when the following code is called:

if (firmware_update_state > 0 & mqtt_client_connected)
{
    LOG_INF("Upload update status %d", firmware_update_state);
    
    //++++++++++++++++++++++++++++++++++++++
    // generate response
    char * mqtt_topic;
    char * response;
    mqtt_topic = k_calloc(100,sizeof(char));
    response = k_calloc(100,sizeof(char));
    
    sprintf(response, "{\"Index\": 1,\"FirmwareStatus\": %d}" , firmware_update_state);
    
    strcpy(mqtt_topic,"test/");
    strcat(mqtt_topic,device_id_string);
    strcat(mqtt_topic,"/update-firmware-start");
    data_publish(&client, MQTT_QOS_1_AT_LEAST_ONCE, mqtt_topic, response, strlen(response));
    //uart_reinit();
    
    k_free(mqtt_topic);
    k_free(response);
    firmware_update_state = NO_UPDATE;
}

This code snippet is the exact code which is used in my main loop. But if this code snippet is called with the debug probe attached and the program is in debug mode the message is not published and the connection is just disconnected.

If the code is started with the debugger attached, but only reading the logging information via RTT Logger then the software results in a buffer overflow of the nrf9160.

The MQTT structure implemented in the software normally works quite fine and it is possible to send and receive messages without any problems. Also both of the k_callocs in the code work fine and are not the problem for the buffer overflow or the MQTT disconnect. Since the MQTT message publishing normally works fine I am slightly confused why in this particular case I get two different errors for one problem. 

Best regards,

Andreas

Related