experiments

All kinds of coding experiments
Log | Files | Refs | Submodules

d1-mini-test.ino (2163B)


      1 #include <ESP8266WiFi.h>
      2 #include "d1-mini-test-credentials.ino"
      3 
      4 // Sends a request to Hue bridge on the push of a button.
      5 // Credentails should be put in the file 'd1-mini-test-credentials.ino' like this:
      6 //    const char* ssid = "secret";
      7 //    const char* password = "secret";
      8 //    const char* host = "secret";
      9 //    const char* url = "secret";
     10 
     11 const char* bodyOn  = "{\"bri\":254,\"on\":true}";
     12 const char* bodyOff = "{\"on\":false}";
     13 const char* cLengthOn = "21";
     14 const char* cLengthOff = "12";
     15 
     16 const int buttonInput = 14;
     17 
     18 bool stateOn = true;
     19 volatile bool processing = false;
     20 
     21 ICACHE_RAM_ATTR void buttonClicked() {
     22   if (processing) return;
     23   processing = true;
     24   Serial.println("Button clicked");
     25 }
     26 
     27 void setup() {
     28   pinMode(buttonInput, INPUT);
     29   attachInterrupt(digitalPinToInterrupt(buttonInput), buttonClicked, FALLING);
     30   Serial.begin(115200);
     31   pinMode(LED_BUILTIN, OUTPUT);
     32   digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
     33   WiFi.begin(ssid, password);
     34   while (WiFi.status() != WL_CONNECTED) {  
     35     delay(500);
     36     Serial.println("Attempting connection...");
     37   }
     38   Serial.println("Connected!");
     39   digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on by making the voltage LOW
     40 }
     41 
     42 void loop() {
     43   while (WiFi.status() != WL_CONNECTED) {  
     44     delay(500);
     45     Serial.println("Attempting reconnection...");
     46   }
     47   delay(100);
     48   if (!processing) return;
     49   
     50   WiFiClient client;
     51   String request = String("PUT ") + url + " HTTP/1.1\r\n" +
     52                  "Host: " + host + "\r\n" +
     53                  "Connection: close\r\n" +
     54                  "Content-Type: application/json\r\n" +
     55                  "Content-Length: " + (stateOn ? cLengthOn : cLengthOff) + "\r\n" +
     56                  "\r\n" + (stateOn ? bodyOn : bodyOff);
     57   if (client.connect(host, 80)) {
     58     client.print(request);
     59     while (client.connected() || client.available()) {
     60       if (client.available()) {
     61         String line = client.readStringUntil('\n');
     62         Serial.println(line);
     63       }
     64     }
     65     client.stop();
     66   } else {
     67     Serial.println("Communication failure :(");
     68     client.stop();
     69   }
     70   stateOn = !stateOn;
     71   processing = false;
     72 }