Alarm and Heating management

In this subforum you can show projects you have made, or you are busy with. Please create your own topic.
Post Reply
User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Alarm and Heating management

Post by Antori91 » Friday 07 April 2017 9:59

Hello,

I use Domoticz for three functions:
- management of an anti-intruder alarm,
- heating management and heating cost optimization,
- weather information.

Regarding alarm, I've always had in my house a high-end wired alarm but this alarm doesn't have the internet interface I had wished. In a first step, I added a Raspberry in the Alarm box with a custom C ++ program. The Raspberry is interfaced via its GPIO to the electronic alarm board and uses the Pubnub middleware to communicate with a personal Android app. This Raspberry alarm system can send Sms and email to notice alarm events. In a second step, I added Domoticz as an additional client communicating with the Pubnub Alarm channel using a Node.js program and JSON api. In Domoticz, I use the Security Panel and various Alarm light device indicators.

Regarding heating, I use electric heating with two supplier tariffs (day and night). I wanted to go further and follow from Domoticz the actual consumption (Degrees-Day algorithm) and optimize the consumption with possible stops of the heating depending at the difference of temperature between inside and outside and the period of the day (effective presence at home, night, ...). To measure the outside and indoor temperature, I installed two probes based on an ESP8266 chip and a DHT22 sensor. These probes include Arduino / C program to send measurements via Web/JSON format. To update Domoticz temperature devices, I use the JSON api with an external Node.js program which polls via WiFi the ESP8266/DHT22 sensors. This function is at on-going status. I still have to implement the electronic hardware to interface the electrical heating appliances.
Last edited by Antori91 on Tuesday 12 December 2017 22:46, edited 3 times in total.
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Wednesday 02 August 2017 11:29

Update : I've deployed for each electrical heater of my house an ACS712 breakout (http://www.electrodragon.com/product/ac ... rrent5a20a) with Electrodragon ESP8266 Wifi Relay board (http://www.electrodragon.com/product/wi ... d-esp8266/) to measure consumption and manage the heater. The ESP boards read every minute the AC current its heater is using, calculate power consumption and send this power consumption to Domoticz via MQTT. Each ESP/Heater has its each virtual P1 Smart Meter at Domoticz side. For energy usage optimization, I use a script which manages the heaters using Domoticz switch selectors. When this script changes a selector level, the corresponding ESP board get it via MQTT and accordingly adapts the heating program of its heater.

To try to make sure that the heating optimization program is really effective, a script compares the total actual consumption against a theoretical consumption based on the theoretical heat loss coefficient of my house, the difference in outside / indoor temperature and a continuous heating mode. To show in a graphic mode, the actual/outlook versus the continuous/forecast heating, I use the features of the P1 Smart Meter, the script put in Usage 1 (day) and 2 (night) the total consumption and in Return 1 and 2 the theoretical consumption. Based on total power consumption and temperature difference, another script feature recalculates / checks the thermal heat loss coefficient.

All the Domoticz scripts are node.js scripts and I use Arduino IDE to program/flash the ESP8266 board.

This solution is inexpensive, less than 10 euros per heater and can use basic/regular heater (No need of new connected heater using proprietary protocol. However, your heaters need a management interface like the "fil pilote"/pilot wire)
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Tuesday 12 September 2017 11:46

Antori91-DomoticZ.JPG
Antori91-DomoticZ.JPG (142.91 KiB) Viewed 4206 times
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

uNGam3R
Posts: 43
Joined: Wednesday 24 December 2014 14:23
Target OS: Raspberry Pi
Domoticz version: beta
Location: Toulouse, France
Contact:

Re: Alarm and Heating management

Post by uNGam3R » Tuesday 12 September 2017 20:23

Thank you for this presentation, I had pleasure reading your project.
I'm running a similar project and you give me idea.

I guess you are french because ... The electrical heater are mainly used in France ... The other country are generally doing better on this point (I'm french too by the way).

What is your algorithm to compute the heating orders regarding outside temperature ?
Are you including something like a (Thermostat temp - Outside temp)*K coefficient in the PID / PI / PD heater command algorithm ?
Or is that just a check like "When outside temperature is 1 degree below the commanded temperature, I stop the heaters" ?

Anyway, thanks for sharing.
---------------------------------------
Want more about Domoticz scripts and DiY devices?
Go to ---------- http://mydomotic.blogspot.com

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Wednesday 13 September 2017 11:39

Hello uNGam3R,

A short answer is the algorithm is basic today and based on the day period, the energy provider tariff ("French heures creuses/pleines tariff"), whether or not we are at home and difference of indoor/outside temperature. Notice that I do not try to regulate the heaters temperature. When they are switched ON (Eco/Confort) or OFF by Domoticz, it is in principle for a "long" period (several hours). And if switched ON, the heaters will then regulate their temperature with their own thermostat.

Actually, I'm still looking for the best algorithm for my house. This winter will be the first use of this system. I plan to try to find during this first use the most efficient algorithm using the comparison to the simulated mode of permanent heating operation based. I compute this theoretical consumption of permanent heating with the H coefficient (thermal loss). This winter, I will start with a H coeff value I have calculated based on the material building of my house. Then I will adjust this H Coeff. The system will give me the real H Coeff value versus the one I have calculated. I want to validate in particular the axiom "when you stop heating whatever the duration, you always make money"
ChauffageVSprovsion.JPG
ChauffageVSprovsion.JPG (93.69 KiB) Viewed 4116 times
DegresDays.JPG
DegresDays.JPG (96.07 KiB) Viewed 4116 times
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

uNGam3R
Posts: 43
Joined: Wednesday 24 December 2014 14:23
Target OS: Raspberry Pi
Domoticz version: beta
Location: Toulouse, France
Contact:

Re: Alarm and Heating management

Post by uNGam3R » Wednesday 13 September 2017 20:41

Well, OK.
I was doing like you in my first winter with domoticz :).
Know I have set up a PID algorithm (if you have good heater, there is no benefit from this).
Regarding outer loop I run the same algorithm than you are.
To be honest, I'm still not sure about the fact of cutting the heaters, I tried both way and the outcome was nothing outstanding ..

Some advices I can give you based on my experience :
- If you want to run an inner loop (like a PID) as short duration order < 5 min take care about the wireless communication. I frequently encountered transmission loss causing heater stuck either in ON or OFF mode ... My wireless was based on 433Mhz I don't know if Wifi is more accurate. Any I now wired all my heaters to domoticz this seems safer and this winter will be the first try of this system :).
- Take care about you temperature sensors, because they are the center of your algorithm. I mean try to anticipate the fact that it could return you 0° or a wrong value (in case of failure, or in case of bug). It happened to me and caused a full power heating during hours in my house. When I returned the house was 23° instead of 19.5°C ... So now I have a plausibility check (example : plausible = between 5° and 40°).
---------------------------------------
Want more about Domoticz scripts and DiY devices?
Go to ---------- http://mydomotic.blogspot.com

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Thursday 14 September 2017 10:18

Regarding reliability and accuracy, my temperature sensors (ESP8266/DHT22) running already now for months, I'm starting to have an idea. At Domoticz side, a node.js script polls every 5 minutes the sensors and then updates Domoticz.
In case of any error (communication error at server side, unable to reach the sensors, bad value returned by a sensor like NOT A NUMBER), the script logs the error in Domoticz and ignores the corresponding value.
For the heaters monitoring, I use MQTT instead of HTTP polling. With MQTT you have automatic heartbeat monitoring. In case of a subscriber/publisher heater failure, a error is logged in Domoticz.

** ESP8266
- reliability : VERY GOOD. For months, I never get a communication failure. I never restart them.

** DHT22
- reliability : GOOD. For the outdoor one, I get from time to time (maybe one/two times per 24 hours) a NAN value. But DHT22 are not supposed to be used outdoor !
- accuracy : GOOD. For the outdoor one, I compare its reading to the official weather station (near my house) ones (via WUnderground in Domoticz ). Very often for long period of time, it is almost the same readings (gap between 0.0 °C and 1°C max, the 1°C gap is always at morning due I think my sensor is at west against a garden shed wall).
--
TempSensorsLog.JPG
TempSensorsLog.JPG (30.39 KiB) Viewed 4080 times
--
TempLog.JPG
TempLog.JPG (173.98 KiB) Viewed 4080 times
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Thursday 28 September 2017 8:31

Hello,

Here is my Node.js/JavaScript regarding ESP8266/DHT22 temperature logging. This script polls via HTTP the temperature sensors every n minutes and then updates Domoticz. This script is written is a way you don't have to add additional lines of code for each sensor. It is able to manage real physical sensors and virtual ones (used here to compute Degrees Days).

If a sensor fails, it logs the error (like an NAN) at Domoticz Log. If serious error, it set to ON a notification (email/sms) virtual switch within Domoticz (I've chosen for myself a smoked detector type with its reset pushbutton).

You will find also the Arduino sketch I use at ESP8266 side to read its DHT22 sensor and answer to the HTTP requests. Both polling the sensors and Domoticz updating are done using JSON API. The ESP8266 Arduino sketch returns HTTP JSON string message like :
{
"SensorID":"$$YOUR_SENSOR_ID$$",
"Temperature_Celsius":" 20.4",
"Humidity_Percentage":" 80.3",
"HeatIndex_Celsius":" 20.6",
"Sensor_Elapse_Running_Time":"67:00:49"
}

With these two scripts, I'm able to implement rather good and cheap (less than 10 Euros per sensor) temperature sensors in my house.

It can also be used as an example how you can build using JavaScript and Arduino IDE your own end-to-end HTTP communication between ESP8266 and Domoticz. Because the Arduino sketch is Domoticz agnostic (i.e. it doesn't call directly any Domoticz JSON API), I think it's a better architecture for the long term (No need to reflash the ESP8266 in the future if your Domoticz IDX numbers change for example).

Last, I don't try to compete against a Domoticz LUA script in term of number of lines. It was rather for me a question to:
- continue to use Node.js (and its efficient asynchronous functions) I've already used for another feature,
- build a "LEGO architecture".

PS: Items to update in the scripts are tagged $$, for examples :
- Domoticz IDX number corresponding to a sensor tagged [$$DOMOTICZ_PARAMETER],
- "$$YOUR_WIFI_PASSWORD$$" in the Arduino sketch,
- ...

************** Node.js (JavaScript) at Domoticz server side >>>>>>>>>>>>

Code: Select all

// ***** Script to poll ESP8266/DHT22 sensors every n minutes and then update Domoticz *****

var httpDomoticz = require('http');
var JSON_API = {
host: 'localhost',         //[$$DOMOTICZ_PARAMETER]
port: 8084,                //[$$DOMOTICZ_PARAMETER]
path: '/'
};

const passwordProtectedDevice  = '$$YOUR_PASSWORD$$';   //[$$DOMOTICZ_PARAMETER]
const idxHeatingSelector       = '17';     //[$$DOMOTICZ_PARAMETER]
const idxTempFailureFlag       = '43';     //[$$DOMOTICZ_PARAMETER]

var DomoticzJsonTalk = function( JsonUrl, callBack, objectToCompute ) {    // Function to talk to DomoticZ. Do Callback if any 
   var savedURL=JSON.stringify(JsonUrl);
   // console.log("\n** DomoticZ URL request=" + savedURL );
   httpDomoticz.get(JsonUrl, function(resp){
      resp.on('data', function(ReturnData){ 
         // console.log("\nDomoticZ answer=" + ReturnData);
         if( callBack ) callBack( null, JSON.parse(ReturnData), objectToCompute );
      });
   }).on("error", function(e){
         // console.log("\n** Error - " + e.message + "\nCan't reach DomoticZ with URL:" + savedURL );     
         if( callBack ) callBack( e, null, objectToCompute );
   });
};   // function DomoticzJsonTalk( JsonUrl ) 

var RaisefailureFlag = function( error, data ) {
  if( error ) return;
  if( data.result[0].Status === "Off" ) {
       JSON_API.path = '/json.htm?type=command&param=switchlight&idx=' + idxTempFailureFlag + '&switchcmd=On&passcode=' + passwordProtectedDevice;
       JSON_API.path = JSON_API.path.replace(/ /g,"");
       DomoticzJsonTalk( JSON_API );                
  }  // if( GetAlarmIDX.result[0].Status === 
}; // var RaisefailureFlag = fu

var ESP8266DHT22 = require('http');
var ExternalSensor = {
Device: "DHT22",
ID: 'OUTDOOR_ESP8266_DHT22',
SensorUnavailable : 1,
NbReadError : 0,
host: '192.168.1.101',
port: 80,
path: '/',
lastTemp: -150,
lastHumidity: -50,
lastHumStat: '-50',
lastHeatIndex: -150,
idxTempHum: 8,            //[$$DOMOTICZ_PARAMETER]
idxHeatIndex: 15          //[$$DOMOTICZ_PARAMETER]
};
var InternalSensor = {
Device: "DHT22",
ID: 'INDOOR_ESP8266_DHT22',
SensorUnavailable : 1,
NbReadError : 0,
host: '192.168.1.102',
port: 80,
path: '/',
lastTemp: -150,
lastHumidity: -50,
lastHumStat: '-50',
lastHeatIndex: -150,
idxTempHum: 9,             //[$$DOMOTICZ_PARAMETER]
idxHeatIndex: 14           //[$$DOMOTICZ_PARAMETER]
};
var DegreesDaysSensor = {          // Virtual device !
Device: "DEGREESDAYS",
ID: 'DEGREESDAYS',
SensorUnavailable : 1,
lastTemp: -150,
lastHumidity: -50,
lastHumStat: '-50',
idxTempHum: 25,            //[$$DOMOTICZ_PARAMETER]
idxHeatIndex: -1,      // -1 means no HeatIndex for this sensor
ComputeDegreesDays: function( error, data, DegreesDaysValue ) {
  // Compute Degrees-days with BaseTemp=18°C
  // TEMP=Degrés-jour = (18°C - ExternalTemp) 
  // HUM=Degrés-jour_Chauffage_Effectif% = 100 * ( (InternalTemp -1°C (apport occupant) - ExternalTemp) / (18°C - ExternalTemp) )
  // Heating level 0/10/20/30 for OFF/HorsGel/Eco/Confort. If OFF or HorsGel, we assume Heating is Power Off (i.e Degrés-jour_Chauffage_Effectif%=0)
  DegreesDaysValue.lastTemp=0; DegreesDaysValue.lastHumidity=100; DegreesDaysValue.lastHumStat='0';
  DegreesDaysValue.SensorUnavailable = ExternalSensor.SensorUnavailable;
  if ( !DegreesDaysValue.SensorUnavailable && ExternalSensor.lastTemp < 18 ) { DegreesDaysValue.lastTemp=(18-ExternalSensor.lastTemp); DegreesDaysValue.lastTemp=DegreesDaysValue.lastTemp.toFixed(1); }
  if( error ) return;
  if ( data.result[0].Level === 0 || data.result[0].Level === 10 ) DegreesDaysValue.lastHumidity=0; 
      else if ( !DegreesDaysValue.SensorUnavailable && ExternalSensor.lastTemp < 18 && !InternalSensor.SensorUnavailable ) { 
                  DegreesDaysValue.lastHumidity=100*(InternalSensor.lastTemp-1-ExternalSensor.lastTemp)/(18-ExternalSensor.lastTemp); DegreesDaysValue.lastHumidity = DegreesDaysValue.lastHumidity.toFixed(1); 
      } 
  if (DegreesDaysValue.lastHumidity <= 50) DegreesDaysValue.lastHumStat='2'; else if (DegreesDaysValue.lastHumidity > 100) DegreesDaysValue.lastHumStat='1';         
  }  // var ComputeDegreesDays
};
// ** Temp sensors list. 
var MyTempSensors = [ExternalSensor, InternalSensor, DegreesDaysSensor];  
const PollingTimer  = 5; // Poll the sensors every n minutes
const SensorTimeOut = 2 * (60/PollingTimer); // If a Sensor is not available for n hours, raise TEMP SENSOR ALARM in DomoticZ
var lastDaySeen     = new Date().getDate();

// ***** INIT
console.log("*** " + new Date() + " - Domoticz iot_ESP8266/DHT22 started ***\n");

// ***** LOOP à la Arduino mode...
setInterval(function(){ // get Temp/Humidity from sensors every n minutes
   
    // *** Print each day, the total number of DHT22 reading errors
    var Today = new Date().getDate();
    if( Today !== lastDaySeen ) {
       console.log("\n*** " + new Date() + " Indoor/Outdoor DHT22 NAN Reading Error=", InternalSensor.NbReadError, "/", ExternalSensor.NbReadError);
       InternalSensor.NbReadError =  ExternalSensor.NbReadError = 0;
       lastDaySeen=Today;
    }

    // *** READ SENSORS LOOP  *** 
    MyTempSensors.forEach(function(value) {
           var ERROR_MESSAGE = "";
           if( value.Device === "DEGREESDAYS" )   {
               JSON_API.path = '/json.htm?type=devices&rid=' + idxHeatingSelector;
               DomoticzJsonTalk( JSON_API, value.ComputeDegreesDays, value );                            
           } else  // if( value.Device === "DEGREESDAYS" )   
               ESP8266DHT22.get(value, function(resp){
                  resp.on('data', function(JSONSensor) {
                     // console.log("Sensor=" + JSONSensor);
                     const CurrentSensorValue = JSON.parse(JSONSensor);                           
                     if( CurrentSensorValue.Temperature_Celsius === "DHT22 ERROR" ) {     // ESP8266 available but a DHT22 reading error occured 
                         value.SensorUnavailable++;  value.NbReadError++;
                         ERROR_MESSAGE="Error - " + value.ID + " has returned a wrong value (NAN)";   
                         ERROR_MESSAGE=ERROR_MESSAGE.replace(/ /g,"%20");
                         JSON_API.path = '/json.htm?type=command&param=addlogmessage&message=' + ERROR_MESSAGE;
                         DomoticzJsonTalk( JSON_API );  
                     } else { 
                         value.lastTemp=CurrentSensorValue.Temperature_Celsius;
                         value.lastHumidity=CurrentSensorValue.Humidity_Percentage;
                         value.lastHeatIndex=CurrentSensorValue.HeatIndex_Celsius;
                         value.lastHumStat='0';
                         if (value.lastHumidity <= 30 ) value.lastHumStat='2'
                            else if (value.lastHumidity >= 70 ) value.lastHumStat='3'
                                 else if (value.lastHumidity >= 45 && value.lastHumidity <= 65 ) value.lastHumStat='1';
                         value.SensorUnavailable = 0;              
                     }  // // if( CurrentSensorValue.Temperature_Celsius == "DHT22 ERROR" )                    
                  }); //resp.on('data', function(JSONSensor
               }).on("error", function(e){                  
                     if( value.SensorUnavailable===1) { // Log this error in DomoticZ only the first time in a row
                         ERROR_MESSAGE="Error - " + value.ID + " " + e.message;   
                         ERROR_MESSAGE=ERROR_MESSAGE.replace(/ /g,"%20");
                         JSON_API.path = '/json.htm?type=command&param=addlogmessage&message=' + ERROR_MESSAGE;
                         DomoticzJsonTalk( JSON_API );
                     }  // if( value.SensorUnavailable===1  
                     value.SensorUnavailable++;  value.NbReadError++;
               }); // ESP8266DHT22.get(value, function(resp){   
    }); // MyTempSensors.forEach(f
     
    //  *** DOMOTICZ UPDATE LOOP  ***
    MyTempSensors.forEach(function(value) {      
           // Log temperature and humidity     
           if( !value.SensorUnavailable )  {
               JSON_API.path = '/json.htm?type=command&param=udevice&idx='+ value.idxTempHum +'&nvalue=0&svalue=' + value.lastTemp + ';' + value.lastHumidity + ';' + value.lastHumStat;
               JSON_API.path = JSON_API.path.replace(/ /g,"");
               DomoticzJsonTalk( JSON_API );  
               // Log HeatIndex temperature  
               if( value.idxHeatIndex !== -1 ) {
                   JSON_API.path = '/json.htm?type=command&param=udevice&idx='+ value.idxHeatIndex +'&nvalue=0&svalue=' + value.lastHeatIndex;
                   JSON_API.path = JSON_API.path.replace(/ /g,"");
                   DomoticzJsonTalk( JSON_API );
               }  // if( value.idxHeatIndex !== -1 ) {
           }  // if( !value.SensorUnavailable )  {
    }); // MyTempSensors.forEach(f
    
    // *** SENSORS HEALTH CHECK LOOP. If we have a sensor failure for n hours, raise TEMP SENSOR FAILURE in DomoticZ *** 
    MyTempSensors.forEach(function(value) {      
           if( value.SensorUnavailable >= SensorTimeOut ) {
               JSON_API.path = '/json.htm?type=devices&rid=' + idxTempFailureFlag;
               DomoticzJsonTalk( JSON_API, RaisefailureFlag );               
           }  //  if( value.SensorUnavaila
    }); // TempSensors.forEach(f
    
}, PollingTimer*60000); // setInterval(function(){  get Temp/Humidity from sensors every n mn
************** Arduino sketch at ESP8266 side >>>>>>>>>>>>

Code: Select all

// ***** Script to read DHTxx sensor and send the measure as HTTP JSON message *****
#include "DHT.h"
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>


const char *ssid = "$$YOUR_SSID$$";
const char *password = "$$YOUR_WIFI_PASSWORD$$";
IPAddress ip(192,168,1,101); 
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
ESP8266WebServer server ( 80 );

#define SID "$$YOUR_SENSOR_ID$$"
#define JSONstart "{"
#define JSONend "}"

#define DHTPIN 5    // what digital pin we're connected to
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE);

void handleRoot() {
	char temp[520];
  char str_t[10];
  char str_h[10];
  char str_hic[10];
 
	int sec = millis() / 1000;
	int min = sec / 60;
	int hr = min / 60;

  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  
  /* Check if any reads failed and exit early (to try again) */
  if ( isnan(h) || isnan(t) ) {
     /* Serial.println("Failed to read from DHT sensor!"); */
     snprintf ( temp, 520,
"%s\n\
\"SensorID\":\"%s\",\n\
\"Temperature_Celsius\":\"%s\",\n\
\"Humidity_Percentage\":\"%s\",\n\
\"HeatIndex_Celsius\":\"%s\",\n\
\"Sensor_Elapse_Running_Time\":\"%02d:%02d:%02d\"\n\
%s",
     JSONstart, SID, "DHT22 ERROR", "DHT22 ERROR", "DHT22 ERROR", hr, min % 60, sec % 60, JSONend
     );
  } // if ( isnan(h) || isnan(t) ) {
  else {
     /* Compute heat index in Celsius (isFahreheit = false) */
     float hic = dht.computeHeatIndex(t, h, false);
     dtostrf(t, 5, 1, str_t);
     dtostrf(h, 5, 1, str_h);
     dtostrf(hic, 5, 1, str_hic);
   	 snprintf ( temp, 520,
"%s\n\
\"SensorID\":\"%s\",\n\
\"Temperature_Celsius\":\"%s\",\n\
\"Humidity_Percentage\":\"%s\",\n\
\"HeatIndex_Celsius\":\"%s\",\n\
\"Sensor_Elapse_Running_Time\":\"%02d:%02d:%02d\"\n\
%s",
     JSONstart, SID, str_t, str_h, str_hic, hr, min % 60, sec % 60, JSONend
     );
  } /* else if if (isnan(h) || isnan(t) || isnan(f)) */
	
	server.send ( 200, "application/json", temp );
} /* void handleRoot() { */

void handleNotFound() {
	String message = "URL Not Found\n\n";
	message += "URI: ";
	message += server.uri();
	message += "\nMethod: ";
	message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
	message += "\nArguments: ";
	message += server.args();
	message += "\n";

	for ( uint8_t i = 0; i < server.args(); i++ ) {
		message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
	}
	server.send ( 404, "text/plain", message );
} /* handleNotFound() { */

void setup ( void ) {

  dht.begin();
	Serial.begin ( 57600 );
	WiFi.begin ( ssid, password );
  WiFi.config(ip, gateway, subnet);
	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() );

	if ( MDNS.begin ( "esp8266" ) ) {
		Serial.println ( "MDNS responder started" );
	}

	server.on ( "/", handleRoot );
	server.on ( "/inline", []() {
		server.send ( 200, "text/plain", "$$YOUR_SENSOR_ID$$.Temp/RESTAPI Reserved Use Mode" );
	} );
	server.onNotFound ( handleNotFound );
	server.begin();
	Serial.println ( "HTTP server started" );
}

void loop ( void ) {
	server.handleClient();
}
My_Switches.JPG
My_Switches.JPG (355.25 KiB) Viewed 3429 times
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Wednesday 06 December 2017 15:23

Hello,

Here is an update with photos regarding my electric heating management project (and water heating appliance).

To summarize the features :
- heaters grouped within zones. A zone can be activated / unactivated at Domoticz using hours programming mode, can also be forced to stop/start,
- for the time programming of the zones, to avoid having as many switches as heaters/zones within Domoticz, I developed a script which allows me to have only two schedule switches: "TOP start time" and "TOP stop time",
- log the electric consumption of each heater (full and off-peak hours) and calculate the overall consumption,
- calculate the actual nominal electrical power of each heater (seems a little different sometimes from the manufacturer label placed on the heater),
- calculate the heat loss rate and cooling rate (this in connection with two temperature probes : indoor and outdoor),
- calculate and log the heating degree-days,
- monitor the overall electricity consumption versus a theoretical consumption calculated with the rate of heat loss. This comparison makes it possible to determine if heating start / stop (via algorithms or not) are efficient,
- alert via email / sms in case of failure of one of the ESP8266,
- also works for the water heating appliance (but not yet installed).

Last, the Arduino program embedded in the ESP8266 is FOTA aware (Flash Over The Air) for possible remote reprogramming via WiFi and talks to Domoticz via MQTT.
Attachments
VueACS712etESP8266.JPG
VueACS712etESP8266.JPG (63.13 KiB) Viewed 3171 times
Chambre-ESP8266_ACS712.JPG
Chambre-ESP8266_ACS712.JPG (27.07 KiB) Viewed 3171 times
PanelConso_.JPG
PanelConso_.JPG (266.85 KiB) Viewed 3171 times
Last edited by Antori91 on Wednesday 06 December 2017 15:34, edited 1 time in total.
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Wednesday 06 December 2017 15:31

SalonN-ESP8266_AC712.JPG
SalonN-ESP8266_AC712.JPG (73.06 KiB) Viewed 3167 times
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Sunday 14 January 2018 22:39

[Update Hot Water Tank]

I've completed today the implementation of my energy consumption dashboard by connecting my hot water tank (300L / 3300W) to an ESP8266. For this measure of consumption, I finally don't use an ACS712 as I did for electric heaters but use one thermostat line as GPIO. However, I use the same Arduino program for heaters and this tank via an integrated configuration management: device type and consumption sensor declaration.
Capture3.JPG
Capture3.JPG (133.08 KiB) Viewed 2686 times
Capture2.JPG
Capture2.JPG (135.44 KiB) Viewed 2686 times
Capture4.JPG
Capture4.JPG (267.96 KiB) Viewed 2686 times
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Friday 19 January 2018 12:17

HWTconnections.JPG
HWTconnections.JPG (201.05 KiB) Viewed 2580 times
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Tuesday 05 June 2018 19:19

Hello,

I've shared on Github https://github.com/Antori91/Home_Automation the ESP8266 code and the node.js server side scripts of my application described above and also here http://www.domoticz.com/forum/viewtopic ... 38&t=21608. The whole code is there except the management modules of my wired alarm.
If this code needs to be modified to run in another environment than mine, it provides the basis I would have liked to have a year ago when I've
started writing it. It can I think be used as template for:
- MQTT support with the https://pubsubclient.knolleary.net/ library and some examples of MQTT commands for Domoticz
- "HttpPolling" example with an ESP8266 module implementing a web server returning readings (in JSON format) from a DHT22 sensor to a polling node.js script that updates Domoticz via JSON API
- the support / decoding JSON of the MQTT commands received from Domoticz with the library https://arduinojson.org/
- OTA support, i.e. able to ESP8266 reflashing via WiFi from the Arduino IDE, cf. https://arduino-esp8266.readthedocs.io/ ... eadme.html
- the electrical power meter feature with the use of the ACS712 analog probe. I had to work hard on the subject and try two algorithms before arriving at a correct accuracy. I later discovered this site https://learn.openenergymonitor.org/ele ... troduction. It gives the principles that I have arrived to have this good accuracy, especially not using the peak-to-peak algorithm that is found everywhere on DIY sites on the internet but a RMS algorithm.
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

kimot
Posts: 55
Joined: Saturday 25 November 2017 18:18
Target OS: Raspberry Pi
Domoticz version: v3.8153
Location: Czech Rep.
Contact:

Re: Alarm and Heating management

Post by kimot » Tuesday 12 June 2018 23:30

One question:
Why you use current sensor for energy measuring for el. heating?
Simply use declared power and if heating is on, send this value to Domoticz.
If you want be very accurate - measure voltage only, because resistance of heating element is constant - so power variates only with voltage changes.
But I think this is not needed, because Domoticz itself calculate energy consumption with error ( cca -8% for daily consumption )

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Wednesday 13 June 2018 8:18

kimot wrote:
Tuesday 12 June 2018 23:30
One question:
Why you use current sensor for energy measuring for el. heating?
Simply use declared power and if heating is on, send this value to Domoticz.
I have schedules within Domoticz to start/stop the heaters (I can also bypass the schedule using the GUI or Android app to force to start/stop). The start/stop commands are then sent to the heaters. When a heater is ON, it is its **own thermostat** which decides actually to heat or not. So, I need this sensor. In other words, I didn't want Domoticz replacing the heater thermostat.
kimot wrote:
Tuesday 12 June 2018 23:30
If you want be very accurate - measure voltage only, because resistance of heating element is constant - so power variates only with voltage changes.
????????
Did you browse this site https://learn.openenergymonitor.org/ele ... troduction
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

kimot
Posts: 55
Joined: Saturday 25 November 2017 18:18
Target OS: Raspberry Pi
Domoticz version: v3.8153
Location: Czech Rep.
Contact:

Re: Alarm and Heating management

Post by kimot » Thursday 14 June 2018 23:49

I have schedules within Domoticz to start/stop the heaters (I can also bypass the schedule using the GUI or Android app to force to start/stop). The start/stop commands are then sent to the heaters. When a heater is ON, it is its **own thermostat** which decides actually to heat or not. So, I need this sensor. In other words, I didn't want Domoticz replacing the heater thermostat.
Sorry, I do not notice, that you use build in bimetalic thermostat on heater.
But I do not know why, when you have got ESP with relay and info about room temperature with possibility use Domoticz setpoint with time scheduling too.
????????
Did you browse this site https://learn.openenergymonitor.org/ele ... troduction
Heaters are pure resistive loads. Its resistivity is constant, no nonlinearity, cos fi constnat and = 1.
So
P = U * I
I = U / R
then

P = U * U / R

For heater you do not need measure current.
Simply use nominal value from heater label or calculate by multimeter measuring voltage and current and calculate power.
Or if you want be very precise - measure R for heater and then in program measure actual voltage and calculate power.
Because, what really changes in your circuit is voltage.
It is difference when is On only one heater or all.
There is some voltage drop on cables to your home or flat.

Instead, you very sophistically calculate actual current and then use at line 576 of your code:

HeaterPower = 230*Arms;

And for last - look what do Domoticz with your very hardly computed power usage.
For example, I send usage 660 W every minute for couple of hours.
If you think, that hourly usage is 660Wh - you are wrong.
No, sorry you are right - Domoticz is wrong, because computes 606Wh for each hour.
Simply put away last 5 min from database and not add them to next hour.
But autors means - it is not bug, it must be that way programmed :o)
The attachment Energy_1.png is no longer available
Energy_1.png
Energy_1.png (315.75 KiB) Viewed 1368 times
And here is my heating system with ESP2866:

https://www.youtube.com/watch?v=1ef6tRinOQ4

lost
Posts: 191
Joined: Thursday 10 November 2016 10:30
Target OS: Raspberry Pi
Domoticz version:
Contact:

Re: Alarm and Heating management

Post by lost » Friday 15 June 2018 8:42

Antori91 wrote:
Wednesday 13 June 2018 8:18
In other words, I didn't want Domoticz replacing the heater thermostat.
This is what I also did. Old heaters were replaced by new ones from a discount shop (Brico-Depot), not very expensive (those that allow complex programs are, but I wanted this all done from Domoticz so this was not a buying criteria) but heat-accumulation ones with a good (& silent, for bedrooms!) electronic regulation.

On heater choice, take care that in one of your photos you've got an IR one near a window: So one part of the heat just goes out! This kind of heaters were only designed for bathroom (so it can heat you from behind the shower cab window were you just cannot install a heater!) in the past, when used somewhere else this can be pure waste of electric power even if those that manufacture them says you'll save money with them!

On my side, this was not DIY modules but Qubino ones that can send the 6 orders heaters are designed for & small enough to be hidden in the wall connection box. Managed by plannings/presence detection mix.

For power consumption, I did not managed to get every heter consumption. I installed a Qubino smart-meter in the circuit breaker enclosure that also manage power cut (bypassing, serially wired, law-fare relay command if needed) of the water tank (if I get near my 9kW max allowed instant consumption).

Even with only this global measure, knowing devices power consumption, I can foresee quite easily which are powered & explain current sum.

In my experience, almost shutting down (using froze-prevent command) heaters an hour before planned absence (heat-accumulation remains almost 1h after shutiing down heaters)/bed time & setting back power progressively 2 or 3 hours (eco mode and -1/-2°C then confort in the last hour) before being back/wake-up saves money, especially if also trying to optimize low fare hours (2h/7h + 14h/17h for me) use.

If presence is detected with heaters active commands used in supposed absent shedules & Tre is under 19°C, a "confort" order is sent to heaters for 30mn (that will be sent again if still there). That's the only simple adaptive thing to allow immediate/full heating if my childs get back at different hours from planning because a teacher was absent for instance.

Quite easy to implement, but with this I just manage to heat a 110 sq.m house with electric heaters for less money than my previous 70 sq.m flat using gas. Devices cost (~500€, not including heaters that were very old/uncomfortably heating & had to be changed) was amortized during this second winter.

As alarm function was added with only a few more z-wave devices + low cost cams (managed by a python FTP/uploaded images monitoring service, able to filter false positives feeding some Domoticz virtual PIRs/alarm weighting mechanism & e-mail images by 10s time-frames) & those able to connect to a network to report events are very expensive, more savings also resulted from ablity to merge things provided by Domoticz platform.

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Friday 15 June 2018 9:13

kimot --> Sorry, I do not notice, that you use build in bimetalic thermostat on heater.
But I do not know why, when you have got ESP with relay and info about room temperature with possibility use Domoticz setpoint with time scheduling too.

Answer --> A short answer is I don't have confidence in such system. You need to have at Domoticz side a thermostat implementing PID or hysteresis algorithm which sends the start/stop commands to the heaters when the temperature moves away or reaches the setpoint. What happens if one the element fails (the temperature sensor in your room, the ESP, network, WiFi router, MQTT software/server, the central server (hardware), Domoticz itself, ...) your heaters don't receive anymore any command or eventually receive wrong commands. You see what I mean....
In my system, if for example network, central server or Domoticz is down, it means that the ESP lost the MQTT connection. And in this case, the ESP put the heater on. I will never get no heating (or heating all day long) because home automation is down or failed.
[UPDATE] Kimot, only after writing this comment, I've seen your youtube video about your system. I understand that using temp sensor at ESP level you've implemented the thermostat feature at ESP side. In my idea it's much better than at Domoticz level. And now, I understand better your questions, you don't need to measure current to get a signal if heater is heating or not because the ESP is the thermostat.


kimot -- > Heaters are pure resistive loads. Its resistivity is constant, no nonlinearity, cos fi constnat and = 1.
So
P = U * I
I = U / R
then

P = U * U / R

For heater you do not need measure current.
Simply use nominal value from heater label or calculate by multimeter measuring voltage and current and calculate power.
Or if you want be very precise - measure R for heater and then in program measure actual voltage and calculate power.
Because, what really changes in your circuit is voltage.
It is difference when is On only one heater or all.


Answer --> I understand what you mean.

Two comments first :
- There is difference between the nominal value from heater label (manufacturer information) and the actual power of the heater (usually less based on my experience).
- I'm not going to open the heaters to measure the resistance of the heater.

But the main reason is : because heating is managed by the heater thermostat and because I want to monitor the energy used, I need to have a signal telling me if heater starts or stops to heat. I have usually no way (except for my hot water tank) to get such signal from the thermostat itself. So, I use the ACS712 to get such signal. In theory you are right : ACS712 should return to me only two values : 0 or the nominal power/230 and the heater power usage has only two values 0 (heater off) or the nominal power (heater on).
By the way, the code I wrote for the ESP8266 can compute the power usage using one of these three ways :
- a nominal power declared within the code or from Domoticz heater/device name (in this case, it is almost your solution and I use it for the hot water tank),
- ACS712 raw values,
- a self-learning algorithm of the heater nominal power using ACS712 raw values.
If device name within Domoticz is something like HEATER_NAME{XXXX} where XXXX is the nominal power, solution 1 (almost your solution) is used, if device name is HEATER_NAME{0} solution 2 is used and if device name is HEATER_NAME without any {} solution 3 is used.


kimot --> And for last - look what do Domoticz with your very hardly computed power usage.
For example, I send usage 660 W every minute for couple of hours.
If you think, that hourly usage is 660Wh - you are wrong.
No, sorry you are right - Domoticz is wrong, because computes 606Wh for each hour.
Simply put away last 5 min from database and not add them to next hour.
But autors means - it is not bug, it must be that way programmed

Answer--> I don't send power usage to Domoticz but energy usage (energy usage is computed by the ESP8266). Then Domoticz computes the power usage. Depending on the Domoticz energy device you use, you can do it in two ways with Domoticz:
- send Energy usage to Domoticz and Domoticz computes power usage or
- send power usage to Domoticz and Domoticz computes Energy usage.
So I'm sure about energy usage, Domoticz "only" stores the energy usage I send to it. And if home automation is down (except of course the ESP8266) energy usage is still computed and will be stored in Domoticz when home automation will be back.
Last edited by Antori91 on Friday 15 June 2018 11:55, edited 7 times in total.
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Friday 15 June 2018 10:17

lost wrote:
Friday 15 June 2018 8:42
Antori91 wrote:
Wednesday 13 June 2018 8:18
In other words, I didn't want Domoticz replacing the heater thermostat.
On heater choice, take care that in one of your photos you've got an IR one near a window: So one part of the heat just goes out! This kind of heaters were only designed for bathroom (so it can heat you from behind the shower cab window were you just cannot install a heater!) in the past, when used somewhere else this can be pure waste of electric power even if those that manufacture them says you'll save money with them!
This heater has both IR and usual resistance heating (two "heating channels"). The IR channel died a long time ago...I have another heater like this one and it is the same for this second one. Based on my experience, IR heaters are not reliable at all. I've changed all of them (except these two ones) for basic heaters. And with basic heaters, no trouble at all.
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

User avatar
Antori91
Posts: 102
Joined: Sunday 12 February 2017 18:12
Target OS: NAS (Synology & others)
Domoticz version: 4.97&3.5
Location: France
Contact:

Re: Alarm and Heating management

Post by Antori91 » Friday 15 June 2018 16:56

Kimot, additional comments/answers to your question " But I do not know why, when you have got ESP with relay and info about room temperature with possibility use Domoticz setpoint with time scheduling too"

I had thought of your solution but did not take it because I feared the following:
- the code embedded in the ESP becomes mission critical (even safety critical), quid for example if due to thermostat code bug, the heater heats all day long,
- the heater power is then switched on/off all day long by the ESP relay. Even though my heaters are basic, some have electronic thermostat (even if not used in your solution), I'm not sure they will like it,
- reliability/accuracy of temperature sensors used in DIY or the ESP librairies interfacing them,
- it is generally accepted that it is better to move away the temperature sensor from the source of heat. It means temperature sensor and relay ESP must be distant, and in this case :
- you can suffer from network/hardware issues,
- you must have two ESP for each room with a heater (1 to manage the heater and 1 for the temp sensor)
Domoticz High Availability Cluster: Synology Dz V3.5877 (Main) - Raspberry Dz V4.97 (Backup) - Scripts Node.js
Alarm server: Raspberry - motionEye - iot_ALARM-SVR Node.js
Sensors/Actuators: ESP8266-Arduino
https://github.com/Antori91/Home_Automation

Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests