能源管控程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

74 lines
2.0 KiB

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