-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFakeGatoScheduler.cpp
More file actions
503 lines (438 loc) · 19.2 KB
/
FakeGatoScheduler.cpp
File metadata and controls
503 lines (438 loc) · 19.2 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
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
/*
Copyright (c) 2025 David Carson (dacarson)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#define CUSTOM_CHAR_HEADER
#include "FakeGatoScheduler.h"
#include "Navien.h"
extern Navien navienSerial;
// Unfortunately, ESP32 doesn't have the timegm() function, so implement one here
time_t timegm(struct tm *tm) {
// Save current TZ
char *oldTZ = getenv("TZ");
char *oldTZCopy = oldTZ ? strdup(oldTZ) : nullptr; // Make a copy
// Temporarily set TZ to UTC
setenv("TZ", "UTC0", 1);
tzset();
// Convert to time_t (interpreted as UTC)
time_t utcTime = mktime(tm);
// Restore previous TZ
if (oldTZCopy) {
setenv("TZ", oldTZCopy, 1);
free(oldTZCopy);
} else {
unsetenv("TZ"); // Reset if there was no previous TZ
}
tzset();
return utcTime;
}
FakeGatoScheduler::FakeGatoScheduler()
: SchedulerBase() {
programData = new Characteristic::ProgramData();
size_t len;
nvs_open("SAVED_DATA",NVS_READWRITE,&savedData); // open a new namespace called SAVED_DATA in the NVS
if(!nvs_get_blob(savedData,"PROG_SEND_DATA",NULL,&len)) { // if PROG_SEND_DATA data found
nvs_get_blob(savedData,"PROG_SEND_DATA",&prog_send_data,&len); // retrieve data
WEBLOG("SCHEDULER Loaded Program State");
// Setup the scheduler state.
if (prog_send_data.schedule_state.schedule_on)
scheduleActive = true;
setVacationState(false);
if (prog_send_data.vacation.enabled)
setVacationState(true);
} else {
WEBLOG("SCHEDULER Initializing Program State");
prog_send_data.temp_offset.offset = 0;
prog_send_data.install_status.status = 0xC0;
prog_send_data.vacation.enabled = 0x00;
setVacationState(false);
prog_send_data.schedule_state.schedule_on = 0x00;
scheduleActive = false;
// clear every day of the weekly schedule
memset(&prog_send_data.weekSchedule.day, 0xFF, sizeof(prog_send_data.weekSchedule.day));
// clear today's schedule
memset(&prog_send_data.currentSchedule.current, 0xFF, sizeof(prog_send_data.currentSchedule.current));
}
updateSchedulerWeekSchedule();
refreshProgramData = true;
}
String FakeGatoScheduler::getSchedulerState(int state) {
switch (state) {
case 0: return "Unknown";
case 1: return "Active";
case 2: return "Inactive";
case 3: return "Vacation";
case 4: return "Override";
default: return "Invalid";
}
}
void FakeGatoScheduler::stateChange(State newState){
time_t nextStateTime;
this->getNextState(&nextStateTime);
struct tm *tm_struct = localtime(&nextStateTime);
Serial.printf("Next event scheduled for: %02d:%02d %02d/%02d/%04d\n",
tm_struct->tm_hour, tm_struct->tm_min,
tm_struct->tm_mon + 1, tm_struct->tm_mday, // tm_mon is 0-based
tm_struct->tm_year + 1900); // tm_year is years since 1900
// Track Override states even if the scheduler is not active
if (!scheduleActive &&
(newState != State::Override && currentState != State::Override)) {
WEBLOG("Ignoring state change, scheduler not active.");
return;
}
// If the schedule is not running and we are leaving Override state
// then we need to go InActive
if (!scheduleActive && currentState == State::Override) {
newState = State::InActive;
}
// Should not need to update the targetState of the Thermostat
// as that will update when the state changes in the Navien
switch (newState) {
case State::Override:
// Fall through
case State::Active:
WEBLOG("SCHEDULER going Active %s", newState == State::Override ? "- Override" : "" );
if (!navienSerial.currentState()->water[0].system_power)
navienSerial.power(true);
if (!navienSerial.currentState()->water[0].recirculation_active)
if (navienSerial.recirculation(true) == -1)
WEBLOG("Failed to enable Recirculation.");
// ignore setpoints as they only go to 30 degC
//navienSerial.setTemp(0.5 * prog_send_data.temperatures.comfortScheduleTemp);
break;
case State::InActive:
WEBLOG("SCHEDULER going Inactive");
if (!navienSerial.currentState()->water[0].system_power)
navienSerial.power(true);
if (navienSerial.recirculation(false) == -1)
WEBLOG("Failed to disable Recirculation.");
// ignore setpoints as they only go to 30 degC
//navienSerial.setTemp(0.5 * prog_send_data.temperatures.comfortScheduleTemp);
break;
case State::Vacation:
WEBLOG("SCHEDULER going Vacation");
navienSerial.recirculation(false);
if (navienSerial.power(false) == -1)
WEBLOG("Failed to turn power off");
break;
}
}
void FakeGatoScheduler::addMilliseconds(PROG_CMD_CURRENT_TIME *timeStruct, uint32_t milliseconds) {
// Convert milliseconds to seconds and remaining milliseconds
uint32_t secondsToAdd = milliseconds / 1000;
milliseconds %= 1000; // Remaining milliseconds (not stored in struct)
// Convert structure to time_t for easier manipulation
struct tm t = { 0 };
t.tm_year = timeStruct->year + 100; // tm_year is years since 1900
t.tm_mon = timeStruct->month - 1; // tm_mon is 0-based
t.tm_mday = timeStruct->day;
t.tm_hour = timeStruct->hours;
t.tm_min = timeStruct->minutes;
t.tm_sec = 0; // Assuming no seconds in the structure
// Add seconds
time_t rawTime = mktime(&t); // Convert struct to time_t
rawTime += secondsToAdd; // Add the seconds
// Convert back to structure
struct tm *updatedTime = localtime(&rawTime);
timeStruct->year = updatedTime->tm_year - 100;
timeStruct->month = updatedTime->tm_mon + 1;
timeStruct->day = updatedTime->tm_mday;
timeStruct->hours = updatedTime->tm_hour;
timeStruct->minutes = updatedTime->tm_min;
}
void FakeGatoScheduler::guessTimeZone(PROG_CMD_CURRENT_TIME *eveLocalTime) {
struct tm eveTimeInfo = {0}; // Initialize to zero
eveTimeInfo.tm_year = eveLocalTime->year + 100; // tm_year is years since 1900
eveTimeInfo.tm_mon = eveLocalTime->month - 1; // tm_mon is 0-based (Jan = 0)
eveTimeInfo.tm_mday = eveLocalTime->day;
eveTimeInfo.tm_hour = eveLocalTime->hours;
eveTimeInfo.tm_min = eveLocalTime->minutes;
eveTimeInfo.tm_sec = 0; // Assuming seconds are zero
time_t localTime = timegm(&eveTimeInfo); // Convert to time_t (Unix timestamp) *IGNORING TIMEZONE*
time_t currentTime = time(nullptr); // Get the current system time
struct tm *deviceLocalTime = localtime(¤tTime); // Convert to local time struct
// Make sure the timezone is set AND the hours are the same
// If hours are different, then we need to update the TZ
if (getenv("TZ") && eveTimeInfo.tm_hour == deviceLocalTime->tm_hour) {
Serial.print("Timezone is correct. ");
Serial.println(getenv("TZ"));
return; // TZ already set.
}
double timeDiffSeconds = difftime(currentTime, localTime);
int timeDiffHours = std::round(timeDiffSeconds / 3600.0);
char tzString[10];
snprintf(tzString, sizeof(tzString), "UTC%+d", timeDiffHours);
if (setTz(String(tzString))) {
WEBLOG("Set estimated TZ %s\n", tzString);
} else {
WEBLOG("Failed to set new TZ %s\n", tzString);
}
}
void FakeGatoScheduler::updateSchedulerWeekSchedule() {
// Note Eve schedules are Monday - Sunday
// SchedulerBase are Sunday - Saturday
for (int day = 0; day < 7; day++) { // Monday - Sunday
CMD_DAY_SCHEDULE *daySchedule = &(prog_send_data.weekSchedule.day[day]);
for (int i = 0; i < 4 && daySchedule->slot[i].offset_start != 0xFF; i++) {
weekSchedule[(day + 1) % 7].slots[i].startHour = (uint8_t)(daySchedule->slot[i].offset_start / 6);
weekSchedule[(day + 1) % 7].slots[i].startMinute = (uint8_t)(daySchedule->slot[i].offset_start % 6) * 10;
weekSchedule[(day + 1) % 7].slots[i].endHour = (uint8_t)(daySchedule->slot[i].offset_end / 6);
weekSchedule[(day + 1) % 7].slots[i].endMinute = (uint8_t)(daySchedule->slot[i].offset_end % 6) * 10;
}
}
// Recalculate current state after schedule update
if (isInitialized) {
initializeCurrentState();
}
}
void FakeGatoScheduler::parseProgramData(uint8_t *data, int len) {
int byte_offset = 0;
bool storeData = false;
while (byte_offset < len) {
switch (data[byte_offset]) {
case BEGIN_BLOCK:
byte_offset++;
break;
case END_BLOCK:
byte_offset++;
// This is the end of the data so drop everything after this
byte_offset = len;
break;
case VALVE_PROTECTION:
{
PROG_CMD_VALVE_PROTECT *valve_prot = (PROG_CMD_VALVE_PROTECT *)(&data[byte_offset]);
Serial.printf("Valve Protection ");
printData(&data[byte_offset], sizeof(PROG_CMD_VALVE_PROTECT));
byte_offset += sizeof(PROG_CMD_VALVE_PROTECT);
break;
}
case TEMPERATURE_OFFSET:
{
PROG_CMD_TEMPERATURE_OFFSET *temp_offset = (PROG_CMD_TEMPERATURE_OFFSET *)(&data[byte_offset]);
temperature_offset = temp_offset->offset;
Serial.printf("Temperature Offset: %0.1f C\n", (float)((int8_t)(temp_offset->offset)) / 10.0);
memcpy(&prog_send_data.temp_offset, temp_offset, sizeof(PROG_CMD_TEMPERATURE_OFFSET));
byte_offset += sizeof(PROG_CMD_TEMPERATURE_OFFSET);
storeData = true;
break;
}
case SCHEDULE_STATE:
{
PROG_CMD_SCHEDULE_STATE *schedule_state = (PROG_CMD_SCHEDULE_STATE *)(&data[byte_offset]);
// Update the current state to what the user wants
if (schedule_state->schedule_on) {
scheduleActive = true;
Serial.println("Schedule: On");
} else {
scheduleActive = false;
Serial.println("Schedule: Off");
}
// Now set the fake state, because the Eve app attempts to turn on the heat if the
// current temperature is less that the target and the schedule is on. So...
// If the scheduler is either off or not active then report that the schedule is turned off
if (!scheduleActive || (currentState != SchedulerBase::Active && currentState != SchedulerBase::Override)) {
schedule_state->schedule_on = 0;
}
// If the user turned it on, but our current state is inactive, then show it as off
if (scheduleActive && (currentState == SchedulerBase::Active || currentState == SchedulerBase::Override)) {
schedule_state->schedule_on = 0;
}
memcpy(&prog_send_data.schedule_state, schedule_state, sizeof(PROG_CMD_SCHEDULE_STATE));
byte_offset += sizeof(PROG_CMD_SCHEDULE_STATE);
storeData = true;
break;
}
case INSTALLED_STATUS: {
PROG_DATA_INSTALLED_STATUS *install_status = (PROG_DATA_INSTALLED_STATUS *)(&data[byte_offset]);
Serial.print("Install status: ");
Serial.println(install_status->status);
// Don't memcpy, keep the default of 0xC0 - installed
byte_offset += sizeof(PROG_DATA_INSTALLED_STATUS);
break;
}
case UNKNOWN_BLOCK: {
PROG_DATA_UNKNOWN_BLOCK *unknown_block = (PROG_DATA_UNKNOWN_BLOCK *)(&data[byte_offset]);
Serial.print("Unknown block: ");
Serial.print(unknown_block->unknown_01);
Serial.print(" ");
Serial.println(unknown_block->unknown_02);
// Don't memcpy, keep the default of 0xC0 - installed
byte_offset += sizeof(PROG_DATA_UNKNOWN_BLOCK);
break;
}
case VACATION_MODE:
{
PROG_CMD_VACATION_MODE *vacationMode = (PROG_CMD_VACATION_MODE *)(&data[byte_offset]);
Serial.printf("Vacation Mode: ");
if (vacationMode->enabled) {
Serial.printf(" On, Set Point %0.1f C\n", (0.5 * vacationMode->away_temp));
setVacationState(true);
} else {
Serial.println(" Off");
setVacationState(false);
}
memcpy(&prog_send_data.vacation, vacationMode, sizeof(PROG_CMD_VACATION_MODE));
byte_offset += sizeof(PROG_CMD_VACATION_MODE);
storeData = true;
break;
}
case CURRENT_SCHEDULE:
{
PROG_CMD_CURRENT_SCHEDULE *currentSchedule = (PROG_CMD_CURRENT_SCHEDULE *)(&data[byte_offset]);
Serial.printf("Current Schedule today %d ", currentScheduleDay);
printDaySchedule(¤tSchedule->current);
//only update if we don't know what day it is
if (currentScheduleDay < 0)
memcpy(&prog_send_data.currentSchedule, currentSchedule, sizeof(PROG_CMD_CURRENT_SCHEDULE));
byte_offset += sizeof(PROG_CMD_CURRENT_SCHEDULE);
storeData = true;
break;
}
case TEMPERATURES:
{
PROG_CMD_TEMPERATURES *temperatures = (PROG_CMD_TEMPERATURES *)(&data[byte_offset]);
Serial.printf("Default Temp: %0.1f C\n", (0.5 * temperatures->defaultTemp));
Serial.printf("Economy Temp: %0.1f C\n", (0.5 * temperatures->economyScheduleTemp));
Serial.printf("Comfort Temp: %0.1f C\n", (0.5 * temperatures->comfortScheduleTemp));
// Override the default and comfort temps with the device set_point because the
// Eve app only allows up to 30degC/86degF
prog_send_data.temperatures.header = TEMPERATURES;
prog_send_data.temperatures.unknown = 0x00;
prog_send_data.temperatures.defaultTemp = navienSerial.currentState()->gas.set_temp * 2;
prog_send_data.temperatures.comfortScheduleTemp = navienSerial.currentState()->gas.set_temp * 2;
prog_send_data.temperatures.economyScheduleTemp = Navien::TEMPERATURE_MIN;
byte_offset += sizeof(PROG_CMD_TEMPERATURES);
storeData = true;
break;
}
case OPEN_WINDOW: {
PROG_DATA_OPEN_WINDOW *open_window = (PROG_DATA_OPEN_WINDOW *)(&data[byte_offset]);
Serial.print("Open window: ");
Serial.print(open_window->unknown_01);
Serial.print(" ");
Serial.print(open_window->unknown_02);
Serial.print(" ");
Serial.println(open_window->unknown_03);
// Should not be sent to the device. But if it does, ignore it.
byte_offset += sizeof(PROG_DATA_OPEN_WINDOW);
break;
}
case WEEK_SCHEDULE:
{
PROG_CMD_WEEK_SCHEDULE *weekSchedule = (PROG_CMD_WEEK_SCHEDULE *)(&data[byte_offset]);
Serial.println("Week Schedule: ");
for (int day = 0; day < 7; day++) {
Serial.printf("Schedule Day %d ", day);
printDaySchedule(&weekSchedule->day[day]);
}
Serial.println("");
memcpy(&prog_send_data.weekSchedule, weekSchedule, sizeof(PROG_CMD_WEEK_SCHEDULE));
updateSchedulerWeekSchedule();
updateCurrentScheduleIfNeeded(true);
initializeCurrentState(); // Recalculate current state after schedule change
byte_offset += sizeof(PROG_CMD_WEEK_SCHEDULE);
storeData = true;
break;
}
case CURRENT_TIME:
{
PROG_CMD_CURRENT_TIME *currentTime = (PROG_CMD_CURRENT_TIME *)(&data[byte_offset]);
Serial.printf("Current Time: ");
Serial.printf("%d:%d ", currentTime->hours, currentTime->minutes);
Serial.printf("Day %d ", currentTime->day);
Serial.printf("Month %d Year 20%d\n", currentTime->month, currentTime->year);
memcpy(&prog_send_data.currentTime, currentTime, sizeof(PROG_CMD_CURRENT_TIME));
clockOffset = millis();
guessTimeZone(currentTime);
byte_offset += sizeof(PROG_CMD_CURRENT_TIME);
break;
}
case UNKNOWN_FF:
{
PROG_CMD_UNKNOWN_FF *unknown_ff = (PROG_CMD_UNKNOWN_FF *)(&data[byte_offset]);
Serial.printf("Unknown_FF ");
Serial.printf("Value 1: %x, ", unknown_ff->unknown_01);
Serial.printf("Value 2: %x", unknown_ff->unknown_02);
Serial.println("");
byte_offset += sizeof(PROG_CMD_UNKNOWN_FF);
break;
}
default:
Serial.printf("Found unknown header packet %d\n", data[byte_offset]);
printData(data, len);
// Stop parsing as I don't know how long this header is
byte_offset = len;
break;
}
}
addMilliseconds(&prog_send_data.currentTime, millis() - clockOffset);
clockOffset = millis();
if (storeData) {
nvs_set_blob(savedData,"PROG_SEND_DATA",&prog_send_data,sizeof(prog_send_data)); // update data in the NVS
nvs_commit(savedData);
refreshProgramData = true;
}
}
void FakeGatoScheduler::updateCurrentScheduleIfNeeded(bool force) {
time_t now = time(nullptr);
struct tm *tm_struct = localtime(&now);
int eveDayOfWeek = (tm_struct->tm_wday + 6) % 7; // Convert to Monday - Sunday
if (force || currentScheduleDay != eveDayOfWeek) {
currentScheduleDay = eveDayOfWeek;
memcpy(&prog_send_data.currentSchedule.current,
&prog_send_data.weekSchedule.day[currentScheduleDay], sizeof(PROG_CMD_CURRENT_SCHEDULE));
}
}
int FakeGatoScheduler::begin() {
if (SchedulerBase::begin()) {
updateCurrentScheduleIfNeeded(true);
return true;
}
return false;
}
void FakeGatoScheduler::loop() {
SchedulerBase::loop();
if (refreshProgramData || programData->timeVal() > 60000) {
updateCurrentScheduleIfNeeded(false);
addMilliseconds(&prog_send_data.currentTime, millis() - clockOffset);
clockOffset = millis();
// Don't announce when there is new program data, Eve app will fetch it when it wants it.
programData->setData((const uint8_t *)&prog_send_data, sizeof(PROG_DATA_FULL_DATA), false);
refreshProgramData = false;
}
}
void FakeGatoScheduler::printData(uint8_t *data, int len) {
Serial.printf("Data %d ", len);
for (int i = 0; i < len; i++) {
if (data[i] < 0x10)
Serial.printf("0%x ", data[i]);
else
Serial.printf("%x ", data[i]);
}
Serial.println("");
}
void FakeGatoScheduler::printDaySchedule(CMD_DAY_SCHEDULE *daySchedule) {
for (int i = 0; i < 4; i++) {
if (daySchedule->slot[i].offset_start != UNSET) {
Serial.printf("%d:%d - %d:%d ", (int)(daySchedule->slot[i].offset_start / 6),
(int)((daySchedule->slot[i].offset_start % 6) * 10),
(int)(daySchedule->slot[i].offset_end / 6),
(int)((daySchedule->slot[i].offset_end % 6) * 10));
}
}
Serial.println("");
}