Created
October 5, 2019 17:31
-
-
Save ShivamJoker/a19ee9d4072876b3d01cfe2cae1e6cb0 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
/* | |
Minimal Esp8266 Websockets Server | |
This sketch: | |
1. Connects to a WiFi network | |
2. Starts a websocket server on port 80 | |
3. Waits for connections | |
4. Once a client connects, it wait for a message from the client | |
5. Sends an "echo" message to the client | |
6. closes the connection and goes back to step 3 | |
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> | |
#include <EasyButton.h> | |
#define BUTTON_CENTER_PIN 4 | |
EasyButton buttonCenter(BUTTON_CENTER_PIN); | |
const char* ssid = "Shivam-Fi"; //Enter SSID | |
const char* password = "1433hacker"; //Enter Password | |
using namespace websockets; | |
WebsocketsServer server; | |
WebsocketsClient* global_client; //pointer to a client | |
void onButtonCenterPressed() { | |
Serial.println("Button center has been pressed!"); | |
global_client->send("center_click"); | |
} | |
#define BUTTON_PIN 15 | |
// Instance of the button. | |
EasyButton button(BUTTON_PIN); | |
void onPressed() { | |
Serial.println("Button has been pressed!"); | |
} | |
void setup() { | |
Serial.begin(115200); | |
buttonCenter.begin(); | |
// Add the callback function to be called when the button1 is pressed. | |
buttonCenter.onPressed(onButtonCenterPressed); | |
button.begin(); | |
// Add the callback function to be called when the button is pressed. | |
button.onPressed(onPressed); | |
// Connect to wifi | |
WiFi.begin(ssid, password); | |
// Wait some time to connect to wifi | |
for(int i = 0; i < 15 && WiFi.status() != WL_CONNECTED; i++) { | |
Serial.print("."); | |
delay(1000); | |
} | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.println("IP address: "); | |
Serial.println(WiFi.localIP()); //You can get IP address assigned to ESP | |
server.listen(80); | |
Serial.print("Is server live? "); | |
Serial.println(server.available()); | |
} | |
void loop() { | |
WebsocketsClient client = server.accept(); | |
global_client = &client; | |
buttonCenter.read(); | |
button.read(); | |
if(client.available()) { | |
WebsocketsMessage msg = client.readBlocking(); | |
// log | |
Serial.print("Got Message: "); | |
Serial.println(msg.data()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment