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.

515 lines
16 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 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. #if HEARTBEAT_ENABLED
  75. void heartbeat() {
  76. unsigned long uptime_seconds = getUptime();
  77. unsigned int free_heap = getFreeHeap();
  78. #if MQTT_SUPPORT
  79. bool serial = !mqttConnected();
  80. #else
  81. bool serial = true;
  82. #endif
  83. // -------------------------------------------------------------------------
  84. // Serial
  85. // -------------------------------------------------------------------------
  86. if (serial) {
  87. DEBUG_MSG_P(PSTR("[MAIN] Uptime: %lu seconds\n"), uptime_seconds);
  88. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %lu bytes\n"), free_heap);
  89. #if ADC_VCC_ENABLED
  90. DEBUG_MSG_P(PSTR("[MAIN] Power: %lu mV\n"), ESP.getVcc());
  91. #endif
  92. #if NTP_SUPPORT
  93. if (ntpSynced()) DEBUG_MSG_P(PSTR("[MAIN] Time: %s\n"), (char *) ntpDateTime().c_str());
  94. #endif
  95. }
  96. // -------------------------------------------------------------------------
  97. // MQTT
  98. // -------------------------------------------------------------------------
  99. #if MQTT_SUPPORT
  100. if (!serial) {
  101. #if (HEARTBEAT_REPORT_INTERVAL)
  102. mqttSend(MQTT_TOPIC_INTERVAL, HEARTBEAT_INTERVAL / 1000);
  103. #endif
  104. #if (HEARTBEAT_REPORT_APP)
  105. mqttSend(MQTT_TOPIC_APP, APP_NAME);
  106. #endif
  107. #if (HEARTBEAT_REPORT_VERSION)
  108. mqttSend(MQTT_TOPIC_VERSION, APP_VERSION);
  109. #endif
  110. #if (HEARTBEAT_REPORT_BOARD)
  111. mqttSend(MQTT_TOPIC_BOARD, getBoardName().c_str());
  112. #endif
  113. #if (HEARTBEAT_REPORT_HOSTNAME)
  114. mqttSend(MQTT_TOPIC_HOSTNAME, getSetting("hostname").c_str());
  115. #endif
  116. #if (HEARTBEAT_REPORT_IP)
  117. mqttSend(MQTT_TOPIC_IP, getIP().c_str());
  118. #endif
  119. #if (HEARTBEAT_REPORT_MAC)
  120. mqttSend(MQTT_TOPIC_MAC, WiFi.macAddress().c_str());
  121. #endif
  122. #if (HEARTBEAT_REPORT_RSSI)
  123. mqttSend(MQTT_TOPIC_RSSI, String(WiFi.RSSI()).c_str());
  124. #endif
  125. #if (HEARTBEAT_REPORT_UPTIME)
  126. mqttSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  127. #endif
  128. #if (HEARTBEAT_REPORT_DATETIME) && (NTP_SUPPORT)
  129. if (ntpSynced()) mqttSend(MQTT_TOPIC_DATETIME, ntpDateTime().c_str());
  130. #endif
  131. #if (HEARTBEAT_REPORT_FREEHEAP)
  132. mqttSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  133. #endif
  134. #if (HEARTBEAT_REPORT_RELAY)
  135. relayMQTT();
  136. #endif
  137. #if (LIGHT_PROVIDER != LIGHT_PROVIDER_NONE) & (HEARTBEAT_REPORT_LIGHT)
  138. lightMQTT();
  139. #endif
  140. #if (HEARTBEAT_REPORT_VCC)
  141. #if ADC_VCC_ENABLED
  142. mqttSend(MQTT_TOPIC_VCC, String(ESP.getVcc()).c_str());
  143. #endif
  144. #endif
  145. #if (HEARTBEAT_REPORT_STATUS)
  146. mqttSend(MQTT_TOPIC_STATUS, MQTT_STATUS_ONLINE, true);
  147. #endif
  148. #if (LOADAVG_REPORT)
  149. mqttSend(MQTT_TOPIC_LOADAVG, String(getLoadAverage()).c_str());
  150. #endif
  151. }
  152. #endif
  153. // -------------------------------------------------------------------------
  154. // InfluxDB
  155. // -------------------------------------------------------------------------
  156. #if INFLUXDB_SUPPORT
  157. #if (HEARTBEAT_REPORT_UPTIME)
  158. idbSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  159. #endif
  160. #if (HEARTBEAT_REPORT_FREEHEAP)
  161. idbSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  162. #endif
  163. #endif
  164. }
  165. #endif /// HEARTBEAT_ENABLED
  166. unsigned int sectors(size_t size) {
  167. return (int) (size + SPI_FLASH_SEC_SIZE - 1) / SPI_FLASH_SEC_SIZE;
  168. }
  169. void info() {
  170. DEBUG_MSG_P(PSTR("\n\n"));
  171. DEBUG_MSG_P(PSTR("[INIT] %s %s\n"), (char *) APP_NAME, (char *) APP_VERSION);
  172. DEBUG_MSG_P(PSTR("[INIT] %s\n"), (char *) APP_AUTHOR);
  173. DEBUG_MSG_P(PSTR("[INIT] %s\n\n"), (char *) APP_WEBSITE);
  174. DEBUG_MSG_P(PSTR("[INIT] CPU chip ID: 0x%06X\n"), ESP.getChipId());
  175. DEBUG_MSG_P(PSTR("[INIT] CPU frequency: %u MHz\n"), ESP.getCpuFreqMHz());
  176. DEBUG_MSG_P(PSTR("[INIT] SDK version: %s\n"), ESP.getSdkVersion());
  177. DEBUG_MSG_P(PSTR("[INIT] Core version: %s\n"), getCoreVersion().c_str());
  178. DEBUG_MSG_P(PSTR("[INIT] Core revision: %s\n"), getCoreRevision().c_str());
  179. DEBUG_MSG_P(PSTR("\n"));
  180. // -------------------------------------------------------------------------
  181. FlashMode_t mode = ESP.getFlashChipMode();
  182. DEBUG_MSG_P(PSTR("[INIT] Flash chip ID: 0x%06X\n"), ESP.getFlashChipId());
  183. DEBUG_MSG_P(PSTR("[INIT] Flash speed: %u Hz\n"), ESP.getFlashChipSpeed());
  184. 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");
  185. DEBUG_MSG_P(PSTR("\n"));
  186. DEBUG_MSG_P(PSTR("[INIT] Flash sector size: %8u bytes\n"), SPI_FLASH_SEC_SIZE);
  187. DEBUG_MSG_P(PSTR("[INIT] Flash size (CHIP): %8u bytes\n"), ESP.getFlashChipRealSize());
  188. DEBUG_MSG_P(PSTR("[INIT] Flash size (SDK): %8u bytes / %4d sectors\n"), ESP.getFlashChipSize(), sectors(ESP.getFlashChipSize()));
  189. DEBUG_MSG_P(PSTR("[INIT] Firmware size: %8u bytes / %4d sectors\n"), ESP.getSketchSize(), sectors(ESP.getSketchSize()));
  190. DEBUG_MSG_P(PSTR("[INIT] OTA size: %8u bytes / %4d sectors\n"), ESP.getFreeSketchSpace(), sectors(ESP.getFreeSketchSpace()));
  191. DEBUG_MSG_P(PSTR("[INIT] EEPROM size: %8u bytes / %4d sectors\n"), settingsMaxSize(), sectors(settingsMaxSize()));
  192. DEBUG_MSG_P(PSTR("[INIT] Empty space: %8u bytes / 4 sectors\n"), 4 * SPI_FLASH_SEC_SIZE);
  193. DEBUG_MSG_P(PSTR("\n"));
  194. // -------------------------------------------------------------------------
  195. #if SPIFFS_SUPPORT
  196. FSInfo fs_info;
  197. bool fs = SPIFFS.info(fs_info);
  198. if (fs) {
  199. DEBUG_MSG_P(PSTR("[INIT] SPIFFS total size: %8u bytes / %4d sectors\n"), fs_info.totalBytes, sectors(fs_info.totalBytes));
  200. DEBUG_MSG_P(PSTR("[INIT] used size: %8u bytes\n"), fs_info.usedBytes);
  201. DEBUG_MSG_P(PSTR("[INIT] block size: %8u bytes\n"), fs_info.blockSize);
  202. DEBUG_MSG_P(PSTR("[INIT] page size: %8u bytes\n"), fs_info.pageSize);
  203. DEBUG_MSG_P(PSTR("[INIT] max files: %8u\n"), fs_info.maxOpenFiles);
  204. DEBUG_MSG_P(PSTR("[INIT] max length: %8u\n"), fs_info.maxPathLength);
  205. } else {
  206. DEBUG_MSG_P(PSTR("[INIT] No SPIFFS partition\n"));
  207. }
  208. DEBUG_MSG_P(PSTR("\n"));
  209. #endif
  210. // -------------------------------------------------------------------------
  211. #ifdef APP_BUILD_FLAGS
  212. DEBUG_MSG_P(PSTR("[INIT] BUILD_FLAGS: %s\n"), APP_BUILD_FLAGS);
  213. #endif
  214. DEBUG_MSG_P(PSTR("[INIT] BOARD: %s\n"), getBoardName().c_str());
  215. DEBUG_MSG_P(PSTR("[INIT] SUPPORT:"));
  216. #if ALEXA_SUPPORT
  217. DEBUG_MSG_P(PSTR(" ALEXA"));
  218. #endif
  219. #if BROKER_SUPPORT
  220. DEBUG_MSG_P(PSTR(" BROKER"));
  221. #endif
  222. #if DEBUG_SERIAL_SUPPORT
  223. DEBUG_MSG_P(PSTR(" DEBUG_SERIAL"));
  224. #endif
  225. #if DEBUG_TELNET_SUPPORT
  226. DEBUG_MSG_P(PSTR(" DEBUG_TELNET"));
  227. #endif
  228. #if DEBUG_UDP_SUPPORT
  229. DEBUG_MSG_P(PSTR(" DEBUG_UDP"));
  230. #endif
  231. #if DOMOTICZ_SUPPORT
  232. DEBUG_MSG_P(PSTR(" DOMOTICZ"));
  233. #endif
  234. #if HOMEASSISTANT_SUPPORT
  235. DEBUG_MSG_P(PSTR(" HOMEASSISTANT"));
  236. #endif
  237. #if I2C_SUPPORT
  238. DEBUG_MSG_P(PSTR(" I2C"));
  239. #endif
  240. #if INFLUXDB_SUPPORT
  241. DEBUG_MSG_P(PSTR(" INFLUXDB"));
  242. #endif
  243. #if LLMNR_SUPPORT
  244. DEBUG_MSG_P(PSTR(" LLMNR"));
  245. #endif
  246. #if MDNS_SERVER_SUPPORT
  247. DEBUG_MSG_P(PSTR(" MDNS_SERVER"));
  248. #endif
  249. #if MDNS_CLIENT_SUPPORT
  250. DEBUG_MSG_P(PSTR(" MDNS_CLIENT"));
  251. #endif
  252. #if MQTT_SUPPORT
  253. DEBUG_MSG_P(PSTR(" MQTT"));
  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 UART_MQTT_SUPPORT
  289. DEBUG_MSG_P(PSTR(" UART_MQTT"));
  290. #endif
  291. #if WEB_SUPPORT
  292. DEBUG_MSG_P(PSTR(" WEB"));
  293. #endif
  294. #if SENSOR_SUPPORT
  295. DEBUG_MSG_P(PSTR("\n"));
  296. DEBUG_MSG_P(PSTR("[INIT] SENSORS:"));
  297. #if ANALOG_SUPPORT
  298. DEBUG_MSG_P(PSTR(" ANALOG"));
  299. #endif
  300. #if BMX280_SUPPORT
  301. DEBUG_MSG_P(PSTR(" BMX280"));
  302. #endif
  303. #if DALLAS_SUPPORT
  304. DEBUG_MSG_P(PSTR(" DALLAS"));
  305. #endif
  306. #if DHT_SUPPORT
  307. DEBUG_MSG_P(PSTR(" DHTXX"));
  308. #endif
  309. #if DIGITAL_SUPPORT
  310. DEBUG_MSG_P(PSTR(" DIGITAL"));
  311. #endif
  312. #if ECH1560_SUPPORT
  313. DEBUG_MSG_P(PSTR(" ECH1560"));
  314. #endif
  315. #if EMON_ADC121_SUPPORT
  316. DEBUG_MSG_P(PSTR(" EMON_ADC121"));
  317. #endif
  318. #if EMON_ADS1X15_SUPPORT
  319. DEBUG_MSG_P(PSTR(" EMON_ADX1X15"));
  320. #endif
  321. #if EMON_ANALOG_SUPPORT
  322. DEBUG_MSG_P(PSTR(" EMON_ANALOG"));
  323. #endif
  324. #if EVENTS_SUPPORT
  325. DEBUG_MSG_P(PSTR(" EVENTS"));
  326. #endif
  327. #if HLW8012_SUPPORT
  328. DEBUG_MSG_P(PSTR(" HLW8012"));
  329. #endif
  330. #if MHZ19_SUPPORT
  331. DEBUG_MSG_P(PSTR(" MHZ19"));
  332. #endif
  333. #if PMSX003_SUPPORT
  334. DEBUG_MSG_P(PSTR(" PMSX003"));
  335. #endif
  336. #if PZEM004T_SUPPORT
  337. DEBUG_MSG_P(PSTR(" PZEM004T"));
  338. #endif
  339. #if SHT3X_I2C_SUPPORT
  340. DEBUG_MSG_P(PSTR(" SHT3X_I2C"));
  341. #endif
  342. #if SI7021_SUPPORT
  343. DEBUG_MSG_P(PSTR(" SI7021"));
  344. #endif
  345. #if V9261F_SUPPORT
  346. DEBUG_MSG_P(PSTR(" V9261F"));
  347. #endif
  348. #endif // SENSOR_SUPPORT
  349. DEBUG_MSG_P(PSTR("\n\n"));
  350. // -------------------------------------------------------------------------
  351. unsigned char reason = resetReason();
  352. if (reason > 0) {
  353. char buffer[32];
  354. strcpy_P(buffer, custom_reset_string[reason-1]);
  355. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), buffer);
  356. } else {
  357. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), (char *) ESP.getResetReason().c_str());
  358. }
  359. DEBUG_MSG_P(PSTR("[INIT] Settings size: %u bytes\n"), settingsSize());
  360. DEBUG_MSG_P(PSTR("[INIT] Free heap: %u bytes\n"), getFreeHeap());
  361. #if ADC_VCC_ENABLED
  362. DEBUG_MSG_P(PSTR("[INIT] Power: %u mV\n"), ESP.getVcc());
  363. #endif
  364. DEBUG_MSG_P(PSTR("[INIT] Power saving delay value: %lu ms\n"), _loopDelay);
  365. #if SYSTEM_CHECK_ENABLED
  366. if (!systemCheck()) DEBUG_MSG_P(PSTR("\n[INIT] Device is in SAFE MODE\n"));
  367. #endif
  368. DEBUG_MSG_P(PSTR("\n"));
  369. }
  370. // -----------------------------------------------------------------------------
  371. // SSL
  372. // -----------------------------------------------------------------------------
  373. #if ASYNC_TCP_SSL_ENABLED
  374. bool sslCheckFingerPrint(const char * fingerprint) {
  375. return (strlen(fingerprint) == 59);
  376. }
  377. bool sslFingerPrintArray(const char * fingerprint, unsigned char * bytearray) {
  378. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  379. if (!sslCheckFingerPrint(fingerprint)) return false;
  380. // walk the fingerprint
  381. for (unsigned int i=0; i<20; i++) {
  382. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  383. }
  384. return true;
  385. }
  386. bool sslFingerPrintChar(const char * fingerprint, char * destination) {
  387. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  388. if (!sslCheckFingerPrint(fingerprint)) return false;
  389. // copy it
  390. strncpy(destination, fingerprint, 59);
  391. // walk the fingerprint replacing ':' for ' '
  392. for (unsigned char i = 0; i<59; i++) {
  393. if (destination[i] == ':') destination[i] = ' ';
  394. }
  395. return true;
  396. }
  397. #endif
  398. // -----------------------------------------------------------------------------
  399. // Reset
  400. // -----------------------------------------------------------------------------
  401. unsigned char resetReason() {
  402. static unsigned char status = 255;
  403. if (status == 255) {
  404. status = EEPROM.read(EEPROM_CUSTOM_RESET);
  405. if (status > 0) resetReason(0);
  406. if (status > CUSTOM_RESET_MAX) status = 0;
  407. }
  408. return status;
  409. }
  410. void resetReason(unsigned char reason) {
  411. EEPROM.write(EEPROM_CUSTOM_RESET, reason);
  412. EEPROM.commit();
  413. }
  414. void reset(unsigned char reason) {
  415. resetReason(reason);
  416. ESP.restart();
  417. }
  418. void deferredReset(unsigned long delay, unsigned char reason) {
  419. _defer_reset.once_ms(delay, reset, reason);
  420. }
  421. // -----------------------------------------------------------------------------
  422. char * ltrim(char * s) {
  423. char *p = s;
  424. while ((unsigned char) *p == ' ') ++p;
  425. return p;
  426. }
  427. double roundTo(double num, unsigned char positions) {
  428. double multiplier = 1;
  429. while (positions-- > 0) multiplier *= 10;
  430. return round(num * multiplier) / multiplier;
  431. }
  432. void nice_delay(unsigned long ms) {
  433. unsigned long start = millis();
  434. while (millis() - start < ms) delay(1);
  435. }