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.

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