diff --git a/lightscontrol-client.ino b/lightscontrol-client.ino index ba8ac99..a70d66c 100644 --- a/lightscontrol-client.ino +++ b/lightscontrol-client.ino @@ -1,6 +1,13 @@ +/* + * Outside Lighting Controll - ESP8266 Client + * + * copyright: Jannik Beyerstedt | http://jannikbeyerstedt.de | code@jannikbeyerstedt.de + * license: http://www.gnu.org/licenses/gpl-3.0.txt GPLv3 License + */ + #include -const char* host = "ursaminor.local"; +const char* host = "ursaminor.fra80"; String serviceUri = "/service.php"; const int httpPort = 8088; @@ -10,39 +17,61 @@ bool lightState = false; unsigned int lightTime = 0; bool updated = false; -void wifiConnect(void) { +const unsigned int wifiConnectTimeout = 20; /* num of 500ms intervals */ +const unsigned int serverConnectAttempts = 10; /* max num of attempts */ +unsigned int srvConnCnt; + +bool wifiConnect(void) { + unsigned int cycles = 0; + Serial.println("Connecting to WiFi"); WiFi.mode(WIFI_STA); WiFi.begin("WLAN-Bey-IoT", "IoT-Fra80"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); + + cycles++; + if (cycles > wifiConnectTimeout) { + return false; + } } Serial.print(" ok, IP: "); Serial.println(WiFi.localIP()); + return true; } void setup() { Serial.begin(115200); delay(100); - wifiConnect(); - pinMode(0, OUTPUT); pinMode(relaisPin, OUTPUT); + digitalWrite(relaisPin, HIGH); /* failsafe */ + + while (!wifiConnect()) { + /* wait 5s and try again */ + delay(5000); + } + + srvConnCnt = 0; } void loop() { + if (srvConnCnt > serverConnectAttempts) { + digitalWrite(relaisPin, HIGH); /* failsafe */ + } + Serial.print("connecting to "); Serial.println(host); - // Use WiFiClient class to create TCP connections WiFiClient client; - if (!client.connect(host, httpPort)) { Serial.println("ERROR connection failed"); + srvConnCnt++; return; } + srvConnCnt = 0; // This will send the request to the server String httpRequest = "GET " + serviceUri + " HTTP/1.1\r\n" + @@ -115,18 +144,20 @@ void loop() { // only deep sleep, if the time is more than 5 minutes if (lightTime >= 5 && lightState == false) { - Serial.println("sleeping with WiFi off"); - Serial.println(""); + Serial.print("sleeping with WiFi off: Minutes "); + Serial.println(lightTime); Serial.flush(); WiFi.mode(WIFI_OFF); delay(lightTime * 60 * 1000); wifiConnect(); } else { - Serial.println("taking a normal sleep"); - if (lightTime <= 1) { + Serial.print("taking a normal sleep: Minutes "); + if (lightTime < 1) { + Serial.println("only 10 seconds"); delay(10 * 1000); } else { + Serial.println(lightTime); delay(lightTime * 60 * 1000); } }