       // Wait 5 seconds before retrying
       delay(5000);
     }
+  }
+
+}
+void publish_heartbeat() {
+  char payload[8];
+  sprintf(payload, "%d", proxim_nominal);
+//  connectClient();
+  if ( mqttClient.connected() ) {
+    mqttClient.publish("/catdoor/avgproxim", payload);
+  }
+  else {
+    Serial.println("Error: mqttClient not connected anymore");
+  }
+}
+
+void publish_state(int8_t state) {
+  char payload[8];
+  if (state) {
+    strcpy(payload, "open");
+  }
+  else {
+    strcpy(payload, "closed");
+  }
+//  connectClient();
+  if ( mqttClient.connected() ) {
+    mqttClient.publish("/catdoor/state", payload);
+  }
+  else {
+    Serial.println("Error: mqttClient not connected anymore");
   }
 }
 

  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void setup() {

    }
    counter++;
  }
  // take a sample for the average every second (update is called at 20Hz)
  if ( counter >= 20 ) {
    counter = 0;
  }
}

void connectClient() {
  while (!mqttClient.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (mqttClient.connect("MistyDoor")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
