Last active
February 28, 2018 20:27
-
-
Save Shashi18/838015f89b01e8e2605f1dfd9c533393 to your computer and use it in GitHub Desktop.
WebSocket ESP8266
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
#include <ESP8266WiFi.h> | |
#include <WebSocketsServer.h> | |
const char* ssid = "********"; | |
const char* password = "**********"; | |
const int pinLed0 = 2; | |
uint8_t num; | |
int a = 0; | |
WebSocketsServer webSocket = WebSocketsServer(81); | |
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) { | |
Serial.printf("[%u] get Message: %s\r\n", num, payload); | |
switch(type) { | |
case WStype_DISCONNECTED: | |
break; | |
case WStype_CONNECTED: | |
{ | |
IPAddress ip = webSocket.remoteIP(num); | |
Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload); | |
} | |
break; | |
case WStype_TEXT: | |
{ | |
//Serial.printf("[%u] get Text: %s\r\n", num, payload); | |
String _payload = String((char *) &payload[0]); | |
//Serial.println(_payload); | |
//String idLed = (_payload.substring(0,4)); | |
//String intensity = (_payload.substring(_payload.indexOf(":")+1,_payload.length())); | |
//int intLed = intensity.toInt(); | |
//Serial.print("Intensity: "); Serial.print(intensity); Serial.print(" to int "); Serial.println(intLed); | |
int x = 0; | |
//webSocket.sendTXT(num, "Hurray", strlen("hurray")); | |
updateLed (_payload); | |
} | |
break; | |
case WStype_BIN: | |
{ | |
hexdump(payload, length); | |
} | |
// echo data back to browser | |
webSocket.sendBIN(num, payload, length); | |
break; | |
} | |
} | |
void setup() { | |
// put your setup code here, to run once: | |
Serial.begin(115200); | |
pinMode(pinLed0, OUTPUT); | |
WiFi.begin(ssid, password); | |
while(WiFi.status() != WL_CONNECTED) { | |
Serial.print("."); | |
delay(200); | |
} | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.println("IP address: "); | |
Serial.println(WiFi.localIP()); | |
delay(500); | |
Serial.println("Start Websocket Server"); | |
webSocket.begin(); | |
webSocket.onEvent(webSocketEvent); | |
} | |
void loop() { | |
webSocket.loop(); | |
a++; | |
String s = String(a); | |
char const *x = s.c_str(); | |
webSocket.sendTXT(num, x, strlen(x)); | |
if(a==10000) | |
a = 0; | |
} | |
void updateLed(String idLed){ | |
float f = idLed.toFloat(); | |
Serial.println(f); | |
Serial.println(idLed); | |
if(idLed=="ON") | |
digitalWrite(pinLed0, LOW); | |
else if(idLed=="OFF") | |
digitalWrite(pinLed0, HIGH); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment