diff --git a/WeatherStation.ino b/WeatherStation.ino index 692515b..3a4a423 100644 --- a/WeatherStation.ino +++ b/WeatherStation.ino @@ -31,7 +31,18 @@ #include "config.h" +#ifdef DHT_TYPE +# include +#endif // DHT_TYPE + ESP8266WebServer server(80); +unsigned long last_update = 0; + +#ifdef DHT_TYPE +DHT dht(DHT_PIN, DHT_TYPE); +float temperature = 0.0; +float humidity = 0.0; +#endif // DHT_TYPE static const char TEXT_PLAIN[] PROGMEM = "text/plain"; @@ -44,9 +55,26 @@ reply_not_found() void send_metrics() { - char message[1]; + static const size_t dht_size = 228; + char message[dht_size + 1]; - snprintf(message, 1, ""); + size_t message_size = +#ifdef DHT_TYPE + dht_size + +#endif // DHT_TYPE + 1; + + snprintf(message, message_size, +#ifdef DHT_TYPE + "# HELP temperature_celsius Temperature in degrees Celsius\n" + "# TYPE temperature_celsius gauge\n" + "temperature_celsius %.2f\n" + "# HELP relative_humidity Relative humidity, in percents\n" + "# TYPE relative_humidity gauge\n" + "relative_humidity %.2f\n", + temperature, humidity +#endif // DHT_TYPE + ); server.send(200, "text/plain; version=0.0.4; charset=utf-8", message); } @@ -86,12 +114,40 @@ setup() MDNS.addService("http", "tcp", 80); + // Initialize sensors +#ifdef DHT_TYPE + dht.begin(); +#endif // DHT_TYPE + Serial.println("All set, starting the loop."); } +void +read_sensors() +{ + // Turn on the LED to indicate that we’re working + digitalWrite(LED_BUILTIN, LOW); + +#ifdef DHT_TYPE + temperature = dht.readTemperature(); + humidity = dht.readHumidity(); +#endif + + // Turn off the LED to indicate work is finished + digitalWrite(LED_BUILTIN, HIGH); +} + void loop() { + unsigned long now = millis(); + MDNS.update(); server.handleClient(); + + if (now - last_update >= 5000) { + read_sensors(); + + last_update = now; + } } diff --git a/config.h.sample b/config.h.sample index 74c3f33..565cadf 100644 --- a/config.h.sample +++ b/config.h.sample @@ -32,3 +32,18 @@ // different for each station you install (e.g. if you want to measure the // temperature and humidity of each room separately) #define MDNS_NAME "internal-hostname" + +// If you have a DHT temperature+humidity sensor of this type will be used, +// remove the #undef line and uncomment one of DHT11 or DHT22. You also have +// to define the PIN your DHT sensor’s data (usually marked as DAT) is +// connected to. +// +// DHT11 sensors are usually blue, and don’t work under freezing point +// (0°C/32°F) +// +// DHT22 sensors are usually white and slightly bigger than DHT11 ones. They +// work well under freezing point (usually above -40°C/-40°F) +#undef DHT_TYPE +//#define DHT_TYPE DHT11 +//#define DHT_TYPE DHT22 +//#define DHT_PIN D5