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.

336 lines
9.2 KiB

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 setBoardName() {
  13. #ifndef ESPURNA_CORE
  14. setSetting("boardName", DEVICE_NAME);
  15. #endif
  16. }
  17. String getBoardName() {
  18. return getSetting("boardName", DEVICE_NAME);
  19. }
  20. String getCoreVersion() {
  21. String version = ESP.getCoreVersion();
  22. #ifdef ARDUINO_ESP8266_RELEASE
  23. if (version.equals("00000000")) {
  24. version = String(ARDUINO_ESP8266_RELEASE);
  25. }
  26. #endif
  27. return version;
  28. }
  29. String getCoreRevision() {
  30. #ifdef ARDUINO_ESP8266_GIT_VER
  31. return String(ARDUINO_ESP8266_GIT_VER);
  32. #else
  33. return String("");
  34. #endif
  35. }
  36. // WTF
  37. // Calling ESP.getFreeHeap() is making the system crash on a specific
  38. // AiLight bulb, but anywhere else...
  39. unsigned int getFreeHeap() {
  40. if (getSetting("wtfHeap", 0).toInt() == 1) return 9999;
  41. return ESP.getFreeHeap();
  42. }
  43. String buildTime() {
  44. const char time_now[] = __TIME__; // hh:mm:ss
  45. unsigned int hour = atoi(&time_now[0]);
  46. unsigned int minute = atoi(&time_now[3]);
  47. unsigned int second = atoi(&time_now[6]);
  48. const char date_now[] = __DATE__; // Mmm dd yyyy
  49. const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  50. unsigned int month = 0;
  51. for ( int i = 0; i < 12; i++ ) {
  52. if (strncmp(date_now, months[i], 3) == 0 ) {
  53. month = i + 1;
  54. break;
  55. }
  56. }
  57. unsigned int day = atoi(&date_now[3]);
  58. unsigned int year = atoi(&date_now[7]);
  59. char buffer[20];
  60. snprintf_P(
  61. buffer, sizeof(buffer), PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
  62. year, month, day, hour, minute, second
  63. );
  64. return String(buffer);
  65. }
  66. unsigned long getUptime() {
  67. static unsigned long last_uptime = 0;
  68. static unsigned char uptime_overflows = 0;
  69. if (millis() < last_uptime) ++uptime_overflows;
  70. last_uptime = millis();
  71. unsigned long uptime_seconds = uptime_overflows * (UPTIME_OVERFLOW / 1000) + (last_uptime / 1000);
  72. return uptime_seconds;
  73. }
  74. void heartbeat() {
  75. unsigned long uptime_seconds = getUptime();
  76. unsigned int free_heap = getFreeHeap();
  77. // -------------------------------------------------------------------------
  78. // MQTT
  79. // -------------------------------------------------------------------------
  80. #if MQTT_SUPPORT
  81. #if (HEARTBEAT_REPORT_INTERVAL)
  82. mqttSend(MQTT_TOPIC_INTERVAL, HEARTBEAT_INTERVAL / 1000);
  83. #endif
  84. #if (HEARTBEAT_REPORT_APP)
  85. mqttSend(MQTT_TOPIC_APP, APP_NAME);
  86. #endif
  87. #if (HEARTBEAT_REPORT_VERSION)
  88. mqttSend(MQTT_TOPIC_VERSION, APP_VERSION);
  89. #endif
  90. #if (HEARTBEAT_REPORT_HOSTNAME)
  91. mqttSend(MQTT_TOPIC_HOSTNAME, getSetting("hostname").c_str());
  92. #endif
  93. #if (HEARTBEAT_REPORT_IP)
  94. mqttSend(MQTT_TOPIC_IP, getIP().c_str());
  95. #endif
  96. #if (HEARTBEAT_REPORT_MAC)
  97. mqttSend(MQTT_TOPIC_MAC, WiFi.macAddress().c_str());
  98. #endif
  99. #if (HEARTBEAT_REPORT_RSSI)
  100. mqttSend(MQTT_TOPIC_RSSI, String(WiFi.RSSI()).c_str());
  101. #endif
  102. #if (HEARTBEAT_REPORT_UPTIME)
  103. mqttSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  104. #endif
  105. #if (HEARTBEAT_REPORT_DATETIME) & (NTP_SUPPORT)
  106. mqttSend(MQTT_TOPIC_DATETIME, String(ntpDateTime()).c_str());
  107. #endif
  108. #if (HEARTBEAT_REPORT_FREEHEAP)
  109. mqttSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  110. #endif
  111. #if (HEARTBEAT_REPORT_RELAY)
  112. relayMQTT();
  113. #endif
  114. #if (LIGHT_PROVIDER != LIGHT_PROVIDER_NONE) & (HEARTBEAT_REPORT_LIGHT)
  115. lightMQTT();
  116. #endif
  117. #if (HEARTBEAT_REPORT_VCC)
  118. #if ADC_VCC_ENABLED
  119. mqttSend(MQTT_TOPIC_VCC, String(ESP.getVcc()).c_str());
  120. #endif
  121. #endif
  122. #if (HEARTBEAT_REPORT_STATUS)
  123. mqttSend(MQTT_TOPIC_STATUS, MQTT_STATUS_ONLINE, true);
  124. #endif
  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: %ld seconds\n"), uptime_seconds);
  134. DEBUG_MSG_P(PSTR("[MAIN] Free heap: %d bytes\n"), free_heap);
  135. #if ADC_VCC_ENABLED
  136. DEBUG_MSG_P(PSTR("[MAIN] Power: %d mV\n"), ESP.getVcc());
  137. #endif
  138. }
  139. #if NTP_SUPPORT
  140. DEBUG_MSG_P(PSTR("[MAIN] Time: %s\n"), (char *) ntpDateTime().c_str());
  141. #endif
  142. // -------------------------------------------------------------------------
  143. // InfluxDB
  144. // -------------------------------------------------------------------------
  145. #if INFLUXDB_SUPPORT
  146. #if (HEARTBEAT_REPORT_UPTIME)
  147. idbSend(MQTT_TOPIC_UPTIME, String(uptime_seconds).c_str());
  148. #endif
  149. #if (HEARTBEAT_REPORT_FREEHEAP)
  150. idbSend(MQTT_TOPIC_FREEHEAP, String(free_heap).c_str());
  151. #endif
  152. #endif
  153. // -------------------------------------------------------------------------
  154. // WebSockets
  155. // -------------------------------------------------------------------------
  156. #if WEB_SUPPORT
  157. #if NTP_SUPPORT
  158. {
  159. char buffer[200];
  160. snprintf_P(
  161. buffer,
  162. sizeof(buffer) - 1,
  163. PSTR("{\"time\": \"%s\", \"uptime\": %lu, \"heap\": %lu}"),
  164. ntpDateTime().c_str(), uptime_seconds, free_heap
  165. );
  166. wsSend(buffer);
  167. }
  168. #endif
  169. #endif
  170. }
  171. // -----------------------------------------------------------------------------
  172. // SSL
  173. // -----------------------------------------------------------------------------
  174. #if ASYNC_TCP_SSL_ENABLED
  175. bool sslCheckFingerPrint(const char * fingerprint) {
  176. return (strlen(fingerprint) == 59);
  177. }
  178. bool sslFingerPrintArray(const char * fingerprint, unsigned char * bytearray) {
  179. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  180. if (!sslCheckFingerPrint(fingerprint)) return false;
  181. // walk the fingerprint
  182. for (unsigned int i=0; i<20; i++) {
  183. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  184. }
  185. return true;
  186. }
  187. bool sslFingerPrintChar(const char * fingerprint, char * destination) {
  188. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  189. if (!sslCheckFingerPrint(fingerprint)) return false;
  190. // copy it
  191. strncpy(destination, fingerprint, 59);
  192. // walk the fingerprint replacing ':' for ' '
  193. for (unsigned char i = 0; i<59; i++) {
  194. if (destination[i] == ':') destination[i] = ' ';
  195. }
  196. return true;
  197. }
  198. #endif
  199. // -----------------------------------------------------------------------------
  200. // Reset
  201. // -----------------------------------------------------------------------------
  202. unsigned char resetReason() {
  203. static unsigned char status = 255;
  204. if (status == 255) {
  205. status = EEPROM.read(EEPROM_CUSTOM_RESET);
  206. if (status > 0) resetReason(0);
  207. if (status > CUSTOM_RESET_MAX) status = 0;
  208. }
  209. return status;
  210. }
  211. void resetReason(unsigned char reason) {
  212. EEPROM.write(EEPROM_CUSTOM_RESET, reason);
  213. EEPROM.commit();
  214. }
  215. void reset(unsigned char reason) {
  216. resetReason(reason);
  217. ESP.restart();
  218. }
  219. void deferredReset(unsigned long delay, unsigned char reason) {
  220. _defer_reset.once_ms(delay, reset, reason);
  221. }
  222. // -----------------------------------------------------------------------------
  223. #if SYSTEM_CHECK_ENABLED
  224. // Call this method on boot with start=true to increase the crash counter
  225. // Call it again once the system is stable to decrease the counter
  226. // If the counter reaches SYSTEM_CHECK_MAX then the system is flagged as unstable
  227. // setting _systemOK = false;
  228. //
  229. // An unstable system will only have serial access, WiFi in AP mode and OTA
  230. bool _systemStable = true;
  231. void systemCheck(bool stable) {
  232. unsigned char value = EEPROM.read(EEPROM_CRASH_COUNTER);
  233. if (stable) {
  234. value = 0;
  235. DEBUG_MSG_P(PSTR("[MAIN] System OK\n"));
  236. } else {
  237. if (++value > SYSTEM_CHECK_MAX) {
  238. _systemStable = false;
  239. value = 0;
  240. DEBUG_MSG_P(PSTR("[MAIN] System UNSTABLE\n"));
  241. }
  242. }
  243. EEPROM.write(EEPROM_CRASH_COUNTER, value);
  244. EEPROM.commit();
  245. }
  246. bool systemCheck() {
  247. return _systemStable;
  248. }
  249. void systemCheckLoop() {
  250. static bool checked = false;
  251. if (!checked && (millis() > SYSTEM_CHECK_TIME)) {
  252. // Check system as stable
  253. systemCheck(true);
  254. checked = true;
  255. }
  256. }
  257. #endif
  258. // -----------------------------------------------------------------------------
  259. char * ltrim(char * s) {
  260. char *p = s;
  261. while ((unsigned char) *p == ' ') ++p;
  262. return p;
  263. }
  264. double roundTo(double num, unsigned char positions) {
  265. double multiplier = 1;
  266. while (positions-- > 0) multiplier *= 10;
  267. return round(num * multiplier) / multiplier;
  268. }
  269. void nice_delay(unsigned long ms) {
  270. unsigned long start = millis();
  271. while (millis() - start < ms) delay(1);
  272. }