-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.cpp
653 lines (560 loc) · 21.7 KB
/
main.cpp
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
#include <Arduino.h>
#include <ACAN2515.h>
// Main Header
#include <main.h>
//——————————————————————————————————————————————————————————————————————————————
// Operation
//——————————————————————————————————————————————————————————————————————————————
// This flag enables the control of the heating. It will be automatically reset to FALSE if another controller sends messages
// It will be re-enabled if there are no messages from other controllers on the network for x seconds as defined by ControllerMessageTimeout
bool OverrideControl = true;
//——————————————————————————————————————————————————————————————————————————————
// Variables
//——————————————————————————————————————————————————————————————————————————————
TaskHandle_t MqttActivityHandle;
TaskHandle_t CanErrorActivityHandle;
//-- WiFi Status Timer Variable
unsigned long wifiConnectMillis = 0L;
//-- Last Controller Message timer
unsigned long controllerMessageTimer = 0L;
//-- Timestamp of last received message from the heating controller
unsigned long lastHeatingMessageTime = 0L;
//-- Timestamp of the last message sent by us
unsigned long lastSentMessageTime = 0L;
//-- Step-Counter
int currentStep = 0;
//-- Date & Time Interval: 0...MAXINT, Ex.: '5' for a 5 second delay between setting time.
int dateTimeSendDelay = 30;
//-- CAN Error Counter
volatile int CanSendErrorCount;
volatile bool SetupMode = false;
void setup()
{
// Init SPIFFS
if (!LittleFS.begin())
LittleFS.begin(true);
// Setup Serial
Serial.begin(115200);
Serial.printf("\e[1;32mRunning Environment: %s\r\n\e[0m", STR(ENV));
Serial.printf("\e[1;32mRunning Build: %s\r\n\e[0m", STR(VERSION));
Serial.println("\e[1;36mPress the \"BOOT\" button within the next 5 seconds to enable Setup Mode!\e[0m");
#pragma region "Setup Mode"
unsigned long curmils = millis();
// Give the user the chance to push the "BOOT" button.
while (millis() - curmils <= 5000)
{
SetupMode = !digitalRead(GPIO_NUM_0);
if (SetupMode)
{
break;
}
}
if (SetupMode)
{
if (!LittleFS.exists("/configuration.json"))
{
Serial.println("\e[1;31mPlease upload the Filesystem image first.\e[0m");
return;
}
// Launch AP Mode to let the user configure the basics.
StartApMode();
ConfigureAndStartWebserver();
ota();
return;
}
#pragma endregion
Serial.println("\e[1;36mSetup Mode not enabled. You can enable it at every time by pressing the \"BOOT\" button once. \e[0m");
// Read configuration
bool result = ReadConfiguration();
if (!result)
{
Log.println("Unable to read configuration.");
return;
}
// Setup Pins
pinMode(configuration.LEDs.StatusLed, OUTPUT);
pinMode(configuration.LEDs.WifiLed, OUTPUT);
pinMode(configuration.LEDs.MqttLed, OUTPUT);
pinMode(configuration.LEDs.HeatingLed, OUTPUT);
// Test Leds
digitalWrite(configuration.LEDs.StatusLed, HIGH);
delay(1000);
digitalWrite(configuration.LEDs.WifiLed, HIGH);
delay(1000);
digitalWrite(configuration.LEDs.MqttLed, HIGH);
delay(1000);
digitalWrite(configuration.LEDs.HeatingLed, HIGH);
delay(100);
digitalWrite(configuration.LEDs.WifiLed, LOW);
delay(100);
digitalWrite(configuration.LEDs.MqttLed, LOW);
delay(100);
digitalWrite(configuration.LEDs.HeatingLed, LOW);
setupMqttClient();
// Setup can module
setupCan();
// Connect WiFi. This call will block the thread until a result of the connection attempt has been received. This is very important for OTA to work.
connectWifi();
//-------------------------------------
//-- NOTE: The code below won't be reached until the WiFi has connected within connectWifi().
ota();
TelnetServer.begin();
initSensors();
lastHeatingMessageTime = millis();
lastSentMessageTime = millis();
xTaskCreate(ReadTemperatures, "Read Aux Temp", 4096, NULL, 5, NULL);
xTaskCreate(ShowHeartbeat, "Heartbeat LED", 1024, NULL, 5, NULL);
xTaskCreate(ShowMqttActivity, "MQTT Activity", 2048, NULL, 5, &MqttActivityHandle);
xTaskCreate(UpdateLeds, "Update LEDs", 2048, NULL, 5, NULL);
xTaskCreate(TrackBoostFunction, "Track Boost", 2048, NULL, 1, NULL);
ConfigureAndStartWebserver();
}
void loop()
{
// Init reboot if requested
if (ShouldReboot) {
// Wait a bit so the client is redirected properly...
vTaskDelay(3000 / portTICK_PERIOD_MS);
WiFi.disconnect();
server->end();
vTaskDelay(3000 / portTICK_PERIOD_MS);
ESP.restart();
}
// Stop executing when SetupMode is active.
if (SetupMode)
{
// But we like to be still able to update files via OTA ofc
ArduinoOTA.handle();
return;
}
// Check if the user has pressed the "BOOT" button
if (digitalRead(GPIO_NUM_0) == LOW)
{
SetupMode = true;
// Disconnect Wifi and launch in AP Mode
StartApMode();
return;
}
// Run Timer Events
events();
// store the current timer millis
unsigned long currentMillis = millis();
// Connect WiFi (if disconnected)
connectWifi();
//-------------------------------------
//-- NOTE: The code below won't be reached until the WiFi has connected within connectWifi().
// Handle OTA
ArduinoOTA.handle();
// Break out if OTA is in Progress
if (otaRunning)
{
return;
}
// MQTT Client Keepalive
client.loop();
// Process incoming CAN messages
processCan();
// Telnet Communication
CheckForConnections();
// Read Telnet commands
ReadFromTelnet();
// Set Date & Time
SetDateTime();
//——————————————————————————————————————————————————————————————————————————————
// Actions performed every second
//——————————————————————————————————————————————————————————————————————————————
runEverySeconds(1)
{
// Ensure that we are connected to MQTT
reconnectMqtt();
// If we didn't spot a controller message on the network for x seconds we will take over control.
// As soon as a message is spotted on the network it will be disabled again. This is controlled within processCan()
if (currentMillis - controllerMessageTimer >= configuration.General.BusMessageTimeout * 1000)
{
// Bail out if we already set this...
if (!OverrideControl)
{
OverrideControl = true;
Log.println("No other controller on the network. Enabling Override.");
}
}
}
//——————————————————————————————————————————————————————————————————————————————
// Control Actions
//——————————————————————————————————————————————————————————————————————————————
// TODO: Seek for a more elegant solution to send each message every 30 seconds. Right now it's 5 because we have 6 Steps and we want an interval of 30 seconds so 30/6 = 5 seconds delay.
runEverySeconds(5)
{
// We will send our data if there was silence on the bus for a specific time. This prevents sending uneccessary payload onto the bus or confusing the boiler if it's slow and brittle.
if (SafeToSendMessage())
{
// Send desired Values to the heating controller
// Note that it cannot perform unrealistic actions.
// The built-in controller of the heating will always take care of staying well within the specs
// We can only "suggest" to set to a certain temperature or switching off the pump(s)
// I have "borrowed" the concept of a step-chain from PLC programming since it appears
// to have been incorporated into the controller as well because values arrive in
// intervals of approximately 1 second.
CANMessage msg;
switch (currentStep)
{
case 0:
// Switch economy mode. This is always the opposite of the desired operational state
msg = PrepareMessage(configuration.CanAddresses.Heating.Economy, 1);
msg.data[0] = !commandedValues.Heating.Active;
if (configuration.General.Debug)
{
Log.printf("DEBUG STEP CHAIN #%i: Heating Economy: %d\r\n", currentStep, !commandedValues.Heating.Active);
}
break;
// Temperature regulation mode
// 1 = Weather guided | 0 = Room Temperature Guided
case 1:
msg = PrepareMessage(configuration.CanAddresses.Heating.Mode, 1);
msg.data[0] = 1;
break;
case 2:
SetFeedTemperature();
if (configuration.General.Debug)
{
Log.printf("DEBUG STEP CHAIN #%i: Heating is %s, Fallback is %s\r\n", currentStep, ceraValues.Heating.Active ? "ON" : "OFF", ceraValues.Fallback.isOnFallback ? "YES" : "NO");
}
break;
// DHW "Now"
case 3:
msg = PrepareMessage(configuration.CanAddresses.HotWater.Now, 1);
msg.data[0] = 0x01;
if (configuration.General.Debug)
{
Log.printf("DEBUG STEP CHAIN #%i: Set DHW Now to %s\r\n", currentStep, ceraValues.Hotwater.Now ? "ON" : "OFF");
}
break;
// DHW Temperature Setpoint
case 4:
msg = PrepareMessage(configuration.CanAddresses.HotWater.SetpointTemperature, 1);
msg.data[0] = 20;
if (configuration.General.Debug)
{
Log.printf("DEBUG STEP CHAIN #%i: Set DHW Setpoint to %.2F\r\n", currentStep, ceraValues.Hotwater.SetPoint);
}
break;
case 5:
// Request? Data
msg = PrepareMessage(0xF9, 0);
if (configuration.General.Debug)
{
Log.printf("DEBUG STEP CHAIN #%i: Sending KeepAlive\r\n", currentStep);
}
break;
default:
// If we reach any undefined number inside the chain, reset to zero
currentStep = 0;
return; // important!
}
// Increase counter
currentStep++;
SendMessage(msg);
}
}
//——————————————————————————————————————————————————————————————————————————————
// Actions performed every five seconds
//——————————————————————————————————————————————————————————————————————————————
runEverySeconds(5)
{
// Publish Status
PublishStatus();
// Request Temperatures and report them back to the MQTT broker
// Note: If 85.00° is shown or "unreachable" then the wiring is bad.
if (configuration.Features.AuxiliaryParameters)
{
PublishAuxiliaryTemperatures();
}
// Publish Heating Temperatures
if (configuration.Features.HeatingParameters)
PublishHeatingTemperaturesAndStatus();
// Publish Water Temperatures
if (configuration.Features.WaterParameters)
PublishWaterTemperatures();
}
//——————————————————————————————————————————————————————————————————————————————
// Actions performed every thirty seconds
//——————————————————————————————————————————————————————————————————————————————
runEverySeconds(30)
{
// Run on fallback values when the connection to the server has been lost.
if (TimeIsSynced() && !client.connected())
{
// Note: negate this statement to try out the fallback mode.
if (!client.connected() && !ceraValues.Fallback.isOnFallback)
{
// Activate fallback
ceraValues.Fallback.isOnFallback = true;
Log.println("Connection lost. Switching over to fallback mode!");
}
// Check if the profile has to be changed depending on the time schedule.
// Check if the current hour is in between the start of both "Start" and "End" marks
if (myTZ.hour() >= ceraValues.Fallback.fallbackStartEntry.StartHour && myTZ.hour() < ceraValues.Fallback.fallbackEndEntry.StartHour)
{
// Check if the minute mark has been passed.
if (myTZ.minute() >= ceraValues.Fallback.fallbackStartEntry.StartMinute)
{
// Activate Heating Profile by overwriting the fields with fallback values
commandedValues.Heating.BasepointTemperature = ceraValues.Fallback.BasepointTemperature;
commandedValues.Heating.EndpointTemperature = ceraValues.Fallback.EndpointTemperature;
commandedValues.Heating.Active = true;
return; // important!
}
}
// Check if we have passed the hour mark.
if (myTZ.hour() > ceraValues.Fallback.fallbackEndEntry.StartHour)
{
// Check if the minute mark has been passed
if (myTZ.minute() >= ceraValues.Fallback.fallbackStartEntry.StartMinute)
{
// Set both Base and Endpoint to the anti-freeze setting.
commandedValues.Heating.BasepointTemperature = ceraValues.Fallback.MinimumFeedTemperature;
commandedValues.Heating.EndpointTemperature = ceraValues.Fallback.MinimumFeedTemperature;
commandedValues.Heating.Active = false;
}
}
}
// Disable fallback mode when connected.
if (client.connected() && ceraValues.Fallback.isOnFallback)
{
ceraValues.Fallback.isOnFallback = false;
Log.println("Connection established. Switching over to SCADA!");
}
if (TimeIsSynced() && !AlarmIsSet)
{
// Set Reboot time next day
setEvent(Reboot, now() + 24 * 3600);
AlarmIsSet = true;
}
}
runEverySeconds(60)
{
// Set Date & Time
SetDateTime();
}
// Allow the CPU to switch tasks.
vTaskDelay(2);
}
void Reboot()
{
ESP.restart();
}
void SendMessage(CANMessage msg)
{
// Send message if not empty and override is true.
if (msg.id != 0 && OverrideControl)
{
if (configuration.General.Debug)
{
Log.printf("DEBUG STEP CHAIN #%i: Sending CAN Message\r\n", currentStep);
WriteMessage(msg, false);
}
if (!can.tryToSend(msg))
{
CanSendErrorCount++;
if (CanErrorActivityHandle == NULL)
{
xTaskCreate(ShowCanError, "Can Error", 2000, NULL, 1, &CanErrorActivityHandle);
}
Log.printf("\e[0;31[%s] Failed to send message [0x%.3X] over CAN. This has happened %i times before in a row.\r\n\e[0m", myTZ.dateTime("d-M-y H:i:s.v").c_str(), msg.id, CanSendErrorCount);
char logMsg[64];
sprintf(logMsg, "CAN send error msg id [0x%.3X]. Err Count: %i", msg.id, CanSendErrorCount);
PublishLog(logMsg, __func__, LogLevel::Error);
}
else
{
if (CanErrorActivityHandle != NULL)
{
vTaskDelete(CanErrorActivityHandle);
CanErrorActivityHandle = NULL;
PublishLog("CAN send error CLEARED", __func__, LogLevel::Info);
Log.printf("\e[0;32[%s] CAN send error CLEARED after %i previously failed attempts.\r\n\e[0m", myTZ.dateTime("d-M-y H:i:s.v").c_str(), CanSendErrorCount);
CanSendErrorCount = 0;
}
}
lastSentMessageTime = millis();
}
}
void WriteMessage(CANMessage msg, bool received /* = true */)
{
// Buffer for storing the formatted values. We have to expect 'FF (255)' which is 8 bytes + 1 for string overhead \0
char dataBuf[255];
String data;
StaticJsonDocument<128> doc;
doc["id"] = msg.id;
doc["len"] = msg.len;
doc["rcv"] = received;
JsonArray msgData = doc.createNestedArray("data");
for (int x = 0; x < msg.len; x++)
{
// A little bit of trickery to assemble the data bytes into a nicely formatted string
sprintf(dataBuf, "\e[1;35m0x%.2X \e[0m(\e[1;36m%i\e[0m)", msg.data[x], msg.data[x]);
// Convert char array to string
String temp(dataBuf);
// Get rid of trailing spaces
temp.trim();
// Concat
data += temp;
msgData.add((int)msg.data[x]);
// Add tab between data
if (x < msg.len - 1)
{
data += "\t";
}
}
String json;
serializeJson(doc, json);
eventSource->send(json.c_str(), "can");
Log.printf("[%s]\t\e[0m[%s]CAN: [\e[1;32m0x%.3X\e[0m] Data:\t%s\r\n", myTZ.dateTime("d-M-y H:i:s.v").c_str(), received ? "\e[1;36m◄\e[0m" : "\e[1;35m►\e[0m", msg.id, data.c_str());
}
void SetDateTime()
{
runEverySeconds(dateTimeSendDelay)
{
if (lastSentMessageTime - millis() >= 1000)
{
CANMessage msg = PrepareMessage(configuration.CanAddresses.General.DateTime, 4);
// Get day of week:
// --> N = ISO-8601 numeric representation of the day of the week. (1 = Monday, 7 = Sunday)
msg.data[0] = myTZ.dateTime("N").toInt();
// Hours and minutes
msg.data[1] = myTZ.hour();
msg.data[2] = myTZ.minute();
// As of now we don't know what this value is for but it seems mandatory.
msg.data[3] = 4;
if (configuration.General.Debug)
{
Log.printf("DEBUG: Date and Time DOW:%li H:%i M:%i\r\n", myTZ.dateTime("N").toInt(), myTZ.hour(), myTZ.minute());
}
SendMessage(msg);
}
}
}
CANMessage PrepareMessage(uint32_t id, int length /* = 8 */)
{
CANMessage msg;
// This was the culprit of messages not arriving as they should.
// We have to set up the length of the message first. The heating doesn't care about that much but the library does!
msg.len = length;
// These are here for reference only and are the default values of the ctr
msg.ext = false;
msg.rtr = false;
msg.idx = 0;
msg.id = id;
return msg;
}
/// @brief Returns if the last sent or received message was a second away
/// @param dontWaitForController Just check for the last message timestamp we sent and not this of the controller.
/// @return
bool SafeToSendMessage(bool dontWaitForController /*= true*/)
{
if (dontWaitForController)
return (lastSentMessageTime - millis() >= 1000);
return (lastHeatingMessageTime - millis() >= 1000 && lastSentMessageTime - millis() >= 1000);
}
void ShowHeartbeat(void *pvParameter)
{
while (true)
{
digitalWrite(configuration.LEDs.StatusLed, HIGH);
vTaskDelay(500 / portTICK_PERIOD_MS);
digitalWrite(configuration.LEDs.StatusLed, LOW);
vTaskDelay(250 / portTICK_PERIOD_MS);
digitalWrite(configuration.LEDs.StatusLed, HIGH);
vTaskDelay(500 / portTICK_PERIOD_MS);
digitalWrite(configuration.LEDs.StatusLed, LOW);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void ShowMqttActivity(void *pvParameter)
{
digitalWrite(configuration.LEDs.MqttLed, LOW);
vTaskDelay(100 / portTICK_PERIOD_MS);
digitalWrite(configuration.LEDs.MqttLed, HIGH);
vTaskDelay(100 / portTICK_PERIOD_MS);
digitalWrite(configuration.LEDs.MqttLed, LOW);
vTaskDelay(100 / portTICK_PERIOD_MS);
digitalWrite(configuration.LEDs.MqttLed, HIGH);
MqttActivityHandle = NULL;
vTaskDelete(NULL);
}
void ShowCanError(void *pvParameter)
{
while (true)
{
digitalWrite(configuration.LEDs.HeatingLed, !digitalRead(configuration.LEDs.HeatingLed));
vTaskDelay(500);
}
}
void UpdateLeds(void *pvParameter)
{
while (true)
{
// Blink Wifi LED
if (!WiFi.isConnected())
{
digitalWrite(configuration.LEDs.WifiLed, !digitalRead(configuration.LEDs.WifiLed));
}
else
{
digitalWrite(configuration.LEDs.WifiLed, HIGH);
}
if (MqttActivityHandle == NULL)
{
// Blink MQTT LED
if (!client.connected())
{
digitalWrite(configuration.LEDs.MqttLed, !digitalRead(configuration.LEDs.MqttLed));
}
else
{
digitalWrite(configuration.LEDs.MqttLed, HIGH);
}
}
if (CanErrorActivityHandle == NULL)
{
// BLink LED if Pump is active but heating isn't. This means the heating is about to go off.
if (ceraValues.Heating.PumpActive && !ceraValues.Heating.Active)
{
digitalWrite(configuration.LEDs.HeatingLed, !digitalRead(configuration.LEDs.HeatingLed));
}
if (!ceraValues.Heating.PumpActive && !ceraValues.Heating.Active)
{
digitalWrite(configuration.LEDs.HeatingLed, LOW);
}
if (ceraValues.Heating.PumpActive && ceraValues.Heating.Active)
{
digitalWrite(configuration.LEDs.HeatingLed, HIGH);
}
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void TrackBoostFunction(void *pvParameter)
{
while (true)
{
// Boost Function
if (commandedValues.Heating.Boost)
{
// Countdown to zero and switch off boost if 0
if (commandedValues.Heating.BoostTimeCountdown > 0)
{
commandedValues.Heating.BoostTimeCountdown--;
if (configuration.General.Debug)
{
Log.printf("[%s][%s] Time: %i Left: %i \r\n", myTZ.dateTime("d-M-y H:i:s.v").c_str(), __func__, commandedValues.Heating.BoostDuration, commandedValues.Heating.BoostTimeCountdown);
}
}
else
{
commandedValues.Heating.Boost = false;
}
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}