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.

547 lines
16 KiB

6 years ago
  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 setBoardName() {
  13. #ifndef ESPURNA_CORE
  14. setSetting("boardName", DEVICE_NAME);
  15. #endif
  16. }
  17. String getBoardName() {
  18. return getSetting("boardName", DEVICE_NAME);
  19. }
  20. String getCoreVersion() {
  21. String version = ESP.getCoreVersion();
  22. #ifdef ARDUINO_ESP8266_RELEASE
  23. if (version.equals("00000000")) {
  24. version = String(ARDUINO_ESP8266_RELEASE);
  25. }
  26. #endif
  27. return version;
  28. }
  29. String getCoreRevision() {
  30. #ifdef ARDUINO_ESP8266_GIT_VER
  31. return String(ARDUINO_ESP8266_GIT_VER);
  32. #else
  33. return String("");
  34. #endif
  35. }
  36. // WTF
  37. // Calling ESP.getFreeHeap() is making the system crash on a specific
  38. // AiLight bulb, but anywhere else...
  39. unsigned int getFreeHeap() {
  40. if (getSetting("wtfHeap", 0).toInt() == 1) return 9999;
  41. return ESP.getFreeHeap();
  42. }
  43. String buildTime() {
  44. const char time_now[] = __TIME__; // hh:mm:ss
  45. unsigned int hour = atoi(&time_now[0]);
  46. unsigned int minute = atoi(&time_now[3]);
  47. unsigned int second = atoi(&time_now[6]);
  48. const char date_now[] = __DATE__; // Mmm dd yyyy
  49. const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  50. unsigned int month = 0;
  51. for ( int i = 0; i < 12; i++ ) {
  52. if (strncmp(date_now, months[i], 3) == 0 ) {
  53. month = i + 1;
  54. break;
  55. }
  56. }
  57. unsigned int day = atoi(&date_now[3]);
  58. unsigned int year = atoi(&date_now[7]);
  59. char buffer[20];
  60. snprintf_P(
  61. buffer, sizeof(buffer), PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
  62. year, month, day, hour, minute, second
  63. );
  64. return String(buffer);
  65. }
  66. unsigned long getUptime() {
  67. static unsigned long last_uptime = 0;
  68. static unsigned char uptime_overflows = 0;
  69. if (millis() < last_uptime) ++uptime_overflows;
  70. last_uptime = millis();
  71. unsigned long uptime_seconds = uptime_overflows * (UPTIME_OVERFLOW / 1000) + (last_uptime / 1000);
  72. return uptime_seconds;
  73. }
  74. void heartbeat() {
  75. unsigned long uptime_seconds = getUptime();
  76. unsigned int free_heap = getFreeHeap();
  77. // -------------------------------------------------------------------------
  78. // MQTT
  79. // -------------------------------------------------------------------------
  80. #if MQTT_SUPPORT
  81. #if (HEARTBEAT_REPORT_INTERVAL)
  82. mqttSend(MQTT_TOPIC_INTERVAL, HEARTBEAT_INTERVAL / 1000);
  83. #endif
  84. #if (HEARTBEAT_REPORT_APP)
  85. mqttSend(MQTT_TOPIC_APP, APP_NAME);
  86. #endif
  87. #if (HEARTBEAT_REPORT_VERSION)
  88. mqttSend(MQTT_TOPIC_VERSION, APP_VERSION);
  89. #endif
  90. #if (HEARTBEAT_REPORT_HOSTNAME)
  91. mqttSend(MQTT_TOPIC_HOSTNAME, getSetting("hostname").c_str());
  92. #endif
  93. #if (HEARTBEAT_REPORT_IP)
  94. mqttSend(MQTT_TOPIC_IP, getIP().c_str());
  95. #endif
  96. #if (HEARTBEAT_REPORT_MAC)
  97. mqttSend(MQTT_TOPIC_MAC, WiFi.macAddress().c_str());
  98. #endif
  99. #if (HEARTBEAT_REPORT_RSSI)
  100. mqttSend(MQTT_TOPIC_RSSI, String(WiFi.RSSI()).c_str());
  101. #endif
  102. #if (HEARTBEAT_REPORT_UPTIME)
  103. mqttSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  104. #endif
  105. #if (HEARTBEAT_REPORT_DATETIME) & (NTP_SUPPORT)
  106. mqttSend(MQTT_TOPIC_DATETIME, String(ntpDateTime()).c_str());
  107. #endif
  108. #if (HEARTBEAT_REPORT_FREEHEAP)
  109. mqttSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  110. #endif
  111. #if (HEARTBEAT_REPORT_RELAY)
  112. relayMQTT();
  113. #endif
  114. #if (LIGHT_PROVIDER != LIGHT_PROVIDER_NONE) & (HEARTBEAT_REPORT_LIGHT)
  115. lightMQTT();
  116. #endif
  117. #if (HEARTBEAT_REPORT_VCC)
  118. #if ADC_VCC_ENABLED
  119. mqttSend(MQTT_TOPIC_VCC, String(ESP.getVcc()).c_str());
  120. #endif
  121. #endif
  122. #if (HEARTBEAT_REPORT_STATUS)
  123. mqttSend(MQTT_TOPIC_STATUS, MQTT_STATUS_ONLINE, true);
  124. #endif
  125. bool serial = !mqttConnected();
  126. #else
  127. bool serial = true;
  128. #endif
  129. // -------------------------------------------------------------------------
  130. // Serial
  131. // -------------------------------------------------------------------------
  132. if (serial) {
  133. DEBUG_MSG_P(PSTR("[MAIN] Uptime: %lu seconds\n"), uptime_seconds);
  134. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %lu bytes\n"), free_heap);
  135. #if ADC_VCC_ENABLED
  136. DEBUG_MSG_P(PSTR("[MAIN] Power: %lu mV\n"), ESP.getVcc());
  137. #endif
  138. }
  139. #if NTP_SUPPORT
  140. DEBUG_MSG_P(PSTR("[MAIN] Time: %s\n"), (char *) ntpDateTime().c_str());
  141. #endif
  142. // -------------------------------------------------------------------------
  143. // InfluxDB
  144. // -------------------------------------------------------------------------
  145. #if INFLUXDB_SUPPORT
  146. #if (HEARTBEAT_REPORT_UPTIME)
  147. idbSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  148. #endif
  149. #if (HEARTBEAT_REPORT_FREEHEAP)
  150. idbSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  151. #endif
  152. #endif
  153. // -------------------------------------------------------------------------
  154. // WebSockets
  155. // -------------------------------------------------------------------------
  156. #if WEB_SUPPORT
  157. #if NTP_SUPPORT
  158. {
  159. char buffer[200];
  160. snprintf_P(
  161. buffer,
  162. sizeof(buffer) - 1,
  163. PSTR("{\"time\": \"%s\", \"uptime\": %lu, \"heap\": %lu}"),
  164. ntpDateTime().c_str(), uptime_seconds, free_heap
  165. );
  166. wsSend(buffer);
  167. }
  168. #endif
  169. #endif
  170. }
  171. unsigned int sectors(size_t size) {
  172. return (int) (size + SPI_FLASH_SEC_SIZE - 1) / SPI_FLASH_SEC_SIZE;
  173. }
  174. void info() {
  175. DEBUG_MSG_P(PSTR("\n\n"));
  176. DEBUG_MSG_P(PSTR("[INIT] %s %s\n"), (char *) APP_NAME, (char *) APP_VERSION);
  177. DEBUG_MSG_P(PSTR("[INIT] %s\n"), (char *) APP_AUTHOR);
  178. DEBUG_MSG_P(PSTR("[INIT] %s\n\n"), (char *) APP_WEBSITE);
  179. DEBUG_MSG_P(PSTR("[INIT] CPU chip ID: 0x%06X\n"), ESP.getChipId());
  180. DEBUG_MSG_P(PSTR("[INIT] CPU frequency: %u MHz\n"), ESP.getCpuFreqMHz());
  181. DEBUG_MSG_P(PSTR("[INIT] SDK version: %s\n"), ESP.getSdkVersion());
  182. DEBUG_MSG_P(PSTR("[INIT] Core version: %s\n"), getCoreVersion().c_str());
  183. DEBUG_MSG_P(PSTR("[INIT] Core revision: %s\n"), getCoreRevision().c_str());
  184. DEBUG_MSG_P(PSTR("\n"));
  185. // -------------------------------------------------------------------------
  186. FlashMode_t mode = ESP.getFlashChipMode();
  187. DEBUG_MSG_P(PSTR("[INIT] Flash chip ID: 0x%06X\n"), ESP.getFlashChipId());
  188. DEBUG_MSG_P(PSTR("[INIT] Flash speed: %u Hz\n"), ESP.getFlashChipSpeed());
  189. 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");
  190. DEBUG_MSG_P(PSTR("\n"));
  191. DEBUG_MSG_P(PSTR("[INIT] Flash sector size: %8u bytes\n"), SPI_FLASH_SEC_SIZE);
  192. DEBUG_MSG_P(PSTR("[INIT] Flash size (CHIP): %8u bytes\n"), ESP.getFlashChipRealSize());
  193. DEBUG_MSG_P(PSTR("[INIT] Flash size (SDK): %8u bytes / %4d sectors\n"), ESP.getFlashChipSize(), sectors(ESP.getFlashChipSize()));
  194. DEBUG_MSG_P(PSTR("[INIT] Firmware size: %8u bytes / %4d sectors\n"), ESP.getSketchSize(), sectors(ESP.getSketchSize()));
  195. DEBUG_MSG_P(PSTR("[INIT] OTA size: %8u bytes / %4d sectors\n"), ESP.getFreeSketchSpace(), sectors(ESP.getFreeSketchSpace()));
  196. #if SPIFFS_SUPPORT
  197. FSInfo fs_info;
  198. bool fs = SPIFFS.info(fs_info);
  199. if (fs) {
  200. DEBUG_MSG_P(PSTR("[INIT] SPIFFS size: %8u bytes / %4d sectors\n"), fs_info.totalBytes, sectors(fs_info.totalBytes));
  201. }
  202. #else
  203. DEBUG_MSG_P(PSTR("[INIT] SPIFFS size: %8u bytes / %4d sectors\n"), 0, 0);
  204. #endif
  205. DEBUG_MSG_P(PSTR("[INIT] EEPROM size: %8u bytes / %4d sectors\n"), settingsMaxSize(), sectors(settingsMaxSize()));
  206. DEBUG_MSG_P(PSTR("[INIT] Empty space: %8u bytes / 4 sectors\n"), 4 * SPI_FLASH_SEC_SIZE);
  207. DEBUG_MSG_P(PSTR("\n"));
  208. // -------------------------------------------------------------------------
  209. #if SPIFFS_SUPPORT
  210. if (fs) {
  211. DEBUG_MSG_P(PSTR("[INIT] SPIFFS total size: %8u bytes\n"), fs_info.totalBytes);
  212. DEBUG_MSG_P(PSTR("[INIT] used size: %8u bytes\n"), fs_info.usedBytes);
  213. DEBUG_MSG_P(PSTR("[INIT] block size: %8u bytes\n"), fs_info.blockSize);
  214. DEBUG_MSG_P(PSTR("[INIT] page size: %8u bytes\n"), fs_info.pageSize);
  215. DEBUG_MSG_P(PSTR("[INIT] max files: %8u\n"), fs_info.maxOpenFiles);
  216. DEBUG_MSG_P(PSTR("[INIT] max length: %8u\n"), fs_info.maxPathLength);
  217. } else {
  218. DEBUG_MSG_P(PSTR("[INIT] No SPIFFS partition\n"));
  219. }
  220. DEBUG_MSG_P(PSTR("\n"));
  221. #endif
  222. // -------------------------------------------------------------------------
  223. DEBUG_MSG_P(PSTR("[INIT] BOARD: %s\n"), getBoardName().c_str());
  224. DEBUG_MSG_P(PSTR("[INIT] SUPPORT:"));
  225. #if ALEXA_SUPPORT
  226. DEBUG_MSG_P(PSTR(" ALEXA"));
  227. #endif
  228. #if DEBUG_SERIAL_SUPPORT
  229. DEBUG_MSG_P(PSTR(" DEBUG_SERIAL"));
  230. #endif
  231. #if DEBUG_TELNET_SUPPORT
  232. DEBUG_MSG_P(PSTR(" DEBUG_TELNET"));
  233. #endif
  234. #if DEBUG_UDP_SUPPORT
  235. DEBUG_MSG_P(PSTR(" DEBUG_UDP"));
  236. #endif
  237. #if DOMOTICZ_SUPPORT
  238. DEBUG_MSG_P(PSTR(" DOMOTICZ"));
  239. #endif
  240. #if HOMEASSISTANT_SUPPORT
  241. DEBUG_MSG_P(PSTR(" HOMEASSISTANT"));
  242. #endif
  243. #if I2C_SUPPORT
  244. DEBUG_MSG_P(PSTR(" I2C"));
  245. #endif
  246. #if INFLUXDB_SUPPORT
  247. DEBUG_MSG_P(PSTR(" INFLUXDB"));
  248. #endif
  249. #if LLMNR_SUPPORT
  250. DEBUG_MSG_P(PSTR(" LLMNR"));
  251. #endif
  252. #if MDNS_SERVER_SUPPORT
  253. DEBUG_MSG_P(PSTR(" MDNS"));
  254. #endif
  255. #if NETBIOS_SUPPORT
  256. DEBUG_MSG_P(PSTR(" NETBIOS"));
  257. #endif
  258. #if NOFUSS_SUPPORT
  259. DEBUG_MSG_P(PSTR(" NOFUSS"));
  260. #endif
  261. #if NTP_SUPPORT
  262. DEBUG_MSG_P(PSTR(" NTP"));
  263. #endif
  264. #if RF_SUPPORT
  265. DEBUG_MSG_P(PSTR(" RF"));
  266. #endif
  267. #if SCHEDULER_SUPPORT
  268. DEBUG_MSG_P(PSTR(" SCHEDULER"));
  269. #endif
  270. #if SENSOR_SUPPORT
  271. DEBUG_MSG_P(PSTR(" SENSOR"));
  272. #endif
  273. #if SPIFFS_SUPPORT
  274. DEBUG_MSG_P(PSTR(" SPIFFS"));
  275. #endif
  276. #if SSDP_SUPPORT
  277. DEBUG_MSG_P(PSTR(" SSDP"));
  278. #endif
  279. #if TELNET_SUPPORT
  280. DEBUG_MSG_P(PSTR(" TELNET"));
  281. #endif
  282. #if TERMINAL_SUPPORT
  283. DEBUG_MSG_P(PSTR(" TERMINAL"));
  284. #endif
  285. #if THINGSPEAK_SUPPORT
  286. DEBUG_MSG_P(PSTR(" THINGSPEAK"));
  287. #endif
  288. #if WEB_SUPPORT
  289. DEBUG_MSG_P(PSTR(" WEB"));
  290. #endif
  291. #if SENSOR_SUPPORT
  292. DEBUG_MSG_P(PSTR("\n[INIT] SENSORS:"));
  293. #if ANALOG_SUPPORT
  294. DEBUG_MSG_P(PSTR(" ANALOG"));
  295. #endif
  296. #if BMX280_SUPPORT
  297. DEBUG_MSG_P(PSTR(" BMX280"));
  298. #endif
  299. #if DALLAS_SUPPORT
  300. DEBUG_MSG_P(PSTR(" DALLAS"));
  301. #endif
  302. #if DHT_SUPPORT
  303. DEBUG_MSG_P(PSTR(" DHTXX"));
  304. #endif
  305. #if DIGITAL_SUPPORT
  306. DEBUG_MSG_P(PSTR(" DIGITAL"));
  307. #endif
  308. #if ECH1560_SUPPORT
  309. DEBUG_MSG_P(PSTR(" ECH1560"));
  310. #endif
  311. #if EMON_ADC121_SUPPORT
  312. DEBUG_MSG_P(PSTR(" EMON_ADC121"));
  313. #endif
  314. #if EMON_ADS1X15_SUPPORT
  315. DEBUG_MSG_P(PSTR(" EMON_ADX1X15"));
  316. #endif
  317. #if EMON_ANALOG_SUPPORT
  318. DEBUG_MSG_P(PSTR(" EMON_ANALOG"));
  319. #endif
  320. #if EVENTS_SUPPORT
  321. DEBUG_MSG_P(PSTR(" EVENTS"));
  322. #endif
  323. #if HLW8012_SUPPORT
  324. DEBUG_MSG_P(PSTR(" HLW8012"));
  325. #endif
  326. #if MHZ19_SUPPORT
  327. DEBUG_MSG_P(PSTR(" MHZ19"));
  328. #endif
  329. #if PMSX003_SUPPORT
  330. DEBUG_MSG_P(PSTR(" PMSX003"));
  331. #endif
  332. #if SHT3X_I2C_SUPPORT
  333. DEBUG_MSG_P(PSTR(" SHT3X_I2C"));
  334. #endif
  335. #if SI7021_SUPPORT
  336. DEBUG_MSG_P(PSTR(" SI7021"));
  337. #endif
  338. #if V9261F_SUPPORT
  339. DEBUG_MSG_P(PSTR(" V9261F"));
  340. #endif
  341. #endif // SENSOR_SUPPORT
  342. DEBUG_MSG_P(PSTR("\n\n"));
  343. // -------------------------------------------------------------------------
  344. unsigned char reason = resetReason();
  345. if (reason > 0) {
  346. char buffer[32];
  347. strcpy_P(buffer, custom_reset_string[reason-1]);
  348. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), buffer);
  349. } else {
  350. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), (char *) ESP.getResetReason().c_str());
  351. }
  352. DEBUG_MSG_P(PSTR("[INIT] Free heap: %u bytes\n"), getFreeHeap());
  353. #if ADC_VCC_ENABLED
  354. DEBUG_MSG_P(PSTR("[INIT] Power: %u mV\n"), ESP.getVcc());
  355. #endif
  356. DEBUG_MSG_P(PSTR("[INIT] Power saving delay value: %lu ms\n"), _loopDelay);
  357. if (!systemCheck()) DEBUG_MSG_P(PSTR("\n[INIT] Device is in SAFE MODE\n"));
  358. DEBUG_MSG_P(PSTR("\n"));
  359. }
  360. // -----------------------------------------------------------------------------
  361. // SSL
  362. // -----------------------------------------------------------------------------
  363. #if ASYNC_TCP_SSL_ENABLED
  364. bool sslCheckFingerPrint(const char * fingerprint) {
  365. return (strlen(fingerprint) == 59);
  366. }
  367. bool sslFingerPrintArray(const char * fingerprint, unsigned char * bytearray) {
  368. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  369. if (!sslCheckFingerPrint(fingerprint)) return false;
  370. // walk the fingerprint
  371. for (unsigned int i=0; i<20; i++) {
  372. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  373. }
  374. return true;
  375. }
  376. bool sslFingerPrintChar(const char * fingerprint, char * destination) {
  377. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  378. if (!sslCheckFingerPrint(fingerprint)) return false;
  379. // copy it
  380. strncpy(destination, fingerprint, 59);
  381. // walk the fingerprint replacing ':' for ' '
  382. for (unsigned char i = 0; i<59; i++) {
  383. if (destination[i] == ':') destination[i] = ' ';
  384. }
  385. return true;
  386. }
  387. #endif
  388. // -----------------------------------------------------------------------------
  389. // Reset
  390. // -----------------------------------------------------------------------------
  391. unsigned char resetReason() {
  392. static unsigned char status = 255;
  393. if (status == 255) {
  394. status = EEPROM.read(EEPROM_CUSTOM_RESET);
  395. if (status > 0) resetReason(0);
  396. if (status > CUSTOM_RESET_MAX) status = 0;
  397. }
  398. return status;
  399. }
  400. void resetReason(unsigned char reason) {
  401. EEPROM.write(EEPROM_CUSTOM_RESET, reason);
  402. EEPROM.commit();
  403. }
  404. void reset(unsigned char reason) {
  405. resetReason(reason);
  406. ESP.restart();
  407. }
  408. void deferredReset(unsigned long delay, unsigned char reason) {
  409. _defer_reset.once_ms(delay, reset, reason);
  410. }
  411. // -----------------------------------------------------------------------------
  412. #if SYSTEM_CHECK_ENABLED
  413. // Call this method on boot with start=true to increase the crash counter
  414. // Call it again once the system is stable to decrease the counter
  415. // If the counter reaches SYSTEM_CHECK_MAX then the system is flagged as unstable
  416. // setting _systemOK = false;
  417. //
  418. // An unstable system will only have serial access, WiFi in AP mode and OTA
  419. bool _systemStable = true;
  420. void systemCheck(bool stable) {
  421. unsigned char value = EEPROM.read(EEPROM_CRASH_COUNTER);
  422. if (stable) {
  423. value = 0;
  424. DEBUG_MSG_P(PSTR("[MAIN] System OK\n"));
  425. } else {
  426. if (++value > SYSTEM_CHECK_MAX) {
  427. _systemStable = false;
  428. value = 0;
  429. DEBUG_MSG_P(PSTR("[MAIN] System UNSTABLE\n"));
  430. }
  431. }
  432. EEPROM.write(EEPROM_CRASH_COUNTER, value);
  433. EEPROM.commit();
  434. }
  435. bool systemCheck() {
  436. return _systemStable;
  437. }
  438. void systemCheckLoop() {
  439. static bool checked = false;
  440. if (!checked && (millis() > SYSTEM_CHECK_TIME)) {
  441. // Check system as stable
  442. systemCheck(true);
  443. checked = true;
  444. }
  445. }
  446. #endif
  447. // -----------------------------------------------------------------------------
  448. char * ltrim(char * s) {
  449. char *p = s;
  450. while ((unsigned char) *p == ' ') ++p;
  451. return p;
  452. }
  453. double roundTo(double num, unsigned char positions) {
  454. double multiplier = 1;
  455. while (positions-- > 0) multiplier *= 10;
  456. return round(num * multiplier) / multiplier;
  457. }
  458. void nice_delay(unsigned long ms) {
  459. unsigned long start = millis();
  460. while (millis() - start < ms) delay(1);
  461. }