ESP8266 (Web Client): Sending Data to Jeedom in TCP / IP Wireless (JSON API) – Part 1

We continue our series of articles on HTTP (TCP/IP) data exchange between an ESP8266 and the Jeedom Home Automation Server. Jeedom provides an API as complete as Domoticz. The documentation is available here. We will go a little faster than for Domoticz, the general principle being the same.

Recommended readings

ESP8266 (Web Client): Sending Data to Domoticz in TCP / IP Wireless (API / JSON) – Part 1

ESP Easy: Using DIY Connected Objects with Jeedom

Documentation API JSON RPC Jeedom

Equipment used

The circuit remains the same, namely a Wemos D1 Mini (ESP8266 ESP-12), a temperature and humidity sensor (DHT22), an atmospheric pressure sensor (BMP180) and a relay shield to control the ignition Of a device from the Jeedom interface.

esp8266 Wemos D1 mini Any ESP8266 ESP-12 module, for example Wemos D1 Mini
 BMP180 Atmospheric pressure

BMP180

Broches DHT22 Temperature and humidity sensor

DHT11 or DHT22

wemos d1 mini dht22 shield Shield DHT22 or DHT11 for Wemos D1 Mini.

The sensor is connected to pin D4 (GPIO2)

wemos d1 mini relai shield Relay shield  (250VAC/10A or 30VDC/10A) for Wemos D1 Mini.

The relay is connected to pin D1 (GPIO5)

jumper dupont Jumper Dupont
breadboard Breadboard

Circuit

Composant Pin ESP8266 Pin (Wemos D1 mini)
DHT22 (shield Wemos D1 Mini) VCC 3V3
GND G
Data D4
BMP180 VCC 3V3
GND G
SDA D2
SCK D1
Relay Shield D1

ESP8266 DHT22 BMP180 wemos Shield Relay jeedom ESP8266HTTPCLIENT_

Retrieve your Jeedom API key

In order to transmit data to Jeedom, it is necessary to retrieve the API key from the administration interface. Connect to your server and go into the configuration (toothed wheels). It is located in the API key field. You will need this key for the Arduino code.

Note. It is possible to generate a new key. All devices that use this key will no longer be able to use the JSON API (this is the goal after all).

 jeedom api key esp8266 http api json

Preparing a Virtual Instrument

We will now create an instrument that will receive the data. Go to the plugins and verify that the Virtual Instrument plugin is installed. If not, do so.

jeedom instrument virtuel

Go to plugins -> Programming -> Virtual and click on + to create a new instrument:

  • Give it a name
  • An object
  • One type (optional)
  • Check Enable and Visible

 jeedom equipement virtuel esp8266 wemos api json

Then go to the Commands tab and add 3 virtual info: temperature, humidity, barometer. You can use this to assign a label for the unit as well as a minimum and maximum value for the scale. Save it. After the backup, an identifier (#) is assigned for each virtual information. Here, temperature (# 78), humidity (# 79) and barometer (# 80). We will need it in the Arduino code.

 jeedom equipement virtuelle commandes temperature humidite api json esp8266 wemos

Arduino Code / ESP8266

This is exactly the same as that developed for Domoticz, only the construction of the HTTP request changes. Unlike Domoticz, one must send the data separately, that is to say that which corresponds to the virtual instrument.

The HTTP request takes the following form

http://#IP_JEEDOM#/core/api/jeeApi.php?apikey=#APIKEY#&type=virtual&id=#ID#&value=#value#

To facilitate the work, you will find at the beginning of the program the following variables that you have to modify by your values:

const char* apiKey   = "mVuQikcXm69l2mDMYZiCsLj0wamT0HsCcrBCuXRxntJDO1kn";
const char* idTemp   = "78";
const char* idHumi   = "79";
const char* idPA     = "80";

It will therefore be necessary to send an HTTP request for each measurement and send it to the corresponding virtual instrument. The SendToJeedom () function uses the ESP8266HTTPClient library to send the Get query (the data being encoded in the URL). In return Jeedom, return code 200 if all went well. If the API key is bad, the ESP8266HTTPClient library returns error -11 (HTTPC_ERROR_READ_TIMEOUT). Jeedom simply remains silent.

boolean sendToJeedom(String url){
  Serial.print("connecting to ");
  Serial.println(host);
  Serial.print("Requesting URL: ");
  Serial.println(url);
  http.begin(host,port,url);
  int httpCode = http.GET();
  Serial.println("closing connection");
  http.end();
}

The request remains a simple character string that is assembled with the different variables, for example for the temperature

String baseurl = "/core/api/jeeApi.php?apikey="; 
baseurl += apiKey;
baseurl += "&type=virtual&id="; 

String url = baseurl + idTemp;
url += url + "&value="; url += String(t); 
sendToJeedom(url);
delay(1000);

This gives, for example, the following query

/core/api/jeeApi.php?apikey=mVuQikcXm69l2mDMYZiCsLj0wamT0HsCcrBCuXRxntJDO1kn&type=virtual&id=78&value=19.8

It is then sufficient to take again the base of the url (baseurl) which is always identical and to assemble it with the identifier and its value. I added a delay of 1s between each publication. To optimize the code, one could verify that the previous shipment was correct before continuing.

Open the Arduino IDE and paste the following code. Edit the variables and upload them.

/*
 * HTTP communication between ESP8266 and Jeedom Smart Home Server
 * Communication HTTP (TCP/IP) entre ESP8266 et le serveur domotique Jeedom
 * Copyright (C) 2017 http://www.projetsdiy.fr - https://www.diyprojects.io
 *   
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <ESP8266WebServer.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecure.h>
#include <DHT.h>
#include <Adafruit_BMP085.h>

#define DHTTYPE   DHT22       // DHT type (DHT11, DHT22)
#define DHTPIN    D4          // Broche du DHT / DHT Pin

const char* ssid     = "xxxxxxxx";
const char* password = "xxxxxxxx";
const char* host     = "xxx.xxx.xxx.xxx";
const int   port     = 80;
const char* apiKey   = "mVuQikcXm69l2mDMYZiCsLj0wamT0HsCcrBCuXRxntJDO1kn";
const char* idTemp   = "78";
const char* idHumi   = "79";
const char* idPA     = "80";
const int   watchdog = 60000;
unsigned long previousMillis = millis(); 
const uint8_t GPIOPIN[5] = {D1,D5,D6,D7,D8};  // Led

DHT dht(DHTPIN, DHTTYPE);
Adafruit_BMP085 bmp;
ESP8266WebServer server ( 80 );
HTTPClient http;

void updateGpio(){
  Serial.println("Update GPIO command from Jeedom : ");
  for ( int i = 0 ; i < server.args(); i++ ) {
    Serial.print(server.argName(i)); Serial.println(server.arg(i));
  }
  String gpio = server.arg("id"); 
  String token = server.arg("token");
  // Vérifie si le serveur est autorisé - Check if server is authorized
  if ( token != "123abCde" ) {
    Serial.println("Not authentified ");
    return;
  }
  int etat = server.arg("etat").toInt();
  int pin = D1;
  if ( gpio == "D1" ) {
    pin = D1;
  } else if ( gpio == "D7" ) {
    pin = D7;
  } else if ( gpio == "D8" ) {
    pin = D8;  
  } else {   
    pin = D1;
  }
  Serial.print("Update GPIO "); Serial.println(pin);
  if ( etat == 1 ) {
    digitalWrite(pin, HIGH);
    Serial.println("GPIO updated : On");
    server.send(200, "application/json","success:1");
  } else if ( etat == 0 ) {
    digitalWrite(pin, LOW);
    Serial.println("GPIO updated : Off");
    server.send(200, "application/json","success:1");
  } else {
    Serial.println("Bad state Value !");
    server.send(200, "application/json","success:0");
  }
}

void setup() {
  Serial.begin(115200);
  delay(10);
  
  Wire.begin(D2,D3);            // Modifie les broches du bus I2C - Change I2C Pins
  if ( !bmp.begin() ) {
    Serial.println("BMP180 KO!");
    while (1);
  } else {
    Serial.println("BMP180 OK");
  }
  
  Serial.setDebugOutput(true);  
  Serial.println("Connecting Wifi...");

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  for ( int x = 0 ; x < 5 ; x++ ) {
    pinMode(GPIOPIN[x], OUTPUT);
  }
  
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.print(WiFi.localIP()); 
  
  server.on("/gpio", updateGpio);
  server.begin();
}

int value = 0;

void loop() {
  server.handleClient();
  unsigned long currentMillis = millis();

  if ( currentMillis - previousMillis > watchdog ) {
    previousMillis = currentMillis;

    if(WiFi.status() != WL_CONNECTED) {
      Serial.println("WiFi not connected !");
    } else {  
      Serial.println("Send data to Jeedom");
      
      float t = dht.readTemperature();
      float h = dht.readHumidity();
      float pa = bmp.readPressure() / 100.0F;
      
      if ( isnan(t) || isnan(h) ) {
        Serial.println("DHT KO");
      } else {
        String baseurl = "/core/api/jeeApi.php?apikey="; 
        baseurl += apiKey;
        baseurl += "&type=virtual&id="; 
        String url = baseurl + idTemp;
        url += url + "&value="; url += String(t); 
        sendToJeedom(url);
        delay(1000);
        
        url = baseurl + idHumi;
        url += url + "&value="; url += String(h);
        sendToJeedom(url);
        delay(1000);

        url = baseurl + idPA;
        url += url + "&value="; url += String(pa);
        sendToJeedom(url);
        delay(1000);
      }
    }
  }
}

boolean sendToJeedom(String url){
  Serial.print("connecting to ");
  Serial.println(host);
  Serial.print("Requesting URL: ");
  Serial.println(url);
  http.begin(host,port,url);
  int httpCode = http.GET();
  Serial.println("closing connection");
  http.end();
}

Back on the Jeedom interface, you can view the measurements that go back from the ESP8266 on the virtual instrument.

jeedom api json wemos d1 mini dht22 bmp180 esp8266httpclient

Subscribe to the weekly newsletter

No spam and no other use will be made of your email. You can unsubscribe anytime.

We will be happy to hear your thoughts

Leave a Reply

DIY Projects
%d bloggers like this: