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.

527 lines
16 KiB

7 years ago
7 years ago
7 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_VCC_ENABLED
  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_VCC_ENABLED
  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 DOMOTICZ_SUPPORT
  237. DEBUG_MSG_P(PSTR(" DOMOTICZ"));
  238. #endif
  239. #if HOMEASSISTANT_SUPPORT
  240. DEBUG_MSG_P(PSTR(" HOMEASSISTANT"));
  241. #endif
  242. #if I2C_SUPPORT
  243. DEBUG_MSG_P(PSTR(" I2C"));
  244. #endif
  245. #if INFLUXDB_SUPPORT
  246. DEBUG_MSG_P(PSTR(" INFLUXDB"));
  247. #endif
  248. #if LLMNR_SUPPORT
  249. DEBUG_MSG_P(PSTR(" LLMNR"));
  250. #endif
  251. #if MDNS_SERVER_SUPPORT
  252. DEBUG_MSG_P(PSTR(" MDNS_SERVER"));
  253. #endif
  254. #if MDNS_CLIENT_SUPPORT
  255. DEBUG_MSG_P(PSTR(" MDNS_CLIENT"));
  256. #endif
  257. #if MQTT_SUPPORT
  258. DEBUG_MSG_P(PSTR(" MQTT"));
  259. #endif
  260. #if NETBIOS_SUPPORT
  261. DEBUG_MSG_P(PSTR(" NETBIOS"));
  262. #endif
  263. #if NOFUSS_SUPPORT
  264. DEBUG_MSG_P(PSTR(" NOFUSS"));
  265. #endif
  266. #if NTP_SUPPORT
  267. DEBUG_MSG_P(PSTR(" NTP"));
  268. #endif
  269. #if RF_SUPPORT
  270. DEBUG_MSG_P(PSTR(" RF"));
  271. #endif
  272. #if SCHEDULER_SUPPORT
  273. DEBUG_MSG_P(PSTR(" SCHEDULER"));
  274. #endif
  275. #if SENSOR_SUPPORT
  276. DEBUG_MSG_P(PSTR(" SENSOR"));
  277. #endif
  278. #if SPIFFS_SUPPORT
  279. DEBUG_MSG_P(PSTR(" SPIFFS"));
  280. #endif
  281. #if SSDP_SUPPORT
  282. DEBUG_MSG_P(PSTR(" SSDP"));
  283. #endif
  284. #if TELNET_SUPPORT
  285. DEBUG_MSG_P(PSTR(" TELNET"));
  286. #endif
  287. #if TERMINAL_SUPPORT
  288. DEBUG_MSG_P(PSTR(" TERMINAL"));
  289. #endif
  290. #if THINGSPEAK_SUPPORT
  291. DEBUG_MSG_P(PSTR(" THINGSPEAK"));
  292. #endif
  293. #if UART_MQTT_SUPPORT
  294. DEBUG_MSG_P(PSTR(" UART_MQTT"));
  295. #endif
  296. #if WEB_SUPPORT
  297. DEBUG_MSG_P(PSTR(" WEB"));
  298. #endif
  299. #if SENSOR_SUPPORT
  300. DEBUG_MSG_P(PSTR("\n"));
  301. DEBUG_MSG_P(PSTR("[INIT] SENSORS:"));
  302. #if AM2320_SUPPORT
  303. DEBUG_MSG_P(PSTR(" AM2320_I2C"));
  304. #endif
  305. #if ANALOG_SUPPORT
  306. DEBUG_MSG_P(PSTR(" ANALOG"));
  307. #endif
  308. #if BMX280_SUPPORT
  309. DEBUG_MSG_P(PSTR(" BMX280"));
  310. #endif
  311. #if DALLAS_SUPPORT
  312. DEBUG_MSG_P(PSTR(" DALLAS"));
  313. #endif
  314. #if DHT_SUPPORT
  315. DEBUG_MSG_P(PSTR(" DHTXX"));
  316. #endif
  317. #if DIGITAL_SUPPORT
  318. DEBUG_MSG_P(PSTR(" DIGITAL"));
  319. #endif
  320. #if ECH1560_SUPPORT
  321. DEBUG_MSG_P(PSTR(" ECH1560"));
  322. #endif
  323. #if EMON_ADC121_SUPPORT
  324. DEBUG_MSG_P(PSTR(" EMON_ADC121"));
  325. #endif
  326. #if EMON_ADS1X15_SUPPORT
  327. DEBUG_MSG_P(PSTR(" EMON_ADX1X15"));
  328. #endif
  329. #if EMON_ANALOG_SUPPORT
  330. DEBUG_MSG_P(PSTR(" EMON_ANALOG"));
  331. #endif
  332. #if EVENTS_SUPPORT
  333. DEBUG_MSG_P(PSTR(" EVENTS"));
  334. #endif
  335. #if GUVAS12SD_SUPPORT
  336. DEBUG_MSG_P(PSTR(" GUVAS12SD"));
  337. #endif
  338. #if HLW8012_SUPPORT
  339. DEBUG_MSG_P(PSTR(" HLW8012"));
  340. #endif
  341. #if MHZ19_SUPPORT
  342. DEBUG_MSG_P(PSTR(" MHZ19"));
  343. #endif
  344. #if PMSX003_SUPPORT
  345. DEBUG_MSG_P(PSTR(" PMSX003"));
  346. #endif
  347. #if PZEM004T_SUPPORT
  348. DEBUG_MSG_P(PSTR(" PZEM004T"));
  349. #endif
  350. #if SHT3X_I2C_SUPPORT
  351. DEBUG_MSG_P(PSTR(" SHT3X_I2C"));
  352. #endif
  353. #if SI7021_SUPPORT
  354. DEBUG_MSG_P(PSTR(" SI7021"));
  355. #endif
  356. #if V9261F_SUPPORT
  357. DEBUG_MSG_P(PSTR(" V9261F"));
  358. #endif
  359. #endif // SENSOR_SUPPORT
  360. DEBUG_MSG_P(PSTR("\n\n"));
  361. // -------------------------------------------------------------------------
  362. unsigned char reason = resetReason();
  363. if (reason > 0) {
  364. char buffer[32];
  365. strcpy_P(buffer, custom_reset_string[reason-1]);
  366. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), buffer);
  367. } else {
  368. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), (char *) ESP.getResetReason().c_str());
  369. }
  370. DEBUG_MSG_P(PSTR("[INIT] Settings size: %u bytes\n"), settingsSize());
  371. DEBUG_MSG_P(PSTR("[INIT] Free heap: %u bytes\n"), getFreeHeap());
  372. #if ADC_VCC_ENABLED
  373. DEBUG_MSG_P(PSTR("[INIT] Power: %u mV\n"), ESP.getVcc());
  374. #endif
  375. DEBUG_MSG_P(PSTR("[INIT] Power saving delay value: %lu ms\n"), systemLoopDelay());
  376. #if SYSTEM_CHECK_ENABLED
  377. if (!systemCheck()) DEBUG_MSG_P(PSTR("\n[INIT] Device is in SAFE MODE\n"));
  378. #endif
  379. DEBUG_MSG_P(PSTR("\n"));
  380. }
  381. // -----------------------------------------------------------------------------
  382. // SSL
  383. // -----------------------------------------------------------------------------
  384. #if ASYNC_TCP_SSL_ENABLED
  385. bool sslCheckFingerPrint(const char * fingerprint) {
  386. return (strlen(fingerprint) == 59);
  387. }
  388. bool sslFingerPrintArray(const char * fingerprint, unsigned char * bytearray) {
  389. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  390. if (!sslCheckFingerPrint(fingerprint)) return false;
  391. // walk the fingerprint
  392. for (unsigned int i=0; i<20; i++) {
  393. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  394. }
  395. return true;
  396. }
  397. bool sslFingerPrintChar(const char * fingerprint, char * destination) {
  398. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  399. if (!sslCheckFingerPrint(fingerprint)) return false;
  400. // copy it
  401. strncpy(destination, fingerprint, 59);
  402. // walk the fingerprint replacing ':' for ' '
  403. for (unsigned char i = 0; i<59; i++) {
  404. if (destination[i] == ':') destination[i] = ' ';
  405. }
  406. return true;
  407. }
  408. #endif
  409. // -----------------------------------------------------------------------------
  410. // Reset
  411. // -----------------------------------------------------------------------------
  412. unsigned char resetReason() {
  413. static unsigned char status = 255;
  414. if (status == 255) {
  415. status = EEPROM.read(EEPROM_CUSTOM_RESET);
  416. if (status > 0) resetReason(0);
  417. if (status > CUSTOM_RESET_MAX) status = 0;
  418. }
  419. return status;
  420. }
  421. void resetReason(unsigned char reason) {
  422. EEPROM.write(EEPROM_CUSTOM_RESET, reason);
  423. EEPROM.commit();
  424. }
  425. void reset(unsigned char reason) {
  426. resetReason(reason);
  427. ESP.restart();
  428. }
  429. void deferredReset(unsigned long delay, unsigned char reason) {
  430. _defer_reset.once_ms(delay, reset, reason);
  431. }
  432. // -----------------------------------------------------------------------------
  433. char * ltrim(char * s) {
  434. char *p = s;
  435. while ((unsigned char) *p == ' ') ++p;
  436. return p;
  437. }
  438. double roundTo(double num, unsigned char positions) {
  439. double multiplier = 1;
  440. while (positions-- > 0) multiplier *= 10;
  441. return round(num * multiplier) / multiplier;
  442. }
  443. void nice_delay(unsigned long ms) {
  444. unsigned long start = millis();
  445. while (millis() - start < ms) delay(1);
  446. }