     Serial.println("Failed to read from sensor!");
     return;
   }
-
-}
-
-void loop() 
-{
-
+}
+
+void loop()
+{
   if (WiFi.status() == WL_CONNECTED) {
     if (!client.connected()) {
-      if  (
-        client.connect(MQTT::Connect((char*) clientName.c_str()).set_clean_session().set_keepalive(120))) {
-        client.subscribe(subtopic);
-        client.publish(hellotopic, "hello from ESP8266 s02");
-        client.set_callback(callback);
+      long now = millis();
+      if (now - lastReconnectAttempt > 5000) {
+        lastReconnectAttempt = now;
+        if (reconnect()) {
+          lastReconnectAttempt = 0;
+        }
       }
-    }
-
-    if (client.connected()) {
+      Serial.print("failed, rc=");
+      Serial.print(client.state());
+    } else {
       client.loop();
-    } else {
-      ESP.restart();
     }
   } else {
-      Serial.println("Could not connect to WIFI");
-      ESP.restart();    
-  }
-
+    wifi_connect();
+  }
 
   changelight();
   runTimerDoLightOff();
-  
+
   pirValue = digitalRead(pir);
-  
+
   payload = "{\"Humidity\":";
   payload += h;
   payload += ",\"Temperature\":";

  return result;
}


/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets


  }

  attachInterrupt(13, motion_detection, RISING);
  attachInterrupt(5, run_lightcmd, CHANGE);

  sensors.begin();
  if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0");
  if (!sensors.getAddress(outsideThermometer, 1)) Serial.println("Unable to find address for Device 1");

  // set the resolution to 9 bit
  sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION);
