WebSocketClient_Demo.ino 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #include <SPI.h>
  2. #include <SC16IS750.h>
  3. #include <WiFly.h>
  4. // Here we define a maximum framelength to 64 bytes. Default is 256.
  5. #define MAX_FRAME_LENGTH 64
  6. // Define how many callback functions you have. Default is 1.
  7. #define CALLBACK_FUNCTIONS 1
  8. #include <WebSocketClient.h>
  9. WiFlyClient client = WiFlyClient();
  10. WebSocketClient webSocketClient;
  11. void setup() {
  12. Serial.begin(9600);
  13. SC16IS750.begin();
  14. WiFly.setUart(&SC16IS750);
  15. WiFly.begin();
  16. // This is for an unsecured network
  17. // For a WPA1/2 network use auth 3, and in another command send 'set wlan phrase PASSWORD'
  18. // For a WEP network use auth 2, and in another command send 'set wlan key KEY'
  19. WiFly.sendCommand(F("set wlan auth 1"));
  20. WiFly.sendCommand(F("set wlan channel 0"));
  21. WiFly.sendCommand(F("set ip dhcp 1"));
  22. Serial.println(F("Joining WiFi network..."));
  23. // Here is where you set the network name to join
  24. if (!WiFly.sendCommand(F("join arduino_wifi"), "Associated!", 20000, false)) {
  25. Serial.println(F("Association failed."));
  26. while (1) {
  27. // Hang on failure.
  28. }
  29. }
  30. if (!WiFly.waitForResponse("DHCP in", 10000)) {
  31. Serial.println(F("DHCP failed."));
  32. while (1) {
  33. // Hang on failure.
  34. }
  35. }
  36. // This is how you get the local IP as an IPAddress object
  37. Serial.println(WiFly.localIP());
  38. // This delay is needed to let the WiFly respond properly
  39. delay(100);
  40. // Connect to the websocket server
  41. if (client.connect("echo.websocket.org", 80)) {
  42. Serial.println("Connected");
  43. } else {
  44. Serial.println("Connection failed.");
  45. while(1) {
  46. // Hang on failure
  47. }
  48. }
  49. // Handshake with the server
  50. webSocketClient.path = "/";
  51. webSocketClient.host = "echo.websocket.org";
  52. if (webSocketClient.handshake(client)) {
  53. Serial.println("Handshake successful");
  54. } else {
  55. Serial.println("Handshake failed.");
  56. while(1) {
  57. // Hang on failure
  58. }
  59. }
  60. }
  61. void loop() {
  62. String data;
  63. if (client.connected()) {
  64. webSocketClient.getData(data);
  65. if (data.length() > 0) {
  66. Serial.print("Received data: ");
  67. Serial.println(data);
  68. }
  69. // capture the value of analog 1, send it along
  70. pinMode(1, INPUT);
  71. data = String(analogRead(1));
  72. webSocketClient.sendData(data);
  73. } else {
  74. Serial.println("Client disconnected.");
  75. while (1) {
  76. // Hang on disconnect.
  77. }
  78. }
  79. // wait to fully let the client disconnect
  80. delay(3000);
  81. }