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.

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