WebServer.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <WebServer.h>
  2. #include <PatternHandler.h>
  3. void WebServer::onPattern(const String& pattern, const HTTPMethod method, PatternHandler::TPatternHandlerFn fn) {
  4. addHandler(new PatternHandler(pattern, method, fn));
  5. }
  6. void WebServer::requireAuthentication(const String& username, const String& password) {
  7. this->username = String(username);
  8. this->password = String(password);
  9. this->authEnabled = true;
  10. }
  11. void WebServer::disableAuthentication() {
  12. this->authEnabled = false;
  13. }
  14. void WebServer::_handleRequest() {
  15. if (this->authEnabled
  16. && !this->authenticate(this->username.c_str(), this->password.c_str())) {
  17. this->requestAuthentication();
  18. } else {
  19. ESP8266WebServer::_handleRequest();
  20. }
  21. }
  22. void WebServer::handleClient() {
  23. if (_currentStatus == HC_NONE) {
  24. WiFiClient client = _server.available();
  25. if (!client) {
  26. return;
  27. }
  28. _currentClient = client;
  29. _currentStatus = HC_WAIT_READ;
  30. _statusChange = millis();
  31. }
  32. if (!_currentClient.connected()) {
  33. _currentClient = WiFiClient();
  34. _currentStatus = HC_NONE;
  35. return;
  36. }
  37. // Wait for data from client to become available
  38. if (_currentStatus == HC_WAIT_READ) {
  39. if (!_currentClient.available()) {
  40. if (millis() - _statusChange > HTTP_MAX_DATA_WAIT) {
  41. _currentClient = WiFiClient();
  42. _currentStatus = HC_NONE;
  43. }
  44. yield();
  45. return;
  46. }
  47. if (!_parseRequest(_currentClient)) {
  48. _currentClient = WiFiClient();
  49. _currentStatus = HC_NONE;
  50. return;
  51. }
  52. _currentClient.setTimeout(HTTP_MAX_SEND_WAIT);
  53. _contentLength = CONTENT_LENGTH_NOT_SET;
  54. _handleRequest();
  55. if (!_currentClient.connected()) {
  56. _currentClient = WiFiClient();
  57. _currentStatus = HC_NONE;
  58. return;
  59. } else {
  60. _currentStatus = HC_WAIT_CLOSE;
  61. _statusChange = millis();
  62. return;
  63. }
  64. }
  65. if (_currentStatus == HC_WAIT_CLOSE) {
  66. if (millis() - _statusChange > HTTP_MAX_CLOSE_WAIT) {
  67. _currentClient = WiFiClient();
  68. _currentStatus = HC_NONE;
  69. } else {
  70. yield();
  71. return;
  72. }
  73. }
  74. }