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.

475 lines
15 KiB

  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 getEspurnaModules() {
  55. return FPSTR(espurna_modules);
  56. }
  57. #if SENSOR_SUPPORT
  58. String getEspurnaSensors() {
  59. return FPSTR(espurna_sensors);
  60. }
  61. #endif
  62. String buildTime() {
  63. const char time_now[] = __TIME__; // hh:mm:ss
  64. unsigned int hour = atoi(&time_now[0]);
  65. unsigned int minute = atoi(&time_now[3]);
  66. unsigned int second = atoi(&time_now[6]);
  67. const char date_now[] = __DATE__; // Mmm dd yyyy
  68. const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  69. unsigned int month = 0;
  70. for ( int i = 0; i < 12; i++ ) {
  71. if (strncmp(date_now, months[i], 3) == 0 ) {
  72. month = i + 1;
  73. break;
  74. }
  75. }
  76. unsigned int day = atoi(&date_now[3]);
  77. unsigned int year = atoi(&date_now[7]);
  78. char buffer[20];
  79. snprintf_P(
  80. buffer, sizeof(buffer), PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
  81. year, month, day, hour, minute, second
  82. );
  83. return String(buffer);
  84. }
  85. bool rtcReady() {
  86. return (year() > 2017);
  87. }
  88. String rtcDateTime(time_t t) {
  89. char buffer[20];
  90. snprintf_P(buffer, sizeof(buffer),
  91. PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
  92. year(t), month(t), day(t), hour(t), minute(t), second(t)
  93. );
  94. return String(buffer);
  95. }
  96. String rtcDateTime() {
  97. if (rtcReady()) return rtcDateTime(now());
  98. return String();
  99. }
  100. unsigned long getUptime() {
  101. static unsigned long last_uptime = 0;
  102. static unsigned char uptime_overflows = 0;
  103. if (millis() < last_uptime) ++uptime_overflows;
  104. last_uptime = millis();
  105. unsigned long uptime_seconds = uptime_overflows * (UPTIME_OVERFLOW / 1000) + (last_uptime / 1000);
  106. return uptime_seconds;
  107. }
  108. #if HEARTBEAT_ENABLED
  109. void heartbeat() {
  110. unsigned long uptime_seconds = getUptime();
  111. unsigned int free_heap = getFreeHeap();
  112. #if MQTT_SUPPORT
  113. bool serial = !mqttConnected();
  114. #else
  115. bool serial = true;
  116. #endif
  117. // -------------------------------------------------------------------------
  118. // Serial
  119. // -------------------------------------------------------------------------
  120. if (serial) {
  121. DEBUG_MSG_P(PSTR("[MAIN] Uptime: %lu seconds\n"), uptime_seconds);
  122. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %lu bytes\n"), free_heap);
  123. #if ADC_MODE_VALUE == ADC_VCC
  124. DEBUG_MSG_P(PSTR("[MAIN] Power: %lu mV\n"), ESP.getVcc());
  125. #endif
  126. #if NTP_SUPPORT
  127. if (rtcReady()) DEBUG_MSG_P(PSTR("[MAIN] Time: %s\n"), (char *) rtcDateTime().c_str());
  128. #endif
  129. }
  130. // -------------------------------------------------------------------------
  131. // MQTT
  132. // -------------------------------------------------------------------------
  133. #if MQTT_SUPPORT
  134. if (!serial) {
  135. #if (HEARTBEAT_REPORT_INTERVAL)
  136. mqttSend(MQTT_TOPIC_INTERVAL, HEARTBEAT_INTERVAL / 1000);
  137. #endif
  138. #if (HEARTBEAT_REPORT_APP)
  139. mqttSend(MQTT_TOPIC_APP, APP_NAME);
  140. #endif
  141. #if (HEARTBEAT_REPORT_VERSION)
  142. mqttSend(MQTT_TOPIC_VERSION, APP_VERSION);
  143. #endif
  144. #if (HEARTBEAT_REPORT_BOARD)
  145. mqttSend(MQTT_TOPIC_BOARD, getBoardName().c_str());
  146. #endif
  147. #if (HEARTBEAT_REPORT_HOSTNAME)
  148. mqttSend(MQTT_TOPIC_HOSTNAME, getSetting("hostname").c_str());
  149. #endif
  150. #if (HEARTBEAT_REPORT_IP)
  151. mqttSend(MQTT_TOPIC_IP, getIP().c_str());
  152. #endif
  153. #if (HEARTBEAT_REPORT_MAC)
  154. mqttSend(MQTT_TOPIC_MAC, WiFi.macAddress().c_str());
  155. #endif
  156. #if (HEARTBEAT_REPORT_RSSI)
  157. mqttSend(MQTT_TOPIC_RSSI, String(WiFi.RSSI()).c_str());
  158. #endif
  159. #if (HEARTBEAT_REPORT_UPTIME)
  160. mqttSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  161. #endif
  162. #if (HEARTBEAT_REPORT_DATETIME) && (NTP_SUPPORT)
  163. if (rtcReady()) mqttSend(MQTT_TOPIC_DATETIME, rtcDateTime().c_str());
  164. #endif
  165. #if (HEARTBEAT_REPORT_FREEHEAP)
  166. mqttSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  167. #endif
  168. #if (HEARTBEAT_REPORT_RELAY)
  169. relayMQTT();
  170. #endif
  171. #if (LIGHT_PROVIDER != LIGHT_PROVIDER_NONE) & (HEARTBEAT_REPORT_LIGHT)
  172. lightMQTT();
  173. #endif
  174. #if (HEARTBEAT_REPORT_VCC)
  175. #if ADC_MODE_VALUE == ADC_VCC
  176. mqttSend(MQTT_TOPIC_VCC, String(ESP.getVcc()).c_str());
  177. #endif
  178. #endif
  179. #if (HEARTBEAT_REPORT_STATUS)
  180. mqttSend(MQTT_TOPIC_STATUS, MQTT_STATUS_ONLINE, true);
  181. #endif
  182. #if (LOADAVG_REPORT)
  183. mqttSend(MQTT_TOPIC_LOADAVG, String(systemLoadAverage()).c_str());
  184. #endif
  185. }
  186. #endif
  187. // -------------------------------------------------------------------------
  188. // InfluxDB
  189. // -------------------------------------------------------------------------
  190. #if INFLUXDB_SUPPORT
  191. #if (HEARTBEAT_REPORT_UPTIME)
  192. idbSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  193. #endif
  194. #if (HEARTBEAT_REPORT_FREEHEAP)
  195. idbSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  196. #endif
  197. #endif
  198. }
  199. #endif /// HEARTBEAT_ENABLED
  200. // -----------------------------------------------------------------------------
  201. // INFO
  202. // -----------------------------------------------------------------------------
  203. extern "C" uint32_t _SPIFFS_start;
  204. extern "C" uint32_t _SPIFFS_end;
  205. unsigned int info_bytes2sectors(size_t size) {
  206. return (int) (size + SPI_FLASH_SEC_SIZE - 1) / SPI_FLASH_SEC_SIZE;
  207. }
  208. unsigned long info_ota_space() {
  209. return (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  210. }
  211. unsigned long info_filesystem_space() {
  212. return ((uint32_t)&_SPIFFS_end - (uint32_t)&_SPIFFS_start);
  213. }
  214. unsigned long info_eeprom_space() {
  215. return EEPROMr.reserved() * SPI_FLASH_SEC_SIZE;
  216. }
  217. void _info_print_memory_layout_line(const char * name, unsigned long bytes, bool reset) {
  218. static unsigned long index = 0;
  219. if (reset) index = 0;
  220. if (0 == bytes) return;
  221. unsigned int _sectors = info_bytes2sectors(bytes);
  222. DEBUG_MSG_P(PSTR("[INIT] %-20s: %8lu bytes / %4d sectors (%4d to %4d)\n"), name, bytes, _sectors, index, index + _sectors - 1);
  223. index += _sectors;
  224. }
  225. void _info_print_memory_layout_line(const char * name, unsigned long bytes) {
  226. _info_print_memory_layout_line(name, bytes, false);
  227. }
  228. void info() {
  229. DEBUG_MSG_P(PSTR("\n\n"));
  230. DEBUG_MSG_P(PSTR("[INIT] %s %s\n"), (char *) APP_NAME, (char *) APP_VERSION);
  231. DEBUG_MSG_P(PSTR("[INIT] %s\n"), (char *) APP_AUTHOR);
  232. DEBUG_MSG_P(PSTR("[INIT] %s\n\n"), (char *) APP_WEBSITE);
  233. DEBUG_MSG_P(PSTR("[INIT] CPU chip ID: 0x%06X\n"), ESP.getChipId());
  234. DEBUG_MSG_P(PSTR("[INIT] CPU frequency: %u MHz\n"), ESP.getCpuFreqMHz());
  235. DEBUG_MSG_P(PSTR("[INIT] SDK version: %s\n"), ESP.getSdkVersion());
  236. DEBUG_MSG_P(PSTR("[INIT] Core version: %s\n"), getCoreVersion().c_str());
  237. DEBUG_MSG_P(PSTR("[INIT] Core revision: %s\n"), getCoreRevision().c_str());
  238. DEBUG_MSG_P(PSTR("\n"));
  239. // -------------------------------------------------------------------------
  240. FlashMode_t mode = ESP.getFlashChipMode();
  241. DEBUG_MSG_P(PSTR("[INIT] Flash chip ID: 0x%06X\n"), ESP.getFlashChipId());
  242. DEBUG_MSG_P(PSTR("[INIT] Flash speed: %u Hz\n"), ESP.getFlashChipSpeed());
  243. 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");
  244. DEBUG_MSG_P(PSTR("\n"));
  245. _info_print_memory_layout_line("Flash size (CHIP)", ESP.getFlashChipRealSize(), true);
  246. _info_print_memory_layout_line("Flash size (SDK)", ESP.getFlashChipSize(), true);
  247. _info_print_memory_layout_line("Reserved", 1 * SPI_FLASH_SEC_SIZE, true);
  248. _info_print_memory_layout_line("Firmware size", ESP.getSketchSize());
  249. _info_print_memory_layout_line("Max OTA size", info_ota_space());
  250. _info_print_memory_layout_line("SPIFFS size", info_filesystem_space());
  251. _info_print_memory_layout_line("EEPROM size", info_eeprom_space());
  252. _info_print_memory_layout_line("Reserved", 4 * SPI_FLASH_SEC_SIZE);
  253. DEBUG_MSG_P(PSTR("\n"));
  254. DEBUG_MSG_P(PSTR("[INIT] EEPROM sectors: %s\n"), (char *) eepromSectors().c_str());
  255. DEBUG_MSG_P(PSTR("\n"));
  256. // -------------------------------------------------------------------------
  257. #if SPIFFS_SUPPORT
  258. FSInfo fs_info;
  259. bool fs = SPIFFS.info(fs_info);
  260. if (fs) {
  261. DEBUG_MSG_P(PSTR("[INIT] SPIFFS total size: %8u bytes / %4d sectors\n"), fs_info.totalBytes, sectors(fs_info.totalBytes));
  262. DEBUG_MSG_P(PSTR("[INIT] used size: %8u bytes\n"), fs_info.usedBytes);
  263. DEBUG_MSG_P(PSTR("[INIT] block size: %8u bytes\n"), fs_info.blockSize);
  264. DEBUG_MSG_P(PSTR("[INIT] page size: %8u bytes\n"), fs_info.pageSize);
  265. DEBUG_MSG_P(PSTR("[INIT] max files: %8u\n"), fs_info.maxOpenFiles);
  266. DEBUG_MSG_P(PSTR("[INIT] max length: %8u\n"), fs_info.maxPathLength);
  267. } else {
  268. DEBUG_MSG_P(PSTR("[INIT] No SPIFFS partition\n"));
  269. }
  270. DEBUG_MSG_P(PSTR("\n"));
  271. #endif
  272. // -------------------------------------------------------------------------
  273. DEBUG_MSG_P(PSTR("[INIT] BOARD: %s\n"), getBoardName().c_str());
  274. DEBUG_MSG_P(PSTR("[INIT] SUPPORT: %s\n"), getEspurnaModules().c_str());
  275. #if SENSOR_SUPPORT
  276. DEBUG_MSG_P(PSTR("[INIT] SENSORS: %s\n"), getEspurnaSensors().c_str());
  277. #endif // SENSOR_SUPPORT
  278. DEBUG_MSG_P(PSTR("[INIT] WEBUI IMAGE CODE: %u\n"), WEBUI_IMAGE);
  279. DEBUG_MSG_P(PSTR("\n"));
  280. // -------------------------------------------------------------------------
  281. unsigned char reason = resetReason();
  282. if (reason > 0) {
  283. char buffer[32];
  284. strcpy_P(buffer, custom_reset_string[reason-1]);
  285. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), buffer);
  286. } else {
  287. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), (char *) ESP.getResetReason().c_str());
  288. }
  289. DEBUG_MSG_P(PSTR("[INIT] Settings size: %u bytes\n"), settingsSize());
  290. DEBUG_MSG_P(PSTR("[INIT] Free heap: %u bytes\n"), getFreeHeap());
  291. #if ADC_MODE_VALUE == ADC_VCC
  292. DEBUG_MSG_P(PSTR("[INIT] Power: %u mV\n"), ESP.getVcc());
  293. #endif
  294. DEBUG_MSG_P(PSTR("[INIT] Power saving delay value: %lu ms\n"), systemLoopDelay());
  295. #if SYSTEM_CHECK_ENABLED
  296. if (!systemCheck()) DEBUG_MSG_P(PSTR("\n[INIT] Device is in SAFE MODE\n"));
  297. #endif
  298. DEBUG_MSG_P(PSTR("\n"));
  299. }
  300. // -----------------------------------------------------------------------------
  301. // SSL
  302. // -----------------------------------------------------------------------------
  303. #if ASYNC_TCP_SSL_ENABLED
  304. bool sslCheckFingerPrint(const char * fingerprint) {
  305. return (strlen(fingerprint) == 59);
  306. }
  307. bool sslFingerPrintArray(const char * fingerprint, unsigned char * bytearray) {
  308. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  309. if (!sslCheckFingerPrint(fingerprint)) return false;
  310. // walk the fingerprint
  311. for (unsigned int i=0; i<20; i++) {
  312. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  313. }
  314. return true;
  315. }
  316. bool sslFingerPrintChar(const char * fingerprint, char * destination) {
  317. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  318. if (!sslCheckFingerPrint(fingerprint)) return false;
  319. // copy it
  320. strncpy(destination, fingerprint, 59);
  321. // walk the fingerprint replacing ':' for ' '
  322. for (unsigned char i = 0; i<59; i++) {
  323. if (destination[i] == ':') destination[i] = ' ';
  324. }
  325. return true;
  326. }
  327. #endif
  328. // -----------------------------------------------------------------------------
  329. // Reset
  330. // -----------------------------------------------------------------------------
  331. unsigned char resetReason() {
  332. static unsigned char status = 255;
  333. if (status == 255) {
  334. status = EEPROMr.read(EEPROM_CUSTOM_RESET);
  335. if (status > 0) resetReason(0);
  336. if (status > CUSTOM_RESET_MAX) status = 0;
  337. }
  338. return status;
  339. }
  340. void resetReason(unsigned char reason) {
  341. EEPROMr.write(EEPROM_CUSTOM_RESET, reason);
  342. EEPROMr.commit();
  343. }
  344. void reset(unsigned char reason) {
  345. resetReason(reason);
  346. ESP.restart();
  347. }
  348. void deferredReset(unsigned long delay, unsigned char reason) {
  349. _defer_reset.once_ms(delay, reset, reason);
  350. }
  351. // -----------------------------------------------------------------------------
  352. char * ltrim(char * s) {
  353. char *p = s;
  354. while ((unsigned char) *p == ' ') ++p;
  355. return p;
  356. }
  357. double roundTo(double num, unsigned char positions) {
  358. double multiplier = 1;
  359. while (positions-- > 0) multiplier *= 10;
  360. return round(num * multiplier) / multiplier;
  361. }
  362. void nice_delay(unsigned long ms) {
  363. unsigned long start = millis();
  364. while (millis() - start < ms) delay(1);
  365. }
  366. // This method is called by the SDK to know where to connect the ADC
  367. int __get_adc_mode() {
  368. return (int) (ADC_MODE_VALUE);
  369. }
  370. bool isNumber(const char * s) {
  371. unsigned char len = strlen(s);
  372. bool decimal = false;
  373. for (unsigned char i=0; i<len; i++) {
  374. if (s[i] == '-') {
  375. if (i>0) return false;
  376. } else if (s[i] == '.') {
  377. if (decimal) return false;
  378. decimal = true;
  379. } else if (!isdigit(s[i])) {
  380. return false;
  381. }
  382. }
  383. return true;
  384. }