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.

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