Pages

Friday, November 13, 2020

Sending data from ESP8266 to Domoticz part III

For a complete index to all my stories click this text

This is the third installment about using the ESP8266 as a means for sending data to Domoticz.
The first story showed how to switch a light on and off by sending commands from the ESP8266 to Domoticz. Re-read that story here: http://lucstechblog.blogspot.com/2020/01/sending-data-from-esp-to-domoticz.html
The second story showed you how to connect a Dallas DS18B20 thermometer to an ESP8266 and send the data to Domoticz. Re-read that story here: http://lucstechblog.blogspot.com/2020/01/sending-data-from-esp-to-domoticz-part.html

This last story (for now) shows you how to build a web-page in the ESP8266 that incorporates two buttons to send commands to Domoticz setting a light ON or OFF and displays the temperature of the Dallas DS18B20 on the webpage and automatically sends the temperature to Domoticz every 5 minutes. So this story combines both previous stories and presents the data on a nice web-page.

Setup

For combining the functions of the previous stories I presume that you have read those stories and setup the hardware on the breadboard and setup a thermometer in Domoticz like shown in those stories. If not please read them first.
Part 1: http://lucstechblog.blogspot.com/2020/01/sending-data-from-esp-to-domoticz.html
Part 2: http://lucstechblog.blogspot.com/2020/01/sending-data-from-esp-to-domoticz-part.html

The Software

Likewise in the previous stories the software is written in the Arduino IDE.  

The Libraries used for the Dallas DS18B20 are:
OneWire.h
DallasTemperature.h


I used a special library for building the webpage and that is:
ESP8266WebServer.h

You can find this webserver Library here:
https://github.com/esp8266/ESPWebServer

Or install it with the Arduino library manager.

The program



// Adapted by Luc Volders
// Webserver with 2 buttons
// to send command to Domoticz to
// to put a lamp on and off
// the we3bpage is refreshed every 15 seconds
// to display the up to date temperature
// and write Dallas temp on screen
// page will send temp to Domoticz every 5 Minutes

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

ESP8266WebServer Webserver(80);

#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is connected to GPIO 2 (D4) on the Wemos D1 mini
#define dallasiopin 2

// Setup a oneWire instance
OneWire oneWire(dallasiopin);

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);

// Replace with your network credentials
const char* ssid = "XXXXXXXXXXXXXXXX";
//const char* password = "password";
const char* password = "PASSWORD";

// HTTP Domoticz settings
const char* host = "192.168.1.66";
const int   port = 8080;
HTTPClient http;

String HTMLpage = "";

unsigned long previousMillis = 0;
// Change interval for your own purposes
// 1000 (MS) * 60 (seconds) * 5 (minutes)
const long interval = 1000 * 60 * 5; 

void setup(void)
{

  sensors.begin();

  buildpage();

  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  
  Webserver.on("/", [](){
    buildpage();
    Webserver.send(200, "text/html", HTMLpage);
  });
  Webserver.on("/lampON", []()
  {
    buildpage();
    Webserver.send(200, "text/html", HTMLpage+"<center><p style = 'color:green;'>LED is ON</p></center>");
    //digitalWrite(LED, HIGH);
        String url = "/json.htm?type=command&param=switchlight&idx=";
        url += String(3);
        url += "&switchcmd=On";
          http.begin(host,port,url);
          int httpCode = http.GET();
          if (httpCode) 
          {
            if (httpCode == 200) 
            {
               String payload = http.getString();
               Serial.println("Domoticz response "); 
               Serial.println(payload);
            }
           }     
    delay(1000);
  }
  );

  
  Webserver.on("/lampOFF", []()
  {
    buildpage();
    Webserver.send(200, "text/html", HTMLpage+"<center><p style = 'color:red;'>LED is OFF</p></center>");
    //digitalWrite(LED, LOW);
    String url = "/json.htm?type=command&param=switchlight&idx=";
    url += String(3);
    url += "&switchcmd=Off";
             http.begin(host,port,url);
          int httpCode = http.GET();
          if (httpCode) 
          {
            if (httpCode == 200) 
            {
               String payload = http.getString();
               Serial.println("Domoticz response "); 
               Serial.println(payload);
            }
           } 
              Serial.println("closing connection");
  http.end();
    delay(1000); 
  }
  );
  
  Webserver.begin();
  Serial.println("HTTP Webserver started");
}
 
void loop(void)
{
  Webserver.handleClient();
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval) 
    {
    // save the last time you blinked the LED 
    previousMillis = currentMillis;   
    senddomo();
    } 
}

void buildpage()
{
   // sensors.begin();
  Serial.println("Requesting temperatures for webpage...");
  sensors.requestTemperatures();
  
  HTMLpage = "";
  HTMLpage += "<body bgcolor=PowderBlue>";
  HTMLpage += "<META HTTP-EQUIV='refresh' CONTENT='15'>";
  HTMLpage += "<center><h1 style = 'color:red;'>Luc's Domoticz Control</h1>" ;
  HTMLpage += "<br>" ;
  HTMLpage += "<center><h1 style = 'color:black;'>Temperature : ";
  HTMLpage += (sensors.getTempCByIndex(0));
  HTMLpage += "</h1><br>" ;
  HTMLpage += "<p><h1>Lamp : </h1>";
  HTMLpage += "<a href=\'lampON\'><button style = 'background-color:green; font-size: 1.2em;'>ON</button></a>";
  HTMLpage += "&nbsp;&nbsp;&nbsp;" ;

  HTMLpage += "<a href=\' lampOFF\'><button  style = 'background-color:red; font-size: 1.2em;'>OFF</button>";
  HTMLpage += "</a></p></center>" ;
}

void senddomo()
{
  Serial.print("temperature is ");
  Serial.println((sensors.getTempCByIndex(0)));

  Serial.println("Requesting temperatures for domoticz ...");
  sensors.requestTemperatures();
  Serial.println("DONE");
  // After retrieving the temperature, we can print it.
  Serial.print("Temperature is: ");
  int TEMP = (sensors.getTempCByIndex(0));
  Serial.println(TEMP);
  // Here is the Json format that Domoticz expects
  // /json.htm?type=command&param=udevice&idx=IDX&nvalue=0&svalue=TEMP
  String url = "/json.htm?type=command&param=udevice&idx=";
         url += String(5297);
         url += "&nvalue=0&svalue="; 
         url += String(TEMP);

  Serial.print("Connecting to ");
  Serial.println(host);
  Serial.print("Requesting URL: ");
  Serial.println(url);
  http.begin(host,port,url);
  int httpCode = http.GET();
    if (httpCode) 
    {
      if (httpCode == 200) 
      {
        String payload = http.getString();
        Serial.println("Domoticz response "); 
        Serial.println(payload);
      }
    }
   
  Serial.println("closing connection");
  http.end();
}


Most of the program is self explanatory. Nevertheless I will highlight some parts for those of you who want to modify it.

ESP8266WebServer Webserver(80);

This line makes sure that the webserver is started on port 80. This is the standard port for web servers in your router.

// Replace with your network credentials
const char* ssid = "XXXXXXXXXXXXXXXX";
//const char* password = "password";
const char* password = "PASSWORD";

Like always replace these values with the name of your router and the password.

// HTTP Domoticz settings
const char* host = "192.168.1.66";
const int   port = 8080;

Same as above. Replace these values with the IP number from your Domoticz system. The port 8080 is the standard port on which Domoticz broadcasts its webpage.

const long interval = 1000 * 60 * 5;

The variable interval defines how often the temperature value is send to Domoticz. In this case 1000 * 60 = 1 minute * 5 makes every 5 minutes. adapt that to your own needs. Replace for example the 5 with 30 if you want the ESP to send the temperature every 30 minutes to Domoticz.

  Webserver.on("/", [](){
    buildpage();
    Webserver.send(200, "text/html", HTMLpage);
  });

This piece of code refreshes the webpage when you use the refresh button in tour browser or just access the webpage for the first time.

Webserver.on("/lampON", []()

The code that follows after this statement is the code that is executed when you push the ON button on the webpage. It also displays the text LED is ON in the color green on the screen. This is also the part where the button ON part is send to Domoticz

Webserver.on("/lampOFF", []()

Same as above but now the part that is executed when you press the OFF button. It puts the text LED is OFF in red on the screen and sends the OFF information to Domoticz.

void loop(void)
{
  Webserver.handleClient();
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval)
    {
    // save the last time you blinked the LED
    previousMillis = currentMillis;  
    senddomo();
    }
}

In the loop the webserver looks if any button is pressed and if that is the case it starts the ON or OFF rourine as described above. Next there is a test wether the time passed in miliseonds is larger as the defined interval variable. If that is the case the senddomo() routine is called which sends the actual temperature to Domoticz.

void buildpage()

This is the routine where the actual webpage is build.

HTMLpage += "<META HTTP-EQUIV='refresh' CONTENT='15'>";

This particular line makes sure that the webpages auto refreshes every 15 seconds to give you  the current temperature. Adjust it to your own liking.
The rest of the lines just build the webpage with the temperature and the buttons.

void senddomo()

This routine retrieves the current temperature from the Dallas DS18B20 and sends it to Domoticz. This routine is called evry X seconds where X is defined by the variable interval as discussed above.

Now open the serial monitor of your Arduino IDE and look at which IP adress the ESP8266 is located.




Put the IP adress in your browser and you will see the above webpage.



And here is ann example of the Domoticz log.

This completes this series. You now have all the tools to control Domoticz switches and send data to Domoticz using an ESP8266. Adapt this to your own needs.

Till next time
Have fun

Luc Volders