regex_patterns.ino 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // A simple server implementation with regex routes:
  3. // * serve static messages
  4. // * read GET and POST parameters
  5. // * handle missing pages / 404s
  6. //
  7. // Add buildflag ASYNCWEBSERVER_REGEX to enable the regex support
  8. // For platformio: platformio.ini:
  9. // build_flags =
  10. // -DASYNCWEBSERVER_REGEX
  11. // For arduino IDE: create/update platform.local.txt
  12. // Windows: C:\Users\(username)\AppData\Local\Arduino15\packages\espxxxx\hardware\espxxxx\{version}\platform.local.txt
  13. // Linux: ~/.arduino15/packages/espxxxx/hardware/espxxxx/{version}/platform.local.txt
  14. //
  15. // compiler.cpp.extra_flags=-DASYNCWEBSERVER_REGEX=1
  16. #include <Arduino.h>
  17. #ifdef ESP32
  18. #include <WiFi.h>
  19. #include <AsyncTCP.h>
  20. #elif defined(ESP8266)
  21. #include <ESP8266WiFi.h>
  22. #include <ESPAsyncTCP.h>
  23. #endif
  24. #include <ESPAsyncWebServer.h>
  25. AsyncWebServer server(80);
  26. const char* ssid = "YOUR_SSID";
  27. const char* password = "YOUR_PASSWORD";
  28. const char* PARAM_MESSAGE = "message";
  29. void notFound(AsyncWebServerRequest *request) {
  30. request->send(404, "text/plain", "Not found");
  31. }
  32. void setup() {
  33. Serial.begin(115200);
  34. WiFi.mode(WIFI_STA);
  35. WiFi.begin(ssid, password);
  36. if (WiFi.waitForConnectResult() != WL_CONNECTED) {
  37. Serial.printf("WiFi Failed!\n");
  38. return;
  39. }
  40. Serial.print("IP Address: ");
  41. Serial.println(WiFi.localIP());
  42. server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  43. request->send(200, "text/plain", "Hello, world");
  44. });
  45. // Send a GET request to <IP>/sensor/<number>
  46. server.on("^\\/sensor\\/([0-9]+)$", HTTP_GET, [] (AsyncWebServerRequest *request) {
  47. String sensorNumber = request->pathArg(0);
  48. request->send(200, "text/plain", "Hello, sensor: " + sensorNumber);
  49. });
  50. // Send a GET request to <IP>/sensor/<number>/action/<action>
  51. server.on("^\\/sensor\\/([0-9]+)\\/action\\/([a-zA-Z0-9]+)$", HTTP_GET, [] (AsyncWebServerRequest *request) {
  52. String sensorNumber = request->pathArg(0);
  53. String action = request->pathArg(1);
  54. request->send(200, "text/plain", "Hello, sensor: " + sensorNumber + ", with action: " + action);
  55. });
  56. server.onNotFound(notFound);
  57. server.begin();
  58. }
  59. void loop() {
  60. }