Secured-Esp8266-Client.ino 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. Secured Esp8266 Websockets Client
  3. This sketch:
  4. 1. Connects to a WiFi network
  5. 2. Connects to a Websockets server (using WSS)
  6. 3. Sends the websockets server a message ("Hello Server")
  7. 4. Sends the websocket server a "ping"
  8. 5. Prints all incoming messages while the connection is open
  9. NOTE:
  10. The sketch dosen't check or indicate about errors while connecting to
  11. WiFi or to the websockets server. For full example you might want
  12. to try the example named "Esp8266-Client" (And use the ssl methods).
  13. Hardware:
  14. For this sketch you only need an ESP8266 board.
  15. Created 15/02/2019
  16. By Gil Maimon
  17. https://github.com/gilmaimon/ArduinoWebsockets
  18. */
  19. #include <ArduinoWebsockets.h>
  20. #include <ESP8266WiFi.h>
  21. const char* ssid = "ssid"; //Enter SSID
  22. const char* password = "password"; //Enter Password
  23. const char* websockets_connection_string = "wss://echo.websocket.org/"; //Enter server adress
  24. // This fingerprint was updated 20.04.2019
  25. const char echo_org_ssl_fingerprint[] PROGMEM = "E0 E7 13 AE F4 38 0F 7F 22 39 5C 32 B3 16 EC BB 95 F3 0B 5B";
  26. using namespace websockets;
  27. void onMessageCallback(WebsocketsMessage message) {
  28. Serial.print("Got Message: ");
  29. Serial.println(message.data());
  30. }
  31. void onEventsCallback(WebsocketsEvent event, String data) {
  32. if(event == WebsocketsEvent::ConnectionOpened) {
  33. Serial.println("Connnection Opened");
  34. } else if(event == WebsocketsEvent::ConnectionClosed) {
  35. Serial.println("Connnection Closed");
  36. } else if(event == WebsocketsEvent::GotPing) {
  37. Serial.println("Got a Ping!");
  38. } else if(event == WebsocketsEvent::GotPong) {
  39. Serial.println("Got a Pong!");
  40. }
  41. }
  42. WebsocketsClient client;
  43. void setup() {
  44. Serial.begin(115200);
  45. // Connect to wifi
  46. WiFi.begin(ssid, password);
  47. // Wait some time to connect to wifi
  48. for(int i = 0; i < 10 && WiFi.status() != WL_CONNECTED; i++) {
  49. Serial.print(".");
  50. delay(1000);
  51. }
  52. // run callback when messages are received
  53. client.onMessage(onMessageCallback);
  54. // run callback when events are occuring
  55. client.onEvent(onEventsCallback);
  56. // Before connecting, set the ssl fingerprint of the server
  57. client.setFingerprint(echo_org_ssl_fingerprint);
  58. // Connect to server
  59. client.connect(websockets_connection_string);
  60. // Send a message
  61. client.send("Hello Server");
  62. // Send a ping
  63. client.ping();
  64. }
  65. void loop() {
  66. client.poll();
  67. }