Created
October 10, 2023 13:59
-
-
Save venetanji/63bae1f96c65a79b4e88ee57142905cf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Esp8266 Websockets Client | |
This sketch: | |
1. Connects to a WiFi network | |
2. Connects to a Websockets server | |
3. Sends the websockets server a message ("Hello Server") | |
4. Prints all incoming messages while the connection is open | |
Hardware: | |
For this sketch you only need an ESP8266 board. | |
Created 15/02/2019 | |
By Gil Maimon | |
https://github.com/gilmaimon/ArduinoWebsockets | |
*/ | |
#include <ArduinoWebsockets.h> | |
#include <ESP8266WiFi.h> | |
const char* ssid = "xxxxxxx"; //Enter SSID | |
const char* password = "xxxxxxx"; //Enter Password | |
const char* websockets_server_host = "xxx.xxx.xxx.xxx"; //Enter server adress | |
const uint16_t websockets_server_port = 1880; // Enter server port | |
using namespace websockets; | |
WebsocketsClient client; | |
void setup() { | |
Serial.begin(9600); | |
// Connect to wifi | |
WiFi.begin(ssid, password); | |
// Wait some time to connect to wifi | |
for(int i = 0; i < 30 && WiFi.status() != WL_CONNECTED; i++) { | |
Serial.print("."); | |
delay(1000); | |
} | |
// Check if connected to wifi | |
if(WiFi.status() != WL_CONNECTED) { | |
Serial.println("No Wifi!"); | |
return; | |
} | |
Serial.println("Connected to Wifi, Connecting to server."); | |
// try to connect to Websockets server | |
bool connected = client.connect(websockets_server_host, websockets_server_port, "/"); | |
if(connected) { | |
Serial.println("Connecetd!"); | |
client.send("Hello Server"); | |
} else { | |
Serial.println("Not Connected!"); | |
} | |
client.onMessage([](WebsocketsMessage msg){ | |
Serial.println(msg.data()); | |
}); | |
} | |
String c; | |
void loop() { | |
client.poll(); | |
if (Serial.available() > 0) { // if serial is available | |
c = Serial.readStringUntil('\n'); // get the last string from the serial | |
client.send(c.substring(0, c.length() - 1)); // trim the new line and send to the websocket | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment