foist
[sensors.git] / arduino / sketch_jun06b.ino
1 //USBtinyISP upload using programmer
2 //ArduinoUno
3
4 #include <DHT.h>
5 #include <ESP8266WiFi.h>
6
7 DHT dht(0, DHT11);
8
9 bool DEBUG = true;   //show more logs
10 int responseTime = 10; //communication timeout
11
12 unsigned long next;
13 unsigned long timeout;
14 char host[] = "some.host.com";
15 int lightPin = A0;
16 int lightValue = 0;
17 const char ssid[] = "SSID";
18 const char pass[] = "PASS";
19 char macstr[20];
20 byte mac[6];
21
22
23 void setup() {
24   Serial.begin(9600);
25   next = millis() + 15000;
26   timeout = millis() + 5000;
27   WiFi.macAddress(mac);
28   snprintf(macstr, 18, "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
29   WiFi.mode(WIFI_STA);
30   WiFi.begin(ssid,pass);
31   WiFi.setAutoReconnect(true);
32   while (WiFi.status() != WL_CONNECTED) {
33     delay(500);
34     Serial.print(".");
35   }
36   Serial.print("Connected, IP address: ");
37   Serial.println(WiFi.localIP());
38   Serial.println("You're connected to the network");
39   Serial.println("Booted");
40   ESP.wdtDisable();
41   ESP.wdtEnable(60000);
42 }
43
44 void loop() {
45   if (((signed long)(millis() - next)) > 0) {
46     if ((WiFi.status() != WL_CONNECTED)) {
47       WiFi.reconnect();
48       int counter=0;
49       while (WiFi.status() != WL_CONNECTED) {
50         delay(200);
51         counter++;
52         if (counter>9) {
53           ESP.restart();
54         }
55       }
56     }
57     WiFiClient client;
58     next = millis() + 15000;
59     timeout = millis() + 15000;
60     if (client.connect(host,8086)) {
61       lightValue = analogRead(lightPin);
62       String PostData = "light,sensor=\"" + String(macstr) + "\" value=" + String(lightValue) + "\ntemp,sensor=\"" + String(macstr) + "\" value=" + String(dht.readTemperature(true)) + "\nhumidity,sensor=\"" + String(macstr) + "\" value=" + String(dht.readHumidity());
63       client.println("POST /write?db=sensors HTTP/1.1");
64       client.print("HOST:   ");
65       client.println(host);
66       client.println("User-Agent: Arduino/1.0");
67       client.println("Connection: close");
68       client.println("Content-Type: application/x-www-form-urlencoded;");
69       client.print("Content-Length: ");
70       client.println(PostData.length());
71       client.println();
72       client.println(PostData);
73       client.flush();
74       client.stop();
75       PostData = "";
76       client.flush();
77       client.stop();
78     }
79   }
80 }