 }
 
 void loop() {
+  checkForIncoming();
+  checkAllSensors();
+}  
+
+void outputState(int i, int type) {
+  Serial.print("{\"result\":{\"type\":\"");
+  Serial.print(TYPES[type]);
+  Serial.print("\",\"id\":");
+  Serial.print(i);
+  Serial.print(",\"state\":");
+  Serial.print(states[i]);
+  Serial.print(",\"millis\":");
+  Serial.print(millis());
+  Serial.println("}}");
+}
+
+
+void checkForIncoming() {
   incoming = "";
   byte incomingByte;
   

      incoming += char(incomingByte);
    }
    
    delay(10);
  }
  
  if (incoming != "") {
    // Serial.print(incoming);
    if (incoming == "{\"message\":\"status\"}") {
      status();
    } else { 
      error("unknown message");
    }
  }
  
  for (int i=22; i<54; i++) {
    //read the pushbutton value into a variable
    states[i] = digitalRead(i);
    
    //print out the value of the pushbutton
    if (states[i] != lastStates[i]) {
      outputState(i, EGRESS);
      lastStates[i] = states[i];
    }
  }
  
  digitalWrite(13, digitalRead(22));
}  

void outputState(int i, int type) {
  Serial.print("{\"type\":\"");
  Serial.print(TYPES[type]);
  Serial.print("\",\"id\":");
  Serial.print(i);
  Serial.print(",\"state\":");
  Serial.print(states[i]);
  Serial.print(",\"millis\":");
  Serial.print(millis());
  Serial.println("}");
}



}


// Get the state of a single input and optionally automatically output it
void inputStatus(int id, bool output) {
  states[id] = digitalRead(id);
    
  if (states[id] != lastStates[id]) {
    if (output) {
      outputState(id, EGRESS);
    }
    lastStates[id] = states[id];
  }
}


// Return status all inputs
void version() {
  Serial.print("{\"result\":\"");
  Serial.print(VERSION);
  Serial.println("\"}");
}


// Return an error messagse
void error(String message) {
  Serial.print("{\"error\":\"");
