Arduino MKR NB does not connect to internet after first failure

Hi,

I am using Arduino MKR 1500 and the issue I am having is when the Arduino initiates, it tries to connect to internet. If it fails at the time of initiation, I reset it by hitting the button or I have a watchdog which resets the micro if it fails. The issue is after reset it never connects or sometime it hangs up and I have to click the reset button twice, load the bootloader firmwareand load the firmware again. Here is my code for reference.

#include <ArduinoMqttClient.h>
#include <MKRNB.h>

// Please enter your sensitive data in the Secret tab or arduino_secrets.h
// PIN Number
const char PINNUMBER[]     = "";

// MQTT Broker and Port
const char broker[] = "test.mosquitto.org"; //
int        port     = 1883;

// Pub/Sub Topics - Make it something unique since we are using a public broker
const char subscribeTopic[]  = "channel";
const char publishTopic[]  = "channel";

// To connect with SSL/TLS:
// 1) Change NBClient to NBSSLClient.
// 2) Change port value from 1883 to 8883.
// 3) Change broker value to a server with a known SSL/TLS root certificate 
//    flashed in the WiFi module.

NBClient client;
GPRS gprs;
NB nbAccess;
MqttClient mqttClient(client);

int LED = 6; // Onboard LED

// Publish interval
long previousMillis = 0; 
long interval = 2000;

void setup() {

  pinMode(LED_BUILTIN, OUTPUT); // Set built in LED pinMode
  
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
 /* while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }*/

  // attempt to connect to GSM and GPRS:
  Serial.print("Attempting to connect to GSM and GPRS");
   // connection state
  bool connected = false;

  // After starting the modem with GSM.begin()
  // attach the shield to the GPRS network with the APN, login and password
  while (!connected) {
    if ((nbAccess.begin(PINNUMBER) == NB_READY) &&
        (gprs.attachGPRS() == GPRS_READY)) {
      connected = true;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("You're connected to the network");
  Serial.println();


  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }

  Serial.println("You're connected to the MQTT broker!");
  Serial.println();

  // set the message receive callback
  mqttClient.onMessage(onMqttMessage);

  Serial.print("Subscribing to topic: ");
  Serial.println(subscribeTopic);
  Serial.println();

  // subscribe to a topic
  mqttClient.subscribe(subscribeTopic);


  Serial.print("Waiting for messages on topic: ");
  Serial.println(subscribeTopic);
  Serial.println();
}

void loop() {
  unsigned long currentMillis = millis(); 
  
  // call poll() regularly to allow the library to receive MQTT messages and
  // send MQTT keep alives which avoids being disconnected by the broker
  mqttClient.poll();

  // Enforce Interval
  if(currentMillis - previousMillis > interval) {
        previousMillis = currentMillis;

        // Call a function that handles publishing message
        publishSensorVal();
      
  }
}

void publishSensorVal() {
    // read the first Analog pin
    int sensorVal = analogRead(0);     
    //String speak = "The sensor val is " + String(sensorVal);
    char adc_sv[30] = {'T', 'h', 'e', ' ', 'a', 'd', 'c', ' '' ', 'v', 'a', 'l', 'u', 'e', ' ', 'i', 's', ' ', '\0'}; //adc_step value
    // Publish our sensor value to the publish topic
    mqttClient.beginMessage(publishTopic);
    mqttClient.print(adc_sv);
    mqttClient.print(sensorVal);
    mqttClient.endMessage();
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1400);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(100);                       // wait for a second
}

void handleCommand(String cmd) {
  if (cmd == "on"){
    digitalWrite(LED, HIGH);
  }else if(cmd == "off"){
    digitalWrite(LED, LOW);
  }
}

void onMqttMessage(int messageSize) {
  // we received a message, print out the topic and contents
  Serial.println("Received a message with topic '");
  Serial.print(mqttClient.messageTopic());
  Serial.print("', length ");
  Serial.print(messageSize);
  Serial.println(" bytes:");

  // We want to read each character into a useable String
  String content = "";
  char character;
  
  // use the Stream interface to print the contents
  while (mqttClient.available()) {
    character = (char)mqttClient.read();
    content.concat(character);
  }

  handleCommand(content); // This function does something with our incoming string

  Serial.println(content);
  Serial.println(); Serial.println(); // double spacing
}

Any help is much appreciated

Why do you insist on the GPRS connection?

What serial output do you get in these cases?

You know that this kind of freezes your board if there is any connection problem, don't you?

When there is a connection error with the MQTT broker it gives me a error message like error 1 is MQTT is unable to connect as it lost internet connection and 2 is invalid mqtt credentials.

My application streams data to the cloud and that is why I am waiting for internet connection.

Again: post the serial output you get after a reset!

But you don't use the GPRS connection so you don't need it (given you mean the GPRS connection by "internet connection").