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.

481 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. if (strlen(APP_REVISION) > 0) {
  232. DEBUG_MSG_P(PSTR("[INIT] %s %s (%s)\n"), (char *) APP_NAME, (char *) APP_VERSION, (char *) APP_REVISION);
  233. } else {
  234. DEBUG_MSG_P(PSTR("[INIT] %s %s\n"), (char *) APP_NAME, (char *) APP_VERSION);
  235. }
  236. DEBUG_MSG_P(PSTR("[INIT] %s\n"), (char *) APP_AUTHOR);
  237. DEBUG_MSG_P(PSTR("[INIT] %s\n\n"), (char *) APP_WEBSITE);
  238. DEBUG_MSG_P(PSTR("[INIT] CPU chip ID: 0x%06X\n"), ESP.getChipId());
  239. DEBUG_MSG_P(PSTR("[INIT] CPU frequency: %u MHz\n"), ESP.getCpuFreqMHz());
  240. DEBUG_MSG_P(PSTR("[INIT] SDK version: %s\n"), ESP.getSdkVersion());
  241. DEBUG_MSG_P(PSTR("[INIT] Core version: %s\n"), getCoreVersion().c_str());
  242. DEBUG_MSG_P(PSTR("[INIT] Core revision: %s\n"), getCoreRevision().c_str());
  243. DEBUG_MSG_P(PSTR("\n"));
  244. // -------------------------------------------------------------------------
  245. FlashMode_t mode = ESP.getFlashChipMode();
  246. DEBUG_MSG_P(PSTR("[INIT] Flash chip ID: 0x%06X\n"), ESP.getFlashChipId());
  247. DEBUG_MSG_P(PSTR("[INIT] Flash speed: %u Hz\n"), ESP.getFlashChipSpeed());
  248. 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");
  249. DEBUG_MSG_P(PSTR("\n"));
  250. _info_print_memory_layout_line("Flash size (CHIP)", ESP.getFlashChipRealSize(), true);
  251. _info_print_memory_layout_line("Flash size (SDK)", ESP.getFlashChipSize(), true);
  252. _info_print_memory_layout_line("Reserved", 1 * SPI_FLASH_SEC_SIZE, true);
  253. _info_print_memory_layout_line("Firmware size", ESP.getSketchSize());
  254. _info_print_memory_layout_line("Max OTA size", info_ota_space());
  255. _info_print_memory_layout_line("SPIFFS size", info_filesystem_space());
  256. _info_print_memory_layout_line("EEPROM size", info_eeprom_space());
  257. _info_print_memory_layout_line("Reserved", 4 * SPI_FLASH_SEC_SIZE);
  258. DEBUG_MSG_P(PSTR("\n"));
  259. DEBUG_MSG_P(PSTR("[INIT] EEPROM sectors: %s\n"), (char *) eepromSectors().c_str());
  260. DEBUG_MSG_P(PSTR("\n"));
  261. // -------------------------------------------------------------------------
  262. #if SPIFFS_SUPPORT
  263. FSInfo fs_info;
  264. bool fs = SPIFFS.info(fs_info);
  265. if (fs) {
  266. DEBUG_MSG_P(PSTR("[INIT] SPIFFS total size: %8u bytes / %4d sectors\n"), fs_info.totalBytes, sectors(fs_info.totalBytes));
  267. DEBUG_MSG_P(PSTR("[INIT] used size: %8u bytes\n"), fs_info.usedBytes);
  268. DEBUG_MSG_P(PSTR("[INIT] block size: %8u bytes\n"), fs_info.blockSize);
  269. DEBUG_MSG_P(PSTR("[INIT] page size: %8u bytes\n"), fs_info.pageSize);
  270. DEBUG_MSG_P(PSTR("[INIT] max files: %8u\n"), fs_info.maxOpenFiles);
  271. DEBUG_MSG_P(PSTR("[INIT] max length: %8u\n"), fs_info.maxPathLength);
  272. } else {
  273. DEBUG_MSG_P(PSTR("[INIT] No SPIFFS partition\n"));
  274. }
  275. DEBUG_MSG_P(PSTR("\n"));
  276. #endif
  277. // -------------------------------------------------------------------------
  278. DEBUG_MSG_P(PSTR("[INIT] BOARD: %s\n"), getBoardName().c_str());
  279. DEBUG_MSG_P(PSTR("[INIT] SUPPORT: %s\n"), getEspurnaModules().c_str());
  280. #if SENSOR_SUPPORT
  281. DEBUG_MSG_P(PSTR("[INIT] SENSORS: %s\n"), getEspurnaSensors().c_str());
  282. #endif // SENSOR_SUPPORT
  283. DEBUG_MSG_P(PSTR("[INIT] WEBUI IMAGE CODE: %u\n"), WEBUI_IMAGE);
  284. DEBUG_MSG_P(PSTR("\n"));
  285. // -------------------------------------------------------------------------
  286. unsigned char reason = resetReason();
  287. if (reason > 0) {
  288. char buffer[32];
  289. strcpy_P(buffer, custom_reset_string[reason-1]);
  290. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), buffer);
  291. } else {
  292. DEBUG_MSG_P(PSTR("[INIT] Last reset reason: %s\n"), (char *) ESP.getResetReason().c_str());
  293. }
  294. DEBUG_MSG_P(PSTR("[INIT] Settings size: %u bytes\n"), settingsSize());
  295. DEBUG_MSG_P(PSTR("[INIT] Free heap: %u bytes\n"), getFreeHeap());
  296. #if ADC_MODE_VALUE == ADC_VCC
  297. DEBUG_MSG_P(PSTR("[INIT] Power: %u mV\n"), ESP.getVcc());
  298. #endif
  299. DEBUG_MSG_P(PSTR("[INIT] Power saving delay value: %lu ms\n"), systemLoopDelay());
  300. #if SYSTEM_CHECK_ENABLED
  301. if (!systemCheck()) DEBUG_MSG_P(PSTR("\n[INIT] Device is in SAFE MODE\n"));
  302. #endif
  303. DEBUG_MSG_P(PSTR("\n"));
  304. }
  305. // -----------------------------------------------------------------------------
  306. // SSL
  307. // -----------------------------------------------------------------------------
  308. #if ASYNC_TCP_SSL_ENABLED
  309. bool sslCheckFingerPrint(const char * fingerprint) {
  310. return (strlen(fingerprint) == 59);
  311. }
  312. bool sslFingerPrintArray(const char * fingerprint, unsigned char * bytearray) {
  313. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  314. if (!sslCheckFingerPrint(fingerprint)) return false;
  315. // walk the fingerprint
  316. for (unsigned int i=0; i<20; i++) {
  317. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  318. }
  319. return true;
  320. }
  321. bool sslFingerPrintChar(const char * fingerprint, char * destination) {
  322. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  323. if (!sslCheckFingerPrint(fingerprint)) return false;
  324. // copy it
  325. strncpy(destination, fingerprint, 59);
  326. // walk the fingerprint replacing ':' for ' '
  327. for (unsigned char i = 0; i<59; i++) {
  328. if (destination[i] == ':') destination[i] = ' ';
  329. }
  330. return true;
  331. }
  332. #endif
  333. // -----------------------------------------------------------------------------
  334. // Reset
  335. // -----------------------------------------------------------------------------
  336. unsigned char resetReason() {
  337. static unsigned char status = 255;
  338. if (status == 255) {
  339. status = EEPROMr.read(EEPROM_CUSTOM_RESET);
  340. if (status > 0) resetReason(0);
  341. if (status > CUSTOM_RESET_MAX) status = 0;
  342. }
  343. return status;
  344. }
  345. void resetReason(unsigned char reason) {
  346. EEPROMr.write(EEPROM_CUSTOM_RESET, reason);
  347. EEPROMr.commit();
  348. }
  349. void reset(unsigned char reason) {
  350. resetReason(reason);
  351. ESP.restart();
  352. }
  353. void deferredReset(unsigned long delay, unsigned char reason) {
  354. _defer_reset.once_ms(delay, reset, reason);
  355. }
  356. // -----------------------------------------------------------------------------
  357. char * ltrim(char * s) {
  358. char *p = s;
  359. while ((unsigned char) *p == ' ') ++p;
  360. return p;
  361. }
  362. double roundTo(double num, unsigned char positions) {
  363. double multiplier = 1;
  364. while (positions-- > 0) multiplier *= 10;
  365. return round(num * multiplier) / multiplier;
  366. }
  367. void nice_delay(unsigned long ms) {
  368. unsigned long start = millis();
  369. while (millis() - start < ms) delay(1);
  370. }
  371. // This method is called by the SDK to know where to connect the ADC
  372. int __get_adc_mode() {
  373. return (int) (ADC_MODE_VALUE);
  374. }
  375. bool isNumber(const char * s) {
  376. unsigned char len = strlen(s);
  377. bool decimal = false;
  378. for (unsigned char i=0; i<len; i++) {
  379. if (s[i] == '-') {
  380. if (i>0) return false;
  381. } else if (s[i] == '.') {
  382. if (decimal) return false;
  383. decimal = true;
  384. } else if (!isdigit(s[i])) {
  385. return false;
  386. }
  387. }
  388. return true;
  389. }