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.

257 lines
6.6 KiB

7 years ago
  1. /*
  2. OTA MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "ArduinoOTA.h"
  6. // -----------------------------------------------------------------------------
  7. // Arduino OTA
  8. // -----------------------------------------------------------------------------
  9. void _otaConfigure() {
  10. ArduinoOTA.setPort(OTA_PORT);
  11. ArduinoOTA.setHostname(getSetting("hostname").c_str());
  12. #if USE_PASSWORD
  13. ArduinoOTA.setPassword(getSetting("adminPass", ADMIN_PASS).c_str());
  14. #endif
  15. }
  16. void _otaLoop() {
  17. ArduinoOTA.handle();
  18. }
  19. // -----------------------------------------------------------------------------
  20. // Terminal OTA
  21. // -----------------------------------------------------------------------------
  22. #if TERMINAL_SUPPORT
  23. #include <ESPAsyncTCP.h>
  24. AsyncClient * _ota_client;
  25. char * _ota_host;
  26. char * _ota_url;
  27. unsigned int _ota_port = 80;
  28. unsigned long _ota_size = 0;
  29. const char OTA_REQUEST_TEMPLATE[] PROGMEM =
  30. "GET %s HTTP/1.1\r\n"
  31. "Host: %s\r\n"
  32. "User-Agent: ESPurna\r\n"
  33. "Connection: close\r\n"
  34. "Content-Type: application/x-www-form-urlencoded\r\n"
  35. "Content-Length: 0\r\n\r\n\r\n";
  36. void _otaFrom(const char * host, unsigned int port, const char * url) {
  37. if (_ota_host) free(_ota_host);
  38. if (_ota_url) free(_ota_url);
  39. _ota_host = strdup(host);
  40. _ota_url = strdup(url);
  41. _ota_port = port;
  42. _ota_size = 0;
  43. if (_ota_client == NULL) {
  44. _ota_client = new AsyncClient();
  45. }
  46. _ota_client->onDisconnect([](void *s, AsyncClient *c) {
  47. DEBUG_MSG_P(PSTR("\n"));
  48. if (Update.end(true)){
  49. DEBUG_MSG_P(PSTR("[OTA] Success: %u bytes\n"), _ota_size);
  50. deferredReset(100, CUSTOM_RESET_OTA);
  51. } else {
  52. #ifdef DEBUG_PORT
  53. Update.printError(DEBUG_PORT);
  54. #endif
  55. }
  56. DEBUG_MSG_P(PSTR("[OTA] Disconnected\n"));
  57. _ota_client->free();
  58. delete _ota_client;
  59. _ota_client = NULL;
  60. free(_ota_host);
  61. _ota_host = NULL;
  62. free(_ota_url);
  63. _ota_url = NULL;
  64. }, 0);
  65. _ota_client->onTimeout([](void *s, AsyncClient *c, uint32_t time) {
  66. _ota_client->close(true);
  67. }, 0);
  68. _ota_client->onData([](void * arg, AsyncClient * c, void * data, size_t len) {
  69. char * p = (char *) data;
  70. if (_ota_size == 0) {
  71. Update.runAsync(true);
  72. if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000)) {
  73. #ifdef DEBUG_PORT
  74. Update.printError(DEBUG_PORT);
  75. #endif
  76. }
  77. p = strstr((char *)data, "\r\n\r\n") + 4;
  78. len = len - (p - (char *) data);
  79. }
  80. if (!Update.hasError()) {
  81. if (Update.write((uint8_t *) p, len) != len) {
  82. #ifdef DEBUG_PORT
  83. Update.printError(DEBUG_PORT);
  84. #endif
  85. }
  86. }
  87. _ota_size += len;
  88. DEBUG_MSG_P(PSTR("[OTA] Progress: %u bytes\r"), _ota_size);
  89. }, NULL);
  90. _ota_client->onConnect([](void * arg, AsyncClient * client) {
  91. #if ASYNC_TCP_SSL_ENABLED
  92. if (443 == _ota_port) {
  93. uint8_t fp[20] = {0};
  94. sslFingerPrintArray(getSetting("otafp", OTA_GITHUB_FP).c_str(), fp);
  95. SSL * ssl = _ota_client->getSSL();
  96. if (ssl_match_fingerprint(ssl, fp) != SSL_OK) {
  97. DEBUG_MSG_P(PSTR("[OTA] Warning: certificate doesn't match\n"));
  98. }
  99. }
  100. #endif
  101. // Backup EEPROM data to last sector
  102. eepromBackup();
  103. DEBUG_MSG_P(PSTR("[OTA] Downloading %s\n"), _ota_url);
  104. char buffer[strlen_P(OTA_REQUEST_TEMPLATE) + strlen(_ota_url) + strlen(_ota_host)];
  105. snprintf_P(buffer, sizeof(buffer), OTA_REQUEST_TEMPLATE, _ota_url, _ota_host);
  106. client->write(buffer);
  107. }, NULL);
  108. #if ASYNC_TCP_SSL_ENABLED
  109. bool connected = _ota_client->connect(host, port, 443 == port);
  110. #else
  111. bool connected = _ota_client->connect(host, port);
  112. #endif
  113. if (!connected) {
  114. DEBUG_MSG_P(PSTR("[OTA] Connection failed\n"));
  115. _ota_client->close(true);
  116. }
  117. }
  118. void _otaFrom(String url) {
  119. // Port from protocol
  120. unsigned int port = 80;
  121. if (url.startsWith("https://")) port = 443;
  122. url = url.substring(url.indexOf("/") + 2);
  123. // Get host
  124. String host = url.substring(0, url.indexOf("/"));
  125. // Explicit port
  126. int p = host.indexOf(":");
  127. if (p > 0) {
  128. port = host.substring(p + 1).toInt();
  129. host = host.substring(0, p);
  130. }
  131. // Get URL
  132. String uri = url.substring(url.indexOf("/"));
  133. _otaFrom(host.c_str(), port, uri.c_str());
  134. }
  135. void _otaInitCommands() {
  136. settingsRegisterCommand(F("OTA"), [](Embedis* e) {
  137. if (e->argc < 2) {
  138. DEBUG_MSG_P(PSTR("-ERROR: Wrong arguments\n"));
  139. } else {
  140. DEBUG_MSG_P(PSTR("+OK\n"));
  141. String url = String(e->argv[1]);
  142. _otaFrom(url);
  143. }
  144. });
  145. }
  146. #endif // TERMINAL_SUPPORT
  147. // -----------------------------------------------------------------------------
  148. void otaSetup() {
  149. _otaConfigure();
  150. #if WEB_SUPPORT
  151. wsOnAfterParseRegister(_otaConfigure);
  152. #endif
  153. #if TERMINAL_SUPPORT
  154. _otaInitCommands();
  155. #endif
  156. // Register loop
  157. espurnaRegisterLoop(_otaLoop);
  158. // -------------------------------------------------------------------------
  159. ArduinoOTA.onStart([]() {
  160. // Backup EEPROM data to last sector
  161. eepromBackup();
  162. DEBUG_MSG_P(PSTR("[OTA] Start\n"));
  163. #if WEB_SUPPORT
  164. wsSend_P(PSTR("{\"message\": 2}"));
  165. #endif
  166. });
  167. ArduinoOTA.onEnd([]() {
  168. DEBUG_MSG_P(PSTR("\n"));
  169. DEBUG_MSG_P(PSTR("[OTA] Done, restarting...\n"));
  170. #if WEB_SUPPORT
  171. wsSend_P(PSTR("{\"action\": \"reload\"}"));
  172. #endif
  173. deferredReset(100, CUSTOM_RESET_OTA);
  174. });
  175. ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  176. DEBUG_MSG_P(PSTR("[OTA] Progress: %u%%\r"), (progress / (total / 100)));
  177. });
  178. ArduinoOTA.onError([](ota_error_t error) {
  179. #if DEBUG_SUPPORT
  180. DEBUG_MSG_P(PSTR("\n[OTA] Error #%u: "), error);
  181. if (error == OTA_AUTH_ERROR) DEBUG_MSG_P(PSTR("Auth Failed\n"));
  182. else if (error == OTA_BEGIN_ERROR) DEBUG_MSG_P(PSTR("Begin Failed\n"));
  183. else if (error == OTA_CONNECT_ERROR) DEBUG_MSG_P(PSTR("Connect Failed\n"));
  184. else if (error == OTA_RECEIVE_ERROR) DEBUG_MSG_P(PSTR("Receive Failed\n"));
  185. else if (error == OTA_END_ERROR) DEBUG_MSG_P(PSTR("End Failed\n"));
  186. #endif
  187. });
  188. ArduinoOTA.begin();
  189. }