   blink(BLINK_COUNT, BLINK_DURATION, 1, 1, 1);
 }
 
+
+
 void loop() {
-  int state = digitalRead(SWITCH);
-     
-  if (switchState != state) {
-    // send state to server
-    if (state == LOW) {
-      sendLock();
-    } else {
-      sendUnlock();
-    }
-  }
-
-  switchState = state;
-
-  if (switchState == LOW) {
+  if (lastState == LOW) {
     count++;
-    digitalWrite(RED, HIGH);
-    digitalWrite(YELLOW, LOW);
-    digitalWrite(GREEN, LOW);
-  } else {
-    if (count > 0) {
-      count -= 6;
+  } else if (count > 0) { 
+      count -= courtesyDelay;
       digitalWrite(RED, LOW);
       digitalWrite(YELLOW, HIGH);
       digitalWrite(GREEN, LOW);
-      
-    } else {
+  } else {
+      count = 0;
       digitalWrite(RED, LOW);
       digitalWrite(YELLOW, LOW);
       digitalWrite(GREEN, HIGH);
-    }
   }
+  
   delay(500);
 }
 

String commandUnlock = "GET /log_visit_state/1 HTTP/1.0\r\n\r\n";

int count;
int switchState;

void setup()
{
  pinMode(ESP_RESET, INPUT);
  //pinMode(ESP_RESET, OUTPUT);
  //digitalWrite(ESP_RESET, HIGH);

  }
}

void onLockStateChange() {
  long now = millis();
  int state = digitalRead(SWITCH);
  if (state != lastState && now - lastStateTimestamp > 50) {
    lastStateTimestamp = millis();
    lastState = state;
    if (lastState == LOW) {
      sendLock();
    } else {
      sendUnlock();
    }
  }
}

bool sendLock() {
  
  digitalWrite(RED, HIGH);
  digitalWrite(YELLOW, LOW);
  digitalWrite(GREEN, LOW);
  
  if (espActive) {
    if (!sendATConnectServer()) return false;
    if (!sendATPrepareLockDoor()) return false;
    if (!sendATLockDoor()) return false;
    if (!sendATCipClose()) return false;
  }
  return true;
}

bool sendUnlock() {

  digitalWrite(RED, LOW);
  digitalWrite(YELLOW, HIGH);
  digitalWrite(GREEN, LOW);
  
  if (espActive) {
    if (!sendATConnectServer()) return false;
    if (!sendATPrepareUnlockDoor()) return false;
    if (!sendATUnlockDoor()) return false;
    if (!sendATCipClose()) return false;
  }
  return true;
}

