 }
 
 void request(String host, int port, String action) {
-    String cmd = "AT+CIPSTART=\"TCP\",\"" + host + "\"," + port;
-    wifi.println(cmd);
+    wifi.println("AT+CIPSTART=\"TCP\",\"" + host + "\"," + port);
     delay(2000);
-
     if (wifi.find("Error")) {
         Serial.println("Connection error");
         return;
     }
+ 
+    Serial.print("Requesting " + action + "... ");
+    action = action + " HTTP/1.0\r\n\r\n";
+    wifi.print("AT+CIPSEND=");
+    delay(500);
+    wifi.println(action.length());
+    delay(500);
+    wifi.println(action);
+    delay(1000);
+    //wifi.println("AT+CIPCLOSE");
+    Serial.println("ok");
+}
 
-    Serial.println("Requesting: " + action);
-    wifi.print("AT+CIPSEND=");
-    wifi.println(action.length());
-    delay(2000);
-    wifi.println(action);
+boolean connectWiFi() {
+    wifi.begin(9600);
+
+    Serial.print("Connecting... ");
+
+    wifi.println("AT");
+    if (!wifi.find("OK")) {
+        Serial.println("error connecting module");
+        return false;
+    }
+
+    wifi.println("AT+RST");
+    wifi.println("AT+CWMODE=1");
+    delay(500); //delay after mode change
+    wifi.println("AT+CWJAP=\"" + SSID + "\",\"" + PASS + "\"");
+    if (wifi.find("OK")) {
+        Serial.println("error connecting AP");
+        return false;
+    }
+
+    Serial.println("ok");
+    return true;
 }

    pinMode(light, OUTPUT);

    Serial.begin(115200);
    while (!connectWiFi()) {
        Serial.println("Retring to reconnect to WIFI");
    }
}

void loop() {
    digitalWrite(light, LOW);
    healthcheck();

    int sensorValue = digitalRead(sensor);

    if (sensorValue == HIGH) {
        registerEvent();
        digitalWrite(light, HIGH);
        delay(500);
        digitalWrite(light, LOW);
        delay(500);
    }
}


boolean connectWiFi() {
    wifi.begin(9600);

    Serial.print("Connecting... ");

    wifi.println("AT+RST");
    wifi.println("AT+CWMODE=1");
    delay(500); //delay after mode change
    wifi.println("AT+RST");
    wifi.println("AT+CWJAP=\"" + SSID + "\",\"" + PASS + "\"");

    if (wifi.find("ready")) {
        Serial.println("ok");
        return true;
    }

    Serial.println("error");
    return false;
}

void healthcheck() {
    request(SERVER_ADDRESS, SERVER_PORT, healthcheckAction);


int SERVER_PORT = 5000;
String SERVER_ADDRESS = "192.168.23.104";
String healthcheckAction = "GET /healthcheck/" + ID;
String eventAction = "POST /room/" + ID + "/event";

AltSoftSerial wifi(8, 9); // RX, TX

int sensor = 2;
int light = 13;
