Skip to content

Instantly share code, notes, and snippets.

@cocoastorm
Last active May 18, 2019 03:42
Show Gist options
  • Save cocoastorm/a1c30b91c09e45a52e77becfb5e78b5c to your computer and use it in GitHub Desktop.
Save cocoastorm/a1c30b91c09e45a52e77becfb5e78b5c to your computer and use it in GitHub Desktop.
ESP8266 HTTP HealthCheck
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
// on board small LED
// #define BOARD_LED 6
// death counter
int ded = 0;
// green led on gpio 14
int greenPin = 14;
// 15 seconds
const int CHECK_EVERY = 1000 * 15;
void connectWiFi() {
int counter = 50;
WiFi.begin("SomeWiFiPoint", "secret");
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
counter--;
if (counter <= 0) {
Serial.println("WiFi failed to connect after 10 attempts");
break;
}
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
void writeLED(bool state) {
digitalWrite(greenPin, state ? HIGH : LOW);
}
void flashLED(int onFor, int offFor, int times) {
for (int i = 0; i < times; i += 1) {
writeLED(true);
delay(onFor);
writeLED(false);
delay(offFor);
}
}
void setup() {
Serial.begin(115200);
pinMode(greenPin, OUTPUT);
connectWiFi();
}
void loop() {
HTTPClient http;
// if WiFi got dropped
// attempt to reconnect
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
if (http.begin("http://192.168.86.36:9000"))
{
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) {
Serial.println("It's alive, Jim!");
flashLED(50, 10, 1);
} else if (httpCode >= 400) {
Serial.println("It's dead, Jim!");
flashLED(50, 50, 3);
ded++;
} else {
Serial.println("Oof");
flashLED(100, 50, 50);
ded++;
}
http.end();
}
delay(CHECK_EVERY);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment