8000 esp8266: share port 80 with regular webserver (#575) · IceWalnut/arduinoWebSockets@826c6b4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 826c6b4

Browse files
authored
esp8266: share port 80 with regular webserver (Links2004#575)
1 parent 7fea0b8 commit 826c6b4

File tree

7 files changed

+459
-137
lines changed

7 files changed

+459
-137
lines changed
Lines changed: 103 additions & 0 deletions
< 10000 td data-grid-cell-id="diff-b4f4687a29c13d3c29bad835135483ce41125a399f7149d1028d459a8fa0706d-empty-14-2" data-line-anchor="diff-b4f4687a29c13d3c29bad835135483ce41125a399f7149d1028d459a8fa0706dR14" data-selected="false" role="gridcell" style="background-color:var(--diffBlob-additionLine-bgColor, var(--diffBlob-addition-bgColor-line));padding-right:24px" tabindex="-1" valign="top" class="focusable-grid-cell diff-text-cell right-side-diff-cell left-side">+
#include <Hash.h>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
/*
2+
* WebSocketServerHooked.ino
3+
*
4+
* Created on: 22.05.2015
5+
* Hooked on: 28.10.2020
6+
*
7+
*/
8+
9+
#include <Arduino.h>
10+
11+
#include <ESP8266WiFi.h>
12+
#include <ESP8266WiFiMulti.h>
13+
#include <WebSockets4WebServer.h>
14
15+
#include <ESP8266mDNS.h>
16+
17+
ESP8266WiFiMulti WiFiMulti;
18+
19+
ESP8266WebServer server(80);
20+
WebSockets4WebServer webSocket;
21+
22+
#define USE_SERIAL Serial
23+
24+
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
25+
26+
switch(type) {
27+
case WStype_DISCONNECTED:
28+
USE_SERIAL.printf("[%u] Disconnected!\n", num);
29+
break;
30+
case WStype_CONNECTED:
31+
{
32+
IPAddress ip = webSocket.remoteIP(num);
33+
USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
34+
35+
// send message to client
36+
webSocket.sendTXT(num, "Connected");
37+
}
38+
break;
39+
case WStype_TEXT:
40+
USE_SERIAL.printf("[%u] get Text: %s\n", num, payload);
41+
42+
// send message to client
43+
// webSocket.sendTXT(num, "message here");
44+
45+
// send data to all connected clients
46+
// webSocket.broadcastTXT("message here");
47+
break;
48+
case WStype_BIN:
49+
USE_SERIAL.printf("[%u] get binary length: %u\n", num, length);
50+
hexdump(payload, length);
51+
52+
// send message to client
53+
// webSocket.sendBIN(num, payload, length);
54+
break;
55+
}
56+
57+
}
58+
59+
void setup() {
60+
// USE_SERIAL.begin(921600);
61+
USE_SERIAL.begin(115200);
62+
63+
//Serial.setDebugOutput(true);
64+
USE_SERIAL.setDebugOutput(true);
65+
66+
USE_SERIAL.println();
67+
USE_SERIAL.println();
68+
USE_SERIAL.println();
69+
70+
for(uint8_t t = 4; t > 0; t--) {
71+
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
72+
USE_SERIAL.flush();
73+
delay(1000);
74+
}
75+
76+
WiFiMulti.addAP("SSID", "passpasspass");
77+
78+
while(WiFiMulti.run() != WL_CONNECTED) {
79+
delay(100);
80+
}
81+
82+
server.on("/", []() {
83+
server.send(200, "text/plain", "I am a regular webserver on port 80!\r\n");
84+
server.send(200, "text/plain", "I am also a websocket server on '/ws' on the same port 80\r\n");
85+
});
86+
87+
server.addHook(webSocket.hookForWebserver("/ws", webSocketEvent));
88+
89+
server.begin();
90+
Serial.println("HTTP server started on port 80");
91+
Serial.println("WebSocket server started on the same port");
92+
Serial.printf("my network address is either 'arduinoWebsockets.local' (mDNS) or '%s'\n", WiFi.localIP().toString().c_str());
93+
94+
if (!MDNS.begin("arduinoWebsockets")) {
95+
Serial.println("Error setting up MDNS responder!");
96+
}
97+
}
98+
99+
void loop() {
100+
server.handleClient();
101+
webSocket.loop();
102+
MDNS.update();
103+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#!/bin/sh
2+
3+
# linux script to compile&run arduinoWebSockets in a mock environment
4+
5+
if [ -z "$ESP8266ARDUINO" ]; then
6+
echo "please set ESP8266ARDUINO env-var to where esp8266/arduino sits"
7+
exit 1
8+
fi
9+
10+
set -e
11+
12+
where=$(pwd)
13+
14+
cd $ESP8266ARDUINO/tests/host/
15+
16+
make -j FORCE32=0 \
17+
ULIBDIRS=../../libraries/Hash/:~/dev/proj/arduino/libraries/arduinoWebSockets \
18+
${where}/WebSocketServerHooked
19+
20+
valgrind ./bin/WebSocketServerHooked/WebSocketServerHooked -b "$@"
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/env python3
2+
3+
# python websocket client to test with
4+
# emulator: server is at ws://127.0.0.1:9080/ws
5+
# esp8266: server is at ws:///ws
6+
# (uncomment the right line below)
7+
8+
#uri = "ws://127.0.0.1:9080/ws"
9+
uri = "ws://arduinoWebsockets.local/ws"
10+
11+
import websocket
12+
try:
13+
import thread
14+
except ImportError:
15+
import _thread as thread
16+
import time
17+
18+
def on_message(ws, message):
19+
print("message");
20+
print(message)
21+
22+
def on_error(ws, error):
23+
print("error")
24+
print(error)
25+
26+
def on_close(ws):
27+
print("### closed ###")
28+
29+
def on_open(ws):
30+
print("opened")
31+
def run(*args):
32+
for i in range(3):
33+
time.sleep(1)
34+
ws.send("Hello %d" % i)
35+
time.sleep(1)
36+
ws.close()
37+
print("thread terminating...")
38+
thread.start_new_thread(run, ())
39+
40+
41+
if __name__ == "__main__":
42+
websocket.enableTrace(True)
43+
ws = websocket.WebSocketApp(uri, on_message = on_message, on_error = on_error, on_close = on_close)
44+
ws.on_open = on_open
45+
ws.run_forever()

src/WebSockets.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242

4343
#ifndef NODEBUG_WEBSOCKETS
4444
#ifdef DEBUG_ESP_PORT
45-
#define DEBUG_WEBSOCKETS(...) DEBUG_ESP_PORT.printf(__VA_ARGS__)
45+
#define DEBUG_WEBSOCKETS(...) { DEBUG_ESP_PORT.printf(__VA_ARGS__); DEBUG_ESP_PORT.flush(); }
4646
#else
4747
//#define DEBUG_WEBSOCKETS(...) os_printf( __VA_ARGS__ )
4848
#endif

src/WebSockets4WebServer.h

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/**
2+
* @file WebSocketsServer.cpp
3+
* @date 28.10.2020
4+
* @author Markus Sattler & esp8266/arduino community
5+
*
6+
* Copyright (c) 2020 Markus Sattler. All rights reserved.
7+
* This file is part of the WebSockets for Arduino.
8+
*
9+
* This library is free software; you can redistribute it and/or
10+
* modify it under the terms of the GNU Lesser General Public
11+
* License as published by the Free Software Foundation; either
12+
* version 2.1 of the License, or (at your option) any later version.
13+
*
14+
* This library is distributed in the hope that it will be useful,
15+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
16+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17+
* Lesser General Public License for more details.
18+
*
19+
* You should have received a copy of the GNU Lesser General Public
20+
* License along with this library; if not, write to the Free Software
21+
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22+
*
23+
*/
24+
25+
#ifndef __WEBSOCKETS4WEBSERVER_H
26+
#define __WEBSOCKETS4WEBSERVER_H
27+
28+
#include <WebSocketsServer.h>
29+
#include <ESP8266WebServer.h>
30+
31+
#if WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266 && WEBSERVER_HAS_HOOK
32+
33+
class WebSockets4WebServer: public WebSocketsServerCore {
34+
public:
35+
36+
WebSockets4WebServer(const String& origin = "", const String& protocol = "arduino"):
37+
WebSocketsServerCore(origin, protocol)
38+
{
39+
begin();
40+
}
41+
42+
ESP8266WebServer::HookFunction hookForWebserver (const String& wsRootDir, WebSocketServerEvent event)
43+
{
44+
onEvent(event);
45+
46+
return [&, wsRootDir](const String & method, const String & url, WiFiClient * tcpClient, ESP8266WebServer::ContentTypeFunction contentType)
47+
{
48+
if (!(method == "GET" && url.indexOf(wsRootDir) == 0)) {
49+
return ESP8266WebServer::CLIENT_REQUEST_CAN_CONTINUE;
50+
}
51+
52+
// allocate a WiFiClient copy (like in WebSocketsServer::handleNewClients())
53+
WEBSOCKETS_NETWORK_CLASS * newTcpClient = new WEBSOCKETS_NETWORK_CLASS(*tcpClient);
54+
55+
// Then initialize a new WSclient_t (like in WebSocketsServer::handleNewClient())
56+
WSclient_t * client = handleNewClient(newTcpClient);
57+
58+
if (client)
59+
{
60+
// give "GET <url>"
61+
String headerLine;
62+
headerLine.reserve(url.length() + 5);
63+
headerLine = "GET ";
64+
headerLine += url;
65+
handleHeader(client, &headerLine);
66+
}
67+
68+
// tell webserver to not close but forget about this client
69+
return ESP8266WebServer::CLIENT_IS_GIVEN;
70+
};
71+
}
72+
};
73+
74+
#endif // WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266 && WEBSERVER_HAS_HOOK
75+
76+
#endif // __WEBSOCKETS4WEBSERVER_H

0 commit comments

Comments
 (0)
0