| 2 |
raymond |
1 |
#include <ESP8266WiFi.h>
|
|
|
2 |
#include <ESPAsyncTCP.h>
|
|
|
3 |
#include <DNSServer.h>
|
|
|
4 |
#include <vector>
|
|
|
5 |
|
|
|
6 |
#include "config.h"
|
|
|
7 |
|
|
|
8 |
static DNSServer DNS;
|
|
|
9 |
|
|
|
10 |
static std::vector<AsyncClient*> clients; // a list to hold all clients
|
|
|
11 |
|
|
|
12 |
/* clients events */
|
|
|
13 |
static void handleError(void* arg, AsyncClient* client, int8_t error) {
|
|
|
14 |
Serial.printf("\n connection error %s from client %s \n", client->errorToString(error), client->remoteIP().toString().c_str());
|
|
|
15 |
}
|
|
|
16 |
|
|
|
17 |
static void handleData(void* arg, AsyncClient* client, void *data, size_t len) {
|
|
|
18 |
Serial.printf("\n data received from client %s \n", client->remoteIP().toString().c_str());
|
|
|
19 |
Serial.write((uint8_t*)data, len);
|
|
|
20 |
|
|
|
21 |
// reply to client
|
|
|
22 |
if (client->space() > 32 && client->canSend()) {
|
|
|
23 |
char reply[32];
|
|
|
24 |
sprintf(reply, "this is from %s", SERVER_HOST_NAME);
|
|
|
25 |
client->add(reply, strlen(reply));
|
|
|
26 |
client->send();
|
|
|
27 |
}
|
|
|
28 |
}
|
|
|
29 |
|
|
|
30 |
static void handleDisconnect(void* arg, AsyncClient* client) {
|
|
|
31 |
Serial.printf("\n client %s disconnected \n", client->remoteIP().toString().c_str());
|
|
|
32 |
}
|
|
|
33 |
|
|
|
34 |
static void handleTimeOut(void* arg, AsyncClient* client, uint32_t time) {
|
|
|
35 |
Serial.printf("\n client ACK timeout ip: %s \n", client->remoteIP().toString().c_str());
|
|
|
36 |
}
|
|
|
37 |
|
|
|
38 |
|
|
|
39 |
/* server events */
|
|
|
40 |
static void handleNewClient(void* arg, AsyncClient* client) {
|
|
|
41 |
Serial.printf("\n new client has been connected to server, ip: %s", client->remoteIP().toString().c_str());
|
|
|
42 |
|
|
|
43 |
// add to list
|
|
|
44 |
clients.push_back(client);
|
|
|
45 |
|
|
|
46 |
// register events
|
|
|
47 |
client->onData(&handleData, NULL);
|
|
|
48 |
client->onError(&handleError, NULL);
|
|
|
49 |
client->onDisconnect(&handleDisconnect, NULL);
|
|
|
50 |
client->onTimeout(&handleTimeOut, NULL);
|
|
|
51 |
}
|
|
|
52 |
|
|
|
53 |
void setup() {
|
|
|
54 |
Serial.begin(115200);
|
|
|
55 |
delay(20);
|
|
|
56 |
|
|
|
57 |
// create access point
|
|
|
58 |
while (!WiFi.softAP(SSID, PASSWORD, 6, false, 15)) {
|
|
|
59 |
delay(500);
|
|
|
60 |
}
|
|
|
61 |
|
|
|
62 |
// start dns server
|
|
|
63 |
if (!DNS.start(DNS_PORT, SERVER_HOST_NAME, WiFi.softAPIP()))
|
|
|
64 |
Serial.printf("\n failed to start dns service \n");
|
|
|
65 |
|
|
|
66 |
AsyncServer* server = new AsyncServer(TCP_PORT); // start listening on tcp port 7050
|
|
|
67 |
server->onClient(&handleNewClient, server);
|
|
|
68 |
server->begin();
|
|
|
69 |
}
|
|
|
70 |
|
|
|
71 |
void loop() {
|
|
|
72 |
DNS.processNextRequest();
|
|
|
73 |
}
|