WebSocketClient.ino 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /*
  2. * WebSocketClient.ino
  3. *
  4. * Created on: 24.05.2015
  5. *
  6. */
  7. #include <Arduino.h>
  8. #include <WiFi.h>
  9. #include <WiFiMulti.h>
  10. #include <WiFiClientSecure.h>
  11. #include <WebSocketsClient.h>
  12. WiFiMulti WiFiMulti;
  13. WebSocketsClient webSocket;
  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(WStype_t type, uint8_t * payload, size_t length) {
  28. switch(type) {
  29. case WStype_DISCONNECTED:
  30. USE_SERIAL.printf("[WSc] Disconnected!\n");
  31. break;
  32. case WStype_CONNECTED:
  33. USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
  34. // send message to server when Connected
  35. webSocket.sendTXT("Connected");
  36. break;
  37. case WStype_TEXT:
  38. USE_SERIAL.printf("[WSc] get text: %s\n", payload);
  39. // send message to server
  40. // webSocket.sendTXT("message here");
  41. break;
  42. case WStype_BIN:
  43. USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
  44. hexdump(payload, length);
  45. // send data to server
  46. // webSocket.sendBIN(payload, length);
  47. break;
  48. case WStype_ERROR:
  49. case WStype_FRAGMENT_TEXT_START:
  50. case WStype_FRAGMENT_BIN_START:
  51. case WStype_FRAGMENT:
  52. case WStype_FRAGMENT_FIN:
  53. break;
  54. }
  55. }
  56. void setup() {
  57. // USE_SERIAL.begin(921600);
  58. USE_SERIAL.begin(115200);
  59. //Serial.setDebugOutput(true);
  60. USE_SERIAL.setDebugOutput(true);
  61. USE_SERIAL.println();
  62. USE_SERIAL.println();
  63. USE_SERIAL.println();
  64. for(uint8_t t = 4; t > 0; t--) {
  65. USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
  66. USE_SERIAL.flush();
  67. delay(1000);
  68. }
  69. WiFiMulti.addAP("SSID", "passpasspass");
  70. //WiFi.disconnect();
  71. while(WiFiMulti.run() != WL_CONNECTED) {
  72. delay(100);
  73. }
  74. // server address, port and URL
  75. webSocket.begin("192.168.0.123", 81, "/");
  76. // event handler
  77. webSocket.onEvent(webSocketEvent);
  78. // use HTTP Basic Authorization this is optional remove if not needed
  79. webSocket.setAuthorization("user", "Password");
  80. // try ever 5000 again if connection has failed
  81. webSocket.setReconnectInterval(5000);
  82. }
  83. void loop() {
  84. webSocket.loop();
  85. }