I used this code to connect Arduino MKR1000 with API(server) using a websocket via WiFi.
#include <WiFi101.h>
#include <WebSocketClient.h>
const char* ssid = "********";
const char* password = "********";
char path[] = "/";
char host[] = "wss://echo.websocket.org";
WebSocketClient webSocketClient;
WiFiClient client;
void setup() {
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
delay(5000);
// Connect to the websocket server
if (client.connect("wss://echo.websocket.org", 443)) {
Serial.println("Connected");
} else {
Serial.println("Connection failed.");
while (1) {
// Hang on failure
}
}
// Handshake with the server
webSocketClient.path = path;
webSocketClient.host = host;
if (webSocketClient.handshake(client)) {
Serial.println("Handshake successful");
} else {
Serial.println("Handshake failed.");
while (1) {
// Hang on failure
}
}
}
void loop() {
String data;
if (client.connected()) {
webSocketClient.getData(data);
if (data.length() > 0) {
Serial.print("Received data: ");
Serial.println(data);
}
// capture the value of analog 9, send it along
pinMode(9, INPUT);
data = String(digitalRead(9));
webSocketClient.sendData(data);
} else {
Serial.println("Client disconnected.");
while (1) {
// Hang on disconnect.
}
}
// wait to fully let the client disconnect
delay(3000);
}
And It always gives me this output:
WiFi connected
IP Address: 192.168.2.149
Connected
Waiting...
Waiting...
Handshake failed.