Commit 58f8807fbaea629d67032fc34ec14d856e7539b8

Authored by Jeroen88
1 parent da4e4938

Add first draft MQTT thermostat example

examples/MQTT_Advanced_Thermostat/MQTT_Advanced_Thermostat.ino 0 → 100644
  1 +/*
  2 + * https://github.com/Jeroen88/EasyOpenTherm
  3 + * https://www.tindie.com/products/Metriot/OpenTherm-adapter/
  4 + *
  5 + * MQTT_Advanced_Thermostat is a program to demonstrate a real working thermostat over MQTT.
  6 + * This thermostat publishes measured room temperature about the boiler to the MQTT broker in topic 'temperature'.
  7 + * It subscribes to topic 'room_temperature_setpoint' to receive the room temperature setpoint.
  8 + *
  9 + * Copyright (C) 2022 Jeroen Döll <info@metriot.nl>
  10 + *
  11 + * This program is free software: you can redistribute it and/or modify
  12 + * it under the terms of the GNU General Public License as published by
  13 + * the Free Software Foundation, either version 3 of the License, or
  14 + * (at your option) any later version.
  15 + *
  16 + * This program is distributed in the hope that it will be useful,
  17 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19 + * GNU General Public License for more details.
  20 + *
  21 + * You should have received a copy of the GNU General Public License
  22 + * along with this program. If not, see <https://www.gnu.org/licenses/>.
  23 + *
  24 + * You need an OpenTherm controller that you can buy at my Tindie store, see <https://www.tindie.com/products/jeroen88/opentherm-controller/>
  25 + * Connect the two boiler wires to the OpenTherm controller pins marked OT. The order of the wires is not important.
  26 + * Connect the OpenTherm controller to your microcontroller's power (3v3) and ground (GND) pins.
  27 + * Connect the OpenTherm TXD pin to the microcontroller's pin defined by #define OT_RX_PIN.
  28 + * Connect the OpenTherm RXD pin to the microcontroller's pin defined by #define OT_TX_PIN.
  29 + *
  30 + * Connect the BME280 temperature sensor SDA pin to the microcontroller's pin defined by #define I2C_SDA_PIN
  31 + * Connect the BME280 temperature sensor SCL pin to the microcontroller's pin defined by #define I2C_SCL_PIN
  32 + * Check your sensor's address, it may differ from the value defined by #define BME_ADDRESS (0x76)
  33 + * Install the Adafruit BME280 library
  34 + * Any other temperature sensor may be used, like a Dallas sensor, BME380, BMP380, BME680 if you adapt the program accordingly.
  35 + *
  36 + * Define the room temperature setpoint (desired room temperature) using #define ROOM_TEMPERATURE_SETPOINT. In a real application this should be settable.
  37 + * Eventually define the maximum central heating boiler temperature setpoint using #define CH_MAX_SETPOINT.
  38 + *
  39 + * Compile and upload the program as normal. If the temperature measured by your sensor is lower than the ROOM_TEMPERATURE_SETPOINT this thermostat program will actually begin to heat up your room
  40 + */
  41 +
  42 +/* IMPORTANT NOTICES
  43 + * You have to do a lot of configuration to get this running! It is not difficult, but you have to be diligent.
  44 + * This example uses a certificate to autenticate the MQTT server and to ecnrypt the connection using TLS (Transport Layer Security) with a WiFiClientSecure. If you do not want to use this feature,
  45 + * because e.g. your MQTT broker does not support it, you have to adapt this program:
  46 + * - Use a WiFiClient instead of a WiFiClientSecure
  47 + * - Do not define const char CACertificate[] (remove it from the program or leave it 'as is')
  48 + * - Do not call wiFiClient.setCACert(CACertificate);
  49 + *
  50 + * You SHOULD provide your #define TIME_ZONE, otherwise the time displayed will be different than your timezone. The value provided for in the example is Central Europe Time with Daylight Saving
  51 + *
  52 + * You MUST provide the GPIO pins the OpenTherm controller is connected to (#define OT_RX_PIN and #define OT_TX_PIN)
  53 + *
  54 + * You MUST use a BME280 temperature sensor board and provide the I2C address of your sensor and the GPIO pins it is connected to (#define BME_ADDRESS, #define I2C_SDA_PIN and I2C_SCL_PIN)
  55 + * You MAY use a completely different sensor, e.g a BME680 or even a Dallas temperature sensor) but then you MUST adapt the program accordingly
  56 + *
  57 + * You MUST provide your WiFi credentials (const char * ssid and const char * password)
  58 + *
  59 + * You MUST provide your MQTT server, MQTT user name and MQTT password (const char * mqtt_server, const char * mqtt_user = "CloudMQTT" and const char * mqtt_password)
  60 + * This thermostat publishes the corrected measured room temperature to the MQTT broker in topic 'temperature'
  61 + * It subscribes to topic 'room_temperature_setpoint' to receive the room temperature setpoint. This temperature is not persistant. If you restart the program, you have to resend it.
  62 + *
  63 + * You MUST provide the CA certificate of your MQTT server (unless you use an insecure connection, see above, const char CACertificate[])
  64 + *
  65 + * You SHOULD calibrate your sensor by measuring a low temperature (e.g. 15 *C, not very critical) and a high temperature (e.g. 20 *C, again not critical) with both the temperature sensor and a
  66 + * calibrated thermomter. Store the results into #define LOWER_MEASURED_TEMPERATURE, LOWER_CALIBRATED_TEMPERATURE, HIGHER_MEASURED_TEMPERATURE and HIGHER_CALIBRATED_TEMPERATURE)
  67 + *
  68 + * You MAY want to change the minimum and maximum room temperature using #define ROOM_TEMPERATURE_MIN_SETPOINT and ROOM_TEMPERATURE_MAX_SETPOINT. On startup the thermostat is set to
  69 + * ROOM_TEMPERATURE_MIN_SETPOINT. In this example these values are set to 12.0 and 25.0 *C
  70 + *
  71 + * You MAY want to change the minimum and maximum Central Heating boiler water temperatures using #define CH_MIN_SETPOINT and #define CH_MAX_SETPOINT. In this example these values are set to
  72 + * 10.0 and 60.0 *C. Remember: lowering the maximum will reduce the power of your central heating, thus increasing the time to heaten up your room and lowering the gas usage per hour. A good
  73 + * practise seems to lower this temperature for a well insulated house and/or using low temperature radiators e.g to 40.0 *C. If it takes too long to warm your house on a very cold winter day,
  74 + * increase to 60.0 *C or even higher in a badly insulated house. Check your boiler manual for the right maximum temperature.
  75 + *
  76 + * I hope you enjoy working with this library, pPlease share ideas in the Github Discussions sessions of this library.
  77 + */
  78 +
  79 +#include <Arduino.h>
  80 +
  81 +#include <WiFi.h>
  82 +#include <WiFiClientSecure.h>
  83 +#include <time.h>
  84 +
  85 +#include <Wire.h>
  86 +#include <Adafruit_Sensor.h>
  87 +#include <Adafruit_BME280.h>
  88 +
  89 +#include <PubSubClient.h>
  90 +
  91 +#include <EasyOpenTherm.h>
  92 +
  93 +
  94 +// Your time zone, used to display times correctly and needed for WiFiClientSecure TLS certificate validation
  95 +#define TIME_ZONE "CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00"
  96 +
  97 +
  98 +// GPIO pin used to read data from the boiler or HVAC. Must support interrupts
  99 +#define OT_RX_PIN (34)
  100 +// GPIO pin used to send data to the boiier or HVAC. Must not be a 'read only' GPIO
  101 +#define OT_TX_PIN (17)
  102 +
  103 +// The address of the BME280 temperature sensor
  104 +#define BME_ADDRESS (0x76)
  105 +// I2C SDA GPIO pin used to read out the BME280 temperature sensor
  106 +#define I2C_SDA_PIN (8)
  107 +// I2C SSCL GPIO pin used to read out the BME280 temperature sensor
  108 +#define I2C_SCL_PIN (9)
  109 +
  110 +
  111 +// The maximum room temperature
  112 +#define ROOM_TEMPERATURE_MAX_SETPOINT (25.0f)
  113 +// The minimum room temperature
  114 +#define ROOM_TEMPERATURE_MIN_SETPOINT (12.0f)
  115 +// The maximum Central Heating boiler temperature. If your house is well isolated and/or you have low temperature radiators this could be as low as 40.0f
  116 +#define CH_MAX_SETPOINT (60.0f)
  117 +// If the boiler starts it will warm up until at least this temperature (unless the desired room temperature is reached before)
  118 +#define CH_MIN_SETPOINT (10.0f)
  119 +
  120 +// If the boiler supports Central Heating (CH), use the boiler for heating
  121 +#define ENABLE_HEATING (true)
  122 +// If the boiler supports cooling, use the boiler for cooling.
  123 +#define ENABLE_COOLING (true)
  124 +// If the boiler supports Domestic Hot Water (DHW), use the boiler for DHW
  125 +#define ENABLE_DOMESTIC_HOT_WATER (true)
  126 +
  127 +
  128 +// Cheap sensor tend to be inaccurate. Accuracy can be increased by adding two temperatures as measured by the sensor and the 'real' temperature as measured with a calibrated thermometer
  129 +// If your sensor is accurate or if you do not want to use this feature, set measured and calibrated values to the same value
  130 +// Make sure that the lower temperatures and higher temperatures are a few degrees apart. Ideal would be to use temperatures around the minimum room temperature setpoint and the maximum room temperature setpoint
  131 +// Make sure that the difference between both lower temperatures and both higher temperatures is about the same, otherwise your temperature sensor is really bad and you might get strange results from recalculateTemperatures();
  132 +// https://www.letscontrolit.com/wiki/index.php?title=Basics:_Calibration_and_Accuracy
  133 +#define LOWER_MEASURED_TEMPERATURE (19.0)
  134 +#define LOWER_CALIBRATED_TEMPERATURE (17.1)
  135 +#define HIGHER_MEASURED_TEMPERATURE (20.9)
  136 +#define HIGHER_CALIBRATED_TEMPERATURE (18.5)
  137 +
  138 +
  139 +// Update these with values suitable for your network.
  140 +const char * ssid = "[YOUR WIFI SSID]";
  141 +const char * password = "YOUR WIFI PASSWORD";
  142 +
  143 +
  144 +// Update these with values suitable for your MQTT broker
  145 +const char * mqtt_server = "YOUR MQTT BROKER SERVER ADDRESS";
  146 +const char * mqtt_user = "YOUR MQTT USERNAME";
  147 +const char * mqtt_password = "YOUR MQTT PASSWORD";
  148 +
  149 +// PubSubClient message buffer size
  150 +#define MSG_BUFFER_SIZE (500)
  151 +
  152 +
  153 +// Define a global WiFiClientSecure instance for WiFi connection
  154 +WiFiClientSecure wiFiClient;
  155 +// Define a global PubSubClient to communicatie with the MQTT broker (server)
  156 +PubSubClient * pubSubClient;
  157 +
  158 +
  159 +// Create a global temperature sensor instance, in this case a BME280 using I2C communication. Any other temperature sensor may be used if you adapt the program accordingly
  160 +Adafruit_BME280 bme;
  161 +
  162 +
  163 +// Create a global OpenTherm instance called 'thermostat' (i.e primary and boiler is secondary) with OT_RX_PIN to receive data from boiler and OT_TX_PIN to send data to boiler
  164 +// Only one OpenTherm object may be created!
  165 +OpenTherm thermostat(OT_RX_PIN, OT_TX_PIN);
  166 +
  167 +
  168 +// Add the valid TLS CA certificate of the MQTT server
  169 +// This is the CA certificate for s1.eu.hivemq.cloud
  170 +const char CACertificate[] = R"CERT(
  171 +-----BEGIN CERTIFICATE-----
  172 +MIIFFjCCAv6gAwIBAgIRAJErCErPDBinU/bWLiWnX1owDQYJKoZIhvcNAQELBQAw
  173 +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
  174 +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMjAwOTA0MDAwMDAw
  175 +WhcNMjUwOTE1MTYwMDAwWjAyMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNTGV0J3Mg
  176 +RW5jcnlwdDELMAkGA1UEAxMCUjMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
  177 +AoIBAQC7AhUozPaglNMPEuyNVZLD+ILxmaZ6QoinXSaqtSu5xUyxr45r+XXIo9cP
  178 +R5QUVTVXjJ6oojkZ9YI8QqlObvU7wy7bjcCwXPNZOOftz2nwWgsbvsCUJCWH+jdx
  179 +sxPnHKzhm+/b5DtFUkWWqcFTzjTIUu61ru2P3mBw4qVUq7ZtDpelQDRrK9O8Zutm
  180 +NHz6a4uPVymZ+DAXXbpyb/uBxa3Shlg9F8fnCbvxK/eG3MHacV3URuPMrSXBiLxg
  181 +Z3Vms/EY96Jc5lP/Ooi2R6X/ExjqmAl3P51T+c8B5fWmcBcUr2Ok/5mzk53cU6cG
  182 +/kiFHaFpriV1uxPMUgP17VGhi9sVAgMBAAGjggEIMIIBBDAOBgNVHQ8BAf8EBAMC
  183 +AYYwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMBMBIGA1UdEwEB/wQIMAYB
  184 +Af8CAQAwHQYDVR0OBBYEFBQusxe3WFbLrlAJQOYfr52LFMLGMB8GA1UdIwQYMBaA
  185 +FHm0WeZ7tuXkAXOACIjIGlj26ZtuMDIGCCsGAQUFBwEBBCYwJDAiBggrBgEFBQcw
  186 +AoYWaHR0cDovL3gxLmkubGVuY3Iub3JnLzAnBgNVHR8EIDAeMBygGqAYhhZodHRw
  187 +Oi8veDEuYy5sZW5jci5vcmcvMCIGA1UdIAQbMBkwCAYGZ4EMAQIBMA0GCysGAQQB
  188 +gt8TAQEBMA0GCSqGSIb3DQEBCwUAA4ICAQCFyk5HPqP3hUSFvNVneLKYY611TR6W
  189 +PTNlclQtgaDqw+34IL9fzLdwALduO/ZelN7kIJ+m74uyA+eitRY8kc607TkC53wl
  190 +ikfmZW4/RvTZ8M6UK+5UzhK8jCdLuMGYL6KvzXGRSgi3yLgjewQtCPkIVz6D2QQz
  191 +CkcheAmCJ8MqyJu5zlzyZMjAvnnAT45tRAxekrsu94sQ4egdRCnbWSDtY7kh+BIm
  192 +lJNXoB1lBMEKIq4QDUOXoRgffuDghje1WrG9ML+Hbisq/yFOGwXD9RiX8F6sw6W4
  193 +avAuvDszue5L3sz85K+EC4Y/wFVDNvZo4TYXao6Z0f+lQKc0t8DQYzk1OXVu8rp2
  194 +yJMC6alLbBfODALZvYH7n7do1AZls4I9d1P4jnkDrQoxB3UqQ9hVl3LEKQ73xF1O
  195 +yK5GhDDX8oVfGKF5u+decIsH4YaTw7mP3GFxJSqv3+0lUFJoi5Lc5da149p90Ids
  196 +hCExroL1+7mryIkXPeFM5TgO9r0rvZaBFOvV2z0gp35Z0+L4WPlbuEjN/lxPFin+
  197 +HlUjr8gRsI3qfJOQFy/9rKIJR0Y/8Omwt/8oTWgy1mdeHmmjk7j1nYsvC9JSQ6Zv
  198 +MldlTTKB3zhThV1+XWYp6rjd5JW1zbVWEkLNxE7GJThEUG3szgBVGP7pSWTUTsqX
  199 +nLRbwHOoq7hHwg==
  200 +-----END CERTIFICATE-----
  201 +)CERT";
  202 +
  203 +
  204 +// Use a PID controller to calculate the CH setpoint. See e.g. https://en.wikipedia.org/wiki/PID_controller
  205 +float pid(float sp,
  206 + float pv,
  207 + float pv_last,
  208 + float & ierr,
  209 + float dt) {
  210 + float KP = 30;
  211 + float KI = 0.02;
  212 +
  213 + float error = sp - pv;
  214 + ierr = ierr + KI * error * dt;
  215 + float dpv = (pv - pv_last) / dt;
  216 + float P = KP * error;
  217 + float I = ierr;
  218 + float op = P + I;
  219 + // anti-reset windup
  220 + if ((op < CH_MIN_SETPOINT) || (op > CH_MAX_SETPOINT)) {
  221 + I = I - KI * error * dt;
  222 + op = max(CH_MIN_SETPOINT, min(CH_MAX_SETPOINT, op));
  223 + }
  224 + ierr = I;
  225 +
  226 + return op;
  227 +}
  228 +
  229 +
  230 +// Lineair recalculation of the temperature measured by the sensor using two calibrated temperatures
  231 +float recalculateTemperature(float temperature) {
  232 + // y = ax + b
  233 + if(LOWER_MEASURED_TEMPERATURE == HIGHER_MEASURED_TEMPERATURE) return temperature; // Lower and higher temperatures should be a few degrees apart, so this is wrong. Return the measured temperature
  234 + float a = float(HIGHER_CALIBRATED_TEMPERATURE - LOWER_CALIBRATED_TEMPERATURE) / float(HIGHER_MEASURED_TEMPERATURE - LOWER_MEASURED_TEMPERATURE);
  235 + float b = float(LOWER_CALIBRATED_TEMPERATURE) - a * float(LOWER_MEASURED_TEMPERATURE);
  236 + return a * temperature + b;
  237 +}
  238 +
  239 +// Global variable to store the room temperature setpoint. It is global because it is used in loop() to feed the PID controller with, to compute the boiler temperature
  240 +float roomTemperatureSetpoint = ROOM_TEMPERATURE_MIN_SETPOINT;
  241 +
  242 +void callback(char* topic, byte* payload, unsigned int length) {
  243 + Serial.print("===================================================== Message arrived [");
  244 + Serial.print(topic);
  245 + Serial.print("] ");
  246 + for (int i = 0; i < length; i++) {
  247 + Serial.print((char)payload[i]);
  248 + }
  249 + Serial.println();
  250 +
  251 + if(strcmp(topic, "room_temperature_setpoint") == 0) {
  252 + // Copy payload into a zero terminated string
  253 + char message[length + 1];
  254 + memcpy(message, payload, length);
  255 + message[length] = '\0';
  256 +
  257 + if(sscanf(message, "%f", &roomTemperatureSetpoint) == 1) {
  258 + Serial.printf("Requested setpoint is %f\n", roomTemperatureSetpoint);
  259 + // Clip between boundaries
  260 + roomTemperatureSetpoint = max(min(roomTemperatureSetpoint, ROOM_TEMPERATURE_MAX_SETPOINT), ROOM_TEMPERATURE_MIN_SETPOINT);
  261 + Serial.printf("Clipped setpoint is %f\n", roomTemperatureSetpoint);
  262 + }
  263 + }
  264 +}
  265 +
  266 +
  267 +void reconnect(PubSubClient & client) {
  268 + Serial.print("Attempting MQTT connection…");
  269 + // Attempt to connect
  270 + // Insert your password
  271 + if (client.connect("ESP32Client - ThermostatClient", mqtt_user, mqtt_password)) {
  272 + Serial.println("connected");
  273 + } else {
  274 + Serial.print("failed, rc = ");
  275 + Serial.print(client.state());
  276 + Serial.println(" try again in 5 seconds");
  277 + // Wait 5 seconds before retrying
  278 + delay(5000);
  279 + }
  280 +}
  281 +
  282 +
  283 +void setup() {
  284 + Serial.begin(115200);
  285 + delay(5000); // For debug only: give the Serial Monitor some time to connect to the native USB of the MCU for output
  286 + Serial.println("\n\nStarted");
  287 +
  288 + // Connect WiFi
  289 + WiFi.mode(WIFI_STA);
  290 + WiFi.begin(ssid, password);
  291 +
  292 + while (WiFi.status() != WL_CONNECTED) {
  293 + delay(500);
  294 + digitalWrite(LED_BUILTIN, digitalRead(LED_BUILTIN) == LOW ? HIGH : LOW);
  295 + Serial.print(".");
  296 + }
  297 +
  298 + Serial.printf("WiFi connected to %s\n", ssid);
  299 + Serial.println("IP address: ");
  300 + Serial.println(WiFi.localIP());
  301 +
  302 +// Set time and date, necessary for HTTPS certificate validation
  303 + configTzTime(TIME_ZONE, "pool.ntp.org", "time.nist.gov");
  304 + setenv("TZ", TIME_ZONE, 1); // Set environment variable with your time zone
  305 + tzset();
  306 +
  307 + Serial.print("Waiting for NTP time sync: ");
  308 + time_t now = time(nullptr);
  309 + while (now < 8 * 3600 * 2) {
  310 + delay(100);
  311 + digitalWrite(LED_BUILTIN, digitalRead(LED_BUILTIN) == LOW ? HIGH : LOW);
  312 + Serial.print(".");
  313 + now = time(nullptr);
  314 + }
  315 + digitalWrite(LED_BUILTIN, LOW);
  316 + Serial.println();
  317 +
  318 + struct tm timeinfo;
  319 + gmtime_r(&now, &timeinfo);
  320 + Serial.printf("%s %s", tzname[0], asctime(&timeinfo));
  321 +
  322 + const struct tm * ti = localtime (&now);
  323 + printf ("Current local time and date: %s", asctime(ti));
  324 +
  325 + wiFiClient.setCACert(CACertificate);
  326 +
  327 + pubSubClient = new PubSubClient(wiFiClient);
  328 +
  329 + pubSubClient->setServer(mqtt_server, 8883);
  330 + pubSubClient->setCallback(callback);
  331 +
  332 +// pubSubClient->subscribe("room_temperature_setpoint");
  333 +
  334 +
  335 + Serial.println(F("\n-- BME280 test --"));
  336 + Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
  337 +
  338 + bool status = bme.begin(BME_ADDRESS);
  339 + if (!status) {
  340 + Serial.println("Could not find a valid BME280 sensor, check wiring and address!");
  341 + while (1);
  342 + }
  343 + Serial.println("-- Temperature sensor present --");
  344 +
  345 + bme.setSampling();
  346 +
  347 + Serial.println("Setup done, start loop...");
  348 +}
  349 +
  350 +
  351 +// Each bit in secondaryFlags has a meaning. The bits are defined in enum class OpenTherm::CONFIGURATION_FLAGS
  352 +// The secondaryMemberIDCode identifies the manufacturer of the boiler
  353 +void showCapabilities(uint8_t secondaryFlags, uint8_t secondaryMemberIDCode) {
  354 + Serial.printf("Secondary configuration flags is 0x%02x, boiler manufacturer's ID is %d (0x%02x)\n", secondaryFlags, secondaryMemberIDCode, secondaryMemberIDCode);
  355 + if(secondaryFlags & uint8_t(OpenTherm::CONFIGURATION_FLAGS::SECONDARY_DHW_PRESENT)) Serial.println("> Domestic Hot Water (DHW) present"); else Serial.println("> Domestic Hot Water (DHW) not present");
  356 + if(secondaryFlags & uint8_t(OpenTherm::CONFIGURATION_FLAGS::SECONDARY_CONTROL_TYPE)) Serial.println("> Control type on/off"); else Serial.println("> Control type modulating");
  357 + if(secondaryFlags & uint8_t(OpenTherm::CONFIGURATION_FLAGS::SECONDARY_COOLING)) Serial.println("> Cooling supported"); else Serial.println("> Cooling not supported");
  358 + if(secondaryFlags & uint8_t(OpenTherm::CONFIGURATION_FLAGS::SECONDARY_DHW)) Serial.println("> Domestic Hot Water (DHW) storage tank"); else Serial.println("> Domestic Hot Water (DHW) instantaneous or not-specified");
  359 + if(secondaryFlags & uint8_t(OpenTherm::CONFIGURATION_FLAGS::SECONDARY_LOW_OFF_PUMP_CTRL)) Serial.println("> Low off and pump control not allowed"); else Serial.println("> Low off and pump control allowed");
  360 + if(secondaryFlags & uint8_t(OpenTherm::CONFIGURATION_FLAGS::SECONDARY_CH2_PRESENT)) Serial.println("> Second Centrel Heating system (CH2) present"); else Serial.println(">Second Central Heating system (CH2) not present");
  361 +}
  362 +
  363 +
  364 +// primaryFlags is used to tell the secondary device (boiler) what available services (Central heating, cooling, domestic hot water) it wants to make use of
  365 +// The meaning of each bit is defined in enum class OpenTherm::STATUS_FLAGS
  366 +uint8_t requestServices(float CHSetpoint) {
  367 + uint8_t primaryFlags = 0;
  368 +
  369 + // ENABLE_DOMESTIC_HOT_WATER is a #define. If defined 'true' then domestic hot water is enabled
  370 + if(ENABLE_DOMESTIC_HOT_WATER) {
  371 + Serial.println("+ Enable Domestic Hot Water (DHW)");
  372 + primaryFlags |= uint8_t(OpenTherm::STATUS_FLAGS::PRIMARY_DHW_ENABLE);
  373 + }
  374 +
  375 + // ENABLE_HEATING is a #define. If defined 'true' then central heating is enabled.
  376 + if(ENABLE_HEATING && CHSetpoint > CH_MIN_SETPOINT) {
  377 + Serial.println("+ Enable Central Heating (CH)");
  378 + primaryFlags |= uint8_t(OpenTherm::STATUS_FLAGS::PRIMARY_CH_ENABLE);
  379 + }
  380 +
  381 + // ENABLE_COOLING is a #define. If defined 'true' then cooling is enabled
  382 + if(ENABLE_COOLING) {
  383 + Serial.println("+ Enable cooling");
  384 + primaryFlags |= uint8_t(OpenTherm::STATUS_FLAGS::PRIMARY_COOLING_ENABLE);
  385 + }
  386 +
  387 + // Enable Outside Temperature Compensation by default
  388 + Serial.println("+ Enable Outside Temperature Compensation by default");
  389 + primaryFlags |= uint8_t(OpenTherm::STATUS_FLAGS::PRIMARY_OTC_ENABLE);
  390 +
  391 + return primaryFlags;
  392 +}
  393 +
  394 +
  395 +// The statusFlags returned by the boiler tell us what the status is. Each bit in statusFlags has a meaning defined in OpenTherm::STATUS_FLAGS
  396 +void showSecondaryStatus(uint8_t statusFlags) {
  397 + Serial.printf("Status flags is 0x%02x\n", statusFlags);
  398 +
  399 + if(statusFlags & uint8_t(OpenTherm::STATUS_FLAGS::SECONDARY_FAULT_INDICATION)) Serial.println("> FAULT NOTIFICATION");
  400 + if(statusFlags & uint8_t(OpenTherm::STATUS_FLAGS::SECONDARY_CH_MODE)) Serial.println("> Central Heating (CH) MODE");
  401 + if(statusFlags & uint8_t(OpenTherm::STATUS_FLAGS::SECONDARY_DHW_MODE)) Serial.println("> Domestc Hot Water (DHW) MODE");
  402 + if(statusFlags & uint8_t(OpenTherm::STATUS_FLAGS::SECONDARY_FLAME_STATUS)) Serial.println("> Flame is on");
  403 + if(statusFlags & uint8_t(OpenTherm::STATUS_FLAGS::SECONDARY_COOLING_STATUS)) Serial.println("> Cooling");
  404 + if(statusFlags & uint8_t(OpenTherm::STATUS_FLAGS::SECONDARY_CH2_MODE)) Serial.println("> Second Central Heating system (CH2) is active");
  405 + if(statusFlags & uint8_t(OpenTherm::STATUS_FLAGS::SECONDARY_DIAGNOSTIC_IND)) Serial.println("> DIAGNOSTICS INDICATION");
  406 +}
  407 +
  408 +
  409 +void loop() {
  410 + // static variables used by the PID controller
  411 + static uint32_t previousTimestamp = millis(); // Previous timestamp
  412 + static float previousTemperature = bme.readTemperature(); // Previous temperature
  413 + static float ierr = 0; // Integral error
  414 +
  415 + static uint32_t latestTimePublished = 0; // Keep track off the latest time the room temperature was published
  416 +
  417 + // Check if we are still connected to the MQTT broker. If not, reconnect and resubscribe to the topic we are interested in (room_temperature_setpoint)
  418 + if(!pubSubClient->connected()) {
  419 + reconnect(*pubSubClient);
  420 + pubSubClient->subscribe("room_temperature_setpoint");
  421 +
  422 + }
  423 + pubSubClient->loop();
  424 +
  425 +
  426 + // The OpenTherm specification specifies that at least each second communication between the primary (thermostat) and secondary (boiler) should take place
  427 + // Below is the main thermostat block of commands. It's steps are:
  428 + // - Get the (corrected) room temperature from the temperature sensor
  429 + // - Compute the Central Heating boiler water temperature using a PID
  430 + // - Show the services available in the boiler by reading the secondary's configuration (DATA-ID SECONDARY_CONFIGURATION)
  431 + // - Tell the boiler the computed Central Heating boiler water temperature (DATA-ID CONTROL_SETPOINT_CH)
  432 + // - Inform the boiler of the current room temperature (DATA-ID ROOM_TEMPERATURE)
  433 + // - Request services from the boiler and read it's status by calling status();
  434 + uint32_t timestamp = millis();
  435 + if(timestamp - previousTimestamp >= 1000) {
  436 + float roomTemperature = bme.readTemperature(); // Read the sensor to get the (raw) current room temperature
  437 + Serial.printf("Measured (raw) room temperature is %.01f *C, room temperature setpoint is %.01f *C\n", roomTemperature, roomTemperatureSetpoint);
  438 + roomTemperature = recalculateTemperature(roomTemperature); // Recalculate to match calibrated temperature
  439 + Serial.printf("Measured (corrected) room temperature is %.01f *C, room temperature setpoint is %.01f *C\n", roomTemperature, roomTemperatureSetpoint);
  440 +
  441 + // Compute the boiler Central Heating water temperature setpoint using a PID controller (Proportional–Integral–Derivative controller)
  442 + float dt = (timestamp - previousTimestamp) / 1000.0; // Time between measurements in seconds
  443 + float CHSetpoint = pid(roomTemperatureSetpoint, roomTemperature, previousTemperature, ierr, dt);
  444 + previousTimestamp = timestamp;
  445 + previousTemperature = roomTemperature;
  446 + Serial.printf("New Central Heating (CH) boiler water temperature setpoint computed by PID is %.01f\n", CHSetpoint);
  447 +
  448 + // First try to connect to the boiler to read it's capabilities. The boiler returns an 8 bit secondaryFlags and each bit has a meaning
  449 + // The secondaryMemberIDCode identifies the manufacturer of the boiler
  450 + // Display the boiler's capabilities and it's manufacturer ID by calling showCapabilities();
  451 + uint8_t secondaryFlags;
  452 + uint8_t secondaryMemberIDCode;
  453 + bool success = thermostat.read(OpenTherm::READ_DATA_ID::SECONDARY_CONFIGURATION, secondaryFlags, secondaryMemberIDCode); // It is mandatory for boiler to suppport SECONDARY_CONFIGURATION
  454 + if(success) {
  455 + showCapabilities(secondaryFlags, secondaryMemberIDCode);
  456 + } else {
  457 + secondaryFlags = 0;
  458 +
  459 + if(thermostat.error() == OpenTherm::ERROR_CODES::UNKNOWN_DATA_ID) {
  460 + // Valid data is received but the for boilers mandatory DATA-ID OpenTherm::READ_DATA_ID::SECONDARY_CONFIGURATION is not recognised. This is not a boiler but another device!
  461 + Serial.println("Your remote device is not a boiler");
  462 + } else {
  463 + // No data or invalid data received
  464 + Serial.println("Failed to get secondary configuration; is a boiler connected?");
  465 + }
  466 + }
  467 +
  468 + if(success) {
  469 + // Tell the boiler the desired CH boiler water temperature
  470 + // This is done by writing this value to DATA-ID OpenTherm::WRITE_DATA_ID::CONTROL_SETPOINT_CH
  471 + if(thermostat.write(OpenTherm::WRITE_DATA_ID::CONTROL_SETPOINT_CH, CHSetpoint)) {
  472 + Serial.printf("Central Heating (CH) temperature setpoint set to %.01f *C\n", CHSetpoint);
  473 + } else {
  474 + Serial.printf("Failed to set Central Heating (CH) temperature setpoint to %.01f *C\n", CHSetpoint);
  475 + }
  476 +
  477 + // Tell the boiler the current room temperature (optional?)
  478 + // This is done by writing this value to DATA-ID OpenTherm::WRITE_DATA_ID::ROOM_TEMPERATURE
  479 + if(thermostat.write(OpenTherm::WRITE_DATA_ID::ROOM_TEMPERATURE, roomTemperature)) {
  480 + Serial.printf("Room temperature set to %.02f *C\n", roomTemperature);
  481 + } else {
  482 + Serial.println("Failed to set room temperature to sensor value");
  483 + }
  484 +
  485 + // Tell the boiler the room temperature setpoint (optional?)
  486 + // This is done by writing this value to DATA-ID OpenTherm::WRITE_DATA_ID::ROOM_SETPOINT
  487 + if(thermostat.write(OpenTherm::WRITE_DATA_ID::ROOM_SETPOINT, roomTemperatureSetpoint)) {
  488 + Serial.printf("Room temperature setpoint set to %.02f *C\n", roomTemperatureSetpoint);
  489 + } else {
  490 + Serial.println("Failed to set room temperature setpoint");
  491 + }
  492 +
  493 +
  494 + // primaryFlags is used to tell the secondary device (boiler) what available services (central heating, cooling, domestic hot water) it wants to make use of
  495 + // Each service is a bit in the primaryFlags. The right bits are set by calling requestServices();
  496 + uint8_t primaryFlags = requestServices(CHSetpoint);
  497 +
  498 + // Send primaryFlags to the boiler to request services. The boiler returns it's status in statusFlags. Each bit has a meaning which is displayed by calling showSecondaryStatus();
  499 + Serial.println("Request services from the boiler and check it's status...");
  500 + uint8_t statusFlags;
  501 + if(thermostat.status(primaryFlags, statusFlags)) { // It is mandatory for the boiler to support it's status
  502 + showSecondaryStatus(statusFlags);
  503 + } else {
  504 + Serial.println("Failed to get status");
  505 + }
  506 + }
  507 + // End of the main thermostat block of commands
  508 +
  509 + // Publish the corrected measured room temperature to the 'temperature' topic using the PubSubClient every minute
  510 + uint32_t epoch = time(nullptr);
  511 + if(epoch >= latestTimePublished + 60) { // Publish room temperature every minute
  512 + latestTimePublished = epoch - (epoch % 60); // Align on exactly a minute
  513 + if(pubSubClient->connected()) {
  514 + char msg[MSG_BUFFER_SIZE];
  515 + snprintf (msg, MSG_BUFFER_SIZE, "%.01f", roomTemperature);
  516 + Serial.print("Publish message: ");
  517 + Serial.println(msg);
  518 + pubSubClient->publish("temperature", msg);
  519 + }
  520 + }
  521 + }
  522 +}
... ...