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.

459 lines
14 KiB

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