//socketserver_demo.ino #include #include #include #include #include ESP8266WiFiMulti WiFiMulti; String router_ssid="YourRouterSSID"; String router_password="RouterPassword"; String wifi_hostname="Socketserver Demo"; int serverport=82; int websocketport=83; //should be serverport+1 String internet_ip; ESP8266WebServer server(serverport); WebSocketsServer webSocket = WebSocketsServer(websocketport); //----------------------------------- void handleRoot() { //----------------------------------- String content; content+="\n"; content+="\n"; content+="\n"; content+="\n"; content+="\n"; content+="\n"; content+="
\n"; content+="

"+wifi_hostname+"

\n"; content+="
\n"; content+=" \n"; content+="

Value sent to SocketServer:

\n"; content+="

Sever Response:

\n"; content+="
\n"; content += "\n"; content+="\n"; server.sendHeader("Cache-Control", "no-cache"); server.send(200, "text/html", content); } //----------------------------------- void handleNotFound() { //----------------------------------- String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); } //----------------------------------- String www(String html_method,String host,String url,int port,String post_data){ //----------------------------------- host.replace(" ","%20"); url.replace(" ","%20"); String head; String response; WiFiClient client; if (!client.connect(host, port)) { Serial.println("Could not connect with "+host+":"+String(port)); return "-1"; } else{ if(html_method=="get"){ client.println("GET "+url+" HTTP/1.1"); client.println("Accept: text/*"); client.println("Host: "+host); client.println("Connection: close"); client.println(""); } if(html_method=="post"){ client.println("POST "+url+" HTTP/1.1"); client.println("Host: "+host); client.println("Content-Type: application/x-www-form-urlencoded"); client.println("Content-Length: "+String(post_data.length()) ); client.println(""); client.println(post_data); } //Timeout if there is not a response within 5 seconds int timeout = millis() + 5000; while (client.available() == 0) { if (timeout-millis()<0){ client.stop(); Serial.println("Timed out looking for "+host+":"+String(port)); return "-1"; } } //receive the repsonse from remoter server String str; while (client.available() > 0) { String line = client.readStringUntil('\n'); head+=line+"\n"; str+=line; } int n=str.indexOf("\r\r"); //Show header received: //Serial.println("---------- header -----"); //Serial.println(head.substring(0,n+1)); //Serial.println("---------- end header ----"); String webpage=str.substring(n); return webpage; } return ""; } //-------------------- void webSocketEvent(uint8_t num, WStype_t type, uint8_t * buff, size_t length) { //-------------------- String payload = (char*)buff; if(type==1){ //disconnected Serial.println("User #"+String(num)+" disconnected."); } if(type==2){ //connected Serial.println("User #"+String(num)+" connected."); IPAddress ip = webSocket.remoteIP(num); Serial.println(String(ip[0])+"."+String(ip[1])+"."+String(ip[2])+"."+String(ip[3])); //Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload); } if(type==3){ //message received Serial.println(String(num)+": "+payload); int v=payload.toInt(); if (v<10){webSocket.sendTXT(num, "Freezing");} if (v>10 && v<30){webSocket.sendTXT(num, "Cold");} if (v>30 && v<40){webSocket.sendTXT(num, "Cool");} if (v>40 && v<50){webSocket.sendTXT(num, "Luke Warm");} if (v>50 && v<60){webSocket.sendTXT(num, "Warm");} if (v>60 && v<70){webSocket.sendTXT(num, "Comfy Warm");} if (v>70 && v<80){webSocket.sendTXT(num, "Very warm");} if (v>80 && v<90){webSocket.sendTXT(num, "Hot");} if (v>90){webSocket.sendTXT(num, "Sizzing");} } } //----------------------------------- void setup(void) { //----------------------------------- Serial.begin(115200); connect_to_router(); start_web_server(); start_socket_server(); } //----------------------------------- void loop(void) { //----------------------------------- server.handleClient(); webSocket.loop(); } //----------------------------------- void connect_to_router(){ //----------------------------------- WiFi.hostname(wifi_hostname); //This is how it will look on router's attached wifi devices WiFi.begin(router_ssid,router_password); Serial.println(""); // Wait for connection Serial.println(""); Serial.println("Negotiating with router .."); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to "); Serial.println(router_ssid); Serial.println("Local IP address: "+WiFi.localIP().toString()+":"+String(serverport)); Serial.println("Determining Internet IP address...."); internet_ip=www("get","api.ipify.org","/?format=text", 80,""); Serial.println("Internet IP address: "+internet_ip+":"+String(serverport)); } //----------------------------------- void start_socket_server(){ //----------------------------------- //..start websocketserver Serial.print("Initiating Websocketserver..."); for(uint8_t t = 4; t > 0; t--) { Serial.print("."); Serial.flush(); delay(1000); } Serial.println(""); WiFiMulti.addAP( (char*)&router_ssid, (char*)&router_password); while(WiFiMulti.run() != WL_CONNECTED) { delay(100); } webSocket.begin(); webSocket.onEvent(webSocketEvent); Serial.println("Websocketserver on port "+String(websocketport)); Serial.println("Javascript line to link to websocket port:"); Serial.println("Local:"); Serial.println(" var ws = new WebSocket('ws://"+WiFi.localIP().toString()+":"+String(websocketport)+"');"); Serial.println("From outside on Internet:"); Serial.println(" var ws = new WebSocket('ws://"+internet_ip+":"+String(websocketport)+"');"); Serial.println(""); Serial.println("Don't forget to open ports "+String(serverport)+" and "+String(websocketport)+" on your router"); Serial.println(" for the internal IP addres "+WiFi.localIP().toString()+"."); } //----------------------------------- void start_web_server(){ //----------------------------------- server.on("/", handleRoot); server.onNotFound(handleNotFound); server.begin(); }