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.

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