-
Notifications
You must be signed in to change notification settings - Fork 307
/
Homie.cpp
407 lines (326 loc) · 12.7 KB
/
Homie.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
#include "Homie.hpp"
using namespace HomieInternals;
HomieClass::HomieClass()
: _setupCalled(false)
, _firmwareSet(false)
, __HOMIE_SIGNATURE("\x25\x48\x4f\x4d\x49\x45\x5f\x45\x53\x50\x38\x32\x36\x36\x5f\x46\x57\x25") {
strlcpy(Interface::get().brand, DEFAULT_BRAND, MAX_BRAND_LENGTH);
Interface::get().bootMode = HomieBootMode::UNDEFINED;
Interface::get().configurationAp.secured = false;
#ifdef ESP32
Interface::get().led.enabled = false;
#ifdef LED_BUILTIN
Interface::get().led.pin = LED_BUILTIN;
#endif // LED_BUILTIN
Interface::get().led.on = LOW;
#elif defined(ESP8266)
Interface::get().led.enabled = true;
Interface::get().led.pin = LED_BUILTIN;
Interface::get().led.on = LOW;
#endif // ESP32
Interface::get().reset.idle = true;
Interface::get().reset.enabled = true;
Interface::get().reset.triggerPin = DEFAULT_RESET_PIN;
Interface::get().reset.triggerState = DEFAULT_RESET_STATE;
Interface::get().reset.triggerTime = DEFAULT_RESET_TIME;
Interface::get().reset.resetFlag = false;
Interface::get().disable = false;
Interface::get().flaggedForSleep = false;
Interface::get().globalInputHandler = [](const HomieNode& node, const HomieRange& range, const String& property, const String& value) { return false; };
Interface::get().broadcastHandler = [](const String& level, const String& value) { return false; };
Interface::get().setupFunction = []() {};
Interface::get().loopFunction = []() {};
Interface::get().eventHandler = [](const HomieEvent& event) {};
Interface::get().ready = false;
Interface::get()._mqttClient = &_mqttClient;
Interface::get()._sendingPromise = &_sendingPromise;
Interface::get()._blinker = &_blinker;
Interface::get()._logger = &_logger;
Interface::get()._config = &_config;
DeviceId::generate();
}
HomieClass::~HomieClass() {
}
void HomieClass::_checkBeforeSetup(const __FlashStringHelper* functionName) const {
if (_setupCalled) {
String message;
message.concat(F("✖ "));
message.concat(functionName);
message.concat(F("(): has to be called before setup()"));
Helpers::abort(message);
}
}
void HomieClass::setup() {
_setupCalled = true;
// Check if firmware is set
if (!_firmwareSet) {
Helpers::abort(F("✖ Firmware name must be set before calling setup()"));
return; // never reached, here for clarity
}
// Check the max allowed setting elements
if (IHomieSetting::settings.size() > MAX_CONFIG_SETTING_SIZE) {
Helpers::abort(F("✖ Settings exceed set limit of elelement."));
return; // never reached, here for clarity
}
// Check if default settings values are valid
bool defaultSettingsValuesValid = true;
for (IHomieSetting* iSetting : IHomieSetting::settings) {
if (iSetting->isBool()) {
HomieSetting<bool>* setting = static_cast<HomieSetting<bool>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
} else if (iSetting->isLong()) {
HomieSetting<long>* setting = static_cast<HomieSetting<long>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
} else if (iSetting->isDouble()) {
HomieSetting<double>* setting = static_cast<HomieSetting<double>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
} else if (iSetting->isConstChar()) {
HomieSetting<const char*>* setting = static_cast<HomieSetting<const char*>*>(iSetting);
if (!setting->isRequired() && !setting->validate(setting->get())) {
defaultSettingsValuesValid = false;
break;
}
}
}
if (!defaultSettingsValuesValid) {
Helpers::abort(F("✖ Default setting value does not pass validator test"));
return; // never reached, here for clarity
}
// boot mode set during this boot by application before Homie.setup()
HomieBootMode _applicationHomieBootMode = Interface::get().bootMode;
// boot mode set before resetting the device. If application has defined a boot mode, this will be ignored
HomieBootMode _nextHomieBootMode = Interface::get().getConfig().getHomieBootModeOnNextBoot();
if (_nextHomieBootMode != HomieBootMode::UNDEFINED) {
Interface::get().getConfig().setHomieBootModeOnNextBoot(HomieBootMode::UNDEFINED);
}
#if HOMIE_CONFIG
HomieBootMode _selectedHomieBootMode = HomieBootMode::CONFIGURATION;
#else
HomieBootMode _selectedHomieBootMode = HomieBootMode::NORMAL;
#endif
// select boot mode source
if (_applicationHomieBootMode != HomieBootMode::UNDEFINED) {
_selectedHomieBootMode = _applicationHomieBootMode;
} else if (_nextHomieBootMode != HomieBootMode::UNDEFINED) {
_selectedHomieBootMode = _nextHomieBootMode;
} else {
_selectedHomieBootMode = HomieBootMode::NORMAL;
}
// load and check config file
bool isConfigured = Interface::get().getConfig().load();
// validate selected mode and fallback as needed
if (_selectedHomieBootMode == HomieBootMode::NORMAL && !isConfigured) {
#if HOMIE_CONFIG
Interface::get().getLogger() << F("Configuration invalid. Using CONFIG MODE") << endl;
_selectedHomieBootMode = HomieBootMode::CONFIGURATION;
#else
Interface::get().getLogger() << F("Configuration invalid. CONFIG MODE is disabled.") << endl;
ESP.restart();
#endif
}
// run selected mode
if (_selectedHomieBootMode == HomieBootMode::NORMAL) {
_boot = &_bootNormal;
Interface::get().event.type = HomieEventType::NORMAL_MODE;
Interface::get().eventHandler(Interface::get().event);
#if HOMIE_CONFIG
} else if (_selectedHomieBootMode == HomieBootMode::CONFIGURATION) {
_boot = &_bootConfig;
Interface::get().event.type = HomieEventType::CONFIGURATION_MODE;
Interface::get().eventHandler(Interface::get().event);
#endif
} else if (_selectedHomieBootMode == HomieBootMode::STANDALONE) {
_boot = &_bootStandalone;
Interface::get().event.type = HomieEventType::STANDALONE_MODE;
Interface::get().eventHandler(Interface::get().event);
} else {
Helpers::abort(F("✖ Boot mode invalid"));
return; // never reached, here for clarity
}
WiFi.disconnect(); // workaround for issue #351
_boot->setup();
}
void HomieClass::loop() {
_boot->loop();
if (_flaggedForReboot && Interface::get().reset.idle) {
Interface::get().getLogger() << F("Device is idle") << endl;
Interface::get().getLogger() << F("Triggering ABOUT_TO_RESET event...") << endl;
Interface::get().event.type = HomieEventType::ABOUT_TO_RESET;
Interface::get().eventHandler(Interface::get().event);
Interface::get().getLogger() << F("↻ Rebooting device...") << endl;
Serial.flush();
ESP.restart();
}
}
HomieClass& HomieClass::disableLogging() {
_checkBeforeSetup(F("disableLogging"));
Interface::get().getLogger().setLogging(false);
return *this;
}
HomieClass& HomieClass::setLoggingPrinter(Print* printer) {
_checkBeforeSetup(F("setLoggingPrinter"));
Interface::get().getLogger().setPrinter(printer);
return *this;
}
HomieClass& HomieClass::disableLedFeedback() {
_checkBeforeSetup(F("disableLedFeedback"));
Interface::get().led.enabled = false;
return *this;
}
HomieClass& HomieClass::setLedPin(uint8_t pin, uint8_t on) {
_checkBeforeSetup(F("setLedPin"));
Interface::get().led.pin = pin;
Interface::get().led.on = on;
Interface::get().led.enabled = true;
return *this;
}
HomieClass& HomieClass::setConfigurationApPassword(const char* password) {
_checkBeforeSetup(F("setConfigurationApPassword"));
Interface::get().configurationAp.secured = true;
strlcpy(Interface::get().configurationAp.password, password, MAX_WIFI_PASSWORD_LENGTH);
return *this;
}
void HomieClass::__setFirmware(const char* name, const char* version) {
_checkBeforeSetup(F("setFirmware"));
if (strlen(name) + 1 - 10 > MAX_FIRMWARE_NAME_LENGTH || strlen(version) + 1 - 10 > MAX_FIRMWARE_VERSION_LENGTH) {
Helpers::abort(F("✖ setFirmware(): either the name or version string is too long"));
return; // never reached, here for clarity
}
strncpy(Interface::get().firmware.name, name + 5, strlen(name) - 10);
Interface::get().firmware.name[strlen(name) - 10] = '\0';
strncpy(Interface::get().firmware.version, version + 5, strlen(version) - 10);
Interface::get().firmware.version[strlen(version) - 10] = '\0';
_firmwareSet = true;
}
void HomieClass::__setBrand(const char* brand) const {
_checkBeforeSetup(F("setBrand"));
if (strlen(brand) + 1 - 10 > MAX_BRAND_LENGTH) {
Helpers::abort(F("✖ setBrand(): the brand string is too long"));
return; // never reached, here for clarity
}
strncpy(Interface::get().brand, brand + 5, strlen(brand) - 10);
Interface::get().brand[strlen(brand) - 10] = '\0';
}
void HomieClass::reset() {
Interface::get().getLogger() << F("Flagged for reset by sketch") << endl;
Interface::get().disable = true;
Interface::get().reset.resetFlag = true;
}
void HomieClass::reboot() {
Interface::get().getLogger() << F("Flagged for reboot by sketch") << endl;
Interface::get().disable = true;
_flaggedForReboot = true;
}
void HomieClass::setIdle(bool idle) {
Interface::get().reset.idle = idle;
}
HomieClass& HomieClass::setGlobalInputHandler(const GlobalInputHandler& globalInputHandler) {
_checkBeforeSetup(F("setGlobalInputHandler"));
Interface::get().globalInputHandler = globalInputHandler;
return *this;
}
HomieClass& HomieClass::setBroadcastHandler(const BroadcastHandler& broadcastHandler) {
_checkBeforeSetup(F("setBroadcastHandler"));
Interface::get().broadcastHandler = broadcastHandler;
return *this;
}
HomieClass& HomieClass::setSetupFunction(const OperationFunction& function) {
_checkBeforeSetup(F("setSetupFunction"));
Interface::get().setupFunction = function;
return *this;
}
HomieClass& HomieClass::setLoopFunction(const OperationFunction& function) {
_checkBeforeSetup(F("setLoopFunction"));
Interface::get().loopFunction = function;
return *this;
}
HomieClass& HomieClass::setHomieBootMode(HomieBootMode bootMode) {
_checkBeforeSetup(F("setHomieBootMode"));
Interface::get().bootMode = bootMode;
return *this;
}
HomieClass& HomieClass::setHomieBootModeOnNextBoot(HomieBootMode bootMode) {
Interface::get().getConfig().setHomieBootModeOnNextBoot(bootMode);
return *this;
}
bool HomieClass::isConfigured() {
return Interface::get().getConfig().isValid();
}
bool HomieClass::isConnected() {
return Interface::get().ready;
}
HomieClass& HomieClass::onEvent(const EventHandler& handler) {
_checkBeforeSetup(F("onEvent"));
Interface::get().eventHandler = handler;
return *this;
}
HomieClass& HomieClass::setResetTrigger(uint8_t pin, uint8_t state, uint16_t time) {
_checkBeforeSetup(F("setResetTrigger"));
Interface::get().reset.enabled = true;
Interface::get().reset.triggerPin = pin;
Interface::get().reset.triggerState = state;
Interface::get().reset.triggerTime = time;
return *this;
}
HomieClass& HomieClass::disableResetTrigger() {
_checkBeforeSetup(F("disableResetTrigger"));
Interface::get().reset.enabled = false;
return *this;
}
const ConfigStruct& HomieClass::getConfiguration() {
return Interface::get().getConfig().get();
}
AsyncMqttClient& HomieClass::getMqttClient() {
return _mqttClient;
}
Logger& HomieClass::getLogger() {
return _logger;
}
void HomieClass::prepareToSleep() {
Interface::get().getLogger() << F("Flagged for sleep by sketch") << endl;
if (Interface::get().ready) {
Interface::get().disable = true;
Interface::get().flaggedForSleep = true;
} else {
Interface::get().disable = true;
Interface::get().getLogger() << F("Triggering READY_TO_SLEEP event...") << endl;
Interface::get().event.type = HomieEventType::READY_TO_SLEEP;
Interface::get().eventHandler(Interface::get().event);
}
}
#ifdef ESP32
void HomieClass::doDeepSleep(uint64_t time_us) {
Interface::get().getLogger() << F("💤 Device is deep sleeping...") << endl;
Serial.flush();
esp_sleep_enable_timer_wakeup(time_us);
esp_deep_sleep_start();
}
void HomieClass::doDeepSleep(gpio_num_t wakeupPin, int logicLevel) {
Interface::get().getLogger() << F("💤 Device is deep sleeping...") << endl;
Serial.flush();
esp_sleep_enable_ext0_wakeup(wakeupPin, logicLevel);
esp_deep_sleep_start();
}
void HomieClass::doDeepSleep(uint64_t pinMask, esp_sleep_ext1_wakeup_mode_t mode) {
Interface::get().getLogger() << F("💤 Device is deep sleeping...") << endl;
Serial.flush();
esp_sleep_enable_ext1_wakeup(pinMask, mode);
esp_deep_sleep_start();
}
#elif defined(ESP8266)
void HomieClass::doDeepSleep(uint64_t time_us, RFMode mode) {
Interface::get().getLogger() << F("💤 Device is deep sleeping...") << endl;
Serial.flush();
ESP.deepSleep(time_us, mode);
}
#endif // ESP32
HomieClass Homie;