Repository navigation
Expand file tree
/
Copy pathconstants.h
More file actions
425 lines (381 loc) · 19.3 KB
/
Copy pathconstants.h
File metadata and controls
425 lines (381 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
#ifndef CONSTANTS_H
#define CONSTANTS_H
#include <WiFiManager.h>
#include <WiFiUdp.h>
#include "EasyLed.h"
#include <EasyButton.h>
#include <ctime>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include "Stove.h"
#include <pelletcore.h> // pure logic, shared with the native unit tests
#ifdef ESP32
#include <FS.h>
#include "ESPTelnet.h"
#include <SPIFFS.h>
#include "esp_log.h"
#include <esp_task_wdt.h>
#define RESET_PIN 13
#define ENABLE_RX 18
#define ONBOARD_LED 2
#define LED 14
// Task watchdog for the loop task (and IDLE0), in seconds. Not 5: one
// WiFiClient::write() to a client that stops reading waits up to 10 x 1 s
// (WIFI_CLIENT_MAX_WRITE_RETRY) without returning, which reset the controller
// during /api/dump. Large answers now check the client first (httpSendLarge,
// httpSendChunk), long handlers feed it themselves.
#define WDT_TIMEOUT 10
#endif
const char* ntpServer = "nl.pool.ntp.org";
const char * defaultTimezone = "CET-1CEST,M3.5.0/2,M10.5.0/3";
int currentDst = 0;
time_t now;
time_t stoveTime;
unsigned long stoveTimeReadMs = 0;
#define STOVE_TIME_READ_MS 300000UL // re-read the stove clock every 5 min once it is known
#define STOVE_TIME_RETRY_MS 10000UL // ... and every 10 s while it is not // millis() when stoveTime was last read from the stove
// The stove clock is only read every 5 min (6 UART reads); in between it is extrapolated
// with millis() so the API, metrics and web app see a clock that ticks every second.
time_t stoveTimeNow() { return (time_t)pc::extrapolateTime((long)stoveTime, stoveTimeReadMs, millis()); }
// The ESP32 system clock keeps running between NTP syncs, so read it directly instead of
// the "now" snapshot that is only refreshed by getNTPtime() every 60 s.
time_t ntpTimeNow() { time_t t; time(&t); return t; }
long unsigned lastNTPtime;
unsigned long lastEntryTime;
WiFiUDP udp;
WiFiClient espClient;
ESPTelnet telnet;
EasyButton resetButton(RESET_PIN);
const char * swaggerUI = "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>Swagger UI</title> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.14.2/swagger-ui.css\"/> <link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.14.2/swagger-ui.css\"/> </head> <body> <div id=\"swagger-ui\"></div><script src=\"https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.14.2/swagger-ui-bundle.js\" charset=\"UTF-8\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.14.2/swagger-ui-standalone-preset.js\" charset=\"UTF-8\"> </script> <script>window.onload=function(){window.ui=SwaggerUIBundle({url: \"api-specs.json\", dom_id: '#swagger-ui', deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset], plugins: [ SwaggerUIBundle.plugins.DownloadUrl], layout: \"StandaloneLayout\"});}; </script> </body></html>";
// OpenAPI spec (docs/openapi.json) and web app (web/app.html), embedded gzipped
// via board_build.embed_files (scripts/gzip_assets.py)
extern const char swaggerJSON[] asm("_binary_docs_openapi_json_gz_start");
extern const char swaggerJSONEnd[] asm("_binary_docs_openapi_json_gz_end");
extern const char webAppHTML[] asm("_binary_web_app_html_gz_start");
// Controller firmware build info, generated by scripts/buildinfo.py (src/buildinfo.cpp)
extern const char* const BUILD_VERSION; // git describe, e.g. 674b88d-dirty
extern const char* const BUILD_BRANCH;
extern const char* const BUILD_TIME; // UTC, ISO 8601
extern const char* const BUILD_ENV; // PlatformIO environment
extern const char* const BUILD_STOVE_MODEL; // stove the firmware is built for (custom_stove_model in platformio.ini)
extern const char webAppHTMLEnd[] asm("_binary_web_app_html_gz_end");
SemaphoreHandle_t stoveMutex = NULL;
// Scoped lock for the stove serial bus (recursive, so nested use is safe).
// Use it around any code that calls stove.read()/stove.write() outside the
// sensor task, e.g. { StoveBusLock lock; ... }.
// Take the stove bus lock, waiting at most maxMs (0 = as long as needed). Waits in
// steps of 0.5 s and feeds the task watchdog in between: the loop task is watched
// (WDT_TIMEOUT), and the sensor task can hold the lock for seconds when the
// stove answers slowly. Returns false when it gave up.
static bool stoveLockTake(uint32_t maxMs = 0)
{
if (!stoveMutex) return true;
uint32_t t0 = millis();
while (xSemaphoreTakeRecursive(stoveMutex, pdMS_TO_TICKS(500)) != pdTRUE) {
esp_task_wdt_reset(); // no effect in a task that is not watched
if (maxMs && millis() - t0 >= maxMs) return false;
}
return true;
}
struct StoveBusLock {
bool held = false;
StoveBusLock() { held = stoveMutex && stoveLockTake(); }
~StoveBusLock() { if (held) xSemaphoreGiveRecursive(stoveMutex); }
StoveBusLock(const StoveBusLock&) = delete;
StoveBusLock& operator=(const StoveBusLock&) = delete;
};
EasyLed led(LED, EasyLed::ActiveLevel::High);
EasyLed onboardLED(ONBOARD_LED, EasyLed::ActiveLevel::High);
WiFiManager wm;
// Wait until the web client of the current request can take more data, feeding
// the task watchdog meanwhile. A write to a client that stopped reading blocks in
// WiFiClient::write() for up to 10 s; check first and give up after maxMs.
static bool httpClientWritable(uint32_t maxMs = 3000)
{
WiFiClient c = wm.server->client();
int fd = c.fd();
if (fd < 0 || !c.connected()) return false;
uint32_t t0 = millis();
for (;;) {
fd_set set;
FD_ZERO(&set);
FD_SET(fd, &set);
struct timeval tv = { 0, 200000 };
int r = select(fd + 1, nullptr, &set, nullptr, &tv);
if (r < 0) return false;
if (r > 0 && FD_ISSET(fd, &set)) return true;
esp_task_wdt_reset();
if (millis() - t0 >= maxMs) return false;
}
}
// The client of the current request stopped taking data (reset at the start of every
// request, auth.h): the rest of the answer is dropped instead of blocking the loop task.
static bool httpStalled = false;
static void httpStall()
{
httpStalled = true;
LOGW("http", "%s: the client took no data for 3 s - answer stopped", wm.server->uri().c_str());
wm.server->client().stop();
}
// Part of a chunked answer (after setContentLength(CONTENT_LENGTH_UNKNOWN)); clears out
static void httpSendChunk(String& out)
{
if (!httpStalled && !httpClientWritable(3000)) httpStall();
if (!httpStalled && out.length()) wm.server->sendContent(out);
out = "";
}
static void httpEndChunks() { if (!httpStalled) wm.server->sendContent(""); }
// A large body from flash (web app, spec, icons) in pieces, each after checking the
// client takes data. Headers added before with sendHeader() are sent along.
static void httpSendLarge(int code, const char* type, const uint8_t* data, size_t len);
static void httpSendText(int code, const char* type, const String& s) { httpSendLarge(code, type, (const uint8_t*)s.c_str(), s.length()); }
static void httpSendLarge(int code, const char* type, const uint8_t* data, size_t len)
{
wm.server->setContentLength(len);
wm.server->send(code, type, "");
WiFiClient c = wm.server->client();
size_t done = 0;
while (done < len && !httpStalled) {
if (!httpClientWritable(3000)) { httpStall(); break; }
size_t n = len - done;
if (n > 1436) n = 1436;
size_t w = c.write(data + done, n);
if (!w) { c.stop(); break; }
done += w;
esp_task_wdt_reset();
}
}
WiFiManagerParameter custom_hydro_mode("hydro", "hydro_mode", "0", 2);
WiFiManagerParameter custom_ntp_server("ntp_server", "NTP server", "nl.pool.ntp.org", 20);
WiFiManagerParameter custom_TimeZone("ntp_server", "NTP server", "CET-1CEST,M3.5.0/2,M10.5.0/3", 20);
bool spiffsMounted = false;
bool wifiConnected = false;
// millis() of the last complete fast / slow read of the stove (0 = never since the start)
unsigned long lastFastStatesAt = 0;
unsigned long lastSlowStatesAt = 0;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
String hydro_mode;
int int_hydro_mode;
// Init the Serial Stove with Hardware UART 2
Stove stove(2);
char buffer[9000];
bool StoveIsOn = false;
char StoveStateStr[32] = "Unknown";
unsigned long StoveStateUpdatedAt = 0;
unsigned long ambTempUpdatedAt = 0;
unsigned long flamePowerpUpdatedAt = 0;
unsigned long fumesTempUpdatedAt = 0;
unsigned long getStatesUpdatedAt = 0;
long previousMillisNTP;
// Verbose sensor logging: log module "stove" at level debug (/api/loglevel?stove=debug)
// Memory types
#define ram 0x00
#define eeprom 0x20
// RAM addresses
#define stoveStateAddr 0x21
#define currentErrorAddr 0x33 // RAM: active error code (same ids as the error memory)
#define ambTempAddr 0x01
#define fumesTempAddr 0x3E
#define waterTempAddr 0x03
#define waterSetAddr 0x36
#define waterPresAddr 0x3C
#define fumeFanRPMAddr 0x37 // Fume fan RPM raw value
#define remoteControlTTLAddr 0x2e // Remote control time-to-live countdown
#define ambTempStoveAddr 0x44 // Ambient temp from stove sensor
#define ambTempRemoteAddr 0x8f // Ambient temp from remote control
// "Installer > INSTELL WIRELESS": enables the optional external wireless
// temperature sensor (manual §23.9). Found by diffing dumps while toggling the
// menu on the remote. RAM 0xB6 is a bit field: bit 0 = 1 -> off, bit 0 = 0 -> on;
// bit 1 meaning unknown (seen 1, 2 and 3). Read-only: the stove restores 0xB6
// right after a write, and the menu confirm could not be emulated over the bus.
// NOTE: the sensor the stove regulates on is chosen in the MULTICOMFORT menu
// (AFSTAND. / KACHEL / WIRELESS, manual §18) - that register is not known yet.
#define wirelessSensorAddr 0xb6
#define menuEditValueAddr 0x19 // RAM: value being edited in the display menu
#define palletSensorAddr 0xa4 // Pellet sensor state (5 = active)
#define augerSpeedAddr 0x0D // Auger speed (raw / 10 = rpm)
#define palletLevelAddr 0x89 // Pellet fill level
#define displayMenuAddr 0x1a // Currently displayed menu / display write target
#define selectedParamAddr 0x18 // Parameter selected in display menu
#define roomFanAddr 0x19 // Room fan speed (RAM, live)
#define stoveTimeMinAddr 0x7d // Current minute (RAM)
#define stoveTimeHourAddr 0x7c // Current hour (RAM)
#define stoveTimeSecAddr 0x7a // Current second (RAM)
#define stoveTimeDayAddr 0x7e // Current day (RAM)
#define stoveTimeMonthAddr 0x7f // Current month (RAM)
#define stoveTimeYearAddr 0x80 // Current year (RAM)
// EEPROM addresses
#define TempSetpointAddr 0x7d // Room temperature setpoint
#define flamePowerEepromAddr 0x7f // Flame power level (setting)
#define roomFanControlAddr 0x0A // RAM: room fan drive value: 0 off, 21/23/25 at speed 1/2/3 (P220 M)
#define roomFanControl2Addr 0xA7 // RAM: second room fan drive value: 0 off, 86/82/78 at speed 1/2/3 (meaning unknown)
#define roomFanRunningAddr 0xD3 // RAM: room fan running (0 = stopped, 2 = running)
#define hotForFanAddr 0x04 // RAM: stove hot enough for the room fan (0 = no)
#define flamePowerActualAddr 0x34 // RAM: flame power the stove currently runs at (modulates to 1 at the set point)
#define roomFanEepromAddr 0x81 // Room fan speed (persisted)
#define beepEnabledAddr 0x4b // Beep enabled flag
#define numberOfStartsHiAddr 0xef // Number of starts (high byte)
#define numberOfStartsLoAddr 0xee // Number of starts (low byte)
#define energySavingStartAddr 0x91 // Energy saving start temperature offset
#define energySavingStopAddr 0x90 // Energy saving stop temperature offset
#define combustionQualityAddr 0xc0 // Combustion quality setting
#define pelletQualityAddr 0xBC // Pellet quality setting
#define errorMemoryBaseAddr 0xe0 // Error memory slots 0-4 (base address)
#define hoursSinceLastServiceAddr 0xE7 // Hours since last service
#define totalRuntimeAddrLow 0xEA // Total runtime low byte (16-bit little-endian)
#define totalRuntimeAddrHigh 0xEB // Total runtime high byte (16-bit little-endian)
#define languageAddr 0x4F // Language setting
// Firmware version (EEPROM) — format: FW-{char0x8A}{char0x8B}-{0x8C}-V-{0x8D}-{0x8E}-{0x8F}
#define fwVariantChar0Addr 0x8A // Firmware variant char 0 (ASCII)
#define fwVariantChar1Addr 0x8B // Firmware variant char 1 (ASCII)
#define fwProductAddr 0x8C // Firmware product number
#define fwMajorAddr 0x8D // Firmware major version
#define fwMinorAddr 0x8E // Firmware minor version
#define fwPatchAddr 0x8F // Firmware patch version
// EEPROM date/time write addresses (BCD encoded)
#define eepromDateDayAddr 0xfb
#define eepromDateMonthAddr 0xfc
#define eepromDateYearAddr 0xfd
#define eepromTimeHourAddr 0xf9
#define eepromTimeMinAddr 0xfa
#define eepromTimeDOWAddr 0xf8
uint8_t waterTemp = 0;
int stoveState = 0;
uint8_t fumesTemp = 0;
int flamePower = 0;
int roomFanSpeed = 0;
float ambTemp = 0;
float ambTempStove = 0;
float ambTempRemoteControl = 0;
float setPointTemp = 0;
float waterPres = 0;
int energySavingStart = 0;
int energySavingStop = 0;
String stoveDebugBuffer = "";
float cachedAugerSpeed = 0.0;
char cachedFirmwareVersion[32] = "Unknown";
int cachedLowPallet = 0;
// Pellet reserve (installer menu PELLET RESERVE, EEPROM 0xC6). How the stove decides
// the reserve is not verified: the alarm is taken as sensor (RAM 0xA4) = 5 and
// counter (RAM 0x89) <= 1. Changes of both are logged in /api/events to find out.
#define pelletReserveEnabledAddr 0xc6
int cachedPelletSensor = -1; // RAM 0xA4, -1 = not read yet
int cachedPelletCounter = -1; // RAM 0x89
int cachedPelletShutdown = -1; // RAM 0x91: pellet reserve, half minutes until the stove switches off (only read in that phase)
int cachedPelletReserveOn = -1; // EEPROM 0xC6
bool cachedBeepEnabled = false;
int cachedNumberOfStarts = 0;
int cachedHoursSinceLastService = 0;
int cachedTotalRuntime = 0;
int cachedCombustionQuality = 0;
int cachedPelletQuality = 0;
int cachedFumeFanRPM = 0;
int cachedRemoteControlLastSeen = -1;
int cachedWirelessSensor = -1; // INSTELL WIRELESS: -1 unknown, 0 off, 1 on
int cachedCurrentError = 0; // RAM 0x33 as read, 0 = no active error
// RAM 0x30: while RAM 0x33 shows an error, seconds until the stove acts on it (alarm /
// switch-off). Verified 18/11/2026 with E1 (hopper lid open, stove working): 55 -> 19
// at 1 per second, back to 55 when the lid was closed. Only read while 0x33 != 0.
int cachedErrorCountdown = -1;
// RAM 0x33 also shows short pre-warnings that are not real errors: e.g. E12 (fume
// fan) for 1-5 s when the stove switches to and from brazier cleaning, while the
// stove keeps running and nothing is stored in the error memory. An error only
// counts once it stays for ERROR_CONFIRM_MS, or right away when the stove is in an
// alarm state (8, 9, 10). Cleared errors are reported right away.
volatile bool netHttpSeen = false; // any HTTP request received (set in metrics.h, used by wifiInfo.h)
const unsigned long ERROR_CONFIRM_MS = 30000;
const unsigned long ERROR_CONFIRM_TRANSITIONAL_MS = 180000; // start-up, ignition, cleaning, shut-down (E1 at start-up, 17/11/2026)
int confirmedCurrentError = 0;
void updateConfirmedError(int stoveStateNow)
{
static pc::ErrorConfirm ec;
confirmedCurrentError = ec.update(cachedCurrentError, stoveStateNow, millis(), ERROR_CONFIRM_MS, ERROR_CONFIRM_TRANSITIONAL_MS);
}
int cachedRoomFanControl = -1; // RAM 0x0A, -1 = not read yet
int cachedRoomFanRunning = -1; // RAM 0xD3
int cachedHotForFan = -1; // RAM 0x04
// Brazier cleaning (verified 16/11/2026): RAM 0x32 counts the minutes to the next
// cleaning while the stove is working; EEPROM 0x02 is the interval in minutes.
#define brazierCountdownAddr 0x32
#define brazierIntervalAddr 0x02
int cachedBrazierCountdown = -1; // RAM 0x32
int cachedBrazierInterval = -1; // EEPROM 0x02
// The room fan power (RAM 0x0A) depends on the selected speed AND the actual flame
// power (measured 16/11/2026 on a P220 M):
// speed 1 speed 2 speed 3
// flame 1 9 14 19
// flame 2 21 23 25
// flame 3 27 ? ? (17/11/2026)
// So there is no separate "reduced" mode: the stove scales the fan with the flame.
// Speed the fan runs at: 0 when stopped (power 0), otherwise the selected speed;
// -1 when not read yet.
int roomFanActual() { return pc::roomFanActual(cachedRoomFanControl, roomFanSpeed); }
// "off" (power 0) or "on"; RAM 0xD3 is not used: it stays 1 after the fan stopped.
const char* roomFanMode() { return pc::roomFanMode(cachedRoomFanControl); }
// Fan really turning: power > 0 (falls back to RAM 0xD3 before 0x0A is read)
int roomFanIsRunning() { return pc::roomFanIsRunning(cachedRoomFanControl, cachedRoomFanRunning); }
int cachedFlameActual = -1; // RAM 0x34, -1 = not read yet
// Bluetooth (BLE) can be disabled to give WiFi the radio. Stored in NVS
// ("ble"/"enabled"); bleEnabled is the state of the running firmware.
bool bleEnabled = true;
volatile bool otaActive = false; // set while an OTA firmware update is running (ota.h)
// Telnet debug menu on port 23, stored in NVS ("telnet"/"enabled"), switchable at runtime
bool telnetEnabled = true;
static const char* wirelessSensorStr()
{
return cachedWirelessSensor == 1 ? "on" : cachedWirelessSensor == 0 ? "off" : "unknown";
}
int cachedErrors[5] = {0, 0, 0, 0, 0};
int cachedTimerEnabled[6] = {0, 0, 0, 0, 0, 0};
int cachedTimerOnVal[6] = {0, 0, 0, 0, 0, 0};
int cachedTimerOffVal[6] = {0, 0, 0, 0, 0, 0};
int cachedTimerSetpoint[6] = {0, 0, 0, 0, 0, 0};
int cachedTimerFlame[6] = {0, 0, 0, 0, 0, 0};
int cachedTimerFan[6] = {0, 0, 0, 0, 0, 0};
int cachedTimerDowMask[6] = {0, 0, 0, 0, 0, 0};
// ── Timer (PR1-PR6) EEPROM layout ───────────────────────────────────────────
// Base addresses for each timer block (8 bytes each)
static const byte timerBases[6] = { 0x3C, 0x50, 0x58, 0x60, 0x68, 0x70 };
// Offsets within each 8-byte timer block
#define TIMER_ONOFF_OFFSET 0 // 0=disabled, 1=enabled
#define TIMER_ONTIME_OFFSET 1 // val*10 = minutes since 00:00; 144=off
#define TIMER_OFFTIME_OFFSET 2 // same encoding
#define TIMER_SETPOINT_OFFSET 3 // °C (7–30)
#define TIMER_FLAME_OFFSET 4 // flame power (1–5)
#define TIMER_FAN_OFFSET 5 // room fan speed (0–3)
#define TIMER_DOW_OFFSET 7 // day-of-week bitmask (Mon=1 … Sun=64)
static String timerValueToTimeStr(int val)
{
char buf[6];
return String(pc::timerValueToStr(val, buf));
}
static String uptimeStr()
{
unsigned long total = millis() / 1000;
unsigned long d = total / 86400;
unsigned long h = (total % 86400) / 3600;
unsigned long m = (total % 3600) / 60;
unsigned long s = total % 60;
char buf[24];
if (d > 0) snprintf(buf, sizeof(buf), "%lud %02luh %02lum %02lus", d, h, m, s);
else if (h > 0) snprintf(buf, sizeof(buf), "%luh %02lum %02lus", h, m, s);
else if (m > 0) snprintf(buf, sizeof(buf), "%lum %02lus", m, s);
else snprintf(buf, sizeof(buf), "%lus", s);
return String(buf);
}
enum stoveStateCode {
UNKNOWN = -1,
OFF = 0,
STARTING = 1,
PALLET_LOADING = 2,
IGNITION = 3,
WORKING = 4,
BRAZIER_CLEANING = 5,
FINAL_CLEANING = 6,
STANDBY = 7,
ALARM = 8,
IGNITION_FAILURE = 9,
ALARM_STATE = 10
};
#endif