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.

507 lines
15 KiB

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. // -------------------------------------------------------------------------
  79. // MQTT
  80. // -------------------------------------------------------------------------
  81. #if MQTT_SUPPORT
  82. #if (HEARTBEAT_REPORT_INTERVAL)
  83. mqttSend(MQTT_TOPIC_INTERVAL, HEARTBEAT_INTERVAL / 1000);
  84. #endif
  85. #if (HEARTBEAT_REPORT_APP)
  86. mqttSend(MQTT_TOPIC_APP, APP_NAME);
  87. #endif
  88. #if (HEARTBEAT_REPORT_VERSION)
  89. mqttSend(MQTT_TOPIC_VERSION, APP_VERSION);
  90. #endif
  91. #if (HEARTBEAT_REPORT_HOSTNAME)
  92. mqttSend(MQTT_TOPIC_HOSTNAME, getSetting("hostname").c_str());
  93. #endif
  94. #if (HEARTBEAT_REPORT_IP)
  95. mqttSend(MQTT_TOPIC_IP, getIP().c_str());
  96. #endif
  97. #if (HEARTBEAT_REPORT_MAC)
  98. mqttSend(MQTT_TOPIC_MAC, WiFi.macAddress().c_str());
  99. #endif
  100. #if (HEARTBEAT_REPORT_RSSI)
  101. mqttSend(MQTT_TOPIC_RSSI, String(WiFi.RSSI()).c_str());
  102. #endif
  103. #if (HEARTBEAT_REPORT_UPTIME)
  104. mqttSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  105. #endif
  106. #if (HEARTBEAT_REPORT_DATETIME) & (NTP_SUPPORT)
  107. mqttSend(MQTT_TOPIC_DATETIME, String(ntpDateTime()).c_str());
  108. #endif
  109. #if (HEARTBEAT_REPORT_FREEHEAP)
  110. mqttSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  111. #endif
  112. #if (HEARTBEAT_REPORT_RELAY)
  113. relayMQTT();
  114. #endif
  115. #if (LIGHT_PROVIDER != LIGHT_PROVIDER_NONE) & (HEARTBEAT_REPORT_LIGHT)
  116. lightMQTT();
  117. #endif
  118. #if (HEARTBEAT_REPORT_VCC)
  119. #if ADC_VCC_ENABLED
  120. mqttSend(MQTT_TOPIC_VCC, String(ESP.getVcc()).c_str());
  121. #endif
  122. #endif
  123. #if (HEARTBEAT_REPORT_STATUS)
  124. mqttSend(MQTT_TOPIC_STATUS, MQTT_STATUS_ONLINE, true);
  125. #endif
  126. bool serial = !mqttConnected();
  127. #else
  128. bool serial = true;
  129. #endif
  130. // -------------------------------------------------------------------------
  131. // Serial
  132. // -------------------------------------------------------------------------
  133. if (serial) {
  134. DEBUG_MSG_P(PSTR("[MAIN] Uptime: %lu seconds\n"), uptime_seconds);
  135. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %lu bytes\n"), free_heap);
  136. #if ADC_VCC_ENABLED
  137. DEBUG_MSG_P(PSTR("[MAIN] Power: %lu mV\n"), ESP.getVcc());
  138. #endif
  139. }
  140. #if NTP_SUPPORT
  141. DEBUG_MSG_P(PSTR("[MAIN] Time: %s\n"), (char *) ntpDateTime().c_str());
  142. #endif
  143. // -------------------------------------------------------------------------
  144. // InfluxDB
  145. // -------------------------------------------------------------------------
  146. #if INFLUXDB_SUPPORT
  147. #if (HEARTBEAT_REPORT_UPTIME)
  148. idbSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  149. #endif
  150. #if (HEARTBEAT_REPORT_FREEHEAP)
  151. idbSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  152. #endif
  153. #endif
  154. // -------------------------------------------------------------------------
  155. // WebSockets
  156. // -------------------------------------------------------------------------
  157. #if WEB_SUPPORT
  158. #if NTP_SUPPORT
  159. {
  160. char buffer[200];
  161. snprintf_P(
  162. buffer,
  163. sizeof(buffer) - 1,
  164. PSTR("{\"time\": \"%s\", \"uptime\": %lu, \"heap\": %lu}"),
  165. ntpDateTime().c_str(), uptime_seconds, free_heap
  166. );
  167. wsSend(buffer);
  168. }
  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. #if SPIFFS_SUPPORT
  199. FSInfo fs_info;
  200. bool fs = SPIFFS.info(fs_info);
  201. if (fs) {
  202. DEBUG_MSG_P(PSTR("[INIT] SPIFFS size: %8u bytes / %4d sectors\n"), fs_info.totalBytes, sectors(fs_info.totalBytes));
  203. }
  204. #else
  205. DEBUG_MSG_P(PSTR("[INIT] SPIFFS size: %8u bytes / %4d sectors\n"), 0, 0);
  206. #endif
  207. DEBUG_MSG_P(PSTR("[INIT] EEPROM size: %8u bytes / %4d sectors\n"), settingsMaxSize(), sectors(settingsMaxSize()));
  208. DEBUG_MSG_P(PSTR("[INIT] Empty space: %8u bytes / 4 sectors\n"), 4 * SPI_FLASH_SEC_SIZE);
  209. DEBUG_MSG_P(PSTR("\n"));
  210. // -------------------------------------------------------------------------
  211. #if SPIFFS_SUPPORT
  212. if (fs) {
  213. DEBUG_MSG_P(PSTR("[INIT] SPIFFS total size: %8u bytes\n"), fs_info.totalBytes);
  214. DEBUG_MSG_P(PSTR("[INIT] used size: %8u bytes\n"), fs_info.usedBytes);
  215. DEBUG_MSG_P(PSTR("[INIT] block size: %8u bytes\n"), fs_info.blockSize);
  216. DEBUG_MSG_P(PSTR("[INIT] page size: %8u bytes\n"), fs_info.pageSize);
  217. DEBUG_MSG_P(PSTR("[INIT] max files: %8u\n"), fs_info.maxOpenFiles);
  218. DEBUG_MSG_P(PSTR("[INIT] max length: %8u\n"), fs_info.maxPathLength);
  219. } else {
  220. DEBUG_MSG_P(PSTR("[INIT] No SPIFFS partition\n"));
  221. }
  222. DEBUG_MSG_P(PSTR("\n"));
  223. #endif
  224. // -------------------------------------------------------------------------
  225. DEBUG_MSG_P(PSTR("[INIT] BOARD: %s\n"), getBoardName().c_str());
  226. DEBUG_MSG_P(PSTR("[INIT] SUPPORT:"));
  227. #if ALEXA_SUPPORT
  228. DEBUG_MSG_P(PSTR(" ALEXA"));
  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 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"));
  256. #endif
  257. #if NETBIOS_SUPPORT
  258. DEBUG_MSG_P(PSTR(" NETBIOS"));
  259. #endif
  260. #if NOFUSS_SUPPORT
  261. DEBUG_MSG_P(PSTR(" NOFUSS"));
  262. #endif
  263. #if NTP_SUPPORT
  264. DEBUG_MSG_P(PSTR(" NTP"));
  265. #endif
  266. #if RF_SUPPORT
  267. DEBUG_MSG_P(PSTR(" RF"));
  268. #endif
  269. #if SCHEDULER_SUPPORT
  270. DEBUG_MSG_P(PSTR(" SCHEDULER"));
  271. #endif
  272. #if SENSOR_SUPPORT
  273. DEBUG_MSG_P(PSTR(" SENSOR"));
  274. #endif
  275. #if SPIFFS_SUPPORT
  276. DEBUG_MSG_P(PSTR(" SPIFFS"));
  277. #endif
  278. #if SSDP_SUPPORT
  279. DEBUG_MSG_P(PSTR(" SSDP"));
  280. #endif
  281. #if TELNET_SUPPORT
  282. DEBUG_MSG_P(PSTR(" TELNET"));
  283. #endif
  284. #if TERMINAL_SUPPORT
  285. DEBUG_MSG_P(PSTR(" TERMINAL"));
  286. #endif
  287. #if THINGSPEAK_SUPPORT
  288. DEBUG_MSG_P(PSTR(" THINGSPEAK"));
  289. #endif
  290. #if WEB_SUPPORT
  291. DEBUG_MSG_P(PSTR(" WEB"));
  292. #endif
  293. #if SENSOR_SUPPORT
  294. DEBUG_MSG_P(PSTR("\n[INIT] SENSORS:"));
  295. #if ANALOG_SUPPORT
  296. DEBUG_MSG_P(PSTR(" ANALOG"));
  297. #endif
  298. #if BMX280_SUPPORT
  299. DEBUG_MSG_P(PSTR(" BMX280"));
  300. #endif
  301. #if DALLAS_SUPPORT
  302. DEBUG_MSG_P(PSTR(" DALLAS"));
  303. #endif
  304. #if DHT_SUPPORT
  305. DEBUG_MSG_P(PSTR(" DHTXX"));
  306. #endif
  307. #if DIGITAL_SUPPORT
  308. DEBUG_MSG_P(PSTR(" DIGITAL"));
  309. #endif
  310. #if ECH1560_SUPPORT
  311. DEBUG_MSG_P(PSTR(" ECH1560"));
  312. #endif
  313. #if EMON_ADC121_SUPPORT
  314. DEBUG_MSG_P(PSTR(" EMON_ADC121"));
  315. #endif
  316. #if EMON_ADS1X15_SUPPORT
  317. DEBUG_MSG_P(PSTR(" EMON_ADX1X15"));
  318. #endif
  319. #if EMON_ANALOG_SUPPORT
  320. DEBUG_MSG_P(PSTR(" EMON_ANALOG"));
  321. #endif
  322. #if EVENTS_SUPPORT
  323. DEBUG_MSG_P(PSTR(" EVENTS"));
  324. #endif
  325. #if HLW8012_SUPPORT
  326. DEBUG_MSG_P(PSTR(" HLW8012"));
  327. #endif
  328. #if MHZ19_SUPPORT
  329. DEBUG_MSG_P(PSTR(" MHZ19"));
  330. #endif
  331. #if PMSX003_SUPPORT
  332. DEBUG_MSG_P(PSTR(" PMSX003"));
  333. #endif
  334. #if SHT3X_I2C_SUPPORT
  335. DEBUG_MSG_P(PSTR(" SHT3X_I2C"));
  336. #endif
  337. #if SI7021_SUPPORT
  338. DEBUG_MSG_P(PSTR(" SI7021"));
  339. #endif
  340. #if V9261F_SUPPORT
  341. DEBUG_MSG_P(PSTR(" V9261F"));
  342. #endif
  343. #endif // SENSOR_SUPPORT
  344. DEBUG_MSG_P(PSTR("\n\n"));
  345. // -------------------------------------------------------------------------
  346. unsigned char reason = resetReason();
  347. if (reason > 0) {
  348. char buffer[32];
  349. strcpy_P(buffer, custom_reset_string[reason-1]);
  350. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), buffer);
  351. } else {
  352. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), (char *) ESP.getResetReason().c_str());
  353. }
  354. DEBUG_MSG_P(PSTR("[INIT] Free heap: %u bytes\n"), getFreeHeap());
  355. #if ADC_VCC_ENABLED
  356. DEBUG_MSG_P(PSTR("[INIT] Power: %u mV\n"), ESP.getVcc());
  357. #endif
  358. DEBUG_MSG_P(PSTR("[INIT] Power saving delay value: %lu ms\n"), _loopDelay);
  359. if (!systemCheck()) DEBUG_MSG_P(PSTR("\n[INIT] Device is in SAFE MODE\n"));
  360. DEBUG_MSG_P(PSTR("\n"));
  361. }
  362. // -----------------------------------------------------------------------------
  363. // SSL
  364. // -----------------------------------------------------------------------------
  365. #if ASYNC_TCP_SSL_ENABLED
  366. bool sslCheckFingerPrint(const char * fingerprint) {
  367. return (strlen(fingerprint) == 59);
  368. }
  369. bool sslFingerPrintArray(const char * fingerprint, unsigned char * bytearray) {
  370. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  371. if (!sslCheckFingerPrint(fingerprint)) return false;
  372. // walk the fingerprint
  373. for (unsigned int i=0; i<20; i++) {
  374. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  375. }
  376. return true;
  377. }
  378. bool sslFingerPrintChar(const char * fingerprint, char * destination) {
  379. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  380. if (!sslCheckFingerPrint(fingerprint)) return false;
  381. // copy it
  382. strncpy(destination, fingerprint, 59);
  383. // walk the fingerprint replacing ':' for ' '
  384. for (unsigned char i = 0; i<59; i++) {
  385. if (destination[i] == ':') destination[i] = ' ';
  386. }
  387. return true;
  388. }
  389. #endif
  390. // -----------------------------------------------------------------------------
  391. // Reset
  392. // -----------------------------------------------------------------------------
  393. unsigned char resetReason() {
  394. static unsigned char status = 255;
  395. if (status == 255) {
  396. status = EEPROM.read(EEPROM_CUSTOM_RESET);
  397. if (status > 0) resetReason(0);
  398. if (status > CUSTOM_RESET_MAX) status = 0;
  399. }
  400. return status;
  401. }
  402. void resetReason(unsigned char reason) {
  403. EEPROM.write(EEPROM_CUSTOM_RESET, reason);
  404. EEPROM.commit();
  405. }
  406. void reset(unsigned char reason) {
  407. resetReason(reason);
  408. ESP.restart();
  409. }
  410. void deferredReset(unsigned long delay, unsigned char reason) {
  411. _defer_reset.once_ms(delay, reset, reason);
  412. }
  413. // -----------------------------------------------------------------------------
  414. char * ltrim(char * s) {
  415. char *p = s;
  416. while ((unsigned char) *p == ' ') ++p;
  417. return p;
  418. }
  419. double roundTo(double num, unsigned char positions) {
  420. double multiplier = 1;
  421. while (positions-- > 0) multiplier *= 10;
  422. return round(num * multiplier) / multiplier;
  423. }
  424. void nice_delay(unsigned long ms) {
  425. unsigned long start = millis();
  426. while (millis() - start < ms) delay(1);
  427. }