Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

462 lines
15 KiB

  1. /*
  2. UTILS MODULE
  3. Copyright (C) 2017-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include <Ticker.h>
  6. Ticker _defer_reset;
  7. String getIdentifier() {
  8. char buffer[20];
  9. snprintf_P(buffer, sizeof(buffer), PSTR("%s-%06X"), APP_NAME, ESP.getChipId());
  10. return String(buffer);
  11. }
  12. void setDefaultHostname() {
  13. if (strlen(HOSTNAME) > 0) {
  14. setSetting("hostname", HOSTNAME);
  15. } else {
  16. setSetting("hostname", getIdentifier());
  17. }
  18. }
  19. void setBoardName() {
  20. #ifndef ESPURNA_CORE
  21. setSetting("boardName", DEVICE_NAME);
  22. #endif
  23. }
  24. String getBoardName() {
  25. return getSetting("boardName", DEVICE_NAME);
  26. }
  27. String getCoreVersion() {
  28. String version = ESP.getCoreVersion();
  29. #ifdef ARDUINO_ESP8266_RELEASE
  30. if (version.equals("00000000")) {
  31. version = String(ARDUINO_ESP8266_RELEASE);
  32. }
  33. #endif
  34. version.replace("_", ".");
  35. return version;
  36. }
  37. String getCoreRevision() {
  38. #ifdef ARDUINO_ESP8266_GIT_VER
  39. return String(ARDUINO_ESP8266_GIT_VER);
  40. #else
  41. return String("");
  42. #endif
  43. }
  44. unsigned long maxSketchSpace() {
  45. return (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  46. }
  47. // WTF
  48. // Calling ESP.getFreeHeap() is making the system crash on a specific
  49. // AiLight bulb, but anywhere else...
  50. unsigned int getFreeHeap() {
  51. if (getSetting("wtfHeap", 0).toInt() == 1) return 9999;
  52. return ESP.getFreeHeap();
  53. }
  54. String getEspurnaModules() {
  55. return FPSTR(espurna_modules);
  56. }
  57. #if SENSOR_SUPPORT
  58. String getEspurnaSensors() {
  59. return FPSTR(espurna_sensors);
  60. }
  61. #endif
  62. String buildTime() {
  63. const char time_now[] = __TIME__; // hh:mm:ss
  64. unsigned int hour = atoi(&time_now[0]);
  65. unsigned int minute = atoi(&time_now[3]);
  66. unsigned int second = atoi(&time_now[6]);
  67. const char date_now[] = __DATE__; // Mmm dd yyyy
  68. const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  69. unsigned int month = 0;
  70. for ( int i = 0; i < 12; i++ ) {
  71. if (strncmp(date_now, months[i], 3) == 0 ) {
  72. month = i + 1;
  73. break;
  74. }
  75. }
  76. unsigned int day = atoi(&date_now[3]);
  77. unsigned int year = atoi(&date_now[7]);
  78. char buffer[20];
  79. snprintf_P(
  80. buffer, sizeof(buffer), PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
  81. year, month, day, hour, minute, second
  82. );
  83. return String(buffer);
  84. }
  85. unsigned long getUptime() {
  86. static unsigned long last_uptime = 0;
  87. static unsigned char uptime_overflows = 0;
  88. if (millis() < last_uptime) ++uptime_overflows;
  89. last_uptime = millis();
  90. unsigned long uptime_seconds = uptime_overflows * (UPTIME_OVERFLOW / 1000) + (last_uptime / 1000);
  91. return uptime_seconds;
  92. }
  93. #if HEARTBEAT_ENABLED
  94. void heartbeat() {
  95. unsigned long uptime_seconds = getUptime();
  96. unsigned int free_heap = getFreeHeap();
  97. #if MQTT_SUPPORT
  98. bool serial = !mqttConnected();
  99. #else
  100. bool serial = true;
  101. #endif
  102. // -------------------------------------------------------------------------
  103. // Serial
  104. // -------------------------------------------------------------------------
  105. if (serial) {
  106. DEBUG_MSG_P(PSTR("[MAIN] Uptime: %lu seconds\n"), uptime_seconds);
  107. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %lu bytes\n"), free_heap);
  108. #if ADC_MODE_VALUE == ADC_VCC
  109. DEBUG_MSG_P(PSTR("[MAIN] Power: %lu mV\n"), ESP.getVcc());
  110. #endif
  111. #if NTP_SUPPORT
  112. if (ntpSynced()) DEBUG_MSG_P(PSTR("[MAIN] Time: %s\n"), (char *) ntpDateTime().c_str());
  113. #endif
  114. }
  115. // -------------------------------------------------------------------------
  116. // MQTT
  117. // -------------------------------------------------------------------------
  118. #if MQTT_SUPPORT
  119. if (!serial) {
  120. #if (HEARTBEAT_REPORT_INTERVAL)
  121. mqttSend(MQTT_TOPIC_INTERVAL, HEARTBEAT_INTERVAL / 1000);
  122. #endif
  123. #if (HEARTBEAT_REPORT_APP)
  124. mqttSend(MQTT_TOPIC_APP, APP_NAME);
  125. #endif
  126. #if (HEARTBEAT_REPORT_VERSION)
  127. mqttSend(MQTT_TOPIC_VERSION, APP_VERSION);
  128. #endif
  129. #if (HEARTBEAT_REPORT_BOARD)
  130. mqttSend(MQTT_TOPIC_BOARD, getBoardName().c_str());
  131. #endif
  132. #if (HEARTBEAT_REPORT_HOSTNAME)
  133. mqttSend(MQTT_TOPIC_HOSTNAME, getSetting("hostname").c_str());
  134. #endif
  135. #if (HEARTBEAT_REPORT_IP)
  136. mqttSend(MQTT_TOPIC_IP, getIP().c_str());
  137. #endif
  138. #if (HEARTBEAT_REPORT_MAC)
  139. mqttSend(MQTT_TOPIC_MAC, WiFi.macAddress().c_str());
  140. #endif
  141. #if (HEARTBEAT_REPORT_RSSI)
  142. mqttSend(MQTT_TOPIC_RSSI, String(WiFi.RSSI()).c_str());
  143. #endif
  144. #if (HEARTBEAT_REPORT_UPTIME)
  145. mqttSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  146. #endif
  147. #if (HEARTBEAT_REPORT_DATETIME) && (NTP_SUPPORT)
  148. if (ntpSynced()) mqttSend(MQTT_TOPIC_DATETIME, ntpDateTime().c_str());
  149. #endif
  150. #if (HEARTBEAT_REPORT_FREEHEAP)
  151. mqttSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  152. #endif
  153. #if (HEARTBEAT_REPORT_RELAY)
  154. relayMQTT();
  155. #endif
  156. #if (LIGHT_PROVIDER != LIGHT_PROVIDER_NONE) & (HEARTBEAT_REPORT_LIGHT)
  157. lightMQTT();
  158. #endif
  159. #if (HEARTBEAT_REPORT_VCC)
  160. #if ADC_MODE_VALUE == ADC_VCC
  161. mqttSend(MQTT_TOPIC_VCC, String(ESP.getVcc()).c_str());
  162. #endif
  163. #endif
  164. #if (HEARTBEAT_REPORT_STATUS)
  165. mqttSend(MQTT_TOPIC_STATUS, MQTT_STATUS_ONLINE, true);
  166. #endif
  167. #if (LOADAVG_REPORT)
  168. mqttSend(MQTT_TOPIC_LOADAVG, String(systemLoadAverage()).c_str());
  169. #endif
  170. }
  171. #endif
  172. // -------------------------------------------------------------------------
  173. // InfluxDB
  174. // -------------------------------------------------------------------------
  175. #if INFLUXDB_SUPPORT
  176. #if (HEARTBEAT_REPORT_UPTIME)
  177. idbSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  178. #endif
  179. #if (HEARTBEAT_REPORT_FREEHEAP)
  180. idbSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  181. #endif
  182. #endif
  183. }
  184. #endif /// HEARTBEAT_ENABLED
  185. // -----------------------------------------------------------------------------
  186. // INFO
  187. // -----------------------------------------------------------------------------
  188. extern "C" uint32_t _SPIFFS_start;
  189. extern "C" uint32_t _SPIFFS_end;
  190. unsigned int info_bytes2sectors(size_t size) {
  191. return (int) (size + SPI_FLASH_SEC_SIZE - 1) / SPI_FLASH_SEC_SIZE;
  192. }
  193. unsigned long info_ota_space() {
  194. return (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  195. }
  196. unsigned long info_filesystem_space() {
  197. return ((uint32_t)&_SPIFFS_end - (uint32_t)&_SPIFFS_start);
  198. }
  199. unsigned long info_eeprom_space() {
  200. return EEPROMr.reserved() * SPI_FLASH_SEC_SIZE;
  201. }
  202. void _info_print_memory_layout_line(const char * name, unsigned long bytes, bool reset) {
  203. static unsigned long index = 0;
  204. if (reset) index = 0;
  205. if (0 == bytes) return;
  206. unsigned int _sectors = info_bytes2sectors(bytes);
  207. DEBUG_MSG_P(PSTR("[INIT] %-20s: %8lu bytes / %4d sectors (%4d to %4d)\n"), name, bytes, _sectors, index, index + _sectors - 1);
  208. index += _sectors;
  209. }
  210. void _info_print_memory_layout_line(const char * name, unsigned long bytes) {
  211. _info_print_memory_layout_line(name, bytes, false);
  212. }
  213. void info() {
  214. DEBUG_MSG_P(PSTR("\n\n"));
  215. if (strlen(APP_REVISION) > 0) {
  216. DEBUG_MSG_P(PSTR("[INIT] %s %s (%s)\n"), (char *) APP_NAME, (char *) APP_VERSION, (char *) APP_REVISION);
  217. } else {
  218. DEBUG_MSG_P(PSTR("[INIT] %s %s\n"), (char *) APP_NAME, (char *) APP_VERSION);
  219. }
  220. DEBUG_MSG_P(PSTR("[INIT] %s\n"), (char *) APP_AUTHOR);
  221. DEBUG_MSG_P(PSTR("[INIT] %s\n\n"), (char *) APP_WEBSITE);
  222. DEBUG_MSG_P(PSTR("[INIT] CPU chip ID: 0x%06X\n"), ESP.getChipId());
  223. DEBUG_MSG_P(PSTR("[INIT] CPU frequency: %u MHz\n"), ESP.getCpuFreqMHz());
  224. DEBUG_MSG_P(PSTR("[INIT] SDK version: %s\n"), ESP.getSdkVersion());
  225. DEBUG_MSG_P(PSTR("[INIT] Core version: %s\n"), getCoreVersion().c_str());
  226. DEBUG_MSG_P(PSTR("[INIT] Core revision: %s\n"), getCoreRevision().c_str());
  227. DEBUG_MSG_P(PSTR("\n"));
  228. // -------------------------------------------------------------------------
  229. FlashMode_t mode = ESP.getFlashChipMode();
  230. DEBUG_MSG_P(PSTR("[INIT] Flash chip ID: 0x%06X\n"), ESP.getFlashChipId());
  231. DEBUG_MSG_P(PSTR("[INIT] Flash speed: %u Hz\n"), ESP.getFlashChipSpeed());
  232. DEBUG_MSG_P(PSTR("[INIT] Flash mode: %s\n"), mode == FM_QIO ? "QIO" : mode == FM_QOUT ? "QOUT" : mode == FM_DIO ? "DIO" : mode == FM_DOUT ? "DOUT" : "UNKNOWN");
  233. DEBUG_MSG_P(PSTR("\n"));
  234. _info_print_memory_layout_line("Flash size (CHIP)", ESP.getFlashChipRealSize(), true);
  235. _info_print_memory_layout_line("Flash size (SDK)", ESP.getFlashChipSize(), true);
  236. _info_print_memory_layout_line("Reserved", 1 * SPI_FLASH_SEC_SIZE, true);
  237. _info_print_memory_layout_line("Firmware size", ESP.getSketchSize());
  238. _info_print_memory_layout_line("Max OTA size", info_ota_space());
  239. _info_print_memory_layout_line("SPIFFS size", info_filesystem_space());
  240. _info_print_memory_layout_line("EEPROM size", info_eeprom_space());
  241. _info_print_memory_layout_line("Reserved", 4 * SPI_FLASH_SEC_SIZE);
  242. DEBUG_MSG_P(PSTR("\n"));
  243. DEBUG_MSG_P(PSTR("[INIT] EEPROM sectors: %s\n"), (char *) eepromSectors().c_str());
  244. DEBUG_MSG_P(PSTR("\n"));
  245. // -------------------------------------------------------------------------
  246. #if SPIFFS_SUPPORT
  247. FSInfo fs_info;
  248. bool fs = SPIFFS.info(fs_info);
  249. if (fs) {
  250. DEBUG_MSG_P(PSTR("[INIT] SPIFFS total size: %8u bytes / %4d sectors\n"), fs_info.totalBytes, sectors(fs_info.totalBytes));
  251. DEBUG_MSG_P(PSTR("[INIT] used size: %8u bytes\n"), fs_info.usedBytes);
  252. DEBUG_MSG_P(PSTR("[INIT] block size: %8u bytes\n"), fs_info.blockSize);
  253. DEBUG_MSG_P(PSTR("[INIT] page size: %8u bytes\n"), fs_info.pageSize);
  254. DEBUG_MSG_P(PSTR("[INIT] max files: %8u\n"), fs_info.maxOpenFiles);
  255. DEBUG_MSG_P(PSTR("[INIT] max length: %8u\n"), fs_info.maxPathLength);
  256. } else {
  257. DEBUG_MSG_P(PSTR("[INIT] No SPIFFS partition\n"));
  258. }
  259. DEBUG_MSG_P(PSTR("\n"));
  260. #endif
  261. // -------------------------------------------------------------------------
  262. DEBUG_MSG_P(PSTR("[INIT] BOARD: %s\n"), getBoardName().c_str());
  263. DEBUG_MSG_P(PSTR("[INIT] SUPPORT: %s\n"), getEspurnaModules().c_str());
  264. #if SENSOR_SUPPORT
  265. DEBUG_MSG_P(PSTR("[INIT] SENSORS: %s\n"), getEspurnaSensors().c_str());
  266. #endif // SENSOR_SUPPORT
  267. DEBUG_MSG_P(PSTR("[INIT] WEBUI IMAGE CODE: %u\n"), WEBUI_IMAGE);
  268. DEBUG_MSG_P(PSTR("\n"));
  269. // -------------------------------------------------------------------------
  270. unsigned char reason = resetReason();
  271. if (reason > 0) {
  272. char buffer[32];
  273. strcpy_P(buffer, custom_reset_string[reason-1]);
  274. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), buffer);
  275. } else {
  276. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), (char *) ESP.getResetReason().c_str());
  277. }
  278. DEBUG_MSG_P(PSTR("[INIT] Settings size: %u bytes\n"), settingsSize());
  279. DEBUG_MSG_P(PSTR("[INIT] Free heap: %u bytes\n"), getFreeHeap());
  280. #if ADC_MODE_VALUE == ADC_VCC
  281. DEBUG_MSG_P(PSTR("[INIT] Power: %u mV\n"), ESP.getVcc());
  282. #endif
  283. DEBUG_MSG_P(PSTR("[INIT] Power saving delay value: %lu ms\n"), systemLoopDelay());
  284. #if SYSTEM_CHECK_ENABLED
  285. if (!systemCheck()) DEBUG_MSG_P(PSTR("\n[INIT] Device is in SAFE MODE\n"));
  286. #endif
  287. DEBUG_MSG_P(PSTR("\n"));
  288. }
  289. // -----------------------------------------------------------------------------
  290. // SSL
  291. // -----------------------------------------------------------------------------
  292. #if ASYNC_TCP_SSL_ENABLED
  293. bool sslCheckFingerPrint(const char * fingerprint) {
  294. return (strlen(fingerprint) == 59);
  295. }
  296. bool sslFingerPrintArray(const char * fingerprint, unsigned char * bytearray) {
  297. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  298. if (!sslCheckFingerPrint(fingerprint)) return false;
  299. // walk the fingerprint
  300. for (unsigned int i=0; i<20; i++) {
  301. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  302. }
  303. return true;
  304. }
  305. bool sslFingerPrintChar(const char * fingerprint, char * destination) {
  306. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  307. if (!sslCheckFingerPrint(fingerprint)) return false;
  308. // copy it
  309. strncpy(destination, fingerprint, 59);
  310. // walk the fingerprint replacing ':' for ' '
  311. for (unsigned char i = 0; i<59; i++) {
  312. if (destination[i] == ':') destination[i] = ' ';
  313. }
  314. return true;
  315. }
  316. #endif
  317. // -----------------------------------------------------------------------------
  318. // Reset
  319. // -----------------------------------------------------------------------------
  320. unsigned char resetReason() {
  321. static unsigned char status = 255;
  322. if (status == 255) {
  323. status = EEPROMr.read(EEPROM_CUSTOM_RESET);
  324. if (status > 0) resetReason(0);
  325. if (status > CUSTOM_RESET_MAX) status = 0;
  326. }
  327. return status;
  328. }
  329. void resetReason(unsigned char reason) {
  330. EEPROMr.write(EEPROM_CUSTOM_RESET, reason);
  331. EEPROMr.commit();
  332. }
  333. void reset(unsigned char reason) {
  334. resetReason(reason);
  335. ESP.restart();
  336. }
  337. void deferredReset(unsigned long delay, unsigned char reason) {
  338. _defer_reset.once_ms(delay, reset, reason);
  339. }
  340. // -----------------------------------------------------------------------------
  341. char * ltrim(char * s) {
  342. char *p = s;
  343. while ((unsigned char) *p == ' ') ++p;
  344. return p;
  345. }
  346. double roundTo(double num, unsigned char positions) {
  347. double multiplier = 1;
  348. while (positions-- > 0) multiplier *= 10;
  349. return round(num * multiplier) / multiplier;
  350. }
  351. void nice_delay(unsigned long ms) {
  352. unsigned long start = millis();
  353. while (millis() - start < ms) delay(1);
  354. }
  355. // This method is called by the SDK to know where to connect the ADC
  356. int __get_adc_mode() {
  357. return (int) (ADC_MODE_VALUE);
  358. }
  359. bool isNumber(const char * s) {
  360. unsigned char len = strlen(s);
  361. bool decimal = false;
  362. for (unsigned char i=0; i<len; i++) {
  363. if (s[i] == '-') {
  364. if (i>0) return false;
  365. } else if (s[i] == '.') {
  366. if (decimal) return false;
  367. decimal = true;
  368. } else if (!isdigit(s[i])) {
  369. return false;
  370. }
  371. }
  372. return true;
  373. }