#include <WiFi.h>
#include <WiFiClient.h>
#include "String.h"
#include <WebSocketClient.h>
WebSocketClient webSocketClient;
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Defining the WiFi channel speeds up the connection:
#define WIFI_CHANNEL 6
void onMessageCallback(WebsocketsMessage message) {
Serial.print("Got Message: ");
Serial.println(message.data());
}
void onEventsCallback(WebsocketsEvent event, String data) {
if(event == WebsocketsEvent::ConnectionOpened) {
Serial.println("Connnection Opened");
} else if(event == WebsocketsEvent::ConnectionClosed) {
Serial.println("Connnection Closed");
} else if(event == WebsocketsEvent::GotPing) {
Serial.println("Got a Ping!");
} else if(event == WebsocketsEvent::GotPong) {
Serial.println("Got a Pong!");
}
}
WebsocketsClient client;
void setup(void) {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connecting to WiFi ");
Serial.print(WIFI_SSID);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Connect to the websocket server
if (client.connect("https://0177-41-191-200-134.ngrok-free.app")) {
Serial.println("Connected");
} else {
Serial.println("Connection failed.");
while(1) {
// Hang on failure
}
}
// Handshake with the server
webSocketClient.path = "/";
webSocketClient.host = "https://0177-41-191-200-134.ngrok-free.app";
if (webSocketClient.handshake(client, true)) {
Serial.println("Handshake successful");
// socket.io upgrade confirmation message (required)
webSocketClient.sendData("5");
} 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);
}
uint64_t now = millis();
if(now - messageTimestamp > MESSAGE_INTERVAL) {
messageTimestamp = now;
// capture the value of analog 1, send it along
// example socket.io message with type "messageType" and JSON payload
char message[128];
sprintf(message, "42[\"messageType\",{\"data\":\"%s\"}]", data.c_str());
webSocket.sendData(message);
}
if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
heartbeatTimestamp = now;
// socket.io heartbeat message
webSocket.sendData("2");
}
} else {
Serial.println("Client disconnected.");
while (1) {
// Hang on disconnect.
}
}
// wait to fully let the client disconnect
delay(3000);
}