* Setup for the web update. Register the authentication procedure and * binary file upload handler required to update the actual sketch binary by OTA. * @param server A pointer to the WebServer instance * @param path URI of the update handler * @param username Username for authentication * @arama password Password for authentication */
| 41 | * @arama password Password for authentication |
| 42 | */ |
| 43 | void HTTPUpdateServer::setup(WebServer* server, const String& path, const String& username, const String& password) { |
| 44 | _server = server; |
| 45 | _username = username; |
| 46 | _password = password; |
| 47 | |
| 48 | // handler for the /update form page |
| 49 | _server->on(path.c_str(), HTTP_GET, [&] () { |
| 50 | if (_username != _emptyString && _password != _emptyString && !_server->authenticate(_username.c_str(), _password.c_str())) |
| 51 | return _server->requestAuthentication(); |
| 52 | _server->send_P(200, PSTR("text/html"), serverIndex); |
| 53 | }); |
| 54 | |
| 55 | // handler for the /update form POST (once file upload finishes) |
| 56 | _server->on(path.c_str(), HTTP_POST, [&] () { |
| 57 | if(!_authenticated) |
| 58 | return _server->requestAuthentication(); |
| 59 | if (Update.hasError()) { |
| 60 | _server->send(200, F("text/html"), String(F("Update error: ")) + _updaterError); |
| 61 | } |
| 62 | else { |
| 63 | _server->client().setNoDelay(true); |
| 64 | _server->send_P(200, PSTR("text/html"), successResponse); |
| 65 | delay(100); |
| 66 | _server->client().stop(); |
| 67 | ESP.restart(); |
| 68 | } |
| 69 | }, [&] () { |
| 70 | // handler for the file upload, get's the sketch bytes, and writes |
| 71 | // them through the Update object |
| 72 | HTTPUpload& upload = _server->upload(); |
| 73 | |
| 74 | if (upload.status == UPLOAD_FILE_START) { |
| 75 | _updaterError = String(); |
| 76 | if (_serial_output) |
| 77 | Serial.setDebugOutput(true); |
| 78 | |
| 79 | _authenticated = (_username == _emptyString || _password == _emptyString || _server->authenticate(_username.c_str(), _password.c_str())); |
| 80 | if (!_authenticated) { |
| 81 | if (_serial_output) |
| 82 | Serial.println("Unauthenticated Update"); |
| 83 | return; |
| 84 | } |
| 85 | |
| 86 | if (_serial_output) |
| 87 | Serial.printf("Update: %s\n", upload.filename.c_str()); |
| 88 | uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; |
| 89 | if (!Update.begin(maxSketchSpace)) { //start with max available size |
| 90 | _setUpdaterError(); |
| 91 | } |
| 92 | } |
| 93 | else if (_authenticated && upload.status == UPLOAD_FILE_WRITE && !_updaterError.length()) { |
| 94 | if (_serial_output) |
| 95 | Serial.print('.'); |
| 96 | if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) |
| 97 | _setUpdaterError(); |
| 98 | } |
| 99 | else if (_authenticated && upload.status == UPLOAD_FILE_END && !_updaterError.length()) { |
| 100 | if (Update.end(true)) { //true to set the size to the current progress |