ArduinoMQTTClient reset connection to Azure IoT Hub

Good day.

I’m having trouble with sending data to the Azure IoT hub. The problem is that after sending a message to the cloud it resets the MQTT connection. I don’t know why this is happening. I’m using the Arduino MKR WiFi 1010 with the ArduinoMqttClient as the mqttclient library.

cpp
#include <WiFiNINA.h>
#include <WiFiUdp.h>
#include <RTCZero.h>
#include <SPI.h>
#include <SD.h>
#include <Arduino_MKRENV.h>
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <utility/ECCX08SelfSignedCert.h>
#include <ArduinoMqttClient.h>
//#include "arduino_secrets.h"

#define CD_CS 4
#define LOGDIR "MKRLOG/"
#define MQTTLED 14
#define WIFILED 13
#define MSGINT 300000 // 5 minutes
#define WGREEN  25
#define WRED    26
#define WBLUE   27

RTCZero rtc;
const int GMT = 8; //change this to adapt it to your time zone

// The values will come from the "settings.txt" located in the SD
char ssid[100];        // your network SSID (name)
char pass[100];        // your network password (use for WPA)
char broker[100];    // broker for MQTT connection
String devID;      // ID registered in Azure IoT Hub

// SD CARD variables
File dataFile;
String logFileName;

float sensor[7];


//WiFi, SSL, and MQTT variables
WiFiClient wifiClient;
BearSSLClient sslClient(wifiClient);
MqttClient mqttClient(sslClient);
int status = WL_IDLE_STATUS;
String sendTopic = "devices/" + devID + "/messages/events/";
String recTopic = "devices/" + devID + "/messages/devicebound/#";


// Timing variables
unsigned long lastMillis = 0, wifiMillis = 0, mqttMillis = 0;

void setup() 
{
  pinMode(WIFILED, OUTPUT);
  pinMode(MQTTLED, OUTPUT);
  Serial.begin(9600);
  while(!Serial);

  // Check all hardwares
  checkHardware();

  // Initialize SD CARD
  SDSetup();

  // Load settings.txt
  loadSettings();

  // Attempt to connect to WiFi network:
  connectWiFi();

  //create log file
  

  // You're connected now, so print out the status:
  printWiFiStatus();
  epochTime();

  startLogs();
  // Reconstruct the certificate
  loadEccCert();

  // Setup MQTT
  setMQTT();

  // Initialize MQTT
  connectMQTT();

  // Initialize timers
  lastMillis = millis();
  wifiMillis = millis();
  mqttMillis = millis();
  Serial.println("All timers initialized!");
}

//============main loop============//
void loop() 
{
  //check if wifi and mqtt is still connected
  if (WiFi.status() != WL_CONNECTED)
  {
    connectWiFi();
  }
  
  if (millis() - wifiMillis > 2000)
  {
    wifiMillis = millis();
    WiFiBlink();
  }
  
  if (!mqttClient.connected())
  {
    connectMQTT();
  }

  if (millis() - mqttMillis > 2500)
  {
    mqttMillis = millis();
    MQTTBlink();
  }
  

  // call poll function regularly to allow the library to receive MQTT messages
  // and end MQTT keepalives which avoids being disconnected by the broker
  mqttClient.poll();
  delay(10);  // fixes the polling time

  if (millis() - lastMillis > MSGINT)
  {
    lastMillis = millis();
    publishMessage();
  }
}

//=============end of main loop=============//

void onMessageReceived(int messageSize)
{
  Serial.print("Received a message with topic: ");
  Serial.print(mqttClient.messageTopic());
  Serial.print("', length ");
  Serial.print(messageSize);
  Serial.println(" bytes:");

  while (mqttClient.available())
  {
    Serial.print((char)mqttClient.read());
  }
  Serial.println();
  Serial.println();
}

void setMQTT()
{
  Serial.println("Setting up MQTT...");
  mqttClient.setId(devID);
  // String username = String(broker) +"/"+ devID +"/"+  "api-version=2018-06-30";
  String username = String(broker) +"/"+ devID +"/"+  "api-version=2016-11-14";
  
  mqttClient.setUsernamePassword(username,"");
  
  Serial.println("mqtt set OK!");
  Serial.println();

  mqttClient.onMessage(onMessageReceived);  // callback
}

void connectMQTT()
{
  Serial.print("Attempting to connect to MQTT broker: ");
  Serial.println(broker);
  while (!mqttClient.connect(broker, 8883))
  {
    switch (abs(mqttClient.connectError()))
    {
    case 1:
      Serial.println("Unacceptable protocol version");
      break;
    case 2:
      Serial.println("Identifier rejected");
      break;
    case 3:
      Serial.println("Server Unavailable");
      break;
    case 4:
      Serial.println("Bad username or password");
      break;
    case 5:
      Serial.println("Not authorized");
      break;
    default:
      Serial.println("Unknown error code");
      break;
    }
    delay(3000);
  }
  Serial.println();
  Serial.println("You're now connected to the MQTT broker");
  Serial.println();

  //subscribe to a topic
  mqttClient.subscribe(recTopic);
}

void publishMessage()
{
  sensor[0] = ENV.readTemperature();
  sensor[1] = ENV.readHumidity();
  sensor[2] = ENV.readPressure();
  sensor[3] = ENV.readIlluminance();
  sensor[4] = ENV.readUVA();
  sensor[5] = ENV.readUVB();
  sensor[6] = ENV.readUVIndex();

  String payload = F("{\"temperature\": {temp}, \"humidity\": {hum}, \"pressure\": {press}, \"Illuminance\": {lux}, \"UV A\": {uva}, \"UV B\": {uvb}, \"UV Index\": {uvI}}");

  //replace all values
  payload.replace(F("{temp}"), String(sensor[0], 2));
  payload.replace(F("{hum}"), String(sensor[1], 2));
  payload.replace(F("{press}"), String(sensor[2], 2));
  payload.replace(F("{lux}"), String(sensor[3], 2));
  payload.replace(F("{uva}"), String(sensor[4], 2));
  payload.replace(F("{uvb}"), String(sensor[5], 2));
  payload.replace(F("{uvI}"), String(sensor[6], 2));

  Serial.print("Publishing message: ");
  Serial.println(getDateTime());
  Serial.println();
  Serial.println(payload.c_str());

  //send message
  mqttClient.beginMessage(sendTopic);
  mqttClient.print(payload);
  mqttClient.endMessage();
  Serial.println("Send message OK!");
  Serial.println();
  saveLogs(sensor[0],sensor[1],sensor[2],sensor[3],sensor[4],sensor[5],sensor[6]);
}

void saveLogs(float t, float h, float p, float i, float a, float b, float uvi)
{
  dataFile = SD.open(logFileName, FILE_WRITE);
  delay(1000);

  dataFile.print(getDateTime());
  dataFile.print(",");
  dataFile.print(t);
  dataFile.print(",");
  dataFile.print(h);
  dataFile.print(",");
  dataFile.print(p);
  dataFile.print(",");
  dataFile.print(i);
  dataFile.print(",");
  dataFile.print(a);
  dataFile.print(",");
  dataFile.print(b);
  dataFile.print(",");
  dataFile.print(uvi);
  dataFile.println();
  dataFile.close();
  delay(100);
  Serial.println("Successfully saved to log file");
}