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.

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