forked from me-no-dev/ESPAsyncWebServer
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathIssue162.ino
102 lines (87 loc) · 2.85 KB
/
Issue162.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// SPDX-License-Identifier: LGPL-3.0-or-later
// Copyright 2016-2025 Hristo Gochkov, Mathieu Carbou, Emil Muratov
/**
*
* Connect to AP and run in bash:
*
* > while true; do echo "PING"; sleep 0.1; done | websocat ws://192.168.4.1/ws
*
*/
#include <Arduino.h>
#ifdef ESP8266
#include <ESP8266WiFi.h>
#endif
#ifdef ESP32
#include <WiFi.h>
#endif
#include <ESPAsyncWebServer.h>
#include <list>
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
if (type == WS_EVT_CONNECT) {
Serial.printf("Client #%" PRIu32 " connected.\n", client->id());
} else if (type == WS_EVT_DISCONNECT) {
Serial.printf("Client #%" PRIu32 " disconnected.\n", client->id());
} else if (type == WS_EVT_ERROR) {
Serial.printf("Client #%" PRIu32 " error.\n", client->id());
} else if (type == WS_EVT_DATA) {
Serial.printf("Client #%" PRIu32 " len: %u\n", client->id(), len);
} else if (type == WS_EVT_PONG) {
Serial.printf("Client #%" PRIu32 " pong.\n", client->id());
} else if (type == WS_EVT_PING) {
Serial.printf("Client #%" PRIu32 " ping.\n", client->id());
}
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_AP);
WiFi.softAP("esp-captive");
ws.onEvent(onWsEvent);
server.addHandler(&ws);
server.on("/close_all_ws_clients", HTTP_GET | HTTP_POST, [](AsyncWebServerRequest *request) {
Serial.println("Closing all WebSocket clients...");
ws.closeAll();
request->send(200, "application/json", "{\"status\":\"all clients closed\"}");
});
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(200, "text/html", R"rawliteral(
<!DOCTYPE html>
<html>
<head></head>
<script>
let ws = new WebSocket("ws://" + window.location.host + "/ws");
ws.addEventListener("open", (e) => {
console.log("WebSocket connected", e);
});
ws.addEventListener("error", (e) => {
console.log("WebSocket error", e);
});
ws.addEventListener("close", (e) => {
console.log("WebSocket close", e);
});
ws.addEventListener("message", (e) => {
console.log("WebSocket message", e);
});
function closeAllWsClients() {
fetch("/close_all_ws_clients", {
method : "POST",
});
};
</script>
<body>
<button onclick = "closeAllWsClients()" style = "width: 200px"> ws close all</button><p></p>
</body>
</html>
)rawliteral");
});
server.begin();
}
uint32_t lastTime = 0;
void loop() {
if (millis() - lastTime > 5000) {
lastTime = millis();
Serial.printf("Client count: %u\n", ws.count());
}
ws.cleanupClients();
}