|
| 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 | + |
| 8 | +#include <Arduino.h> |
| 9 | +#ifdef ESP32 |
| 10 | +#include <WiFi.h> |
| 11 | +#include <AsyncTCP.h> |
| 12 | +#elif defined(ESP8266) |
| 13 | +#include <ESP8266WiFi.h> |
| 14 | +#include <ESPAsyncTCP.h> |
| 15 | +#endif |
| 16 | +#include <ESPAsyncWebServer.h> |
| 17 | + |
| 18 | +AsyncWebServer server(80); |
| 19 | + |
| 20 | +const char* ssid = "YOUR_SSID"; |
| 21 | +const char* password = "YOUR_PASSWORD"; |
| 22 | + |
| 23 | +const char* PARAM_MESSAGE = "message"; |
| 24 | + |
| 25 | +void notFound(AsyncWebServerRequest *request) { |
| 26 | + request->send(404, "text/plain", "Not found"); |
| 27 | +} |
| 28 | + |
| 29 | +void setup() { |
| 30 | + |
| 31 | + Serial.begin(115200); |
| 32 | + WiFi.mode(WIFI_STA); |
| 33 | + WiFi.begin(ssid, password); |
| 34 | + if (WiFi.waitForConnectResult() != WL_CONNECTED) { |
| 35 | + Serial.printf("WiFi Failed!\n"); |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + Serial.print("IP Address: "); |
| 40 | + Serial.println(WiFi.localIP()); |
| 41 | + |
| 42 | + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ |
| 43 | + request->send(200, "text/plain", "Hello, world"); |
| 44 | + }); |
| 45 | + |
| 46 | + // Send a GET request to <IP>/sensor/<number> |
| 47 | + server.on("^\\/sensor\\/([0-9]+)$", HTTP_GET, [] (AsyncWebServerRequest *request) { |
| 48 | + String sensorNumber = request->pathArg(0); |
| 49 | + request->send(200, "text/plain", "Hello, sensor: " + sensorNumber); |
| 50 | + }); |
| 51 | + |
| 52 | + // Send a GET request to <IP>/sensor/<number>/action/<action> |
| 53 | + server.on("^\\/sensor\\/([0-9]+)\\/action\//([a-zA-Z0-9]+)$", HTTP_GET, [] (AsyncWebServerRequest *request) { |
| 54 | + String sensorNumber = request->pathArg(0); |
| 55 | + String action = request->pathArg(1); |
| 56 | + request->send(200, "text/plain", "Hello, sensor: " + sensorNumber + ", with action: " + action); |
| 57 | + }); |
| 58 | + |
| 59 | + server.onNotFound(notFound); |
| 60 | + |
| 61 | + server.begin(); |
| 62 | +} |
| 63 | + |
| 64 | +void loop() { |
| 65 | +} |
0 commit comments