WebServer.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. Serial.println(this->username);
  18. Serial.println(this->password);
  19. this->requestAuthentication();
  20. } else {
  21. ESP8266WebServer::_handleRequest();
  22. }
  23. }
  24. void WebServer::handleClient() {
  25. if (_currentStatus == HC_NONE) {
  26. WiFiClient client = _server.available();
  27. if (!client) {
  28. return;
  29. }
  30. _currentClient = client;
  31. _currentStatus = HC_WAIT_READ;
  32. _statusChange = millis();
  33. }
  34. if (!_currentClient.connected()) {
  35. _currentClient = WiFiClient();
  36. _currentStatus = HC_NONE;
  37. return;
  38. }
  39. // Wait for data from client to become available
  40. if (_currentStatus == HC_WAIT_READ) {
  41. if (!_currentClient.available()) {
  42. if (millis() - _statusChange > HTTP_MAX_DATA_WAIT) {
  43. _currentClient = WiFiClient();
  44. _currentStatus = HC_NONE;
  45. }
  46. yield();
  47. return;
  48. }
  49. if (!_parseRequest(_currentClient)) {
  50. _currentClient = WiFiClient();
  51. _currentStatus = HC_NONE;
  52. return;
  53. }
  54. _currentClient.setTimeout(HTTP_MAX_SEND_WAIT);
  55. _contentLength = CONTENT_LENGTH_NOT_SET;
  56. _handleRequest();
  57. if (!_currentClient.connected()) {
  58. _currentClient = WiFiClient();
  59. _currentStatus = HC_NONE;
  60. return;
  61. } else {
  62. _currentStatus = HC_WAIT_CLOSE;
  63. _statusChange = millis();
  64. return;
  65. }
  66. }
  67. if (_currentStatus == HC_WAIT_CLOSE) {
  68. if (millis() - _statusChange > HTTP_MAX_CLOSE_WAIT) {
  69. _currentClient = WiFiClient();
  70. _currentStatus = HC_NONE;
  71. } else {
  72. yield();
  73. return;
  74. }
  75. }
  76. }