WebSocketClient.ino 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * WebSocketClient.ino
  3. *
  4. * Created on: 24.05.2015
  5. *
  6. */
  7. #include <Arduino.h>
  8. #include <ESP8266WiFi.h>
  9. #include <ESP8266WiFiMulti.h>
  10. #include <WebSocketsClient.h>
  11. #include <Hash.h>
  12. ESP8266WiFiMulti WiFiMulti;
  13. WebSocketsClient webSocket;
  14. #define USE_SERIAL Serial1
  15. void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
  16. switch(type) {
  17. case WStype_DISCONNECTED:
  18. USE_SERIAL.printf("[WSc] Disconnected!\n");
  19. break;
  20. case WStype_CONNECTED: {
  21. USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
  22. // send message to server when Connected
  23. webSocket.sendTXT("Connected");
  24. }
  25. break;
  26. case WStype_TEXT:
  27. USE_SERIAL.printf("[WSc] get text: %s\n", payload);
  28. // send message to server
  29. // webSocket.sendTXT("message here");
  30. break;
  31. case WStype_BIN:
  32. USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
  33. hexdump(payload, length);
  34. // send data to server
  35. // webSocket.sendBIN(payload, length);
  36. break;
  37. case WStype_PING:
  38. // pong will be send automatically
  39. USE_SERIAL.printf("[WSc] get ping\n");
  40. break;
  41. case WStype_PONG:
  42. // answer to a ping we send
  43. USE_SERIAL.printf("[WSc] get pong\n");
  44. break;
  45. }
  46. }
  47. void setup() {
  48. // USE_SERIAL.begin(921600);
  49. USE_SERIAL.begin(115200);
  50. //Serial.setDebugOutput(true);
  51. USE_SERIAL.setDebugOutput(true);
  52. USE_SERIAL.println();
  53. USE_SERIAL.println();
  54. USE_SERIAL.println();
  55. for(uint8_t t = 4; t > 0; t--) {
  56. USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
  57. USE_SERIAL.flush();
  58. delay(1000);
  59. }
  60. WiFiMulti.addAP("SSID", "passpasspass");
  61. //WiFi.disconnect();
  62. while(WiFiMulti.run() != WL_CONNECTED) {
  63. delay(100);
  64. }
  65. // server address, port and URL
  66. webSocket.begin("192.168.0.123", 81, "/");
  67. // event handler
  68. webSocket.onEvent(webSocketEvent);
  69. // use HTTP Basic Authorization this is optional remove if not needed
  70. webSocket.setAuthorization("user", "Password");
  71. // try ever 5000 again if connection has failed
  72. webSocket.setReconnectInterval(5000);
  73. // start heartbeat (optional)
  74. // ping server every 15000 ms
  75. // expect pong from server within 3000 ms
  76. // consider connection disconnected if pong is not received 2 times
  77. webSocket.enableHeartbeat(15000, 3000, 2);
  78. }
  79. void loop() {
  80. webSocket.loop();
  81. }