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.

457 lines
14 KiB

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