|
| 1 | +/* |
| 2 | + Simple WebSocket client for ArduinoHttpClient library |
| 3 | + Connects to the WebSocket server, and sends a hello |
| 4 | + message every 5 seconds |
| 5 | +
|
| 6 | + note: WiFi SSID and password are stored in config.h file. |
| 7 | + If it is not present, add a new tab, call it "config.h" |
| 8 | + and add the following variables: |
| 9 | + char ssid[] = "ssid"; // your network SSID (name) |
| 10 | + char pass[] = "password"; // your network password |
| 11 | +
|
| 12 | + created 28 Jun 2016 |
| 13 | + by Sandeep Mistry |
| 14 | +
|
| 15 | + this example is in the public domain |
| 16 | +*/ |
| 17 | +#include <ArduinoHttpClient.h> |
| 18 | +#include <WiFi101.h> |
| 19 | +#include "config.h" |
| 20 | + |
| 21 | +char serverAddress[] = "echo.websocket.org"; // server address |
| 22 | +int port = 80; |
| 23 | + |
| 24 | +WiFiClient wifi; |
| 25 | +WebSocketClient client = WebSocketClient(wifi, serverAddress, port); |
| 26 | +int status = WL_IDLE_STATUS; |
| 27 | +int count = 0; |
| 28 | + |
| 29 | +void setup() { |
| 30 | + Serial.begin(9600); |
| 31 | + while ( status != WL_CONNECTED) { |
| 32 | + Serial.print("Attempting to connect to Network named: "); |
| 33 | + Serial.println(ssid); // print the network name (SSID); |
| 34 | + |
| 35 | + // Connect to WPA/WPA2 network: |
| 36 | + status = WiFi.begin(ssid, pass); |
| 37 | + } |
| 38 | + |
| 39 | + // print the SSID of the network you're attached to: |
| 40 | + Serial.print("SSID: "); |
| 41 | + Serial.println(WiFi.SSID()); |
| 42 | + |
| 43 | + // print your WiFi shield's IP address: |
| 44 | + IPAddress ip = WiFi.localIP(); |
| 45 | + Serial.print("IP Address: "); |
| 46 | + Serial.println(ip); |
| 47 | +} |
| 48 | + |
| 49 | +void loop() { |
| 50 | + Serial.println("starting WebSocket client"); |
| 51 | + client.begin(); |
| 52 | + |
| 53 | + while (client.connected()) { |
| 54 | + Serial.print("Sending hello "); |
| 55 | + Serial.println(count); |
| 56 | + |
| 57 | + // send a hello # |
| 58 | + client.beginMessage(TYPE_TEXT); |
| 59 | + client.print("hello "); |
| 60 | + client.print(count); |
| 61 | + client.endMessage(); |
| 62 | + |
| 63 | + // increment count for next message |
| 64 | + count++; |
| 65 | + |
| 66 | + // check if a message is available to be received |
| 67 | + int messageSize = client.parseMessage(); |
| 68 | + |
| 69 | + if (messageSize > 0) { |
| 70 | + Serial.println("Received a message:"); |
| 71 | + Serial.println(client.readString()); |
| 72 | + } |
| 73 | + |
| 74 | + // wait 5 seconds |
| 75 | + delay(5000); |
| 76 | + } |
| 77 | + |
| 78 | + Serial.println("disconnected"); |
| 79 | +} |
| 80 | + |
0 commit comments