Smarthome Bundle with AZ-Touch, AZ-Envy and Smarthome Book

Today it is about MQTT (Message Queuing Telemetry Transport), a protocol that is very often used in the smart home sector. We want the Envy from today's offer equip with this protocol  so that it can be easily connected to smart home systems. We will also get to know such a connection. We will connect the Envy with the Smarthome Center as described in the Smarthome book .

An MQTT message consists of a so-called topic and the associated data. The topic is structured hierarchically like a directory path. The individual levels are separated by slashes. Wildcards can be used. How MQTT works in detail is described in chapter 6 of the Smarthome book.

The data is represented as an object in JSON (Java Script Object Notation) format. The advantage of this format is that all data is transmitted as readable strings. Measured values ​​and units are represented as properties of an object. For the Envy we will define the following properties.

  • sensor Name of the sensor (configurable)
  • t Temperature value from SHT30
  • do Unit of temperature "° C" or "° F" (configurable)
  • H Humidity of the SHT30
  • hu Unit for the humidity fix "%"
  • G Gas concentration from MQ2
  • gu Unit for the gas concentration fixed "ppm"

As mentioned in the list, the name of the sensor and the desired temperature unit should be configurable. It should also be possible to configure the type of gas to be examined. So that the Envy can connect to the WLAN and then to the MQTT broker, we need access data for the WLAN, the address of the broker, access data to the broker, the MQTT topic and the repetition rate for the measurement (e.g. one measurement per minute). All of these values ​​should also be configurable.

Since the Envy has no input or display elements, the configuration can be done using constants that are hard-coded in the program or, more elegantly, using a browser. The WebConfig library is available for configuration via a browser, which can provide a freely configurable web form via a web server. This library is also described in the Smarthome book from page 168.

Since it is not possible to log into the WLAN without configuration, in this case we will first start an access point that delivers the configuration website via the address 168.178.4.1. There we can then enter the access data and restart the Envy. If the Envy has a configuration and can log into the WLAN, no access point is started. The configuration page can then be accessed via the address that the Envy receives when it logs on to the WLAN.

Since this procedure can always be used when an ESP8266 is to provide measured values ​​via MQTT, a library was developed in connection with the Smarthome book that provides an include file that takes on all the tasks described above. The library is in Material for the book but can also be downloaded from GitHub. The function of this auxiliary file is also described in the book starting on page 176.

This brings us to our sketch for the Envy. The following libraries must be installed.

  • ClosedCube_SHT31D.h for the SHT30 from the Arduino library management
  • MQUnifiedsensor.h for the gas sensor from the Arduino library management
  • ESP8266_MQTT_Conf.h from ZIP file of GitHub
  • ArduinoJson.h for the JSON format from the Arduino library management
  • PubSubClient.h  for the MQTT protocol from the Arduino library management

After all of these libraries have been installed, the sketch can be compiled.

#include "ESP8266_MQTT_Conf.h" //Includedatei enthält alles für WiFi, Konfiguration und MQTT
#include <Wire.h> //Notwendig für SHT30
#include "ClosedCube_SHT31D.h" //Bibliothek für SHT30
#include <MQUnifiedsensor.h> //Bibliothek für Gassensor

//Parameter für den Gassensor
/************************Hardware Related Macros************************************/
#define Board ("ESP8266")
#define Pin (A0) //Analog input
/***********************Software Related Macros************************************/
#define Type ("MQ-2") //MQ2
#define Voltage_Resolution (3.3)
#define ADC_Bit_Resolution (10) // For arduino UNO/MEGA/NANO
#define RatioMQ2CleanAir (9.83) //RS / R0 = 9.83 ppm


//Spezifische Einträge für das Konfigurationsformular
String param = "["
  "{"
"'name':'thema',"
"'label':'MQTT Thema Temp.',"
"'type':"+String(INPUTTEXT)+","
"'default':'envy'"
  "},"
  "{"
"'name':'sensor',"
"'label':'Name des Sensors',"
"'type':"+String(INPUTTEXT)+","
"'default':'SHT30'"
  "},"
  "{"
"'name':'typ',"
"'label':'Welches Gas?',"
"'type':"+String(INPUTSELECT)+","
"'default':'1',"
"'options':["
"{'v':0,'l':'Wasserstoff'},"
"{'v':1,'l':'LPG'},"
"{'v':2,'l':'Kohlenmonoxyd'},"
"{'v':3,'l':'Alkohol'},"
"{'v':4,'l':'Propan'}"
  "]},"
  "{"
"'name':'fahrenheit',"
"'label':'Fahrenheit',"
"'type':"+String(INPUTCHECKBOX)+","
"'default':'0'"
  "}"
  "]";


//SHT Sensor Instanz
ClosedCube_SHT31D sht;
//MQ2 Sensor Instanz
MQUnifiedsensor MQ2(Board, Voltage_Resolution, ADC_Bit_Resolution, Pin, Type);

//Einstellwerte für verschiedene Gase
const float gase[5][2] {
{987.99,-2.162}, //Wasserstoff
{574.25,-2.222}, //LPG
{36974,-3.109}, //Kohlenmonoxyd
{3616.1,-2.675}, //Alkohol
{658.71,-2.168} //Propan
  };

//Daten an den MQTT Broker senden
void publishData() {
//Daten von SHT30 lesen die hohe Wiederholbarkeit verringert das Rauschen.
//Der Parameter 50 gibt den Timeout an
SHT31D result = sht.readTempAndHumidityPolling(SHT3XD_REPEATABILITY_HIGH, 50);
//Messwerte in Variable übernehmen
float humidity = result.rh;
float temperature = result.t;
String unit = "°C";
temperature = temperature - 6; //Korrektur wegen Erwärmung durch Gassensor und Controller.
//Falls Fahrenheit gewählt wurde, die Temperatur umrechnen
if (conf.getBool("fahrenheit")) {
temperature= temperature * 1.8 +32;
unit="°F";
  }
//Messwerte vom Gassensor
MQ2.update(); // Update die Spannung am Analogeingang wird gemessen
float gas=MQ2.readSensor(); //Die Gaskonzentration in ppm ermitteln
char buffer[1000]; //Buffer für die JSON Zeichenkette
//Der temporäre Speicher für das JSON Dokument wird angelegt
//Wir reservieren 500 Zeichen
StaticJsonDocument<500> doc;
//Das JSON Objekt wird mit Daten befüllt
doc["sensor"]=conf.getValue("sensor"); //Name des Sensors
doc["t"]=temperature; //Temperatur
doc["tu"]=unit; //Einheit
doc["h"]=humidity; //Feuchte
doc["hu"]="%";
doc["g"]=gas; //Gaskonzentration
doc["gu"]="ppm";
//Aus dem Objekt wird die JSON Zeichenkette im Buffer gebildet
uint16_t n = serializeJson(doc, buffer);
//Kontrollausgabe
Serial.println(buffer);
//Der Messwert wird mit dem Thema an den Broker gesendet
if (!client.publish(conf.getValue("thema"), buffer, n)) {
Serial.print("Fehler beim Senden an MQTT Server = ");
Serial.println(client.state());
  }
Serial.printf("Temperatur = %f %s Feuchtigkeit = %f %%   Gaskonzentration = %f       ppm\n",temperature,unit.c_str(),humidity,gas);
}


void setup() {
Serial.begin(74880); //Damit auch Bootmeldungen des ESP8266 angezeigt werden
//I2C Bus starten
Wire.begin();
//Start des SHT30
sht.begin(0x44);
//Seriennummer des SHT30 anzeigen
Serial.print("Serial #");
Serial.println(sht.readSerialNumber());
//Die Setupfunktion in der Include Datei aufrufen
//WLAN und Konfiguration werden vorbereitet
//Verbindung zum MQTT Broker wird hergestellt
// The param parameter contains additional form entries
// for the configuration form, true means that we have a
// have sensor
ESP_MQTT_setup (param, true);
// Register the callback function for sending the data
onPublish = publishData;
// The regression model for the gas concentration is selected
MQ2.setRegressionMethod (1); // _ PPM = a * ratio ^ b
int gas = conf.getInt ("type");
// The parameters for the selected in the configuration
// Gas are set
MQ2.setA (gases [gas] [0]); MQ2.setB (gases [gas] [1]);
// Initialize the gas sensor library
MQ2.init ();
// Calibrate the gas sensor
Serial.print ("Calibrating please wait.");
float calcR0 = 0;
for (int i = 1; i <= 10; i ++)
  {
MQ2.update (); // Update data, the arduino will be read the voltage on the analog pin
calcR0 + = MQ2.calibrate (RatioMQ2CleanAir);
Serial.print (".");
  }
MQ2.setR0 (calcR0 / 10);
Serial.println ("done !.");

if (isinf (calcR0)) {Serial.println ("Warning: Conection issue founded, R0 is infite (Open circuit detected) please check your wiring and supply"); while (1);}
if (calcR0 == 0) {Serial.println ("Warning: Conection issue founded, R0 is zero (Analog pin with short circuit to ground) please check your wiring and supply"); while (1);}
}

void loop () {
// Call the loop function of the integrated auxiliary file
// Ensures that the readings are in regular
// Time intervals are determined and sent to the broker
ESP_MQTT_loop ();
}

Download sketch

The compiler warning that a library may not be compatible with the board can be ignored.

Since many functions are implemented in the include file, the code remains manageable. The most important function is the callback function publishData (), which is always called when new data from the sensors are to be transmitted to the broker. The sensors are prepared in the setup function and then the setup of the include file is called. In the main loop, only the loop function of the include file is called. Right at the beginning the string constant param is defined, which contains the form description of the special configurations for the Envy.

Now we can upload the sketch to the Envy. For that we need one FDTI adapter where we connect GND, TX and RX to the same pins on the Envy.

 


After the sketch has been uploaded, the program can be started. Since there is no configuration yet, an access point is started. We connect to this access point with a smartphone (no password is required) and call the address in a browser http://192.168.4.1 on. The configuration page should now be displayed.

 

After the configuration has been saved and the Envy restarted, it sends a data telegram to the MQTT broker in the configured measurement interval. The figure shows the messages that the broker receives.

 

Now that the Envy provides its measured values ​​as MQTT messages, we want to display the measured values ​​in the smart home center on the AZ-Touch. How to get to the smart home center and how to use it, you can find out from the smart home book. I just want to show a suitable configuration for displaying the data from the Envy. A functional smart home center is required for this.


Important NOTE!!

When the book was finished, the AZ-Touch MOD and the 2.8 inch display did not yet exist. There are therefore small changes to the SmarthomeZentrale_x.ino sketches in Material for the book necessary. Except for the Sketch SmarthomeZentrale_8.ino in the “New” folder, which already contains all changes for the AZ-Touch MOD with 2.8 inch display. The changes to be made are described in the ReadMe.txt file.

We add a new blank page in the smart home center. On this page, we are adding three color bar widgets that are 4 units wide and 14 units high. The figures show the set values:

 


Since the limit values ​​do not fit, we will also adjust the specific settings of the widgets. The figures show the set values:

 


The display page for the Envy should then look like this:

 

 

Have fun with the AZ Envy.

Specials

6 comments

Norbert

Norbert

Hallo,
die SmarthomeZentrale ist interessant, leider kann die sich nicht mit dem MQTT-Server verbinden, da der User und Password fehlt.
Gibt es da eine Lösung ?

Gruß Norbert

Jan

Jan

Alles klar – vielen Dank für die Info – probiere die Beispiele mal aus…

Grüße, Jan

Bernd Albrecht

Bernd Albrecht

Die Frage bezieht sich auf den Sensor MQ-2, der auch separat im Sortiment von AZ-Delivery verkauft wird. Auf der Produktseite gibt es dazu weiterführende Dokumentation.
https://www.az-delivery.de/en/products/gas-sensor-modul?pos=1&_sid=d98f89d48&ss=r
Kurz und knapp: Der Sensor liefert (nur) einen analogen Wert, der ungefähr einer bestimmten Gaskonzentration entspricht. Der Messtechniker nennt so etwas „Schätzeisen“. Wenn Sie nur den analogen Wert messen ( analogRead(A0) ) und einen Schwellenwert für einen Alarm festlegen, dann wird auch bei Rauch dieser Alarm ausgelöst.
Erfahrungswert: Bei einem 10-bit ADC (max. Wert 1023) liegt der Wert für normales Raumklima bei 70 – 110. Wenn Sie den Schwellenwert dann auf 200 festlegen, wird Alarm ausgelöst, wenn ein Schnapsglas in der Nähe verschüttet wird oder der offene Kamin nicht richtig zieht.

Jan

Jan

Hallo,
wie kann ich mir den Rauch(Smoke) ausgeben lassen?
Ihr bietet nur die Gase an…

Danke,

Jan

Gerald Lechner

Gerald Lechner

Hallo Thomas,
Du hast nichts falsch gemacht. Beim Upload der Files auf GitHub ist etwas schief gelaufen und damit war das ZIP File bis auf die Readme Datei leer. Das ist jetzt behoben. Bitte nochmals runterladen.
Sorry Gerald

Thomas Ücok

Thomas Ücok

Hallo,

die ESP8266_MQTT_Conf.h befindet sich nicht in dem GITHub Download. Oder mache ich da etwas
falsch ?

Gruß

Thomas Ücok

Leave a comment

All comments are moderated before being published

Recommended blog posts

  1. Install ESP32 now from the board manager
  2. Lüftersteuerung Raspberry Pi
  3. Arduino IDE - Programmieren für Einsteiger - Teil 1
  4. ESP32 - das Multitalent
  5. OTA - Over the Air - ESP programming via WLAN