-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDEV_Navien.ino
More file actions
369 lines (303 loc) · 13.5 KB
/
Copy pathDEV_Navien.ino
File metadata and controls
369 lines (303 loc) · 13.5 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
/*
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.
*/
#include "HomeSpan.h"
#include "esp_mac.h" // required - exposes esp_mac_type_t values
#include "FakeGatoScheduler.h"
#include "FakeGatoHistoryService.h"
extern Navien navienSerial;
// Global so that Telnet can dump history state.
FakeGatoHistoryService *historyService;
FakeGatoScheduler *scheduler;
CUSTOM_CHAR(ValvePosition, E863F12E-079E-48FF-8F27-9C2605A29F52, PR+EV, UINT8, 0, 0, 100, true);
CUSTOM_CHAR_DATA(ProgramCommand, E863F12C-079E-48FF-8F27-9C2605A29F52, PW + EV);
Characteristic::FirmwareRevision *firmwareRevision;
Characteristic::HardwareRevision *hardwareRevision;
struct DEV_Navien : Service::Thermostat {
enum {
OFF = 0,
HEAT = 1,
COOL = 2,
AUTO = 3
}; // Target States
enum {
CELSIUS = 0,
FAHRENHEIT = 1
}; // Display Units
enum {
IDLE = 0,
HEATING = 1,
COOLING = 2
}; // Current States
// Declare the Themo characteristics
Characteristic::CurrentHeatingCoolingState *currentState;
Characteristic::TargetHeatingCoolingState *targetState;
Characteristic::CurrentTemperature *currentTemp;
Characteristic::TargetTemperature *targetTemp;
Characteristic::ProgramMode programMode;
Characteristic::TemperatureDisplayUnits displayUnits{ 0, true };
// Declare the Custom characteristics
Characteristic::ProgramCommand *programCommand;
Characteristic::ValvePosition *valvePosition;
bool accessoryInfoSet = false;
bool activelyControllingUnit = false;
DEV_Navien()
: Service::Thermostat() {
Serial.printf("\n*** Creating Navien Thermostat***\n");
// Current Heating Cooling State (Read-Only)
currentState = new Characteristic::CurrentHeatingCoolingState();
// Target Heating Cooling State (User Selectable)
targetState = new Characteristic::TargetHeatingCoolingState(OFF); // Default: Off
targetState->setValidValues(OFF, HEAT);
// Current Temperature
currentTemp = new Characteristic::CurrentTemperature(45.0); // Default 22°C
// Target Temperature
targetTemp = new Characteristic::TargetTemperature(40.0); // Default 40°C
targetTemp->setRange(Navien::TEMPERATURE_MIN, Navien::TEMPERATURE_MAX, 0.5); // Set min/max/step values
valvePosition = new Characteristic::ValvePosition(0);
valvePosition->setDescription("Actuation");
valvePosition->setUnit("percentage");
programCommand = new Characteristic::ProgramCommand();
// Create the scheduler class that will handle schedule management
// and operations.
scheduler = new FakeGatoScheduler();
scheduler->begin();
// Create a history service
historyService = new FakeGatoHistoryService();
}
boolean update() override {
int ret = 0;
if (targetState->updated()) {
// Check to see if the user overrides current schedule
switch (targetState->getNewVal()) {
case OFF:
if (navienSerial.currentState()->water[0].recirculation_active) {
ret = navienSerial.recirculation(0);
WEBLOG("Ignore schedule, turning off recirculation: %s\n", ret > 0 ? "Success" : "Failed");
} else {
WEBLOG("Ignore schedule, leaving recirculation off\n");
}
break;
case HEAT:
// If the schedule is not enabled, or is enabled and not active, then allow override
// If the scheduler is enabled and active, override doesn't do anything
if (!scheduler->enabled() || (scheduler->enabled() && !scheduler->isActive())) {
if (scheduler->getCurrentState() != SchedulerBase::Override) {
scheduler->activateOverride();
WEBLOG("Requesting Heat NOW for 5 mins");
} else {
Serial.println("Requesting override twice, so ignoring it");
}
} else {
WEBLOG("Ignoring Heat NOW request as it's already running via schedule");
}
break;
}
}
if (targetTemp->updated()) {
// Ignore temparature requests that are not valid
float newSetPoint = targetTemp->getNewVal<float>();
if (newSetPoint >= Navien::TEMPERATURE_MIN && newSetPoint <= Navien::TEMPERATURE_MAX) {
ret = navienSerial.setTemp(targetTemp->getNewVal<float>());
WEBLOG("Temperature target changed to %s: %s\n", temp2String(targetTemp->getNewVal<float>()).c_str(), ret > 0 ? "Success" : "Failed");
} else {
WEBLOG("Ignoring Temperature target of %s as it is out of range", temp2String(targetTemp->getNewVal<float>()).c_str());
}
}
if (programCommand->updated()) {
int len = programCommand->getNewData(0, 0);
uint8_t* data = new uint8_t[len];
programCommand->getNewData(data, len);
scheduler->parseProgramData(data, len);
delete data;
}
return (true);
}
void loop() override {
// Is the scheduler ready
if (scheduler->getCurrentState() != SchedulerBase::Unknown) {
// Are we taking over controlling the unit
if (!activelyControllingUnit && navienSerial.controlAvailable()) {
WEBLOG("No Navilink present, taking control of Navien and setting initial state");
activelyControllingUnit = true;
takeControl();
} else if (activelyControllingUnit && !navienSerial.controlAvailable()) {
WEBLOG("Navilink present, no longer controlling the unit");
activelyControllingUnit = false;
}
}
float outletTemp = navienSerial.currentState()->gas.outlet_temp;
if (currentTemp->timeVal() > 5000 && fabs(currentTemp->getVal<float>() - outletTemp) > 0.50) { // if it's been more than 5 seconds since last update, and temperature has changed
currentTemp->setVal(outletTemp);
//Serial.printf("Navien current Temperature is %s.\n", temp2String(currentTemp->getNewVal<float>()).c_str());
}
int operatingCap = (int)roundf(navienSerial.currentState()->water[0].operating_capacity);
if (operatingCap != valvePosition->getVal()) {
valvePosition->setVal(operatingCap);
}
if (!scheduler->enabled() && !navienSerial.currentState()->water[0].external_recirculation && !navienSerial.currentState()->water[0].internal_recirculation) {
programMode.setVal(0);
} else if (scheduler->getCurrentState() == SchedulerBase::Override) {
programMode.setVal(2);
} else {
programMode.setVal(1);
}
// Navien is actively maintaining the set point
bool navienActivelyMaintainingTemp =
navienSerial.currentState()->water[0].recirculation_active || navienSerial.currentState()->gas.current_gas_usage > 0;
float setTemp = navienSerial.currentState()->gas.set_temp;
if ((targetTemp->getVal<float>() != setTemp) && (setTemp >= Navien::TEMPERATURE_MIN) && (setTemp <= Navien::TEMPERATURE_MAX)) {
targetTemp->setVal(setTemp);
Serial.printf("Navien target Temperature is %s.\n", temp2String(targetTemp->getNewVal<float>()).c_str());
}
// Check the state of the Navien and update appropriately
int heating_state = navienSerial.currentState()->gas.current_gas_usage > 0 ? HEATING : IDLE;
if (currentState->getVal() != heating_state) {
Serial.printf("Updating heat state %d\n", heating_state);
currentState->setVal(heating_state);
}
if (navienActivelyMaintainingTemp) {
if (targetState->getVal() != HEAT) {
targetState->setVal(HEAT);
Serial.println("Forcing target state to Heat");
}
} else { // Scheduler is off and we're not heating so we are off
if (targetState->getVal() != OFF) {
targetState->setVal(OFF);
Serial.println("Forcing target state to Off");
}
}
// display_metric is 1 for Metric, 0 for Imperial.
bool display_metric = navienSerial.currentState()->water[0].display_metric;
if (display_metric && displayUnits.getVal() != CELSIUS) {
displayUnits.setVal(CELSIUS);
} else if (!display_metric && displayUnits.getVal() != FAHRENHEIT) {
displayUnits.setVal(FAHRENHEIT);
}
// Try updating the version number
if (!accessoryInfoSet) {
firmwareRevision->setString(String(navienSerial.currentState()->gas.controller_version).c_str());
hardwareRevision->setString(String(navienSerial.currentState()->gas.panel_version).c_str());
accessoryInfoSet = true;
}
// Make the logging pretty. Bounce the setTemp in the log *only* between the actual setTemp when
// it is heating and Navien's min temperature when it isn't
float logSetTemp = navienActivelyMaintainingTemp ? setTemp : Navien::TEMPERATURE_MIN;
historyService->accumulateLogEntry(outletTemp, logSetTemp, (uint8_t)operatingCap, targetState->getVal(), 0);
scheduler->loop();
}
// This "helper" function makes it easy to display temperatures on the serial monitor in either F or C depending on TemperatureDisplayUnits
String temp2String(float temp) {
String t = displayUnits.getVal() ? String(round(temp * 1.8 + 32.0)) : String(temp);
t += displayUnits.getVal() ? " F" : " C";
return (t);
}
void takeControl() {
// When a NaviLink unit disappears, the Navien state changes.
// We need to set the Navien to the state the scheduler expects
// Do nothing if the scheduler is not enabled
if (!scheduler->enabled()) {
return;
}
switch (scheduler->getCurrentState()) {
case SchedulerBase::InActive:
// Unit should be on and Reciculation should be off
if (!navienSerial.currentState()->water[0].system_power)
navienSerial.power(1);
if (navienSerial.currentState()->water[0].recirculation_active)
navienSerial.recirculation(0);
break;
case SchedulerBase::Active:
case SchedulerBase::Override:
// Unit should be on and Reciculation should be on
if (!navienSerial.currentState()->water[0].system_power)
navienSerial.power(1);
if (!navienSerial.currentState()->water[0].recirculation_active)
navienSerial.recirculation(0);
break;
case SchedulerBase::Vacation:
// Unit should be Off
if (navienSerial.currentState()->water[0].system_power)
navienSerial.power(0);
break;
}
}
};
struct DEV_HotWaterSwitch : Service::Switch {
Characteristic::On *switchOn;
DEV_HotWaterSwitch()
: Service::Switch() {
Serial.printf("\n*** Creating Hot Water Switch ***\n");
switchOn = new Characteristic::On(false);
}
boolean update() override {
if (switchOn->updated() && switchOn->getNewVal()) {
// Turning off is a no-op; sole purpose is to trigger override
if (!scheduler->enabled() || (scheduler->enabled() && !scheduler->isActive())) {
if (scheduler->getCurrentState() != SchedulerBase::Override) {
scheduler->activateOverride();
WEBLOG("Hot Water Switch: Requesting Heat NOW for 5 mins");
} else {
Serial.println("Hot Water Switch: Override already active, ignoring");
}
} else {
WEBLOG("Hot Water Switch: Already running via schedule, ignoring");
}
}
return true;
}
void loop() override {
bool navienActivelyMaintainingTemp =
navienSerial.currentState()->water[0].recirculation_active ||
navienSerial.currentState()->gas.current_gas_usage > 0;
if (switchOn->getVal<bool>() != navienActivelyMaintainingTemp) {
switchOn->setVal(navienActivelyMaintainingTemp);
}
}
};
// Fetch the fused MAC address as WiFi object may not be connected yet, and it's value will be zero
// Use the mac address without colons as the device serial number.
String getSerialNumber() {
String mac = "";
unsigned char mac_base[6] = {0};
if (esp_efuse_mac_get_default(mac_base) == ESP_OK) {
char buffer[13]; // 6*2 characters for hex + 1 character for null terminator
sprintf(buffer, "%02X%02X%02X%02X%02X%02X", mac_base[0], mac_base[1], mac_base[2], mac_base[3], mac_base[4], mac_base[5]);
mac = buffer;
}
return mac;
}
void setupHomeSpanAccessories() {
new SpanAccessory();
new Service::AccessoryInformation();
new Characteristic::Identify();
new Characteristic::Manufacturer("Navien");
new Characteristic::Model("NPE-240A");
firmwareRevision = new Characteristic::FirmwareRevision("-");
hardwareRevision = new Characteristic::HardwareRevision("-");
new Characteristic::SerialNumber(getSerialNumber().c_str());
new DEV_Navien();
new SpanAccessory();
new Service::AccessoryInformation();
new Characteristic::Identify();
new Characteristic::Name("Hot Water");
new Characteristic::Manufacturer("Navien");
new Characteristic::Model("NPE-240A");
new Characteristic::SerialNumber((getSerialNumber() + "-SW").c_str());
new DEV_HotWaterSwitch();
}