WebSocketServer.ino 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * WebSocketServer.ino
  3. *
  4. * Created on: 22.05.2015
  5. *
  6. */
  7. #include <Arduino.h>
  8. #include <WiFi.h>
  9. #include <WiFiMulti.h>
  10. #include <WiFiClientSecure.h>
  11. #include <WebSocketsServer.h>
  12. WiFiMulti WiFiMulti;
  13. WebSocketsServer webSocket = WebSocketsServer(81);
  14. #define USE_SERIAL Serial1
  15. void hexdump(const void *mem, uint32_t len, uint8_t cols = 16) {
  16. const uint8_t* src = (const uint8_t*) mem;
  17. USE_SERIAL.printf("\n[HEXDUMP] Address: 0x%08X len: 0x%X (%d)", (ptrdiff_t)src, len, len);
  18. for(uint32_t i = 0; i < len; i++) {
  19. if(i % cols == 0) {
  20. USE_SERIAL.printf("\n[0x%08X] 0x%08X: ", (ptrdiff_t)src, i);
  21. }
  22. USE_SERIAL.printf("%02X ", *src);
  23. src++;
  24. }
  25. USE_SERIAL.printf("\n");
  26. }
  27. void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
  28. switch(type) {
  29. case WStype_DISCONNECTED:
  30. USE_SERIAL.printf("[%u] Disconnected!\n", num);
  31. break;
  32. case WStype_CONNECTED:
  33. {
  34. IPAddress ip = webSocket.remoteIP(num);
  35. USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
  36. // send message to client
  37. webSocket.sendTXT(num, "Connected");
  38. }
  39. break;
  40. case WStype_TEXT:
  41. USE_SERIAL.printf("[%u] get Text: %s\n", num, payload);
  42. // send message to client
  43. // webSocket.sendTXT(num, "message here");
  44. // send data to all connected clients
  45. // webSocket.broadcastTXT("message here");
  46. break;
  47. case WStype_BIN:
  48. USE_SERIAL.printf("[%u] get binary length: %u\n", num, length);
  49. hexdump(payload, length);
  50. // send message to client
  51. // webSocket.sendBIN(num, payload, length);
  52. break;
  53. case WStype_ERROR:
  54. case WStype_FRAGMENT_TEXT_START:
  55. case WStype_FRAGMENT_BIN_START:
  56. case WStype_FRAGMENT:
  57. case WStype_FRAGMENT_FIN:
  58. break;
  59. }
  60. }
  61. void setup() {
  62. // USE_SERIAL.begin(921600);
  63. USE_SERIAL.begin(115200);
  64. //Serial.setDebugOutput(true);
  65. USE_SERIAL.setDebugOutput(true);
  66. USE_SERIAL.println();
  67. USE_SERIAL.println();
  68. USE_SERIAL.println();
  69. for(uint8_t t = 4; t > 0; t--) {
  70. USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
  71. USE_SERIAL.flush();
  72. delay(1000);
  73. }
  74. WiFiMulti.addAP("SSID", "passpasspass");
  75. while(WiFiMulti.run() != WL_CONNECTED) {
  76. delay(100);
  77. }
  78. webSocket.begin();
  79. webSocket.onEvent(webSocketEvent);
  80. }
  81. void loop() {
  82. webSocket.loop();
  83. }