This commit is contained in:
proddy
2019-03-17 14:59:37 +01:00
parent 3f3a475ee1
commit 4a559866c7
7 changed files with 173 additions and 106 deletions

View File

@@ -53,6 +53,9 @@ MyESP::MyESP() {
_wifi_callback = NULL; _wifi_callback = NULL;
_wifi_connected = false; _wifi_connected = false;
_ota_pre_callback = NULL;
_ota_post_callback = NULL;
_suspendOutput = false; _suspendOutput = false;
} }
@@ -86,7 +89,6 @@ void MyESP::myDebug(const char * format, ...) {
delete[] buffer; delete[] buffer;
} }
// for flashmemory. Must use PSTR() // for flashmemory. Must use PSTR()
void MyESP::myDebug_P(PGM_P format_P, ...) { void MyESP::myDebug_P(PGM_P format_P, ...) {
if (_suspendOutput) if (_suspendOutput)
@@ -105,10 +107,12 @@ void MyESP::myDebug_P(PGM_P format_P, ...) {
va_end(args); va_end(args);
#ifdef MYESP_TIMESTAMP
// capture & print timestamp // capture & print timestamp
char timestamp[10] = {0}; char timestamp[10] = {0};
snprintf_P(timestamp, sizeof(timestamp), PSTR("[%06lu] "), millis() % 1000000); snprintf_P(timestamp, sizeof(timestamp), PSTR("[%06lu] "), millis() % 1000000);
SerialAndTelnet.print(timestamp); SerialAndTelnet.print(timestamp);
#endif
SerialAndTelnet.println(buffer); SerialAndTelnet.println(buffer);
@@ -150,12 +154,12 @@ void MyESP::_wifiCallback(justwifi_messages_t code, char * parameter) {
// finally if we don't want Serial anymore, turn it off // finally if we don't want Serial anymore, turn it off
if (!_use_serial) { if (!_use_serial) {
Serial.println(FPSTR("Disabling serial port")); myDebug_P(PSTR("Disabling serial port"));
Serial.flush(); Serial.flush();
Serial.end(); Serial.end();
SerialAndTelnet.setSerial(NULL); SerialAndTelnet.setSerial(NULL);
} else { } else {
Serial.println(FPSTR("Using serial port output")); myDebug_P(PSTR("Using serial port output"));
} }
// call any final custom settings // call any final custom settings
@@ -175,9 +179,12 @@ void MyESP::_wifiCallback(justwifi_messages_t code, char * parameter) {
myDebug_P(PSTR("[WIFI] MAC %s"), WiFi.softAPmacAddress().c_str()); myDebug_P(PSTR("[WIFI] MAC %s"), WiFi.softAPmacAddress().c_str());
// we could be in panic mode so enable Serial again // we could be in panic mode so enable Serial again
SerialAndTelnet.setSerial(&Serial); if (!_use_serial) {
Serial.println(FPSTR("Enabling serial port output")); SerialAndTelnet.setSerial(&Serial);
_use_serial = true; _use_serial = true;
}
myDebug_P(PSTR("Enabling serial port output"));
// call any final custom settings // call any final custom settings
if (_wifi_callback) { if (_wifi_callback) {
@@ -201,6 +208,12 @@ void MyESP::_wifiCallback(justwifi_messages_t code, char * parameter) {
} }
} }
// return true if in WiFi AP mode
// does not work after wifi reset on ESP32 yet. See https://github.com/espressif/arduino-esp32/issues/1306
bool MyESP::isAPmode() {
return (WiFi.getMode() & WIFI_AP);
}
// received MQTT message // received MQTT message
// we send this to the call back function. Important to parse are the event strings such as MQTT_MESSAGE_EVENT and MQTT_CONNECT_EVENT // we send this to the call back function. Important to parse are the event strings such as MQTT_MESSAGE_EVENT and MQTT_CONNECT_EVENT
void MyESP::_mqttOnMessage(char * topic, char * payload, size_t len) { void MyESP::_mqttOnMessage(char * topic, char * payload, size_t len) {
@@ -314,12 +327,15 @@ void MyESP::_wifi_setup() {
jw.cleanNetworks(); // Clean existing network configuration jw.cleanNetworks(); // Clean existing network configuration
jw.addNetwork(_wifi_ssid, _wifi_password); // Add a network jw.addNetwork(_wifi_ssid, _wifi_password); // Add a network
#if defined(ESP8266)
WiFi.setSleepMode(WIFI_NONE_SLEEP); // added to possibly fix wifi dropouts in arduino core 2.5.0 WiFi.setSleepMode(WIFI_NONE_SLEEP); // added to possibly fix wifi dropouts in arduino core 2.5.0
#endif
} }
// set the callback function for the OTA onstart // set the callback function for the OTA onstart
void MyESP::setOTA(ota_callback_f OTACallback) { void MyESP::setOTA(ota_callback_f OTACallback_pre, ota_callback_f OTACallback_post) {
_ota_callback = OTACallback; _ota_pre_callback = OTACallback_pre;
_ota_post_callback = OTACallback_post;
} }
// OTA callback when the upload process starts // OTA callback when the upload process starts
@@ -341,8 +357,8 @@ void MyESP::_OTACallback() {
EEPROMr.commit(); EEPROMr.commit();
#endif #endif
if (_ota_callback) { if (_ota_pre_callback) {
(_ota_callback)(); // call custom function to handle mqtt receives (_ota_pre_callback)(); // call custom function
} }
} }
@@ -438,27 +454,23 @@ void MyESP::_telnet_setup() {
// Show help of commands // Show help of commands
void MyESP::_consoleShowHelp() { void MyESP::_consoleShowHelp() {
SerialAndTelnet.println(); myDebug_P(PSTR(""));
SerialAndTelnet.printf(PSTR("* Connected to: %s version %s"), _app_name, _app_version); myDebug_P(PSTR("* Connected to: %s version %s"), _app_name, _app_version);
SerialAndTelnet.println();
if (WiFi.getMode() & WIFI_AP) { if (isAPmode()) {
SerialAndTelnet.printf(PSTR("* Device is in AP mode with SSID %s"), jw.getAPSSID().c_str()); myDebug_P(PSTR("* Device is in AP mode with SSID %s"), jw.getAPSSID().c_str());
} else { } else {
SerialAndTelnet.printf(PSTR("* Hostname: %s (%s)"), getESPhostname().c_str(), WiFi.localIP().toString().c_str()); myDebug_P(PSTR("* Hostname: %s (%s)"), _getESPhostname().c_str(), WiFi.localIP().toString().c_str());
SerialAndTelnet.println(); myDebug_P(PSTR("* WiFi SSID: %s (signal %d%%)"), WiFi.SSID().c_str(), getWifiQuality());
SerialAndTelnet.printf(PSTR("* WiFi SSID: %s (signal %d%%)"), WiFi.SSID().c_str(), getWifiQuality()); myDebug_P(PSTR("* MQTT is %s"), mqttClient.connected() ? "connected" : "disconnected");
SerialAndTelnet.println();
SerialAndTelnet.printf(PSTR("* MQTT is %s"), mqttClient.connected() ? "connected" : "disconnected");
} }
SerialAndTelnet.println(); myDebug_P(PSTR("*"));
SerialAndTelnet.println(FPSTR("*")); myDebug_P(PSTR("* Commands:"));
SerialAndTelnet.println(FPSTR("* Commands:")); myDebug_P(PSTR("* ?=help, CTRL-D=quit telnet"));
SerialAndTelnet.println(FPSTR("* ?=help, CTRL-D=quit telnet")); myDebug_P(PSTR("* set, system, reboot"));
SerialAndTelnet.println(FPSTR("* set, system, reboot"));
#ifdef CRASH #ifdef CRASH
SerialAndTelnet.println(FPSTR("* crash <dump | clear | test [n]>")); myDebug_P(PSTR("* crash <dump | clear | test [n]>"));
#endif #endif
// print custom commands if available. Taken from progmem // print custom commands if available. Taken from progmem
@@ -482,20 +494,18 @@ void MyESP::_consoleShowHelp() {
} }
} }
} }
myDebug_P(PSTR("")); // newline
SerialAndTelnet.println(); // newline
} }
// print all set commands and current values // print all set commands and current values
void MyESP::_printSetCommands() { void MyESP::_printSetCommands() {
SerialAndTelnet.println(); // newline myDebug_P(PSTR("")); // newline
SerialAndTelnet.println(FPSTR("The following set commands are available:")); myDebug_P(PSTR("The following set commands are available:"));
SerialAndTelnet.println(); myDebug_P(PSTR("")); // newline
SerialAndTelnet.println(FPSTR("* set erase")); myDebug_P(PSTR("* set erase"));
SerialAndTelnet.println(FPSTR("* set wifi [ssid] [password]")); myDebug_P(PSTR("* set wifi [ssid] [password]"));
SerialAndTelnet.println(FPSTR("* set <mqtt_host | mqtt_username | mqtt_password> [value]")); myDebug_P(PSTR("* set <mqtt_host | mqtt_username | mqtt_password> [value]"));
SerialAndTelnet.println(FPSTR("* set serial")); myDebug_P(PSTR("* set serial"));
// print custom commands if available. Taken from progmem // print custom commands if available. Taken from progmem
if (_telnetcommand_callback) { if (_telnetcommand_callback) {
@@ -519,21 +529,19 @@ void MyESP::_printSetCommands() {
} }
} }
SerialAndTelnet.println(); // newline myDebug_P(PSTR("")); // newline
SerialAndTelnet.println(FPSTR("Stored settings:")); myDebug_P(PSTR("Stored settings:"));
SerialAndTelnet.println(); myDebug_P(PSTR("")); // newline
SerialAndTelnet.printf(" wifi=%s ", (!_wifi_ssid) ? "<not set>" : _wifi_ssid); SerialAndTelnet.printf(PSTR(" wifi=%s "), (!_wifi_ssid) ? "<not set>" : _wifi_ssid);
if (!_wifi_password) { if (!_wifi_password) {
SerialAndTelnet.print(FPSTR("<not set>")); SerialAndTelnet.print(FPSTR("<not set>"));
} else { } else {
for (uint8_t i = 0; i < strlen(_wifi_password); i++) for (uint8_t i = 0; i < strlen(_wifi_password); i++)
SerialAndTelnet.print(FPSTR("*")); SerialAndTelnet.print(FPSTR("*"));
} }
SerialAndTelnet.println(); myDebug_P(PSTR("")); // newline
SerialAndTelnet.printf(" mqtt_host=%s", (!_mqtt_host) ? "<not set>" : _mqtt_host); myDebug_P(PSTR(" mqtt_host=%s"), (!_mqtt_host) ? "<not set>" : _mqtt_host);
SerialAndTelnet.println(); myDebug_P(PSTR(" mqtt_username=%s"), (!_mqtt_username) ? "<not set>" : _mqtt_username);
SerialAndTelnet.printf(" mqtt_username=%s", (!_mqtt_username) ? "<not set>" : _mqtt_username);
SerialAndTelnet.println();
SerialAndTelnet.print(FPSTR(" mqtt_password=")); SerialAndTelnet.print(FPSTR(" mqtt_password="));
if (!_mqtt_password) { if (!_mqtt_password) {
SerialAndTelnet.print(FPSTR("<not set>")); SerialAndTelnet.print(FPSTR("<not set>"));
@@ -542,15 +550,13 @@ void MyESP::_printSetCommands() {
SerialAndTelnet.print(FPSTR("*")); SerialAndTelnet.print(FPSTR("*"));
} }
SerialAndTelnet.println(); myDebug_P(PSTR("")); // newline
SerialAndTelnet.printf(" serial=%s", (_use_serial) ? "on" : "off"); myDebug_P(PSTR(" serial=%s"), (_use_serial) ? "on" : "off");
SerialAndTelnet.println();
// print any custom settings // print any custom settings
(_fs_settings_callback)(MYESP_FSACTION_LIST, 0, NULL, NULL); (_fs_settings_callback)(MYESP_FSACTION_LIST, 0, NULL, NULL);
SerialAndTelnet.println(); myDebug_P(PSTR("")); // newline
} }
// reset / restart // reset / restart
@@ -588,10 +594,10 @@ void MyESP::_changeSetting2(const char * setting, const char * value1, const cha
} }
(void)fs_saveConfig(); (void)fs_saveConfig();
SerialAndTelnet.println("WiFi settings changed. Reconnecting..."); myDebug_P(PSTR("WiFi settings changed. Reboot ESP."));
jw.disconnect(); //jw.disconnect();
jw.cleanNetworks(); //jw.cleanNetworks();
jw.addNetwork(_wifi_ssid, _wifi_password); //jw.addNetwork(_wifi_ssid, _wifi_password);
} }
} }
@@ -644,11 +650,11 @@ void MyESP::_changeSetting(uint8_t wc, const char * setting, const char * value)
if (strcmp(value, "on") == 0) { if (strcmp(value, "on") == 0) {
_use_serial = true; _use_serial = true;
ok = true; ok = true;
SerialAndTelnet.println(FPSTR("Please reboot ESP to activate Serial mode.")); myDebug_P(PSTR("Reboot ESP to activate Serial mode."));
} else if (strcmp(value, "off") == 0) { } else if (strcmp(value, "off") == 0) {
_use_serial = false; _use_serial = false;
ok = true; ok = true;
SerialAndTelnet.println(FPSTR("Please reboot ESP to deactivate Serial mode.")); myDebug_P(PSTR("Reboot ESP to deactivate Serial mode."));
} else { } else {
ok = false; ok = false;
} }
@@ -659,18 +665,19 @@ void MyESP::_changeSetting(uint8_t wc, const char * setting, const char * value)
} }
if (!ok) { if (!ok) {
SerialAndTelnet.println(FPSTR("\nInvalid parameter for set command.")); myDebug_P(PSTR("\nInvalid parameter for set command."));
return; return;
} }
// check for 2 params // check for 2 params
if (value == nullptr) { if (value == nullptr) {
SerialAndTelnet.printf(PSTR("%s setting reset to its default value."), setting); myDebug_P(PSTR("%s setting reset to its default value."), setting);
} else { } else {
// must be 3 params // must be 3 params
SerialAndTelnet.printf(PSTR("%s changed."), setting); myDebug_P(PSTR("%s changed."), setting);
} }
SerialAndTelnet.println();
myDebug_P(PSTR("")); // newline
(void)fs_saveConfig(); (void)fs_saveConfig();
} }
@@ -725,8 +732,8 @@ void MyESP::_telnetCommand(char * commandLine) {
return; return;
} }
// crash command
// crash command #ifdef CRASH
if ((strcmp(ptrToCommandName, "crash") == 0) && (wc >= 2)) { if ((strcmp(ptrToCommandName, "crash") == 0) && (wc >= 2)) {
char * cmd = _telnet_readWord(); char * cmd = _telnet_readWord();
if (strcmp(cmd, "dump") == 0) { if (strcmp(cmd, "dump") == 0) {
@@ -739,13 +746,14 @@ void MyESP::_telnetCommand(char * commandLine) {
} }
return; // don't call custom command line callback return; // don't call custom command line callback
} }
#endif
// call callback function // call callback function
(_telnetcommand_callback)(wc, commandLine); (_telnetcommand_callback)(wc, commandLine);
} }
// returns WiFi hostname as a String object // returns WiFi hostname as a String object
String MyESP::getESPhostname() { String MyESP::_getESPhostname() {
String hostname; String hostname;
#if defined(ARDUINO_ARCH_ESP32) #if defined(ARDUINO_ARCH_ESP32)
@@ -807,10 +815,10 @@ void MyESP::showSystemStats() {
myDebug_P(PSTR("[APP] Uptime: %d seconds"), _getUptime()); myDebug_P(PSTR("[APP] Uptime: %d seconds"), _getUptime());
myDebug_P(PSTR("[APP] System Load: %d%%"), getSystemLoadAverage()); myDebug_P(PSTR("[APP] System Load: %d%%"), getSystemLoadAverage());
if (WiFi.getMode() & WIFI_AP) { if (isAPmode()) {
myDebug_P(PSTR("[WIFI] Device is in AP mode with SSID %s"), jw.getAPSSID().c_str()); myDebug_P(PSTR("[WIFI] Device is in AP mode with SSID %s"), jw.getAPSSID().c_str());
} else { } else {
myDebug_P(PSTR("[WIFI] WiFi Hostname: %s"), getESPhostname().c_str()); myDebug_P(PSTR("[WIFI] WiFi Hostname: %s"), _getESPhostname().c_str());
myDebug_P(PSTR("[WIFI] WiFi IP: %s"), WiFi.localIP().toString().c_str()); myDebug_P(PSTR("[WIFI] WiFi IP: %s"), WiFi.localIP().toString().c_str());
myDebug_P(PSTR("[WIFI] WiFi signal strength: %d%%"), getWifiQuality()); myDebug_P(PSTR("[WIFI] WiFi signal strength: %d%%"), getWifiQuality());
} }
@@ -836,30 +844,38 @@ void MyESP::showSystemStats() {
myDebug_P(PSTR("[SYSTEM] Board: %s"), ARDUINO_BOARD); myDebug_P(PSTR("[SYSTEM] Board: %s"), ARDUINO_BOARD);
#endif #endif
myDebug_P(PSTR("[SYSTEM] CPU chip ID: 0x%06X"), ESP.getChipId());
myDebug_P(PSTR("[SYSTEM] CPU frequency: %u MHz"), ESP.getCpuFreqMHz()); myDebug_P(PSTR("[SYSTEM] CPU frequency: %u MHz"), ESP.getCpuFreqMHz());
myDebug_P(PSTR("[SYSTEM] SDK version: %s"), ESP.getSdkVersion()); myDebug_P(PSTR("[SYSTEM] SDK version: %s"), ESP.getSdkVersion());
#if defined(ESP8266)
myDebug_P(PSTR("[SYSTEM] CPU chip ID: 0x%06X"), ESP.getChipId());
myDebug_P(PSTR("[SYSTEM] Core version: %s"), ESP.getCoreVersion().c_str()); myDebug_P(PSTR("[SYSTEM] Core version: %s"), ESP.getCoreVersion().c_str());
myDebug_P(PSTR("[SYSTEM] Boot version: %d"), ESP.getBootVersion()); myDebug_P(PSTR("[SYSTEM] Boot version: %d"), ESP.getBootVersion());
myDebug_P(PSTR("[SYSTEM] Boot mode: %d"), ESP.getBootMode()); myDebug_P(PSTR("[SYSTEM] Boot mode: %d"), ESP.getBootMode());
//myDebug_P(PSTR("[SYSTEM] Firmware MD5: %s"), (char *)ESP.getSketchMD5().c_str()); //myDebug_P(PSTR("[SYSTEM] Firmware MD5: %s"), (char *)ESP.getSketchMD5().c_str());
#endif
FlashMode_t mode = ESP.getFlashChipMode(); FlashMode_t mode = ESP.getFlashChipMode();
#if defined(ESP8266)
myDebug_P(PSTR("[FLASH] Flash chip ID: 0x%06X"), ESP.getFlashChipId()); myDebug_P(PSTR("[FLASH] Flash chip ID: 0x%06X"), ESP.getFlashChipId());
#endif
myDebug_P(PSTR("[FLASH] Flash speed: %u Hz"), ESP.getFlashChipSpeed()); myDebug_P(PSTR("[FLASH] Flash speed: %u Hz"), ESP.getFlashChipSpeed());
myDebug_P(PSTR("[FLASH] Flash mode: %s"), myDebug_P(PSTR("[FLASH] Flash mode: %s"),
mode == FM_QIO ? "QIO" : mode == FM_QOUT ? "QOUT" : mode == FM_DIO ? "DIO" : mode == FM_DOUT ? "DOUT" : "UNKNOWN"); mode == FM_QIO ? "QIO" : mode == FM_QOUT ? "QOUT" : mode == FM_DIO ? "DIO" : mode == FM_DOUT ? "DOUT" : "UNKNOWN");
#if defined(ESP8266)
myDebug_P(PSTR("[FLASH] Flash size (CHIP): %d"), ESP.getFlashChipRealSize()); myDebug_P(PSTR("[FLASH] Flash size (CHIP): %d"), ESP.getFlashChipRealSize());
#endif
myDebug_P(PSTR("[FLASH] Flash size (SDK): %d"), ESP.getFlashChipSize()); myDebug_P(PSTR("[FLASH] Flash size (SDK): %d"), ESP.getFlashChipSize());
myDebug_P(PSTR("[FLASH] Flash Reserved: %d"), 1 * SPI_FLASH_SEC_SIZE); myDebug_P(PSTR("[FLASH] Flash Reserved: %d"), 1 * SPI_FLASH_SEC_SIZE);
myDebug_P(PSTR("[MEM] Firmware size: %d"), ESP.getSketchSize()); myDebug_P(PSTR("[MEM] Firmware size: %d"), ESP.getSketchSize());
myDebug_P(PSTR("[MEM] Max OTA size: %d"), (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000); myDebug_P(PSTR("[MEM] Max OTA size: %d"), (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000);
myDebug_P(PSTR("[MEM] OTA Reserved: %d"), 4 * SPI_FLASH_SEC_SIZE); myDebug_P(PSTR("[MEM] OTA Reserved: %d"), 4 * SPI_FLASH_SEC_SIZE);
myDebug_P(PSTR("[MEM] Free Heap: %d"), ESP.getFreeHeap()); myDebug_P(PSTR("[MEM] Free Heap: %d"), ESP.getFreeHeap());
#if defined(ESP8266)
myDebug_P(PSTR("[MEM] Stack: %d"), ESP.getFreeContStack()); myDebug_P(PSTR("[MEM] Stack: %d"), ESP.getFreeContStack());
#endif
} }
// handler for Telnet // handler for Telnet
void MyESP::_telnetHandle() { void MyESP::_telnetHandle() {
SerialAndTelnet.handle(); SerialAndTelnet.handle();
@@ -869,7 +885,7 @@ void MyESP::_telnetHandle() {
while (SerialAndTelnet.available()) { while (SerialAndTelnet.available()) {
char c = SerialAndTelnet.read(); char c = SerialAndTelnet.read();
SerialAndTelnet.serialPrint(c); // echo to Serial if connected SerialAndTelnet.serialPrint(c); // echo to Serial (if connected)
switch (c) { switch (c) {
case '\r': // likely have full command in buffer now, commands are terminated by CR and/or LF case '\r': // likely have full command in buffer now, commands are terminated by CR and/or LF
@@ -887,7 +903,6 @@ void MyESP::_telnetHandle() {
case '\b': // (^H) handle backspace in input: put a space in last char - coded by Simon Arlott case '\b': // (^H) handle backspace in input: put a space in last char - coded by Simon Arlott
case 0x7F: // (^?) case 0x7F: // (^?)
if (charsRead > 0) { if (charsRead > 0) {
_command[--charsRead] = '\0'; _command[--charsRead] = '\0';
@@ -1070,7 +1085,6 @@ char * MyESP::_mqttTopic(const char * topic) {
return _mqtt_topic; return _mqtt_topic;
} }
// print contents of file // print contents of file
// assumes Serial is open // assumes Serial is open
void MyESP::_fs_printConfig() { void MyESP::_fs_printConfig() {
@@ -1078,14 +1092,14 @@ void MyESP::_fs_printConfig() {
File configFile = SPIFFS.open(MYEMS_CONFIG_FILE, "r"); File configFile = SPIFFS.open(MYEMS_CONFIG_FILE, "r");
if (!configFile) { if (!configFile) {
Serial.println(F("[FS] Failed to read file for printing")); myDebug_P(PSTR("[FS] Failed to read file for printing"));
return; return;
} }
while (configFile.available()) { while (configFile.available()) {
SerialAndTelnet.print((char)configFile.read()); SerialAndTelnet.print((char)configFile.read());
} }
SerialAndTelnet.println(); myDebug_P(PSTR("")); // newline
configFile.close(); configFile.close();
} }
@@ -1133,6 +1147,7 @@ bool MyESP::_fs_loadConfig() {
const char * value; const char * value;
// fetch the standard system parameters
value = json["wifi_ssid"]; value = json["wifi_ssid"];
_wifi_ssid = (value) ? strdup(value) : NULL; _wifi_ssid = (value) ? strdup(value) : NULL;
@@ -1161,6 +1176,12 @@ bool MyESP::_fs_loadConfig() {
// save settings to spiffs // save settings to spiffs
bool MyESP::fs_saveConfig() { bool MyESP::fs_saveConfig() {
bool ok = true;
if (_ota_pre_callback) {
(_ota_pre_callback)();
}
StaticJsonDocument<SPIFFS_MAXSIZE> doc; StaticJsonDocument<SPIFFS_MAXSIZE> doc;
JsonObject json = doc.to<JsonObject>(); JsonObject json = doc.to<JsonObject>();
@@ -1183,18 +1204,29 @@ bool MyESP::fs_saveConfig() {
File configFile = SPIFFS.open(MYEMS_CONFIG_FILE, "w"); File configFile = SPIFFS.open(MYEMS_CONFIG_FILE, "w");
if (!configFile) { if (!configFile) {
Serial.println("[FS] Failed to open config file for writing"); myDebug_P(PSTR("[FS] Failed to open config file for writing"));
return false; ok = false;
} }
/*
if (ok) {
myDebug_P(PSTR("[FS] Writing config file"));
}
*/
// Serialize JSON to file // Serialize JSON to file
if (serializeJson(json, configFile) == 0) { if (serializeJson(json, configFile) == 0) {
Serial.println(F("[FS] Failed to write to file")); myDebug_P(PSTR("[FS] Failed to write to file"));
ok = false;
} }
configFile.close(); configFile.close();
return true; if (_ota_post_callback) {
(_ota_post_callback)();
}
return ok;
} }
// init the SPIFF file system and load the config // init the SPIFF file system and load the config
@@ -1202,14 +1234,14 @@ bool MyESP::fs_saveConfig() {
// force Serial for debugging, and turn it off afterwards // force Serial for debugging, and turn it off afterwards
void MyESP::_fs_setup() { void MyESP::_fs_setup() {
if (!SPIFFS.begin()) { if (!SPIFFS.begin()) {
Serial.println("[FS] Failed to mount the file system"); myDebug_P(PSTR("[FS] Failed to mount the file system. Erasing..."));
_fs_eraseConfig(); // fix for ESP32 _fs_eraseConfig(); // fix for ESP32
return; return;
} }
// load the config file. if it doesn't exist (function returns false) create it // load the config file. if it doesn't exist (function returns false) create it
if (!_fs_loadConfig()) { if (!_fs_loadConfig()) {
// Serial.println("[FS] Re-creating config file"); myDebug_P(PSTR("[FS] Re-creating config file"));
fs_saveConfig(); fs_saveConfig();
} }
@@ -1417,16 +1449,12 @@ void MyESP::crashDump() {
} }
#else #else
void MyESP::crashTest(uint8_t t) { void MyESP::crashTest(uint8_t t) {
myDebug("[CRASH] disabled or not supported. Compile with -DCRASH");
} }
void MyESP::crashClear() { void MyESP::crashClear() {
myDebug("[CRASH] disabled or not supported. Compile with -DCRASH");
} }
void MyESP::crashDump() { void MyESP::crashDump() {
myDebug("[CRASH] disabled or not supported. Compile with -DCRASH");
} }
void MyESP::crashInfo() { void MyESP::crashInfo() {
myDebug("[CRASH] disabled or not supported. Compile with -DCRASH");
} }
#endif #endif

View File

@@ -9,7 +9,7 @@
#ifndef MyEMS_h #ifndef MyEMS_h
#define MyEMS_h #define MyEMS_h
#define MYESP_VERSION "1.1.6" #define MYESP_VERSION "1.1.6b1"
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <ArduinoOTA.h> #include <ArduinoOTA.h>
@@ -144,6 +144,7 @@ class MyESP {
void setWIFICallback(void (*callback)()); void setWIFICallback(void (*callback)());
void setWIFI(const char * wifi_ssid, const char * wifi_password, wifi_callback_f callback); void setWIFI(const char * wifi_ssid, const char * wifi_password, wifi_callback_f callback);
bool isWifiConnected(); bool isWifiConnected();
bool isAPmode();
// mqtt // mqtt
bool isMQTTConnected(); bool isMQTTConnected();
@@ -163,7 +164,7 @@ class MyESP {
mqtt_callback_f callback); mqtt_callback_f callback);
// OTA // OTA
void setOTA(ota_callback_f OTACallback); void setOTA(ota_callback_f OTACallback_pre, ota_callback_f OTACallback_post);
// debug & telnet // debug & telnet
void myDebug(const char * format, ...); void myDebug(const char * format, ...);
@@ -175,7 +176,7 @@ class MyESP {
void setSettings(fs_callback_f callback, fs_settings_callback_f fs_settings_callback); void setSettings(fs_callback_f callback, fs_settings_callback_f fs_settings_callback);
bool fs_saveConfig(); bool fs_saveConfig();
// CRASH // Crash
void crashClear(); void crashClear();
void crashDump(); void crashDump();
void crashTest(uint8_t t); void crashTest(uint8_t t);
@@ -224,10 +225,11 @@ class MyESP {
char * _wifi_ssid; char * _wifi_ssid;
char * _wifi_password; char * _wifi_password;
bool _wifi_connected; bool _wifi_connected;
String getESPhostname(); String _getESPhostname();
// ota // ota
ota_callback_f _ota_callback; ota_callback_f _ota_pre_callback;
ota_callback_f _ota_post_callback;
void _ota_setup(); void _ota_setup();
void _OTACallback(); void _OTACallback();

View File

@@ -13,10 +13,10 @@ platform = ${common.platform_def}
flash_mode = dout flash_mode = dout
; for production ; for production
;build_flags = -Os build_flags = -Os -w
; for debug ; for debug
build_flags = -g -Wall -Wextra -Werror -Wno-missing-field-initializers -Wno-unused-parameter -Wno-unused-variable -DCRASH ; build_flags = -g -Wall -Wextra -Werror -Wno-missing-field-initializers -Wno-unused-parameter -Wno-unused-variable -DCRASH
wifi_settings = wifi_settings =
; hard code if you prefer. Recommendation is to set from within the app when in Serial or AP mode ; hard code if you prefer. Recommendation is to set from within the app when in Serial or AP mode

View File

@@ -436,16 +436,17 @@ void showInfo() {
// send all dallas sensor values as a JSON package to MQTT // send all dallas sensor values as a JSON package to MQTT
void publishSensorValues() { void publishSensorValues() {
StaticJsonDocument<MQTT_MAX_SIZE> doc; StaticJsonDocument<MQTT_MAX_SIZE> doc;
bool hasdata = false; JsonObject sensors = doc.to<JsonObject>();
bool hasdata = false;
char label[8] = {0};
char valuestr[8] = {0}; // for formatting temp
// see if the sensor values have changed, if so send // see if the sensor values have changed, if so send
JsonObject sensors = doc.to<JsonObject>();
for (uint8_t i = 0; i < EMSESP_Status.dallas_sensors; i++) { for (uint8_t i = 0; i < EMSESP_Status.dallas_sensors; i++) {
double sensorValue = ds18.getValue(i); double sensorValue = ds18.getValue(i);
if (sensorValue != DS18_DISCONNECTED && sensorValue != DS18_CRC_ERROR) { if (sensorValue != DS18_DISCONNECTED && sensorValue != DS18_CRC_ERROR) {
char label[8] = {0}; sprintf(label, PAYLOAD_EXTERNAL_SENSORS, (i + 1));
char valuestr[8] = {0}; // for formatting temp
sprintf(label, "temp_%d", (i + 1));
sensors[label] = _float_to_char(valuestr, sensorValue); sensors[label] = _float_to_char(valuestr, sensorValue);
hasdata = true; hasdata = true;
} }
@@ -643,53 +644,64 @@ void startThermostatScan(uint8_t start) {
// callback for loading/saving settings to the file system (SPIFFS) // callback for loading/saving settings to the file system (SPIFFS)
bool FSCallback(MYESP_FSACTION action, const JsonObject json) { bool FSCallback(MYESP_FSACTION action, const JsonObject json) {
bool recreate_config = false;
if (action == MYESP_FSACTION_LOAD) { if (action == MYESP_FSACTION_LOAD) {
// led // led
if (!(EMSESP_Status.led_enabled = json["led"])) { if (!(EMSESP_Status.led_enabled = json["led"])) {
EMSESP_Status.led_enabled = LED_BUILTIN; // default value EMSESP_Status.led_enabled = LED_BUILTIN; // default value
recreate_config = true;
} }
// led_gpio // led_gpio
if (!(EMSESP_Status.led_gpio = json["led_gpio"])) { if (!(EMSESP_Status.led_gpio = json["led_gpio"])) {
EMSESP_Status.led_gpio = EMSESP_LED_GPIO; // default value EMSESP_Status.led_gpio = EMSESP_LED_GPIO; // default value
recreate_config = true;
} }
// dallas_gpio // dallas_gpio
if (!(EMSESP_Status.dallas_gpio = json["dallas_gpio"])) { if (!(EMSESP_Status.dallas_gpio = json["dallas_gpio"])) {
EMSESP_Status.dallas_gpio = EMSESP_DALLAS_GPIO; // default value EMSESP_Status.dallas_gpio = EMSESP_DALLAS_GPIO; // default value
recreate_config = true;
} }
// dallas_parasite // dallas_parasite
if (!(EMSESP_Status.dallas_parasite = json["dallas_parasite"])) { if (!(EMSESP_Status.dallas_parasite = json["dallas_parasite"])) {
EMSESP_Status.dallas_parasite = EMSESP_DALLAS_PARASITE; // default value EMSESP_Status.dallas_parasite = EMSESP_DALLAS_PARASITE; // default value
recreate_config = true;
} }
// thermostat_type // thermostat_type
if (!(EMS_Thermostat.type_id = json["thermostat_type"])) { if (!(EMS_Thermostat.type_id = json["thermostat_type"])) {
EMS_Thermostat.type_id = EMSESP_THERMOSTAT_TYPE; // set default EMS_Thermostat.type_id = EMSESP_THERMOSTAT_TYPE; // set default
recreate_config = true;
} }
// boiler_type // boiler_type
if (!(EMS_Boiler.type_id = json["boiler_type"])) { if (!(EMS_Boiler.type_id = json["boiler_type"])) {
EMS_Boiler.type_id = EMSESP_BOILER_TYPE; // set default EMS_Boiler.type_id = EMSESP_BOILER_TYPE; // set default
recreate_config = true;
} }
// test mode // test mode
if (!(EMSESP_Status.test_mode = json["test_mode"])) { if (!(EMSESP_Status.test_mode = json["test_mode"])) {
EMSESP_Status.test_mode = false; // default value EMSESP_Status.test_mode = false; // default value
recreate_config = true;
} }
// shower_timer // shower_timer
if (!(EMSESP_Status.shower_timer = json["shower_timer"])) { if (!(EMSESP_Status.shower_timer = json["shower_timer"])) {
EMSESP_Status.shower_timer = false; // default value EMSESP_Status.shower_timer = false; // default value
recreate_config = true;
} }
// shower_alert // shower_alert
if (!(EMSESP_Status.shower_alert = json["shower_alert"])) { if (!(EMSESP_Status.shower_alert = json["shower_alert"])) {
EMSESP_Status.shower_alert = false; // default value EMSESP_Status.shower_alert = false; // default value
recreate_config = true;
} }
return false; // always save the settings return recreate_config; // return false if some settings are missing and we need to rebuild the file
} }
if (action == MYESP_FSACTION_SAVE) { if (action == MYESP_FSACTION_SAVE) {
@@ -709,7 +721,7 @@ bool FSCallback(MYESP_FSACTION action, const JsonObject json) {
return false; return false;
} }
// callback for custom settings when showing Stored Settings // callback for custom settings when showing Stored Settings with the 'set' command
// wc is number of arguments after the 'set' command // wc is number of arguments after the 'set' command
// returns true if the setting was recognized and changed // returns true if the setting was recognized and changed
bool SettingsCallback(MYESP_FSACTION action, uint8_t wc, const char * setting, const char * value) { bool SettingsCallback(MYESP_FSACTION action, uint8_t wc, const char * setting, const char * value) {
@@ -727,6 +739,8 @@ bool SettingsCallback(MYESP_FSACTION action, uint8_t wc, const char * setting, c
// let's make sure LED is really off // let's make sure LED is really off
digitalWrite(EMSESP_Status.led_gpio, digitalWrite(EMSESP_Status.led_gpio,
(EMSESP_Status.led_gpio == LED_BUILTIN) ? HIGH : LOW); // light off. For onboard high=off (EMSESP_Status.led_gpio == LED_BUILTIN) ? HIGH : LOW); // light off. For onboard high=off
} else {
myDebug("Error. Usage: set led <on | off>");
} }
} }
@@ -739,6 +753,8 @@ bool SettingsCallback(MYESP_FSACTION action, uint8_t wc, const char * setting, c
} else if (strcmp(value, "off") == 0) { } else if (strcmp(value, "off") == 0) {
EMSESP_Status.test_mode = false; EMSESP_Status.test_mode = false;
ok = true; ok = true;
} else {
myDebug("Error. Usage: set test_mode <on | off>");
} }
} }
@@ -765,6 +781,8 @@ bool SettingsCallback(MYESP_FSACTION action, uint8_t wc, const char * setting, c
} else if (strcmp(value, "off") == 0) { } else if (strcmp(value, "off") == 0) {
EMSESP_Status.dallas_parasite = false; EMSESP_Status.dallas_parasite = false;
ok = true; ok = true;
} else {
myDebug("Error. Usage: set dallas_parasite <on | off>");
} }
} }
@@ -788,6 +806,8 @@ bool SettingsCallback(MYESP_FSACTION action, uint8_t wc, const char * setting, c
} else if (strcmp(value, "off") == 0) { } else if (strcmp(value, "off") == 0) {
EMSESP_Status.shower_timer = false; EMSESP_Status.shower_timer = false;
ok = true; ok = true;
} else {
myDebug("Error. Usage: set shower_timer <on | off>");
} }
} }
@@ -799,6 +819,8 @@ bool SettingsCallback(MYESP_FSACTION action, uint8_t wc, const char * setting, c
} else if (strcmp(value, "off") == 0) { } else if (strcmp(value, "off") == 0) {
EMSESP_Status.shower_alert = false; EMSESP_Status.shower_alert = false;
ok = true; ok = true;
} else {
myDebug("Error. Usage: set shower_alert <on | off>");
} }
} }
} }
@@ -969,10 +991,16 @@ void TelnetCommandCallback(uint8_t wc, const char * commandLine) {
// OTA callback when the OTA process starts // OTA callback when the OTA process starts
// so we can disable the EMS to avoid any noise // so we can disable the EMS to avoid any noise
void OTACallback() { void OTACallback_pre() {
emsuart_stop(); emsuart_stop();
} }
// OTA callback when the OTA process finishes
// so we can re-enable the UART
void OTACallback_post() {
emsuart_start();
}
// MQTT Callback to handle incoming/outgoing changes // MQTT Callback to handle incoming/outgoing changes
void MQTTCallback(unsigned int type, const char * topic, const char * message) { void MQTTCallback(unsigned int type, const char * topic, const char * message) {
// we're connected. lets subscribe to some topics // we're connected. lets subscribe to some topics
@@ -1280,7 +1308,7 @@ void setup() {
MQTTCallback); MQTTCallback);
// OTA callback which is called when OTA is starting // OTA callback which is called when OTA is starting
myESP.setOTA(OTACallback); myESP.setOTA(OTACallback_pre, OTACallback_post);
// custom settings in SPIFFS // custom settings in SPIFFS
myESP.setSettings(FSCallback, SettingsCallback); myESP.setSettings(FSCallback, SettingsCallback);

View File

@@ -129,13 +129,13 @@ void ICACHE_FLASH_ATTR emsuart_init() {
system_os_task(emsuart_recvTask, EMSUART_recvTaskPrio, recvTaskQueue, EMSUART_recvTaskQueueLen); system_os_task(emsuart_recvTask, EMSUART_recvTaskPrio, recvTaskQueue, EMSUART_recvTaskQueueLen);
// disable esp debug which will go to Tx and mess up the line // disable esp debug which will go to Tx and mess up the line
// system_set_os_print(0); // https://github.com/espruino/Espruino/issues/655 system_set_os_print(0); // https://github.com/espruino/Espruino/issues/655
ETS_UART_INTR_ATTACH(emsuart_rx_intr_handler, NULL);
ETS_UART_INTR_ENABLE();
// swap Rx and Tx pins to use GPIO13 (D7) and GPIO15 (D8) respectively // swap Rx and Tx pins to use GPIO13 (D7) and GPIO15 (D8) respectively
system_uart_swap(); system_uart_swap();
ETS_UART_INTR_ATTACH(emsuart_rx_intr_handler, NULL);
ETS_UART_INTR_ENABLE();
} }
/* /*
@@ -143,12 +143,19 @@ void ICACHE_FLASH_ATTR emsuart_init() {
*/ */
void ICACHE_FLASH_ATTR emsuart_stop() { void ICACHE_FLASH_ATTR emsuart_stop() {
ETS_UART_INTR_DISABLE(); ETS_UART_INTR_DISABLE();
ETS_UART_INTR_ATTACH(NULL, NULL); //ETS_UART_INTR_ATTACH(NULL, NULL);
system_uart_swap(); // to be sure, swap Tx/Rx back. Idea from Simon Arlott //system_uart_swap(); // to be sure, swap Tx/Rx back. Idea from Simon Arlott
//detachInterrupt(digitalPinToInterrupt(D7)); //detachInterrupt(digitalPinToInterrupt(D7));
//noInterrupts(); //noInterrupts();
} }
/*
* re-start UART0 driver
*/
void ICACHE_FLASH_ATTR emsuart_start() {
ETS_UART_INTR_ENABLE();
}
/* /*
* Send a BRK signal * Send a BRK signal
* Which is a 11-bit set of zero's (11 cycles) * Which is a 11-bit set of zero's (11 cycles)

View File

@@ -31,6 +31,7 @@ typedef struct {
void ICACHE_FLASH_ATTR emsuart_init(); void ICACHE_FLASH_ATTR emsuart_init();
void ICACHE_FLASH_ATTR emsuart_stop(); void ICACHE_FLASH_ATTR emsuart_stop();
void ICACHE_FLASH_ATTR emsuart_start();
void ICACHE_FLASH_ATTR emsuart_tx_buffer(uint8_t * buf, uint8_t len); void ICACHE_FLASH_ATTR emsuart_tx_buffer(uint8_t * buf, uint8_t len);
void ICACHE_FLASH_ATTR emsaurt_tx_poll(); void ICACHE_FLASH_ATTR emsaurt_tx_poll();
void ICACHE_FLASH_ATTR emsuart_tx_brk(); void ICACHE_FLASH_ATTR emsuart_tx_brk();

View File

@@ -45,7 +45,8 @@
#define TOPIC_SHOWER_COLDSHOT "shower_coldshot" // used to trigger a coldshot from an MQTT command #define TOPIC_SHOWER_COLDSHOT "shower_coldshot" // used to trigger a coldshot from an MQTT command
// MQTT for EXTERNAL SENSORS // MQTT for EXTERNAL SENSORS
#define TOPIC_EXTERNAL_SENSORS "sensors" // for sending sensor values to MQTT #define TOPIC_EXTERNAL_SENSORS "sensors" // for sending sensor values to MQTT
#define PAYLOAD_EXTERNAL_SENSORS "temp_%d" // for formatting the payload for each external dallas sensor
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
// THESE DEFAULT VALUES CAN ALSO BE SET AND STORED WITHTIN THE APPLICATION (see 'set' command) // // THESE DEFAULT VALUES CAN ALSO BE SET AND STORED WITHTIN THE APPLICATION (see 'set' command) //