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.

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