Teens41-Client.ino 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. Teensy41 Websockets Client (using NativeEthernet)
  3. This sketch:
  4. 1. Connects to a ethernet network
  5. 2. Connects to a websockets server at port 80
  6. 3. Sends the websockets server a message ("Hello Server")
  7. 4. Prints all incoming messages while the connection is open
  8. Note:
  9. Make sure you share your computer's internet connection with the Teensy
  10. via ethernet.
  11. Libraries:
  12. To use this sketch install
  13. * TeensyID library (https://github.com/sstaub/TeensyID)
  14. * NativeEthernet (https://github.com/vjmuzik/NativeEthernet)
  15. Hardware:
  16. For this sketch you need a Teensy 4.1 board and the Teensy 4.1 Ethernet Kit
  17. (https://www.pjrc.com/store/ethernet_kit.html).
  18. */
  19. #include <NativeEthernet.h>
  20. #include <ArduinoWebsockets.h>
  21. #include <TeensyID.h>
  22. #include <SPI.h>
  23. using namespace websockets;
  24. WebsocketsClient client;
  25. // We will set the MAC address at the beginning of `setup()` using TeensyID's
  26. // `teensyMac` helper.
  27. byte mac[6];
  28. // Enter websockets url.
  29. // Note: wss:// currently not working.
  30. const char* url = "ws://echo.websocket.org";
  31. void setup() {
  32. // Set the MAC address.
  33. teensyMAC(mac);
  34. // Start Serial and wait until it is ready.
  35. Serial.begin(9600);
  36. while (!Serial) {}
  37. // Connect to ethernet.
  38. if (Ethernet.begin(mac)) {
  39. Serial.print("Ethernet connected (");
  40. Serial.print(Ethernet.localIP());
  41. Serial.println(")");
  42. } else {
  43. Serial.println("Ethernet failed");
  44. }
  45. // Connect to websocket server.
  46. if (client.connect(url)) {
  47. Serial.printf("Connected to server %s\n", url);
  48. // Send welcome message.
  49. client.send("Hello Server");
  50. } else {
  51. Serial.println("Couldn't connect to server!");
  52. }
  53. // Run callback when messages are received.
  54. client.onMessage([&](WebsocketsMessage message) {
  55. Serial.print("Got Message: ");
  56. Serial.println(message.data());
  57. });
  58. }
  59. void loop() {
  60. // Check for incoming messages.
  61. if (client.available()) {
  62. client.poll();
  63. }
  64. }