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.

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