Add "grande chambre" (using esp8266 nodemcu)
[manu/arduino-maison.git] / grande-chambre / grande-chambre.ino
1 // Board ESP8266 - NodeMCU 1.0 (ESP-12E module)
2 #include <Arduino.h>
3 #include <ESP8266WiFi.h>
4 #include <WiFiUdp.h>
5 #include <Adafruit_Sensor.h>
6 #include <DHT.h>
7 #include <DHT_U.h>
8
9 #include "grande-chambre-config.h"
10
11 const char*    wifi_ssid = WIFI_SSID;
12 const char*    wifi_pass = WIFI_PASS;
13
14 // Grafana
15 IPAddress      influxdb_ip(INFLUXDB_IP);
16 long           influxdb_port = INFLUXDB_PORT;
17 unsigned int   localPort = 2390;
18 // MilliSeconds
19 long unsigned  poll_int = POLL_INT;
20 String city = CITY;
21 String location = LOCATION;
22 WiFiUDP Udp;
23
24 // Temp
25 // 5 = D1 on esp8266
26 #define DHTPIN 5
27 #define DHTTYPE DHT22
28 DHT_Unified dht(DHTPIN, DHTTYPE);
29
30 void setup() {
31
32   Serial.begin(9600);
33   // Not for esp8266 WiFi.mode(WIFI_STA);
34   WiFi.begin(WIFI_SSID, WIFI_PASS);
35   while (WiFi.status() != WL_CONNECTED) {
36     delay(500);
37   }
38
39   dht.begin();
40   sensor_t sensor;
41   dht.temperature().getSensor(&sensor);
42   dht.humidity().getSensor(&sensor);
43
44 }
45
46 void loop() {
47   delay(POLL_INT);
48   // Check wifi connexion
49   if ( WiFi.status() != WL_CONNECTED ) {
50       int retry = 0;
51       // Not for esp8266 WiFi.mode(WIFI_STA);
52       WiFi.begin(WIFI_SSID, WIFI_PASS);
53       while (retry < 10 || WiFi.status() != WL_CONNECTED) {
54           retry++;
55           delay(500);
56       }
57   }
58
59   if ( WiFi.status() == WL_CONNECTED ) {
60       sensors_event_t event;
61       
62       dht.temperature().getEvent(&event);
63       if (isnan(event.temperature)) {
64         // Error
65       } else {
66           sendToInfluxDB("temperature,city="+city+",location="+location, "value", String(event.temperature));
67       }
68       dht.humidity().getEvent(&event);
69       if (isnan(event.relative_humidity)) {
70         // Error
71       } else {
72           sendToInfluxDB("humidity,city="+city+",location="+location, "value", String(event.relative_humidity));
73       }
74   }
75 }
76
77 void sendToInfluxDB(String measure, String key, String value) {
78   String line = measure+" "+key+"="+value;
79   Udp.begin(localPort);
80   Udp.beginPacket(influxdb_ip, influxdb_port);
81   Udp.print(line);
82   Udp.endPacket();
83 }