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.

550 lines
17 KiB

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