forked from Links2004/arduinoWebSockets
Compare commits
86 Commits
Author | SHA1 | Date | |
---|---|---|---|
f40a390ab1 | |||
b6c27f74cd | |||
c64a082270 | |||
522a67bc1b | |||
29df9c30f7 | |||
0ca020bbd2 | |||
cc3ce02c67 | |||
96c266101e | |||
64c8908b05 | |||
87c6c80c67 | |||
adb255bda0 | |||
d0ab6c4fd1 | |||
fcb623ce91 | |||
669f0b489e | |||
32cb052f23 | |||
42ab3168c5 | |||
86d2e2400a | |||
ad07f3c665 | |||
a4533a028c | |||
ae3dd103a1 | |||
40f84c19f4 | |||
f68d9d8030 | |||
c911776860 | |||
adb52b11e9 | |||
81e567b248 | |||
1afe317c7d | |||
177ec8239d | |||
e675c7590e | |||
615926ae1e | |||
acd0a603eb | |||
26140be6c9 | |||
3b1dabbe1e | |||
55bc7db7ad | |||
1a6f46c67d | |||
210f2e8fa1 | |||
34a2d282e4 | |||
e93a323e56 | |||
6da0bc97e8 | |||
ae2ba7effe | |||
dc426c9a61 | |||
60e3d1080e | |||
26fc61f7a2 | |||
604a781122 | |||
f52d718cf2 | |||
6757b8b74c | |||
bef2541ede | |||
dac71c4c23 | |||
60903a2fa5 | |||
0aaf50f87f | |||
2add886219 | |||
ab3b5bae46 | |||
45bb7dbe23 | |||
92032289ec | |||
5cd68c5304 | |||
ddaeea0e4b | |||
a097f0defd | |||
689e3ef921 | |||
75133dfa6d | |||
d2719573d4 | |||
0d9aa043f0 | |||
7810d0d0b3 | |||
1defe6d8e1 | |||
d036dcd8e2 | |||
529a86cc26 | |||
958ab08a6b | |||
7361e2b1b6 | |||
1961ddc159 | |||
cdee9fec05 | |||
ab0d8ff526 | |||
b3d4367d10 | |||
ab51930730 | |||
1ed734ec3f | |||
b99bae459d | |||
26130dc874 | |||
815093a123 | |||
7e5c64a573 | |||
97443ae777 | |||
e589b40b25 | |||
eb2351a4fd | |||
bf3cfa6237 | |||
f8a5acc9b7 | |||
8190e8121c | |||
6a914fc5ea | |||
48ee5fc6fb | |||
b1685962c5 | |||
c4e5f5c7e7 |
37
.travis.yml
Normal file
37
.travis.yml
Normal file
@ -0,0 +1,37 @@
|
||||
sudo: false
|
||||
language: bash
|
||||
os:
|
||||
- linux
|
||||
|
||||
script:
|
||||
- /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16
|
||||
- sleep 3
|
||||
- export DISPLAY=:1.0
|
||||
- wget http://downloads.arduino.cc/arduino-1.6.5-linux64.tar.xz
|
||||
- tar xf arduino-1.6.5-linux64.tar.xz
|
||||
- mv arduino-1.6.5 $HOME/arduino_ide
|
||||
- export PATH="$HOME/arduino_ide:$PATH"
|
||||
- which arduino
|
||||
- mkdir -p $HOME/Arduino/libraries
|
||||
- cp -r $TRAVIS_BUILD_DIR $HOME/Arduino/libraries/arduinoWebSockets
|
||||
- cd $HOME/arduino_ide/hardware
|
||||
- mkdir esp8266com
|
||||
- cd esp8266com
|
||||
- git clone https://github.com/esp8266/Arduino.git esp8266
|
||||
- cd esp8266/tools
|
||||
- python get.py
|
||||
- source $TRAVIS_BUILD_DIR/travis/common.sh
|
||||
- arduino --board esp8266com:esp8266:generic --save-prefs
|
||||
- arduino --get-pref sketchbook.path
|
||||
- build_sketches arduino $HOME/Arduino/libraries/arduinoWebSockets esp8266
|
||||
|
||||
notifications:
|
||||
email:
|
||||
on_success: change
|
||||
on_failure: change
|
||||
webhooks:
|
||||
urls:
|
||||
- https://webhooks.gitter.im/e/1aa78fbe15080b0c2e37
|
||||
on_success: change # options: [always|never|change] default: always
|
||||
on_failure: always # options: [always|never|change] default: always
|
||||
on_start: false # default: false
|
68
README.md
68
README.md
@ -1,54 +1,90 @@
|
||||
WebSocket Server and Client for Arduino
|
||||
WebSocket Server and Client for Arduino [](https://travis-ci.org/Links2004/arduinoWebSockets)
|
||||
===========================================
|
||||
|
||||
a WebSocket Server and Client for Arduino based on RFC6455.
|
||||
|
||||
|
||||
|
||||
##### Supported features of RFC6455 #####
|
||||
- text frame
|
||||
- binary frame
|
||||
- connection close
|
||||
- ping
|
||||
- pong
|
||||
|
||||
##### Not supported features of RFC6455 #####
|
||||
- continuation frame
|
||||
|
||||
|
||||
##### Limitations #####
|
||||
- max input length is limited to the ram size and the ```WEBSOCKETS_MAX_DATA_SIZE``` define
|
||||
- max output length has no limit (the hardware is the limit)
|
||||
- Client send big frames with mask 0x00000000 (on AVR all frames)
|
||||
|
||||
- continuation frame reassembly need to be handled in the application code
|
||||
|
||||
##### Limitations for Async #####
|
||||
- Functions called from within the context of the websocket event might not honor `yield()` and/or `delay()`. See [this issue](https://github.com/Links2004/arduinoWebSockets/issues/58#issuecomment-192376395) for more info and a potential workaround.
|
||||
- wss / SSL is not possible.
|
||||
|
||||
|
||||
##### Supported Hardware #####
|
||||
- ESP8266 [Arduino for ESP8266](https://github.com/Links2004/Arduino)
|
||||
- ESP31B
|
||||
- ATmega328 with Ethernet Shield (ATmega branch)
|
||||
- ATmega328 with enc28j60 (ATmega branch)
|
||||
- ATmega2560 with Ethernet Shield (ATmega branch)
|
||||
- ATmega2560 with enc28j60 (ATmega branch)
|
||||
|
||||
- Particle with STM32 ARM Cortex M3
|
||||
- ATmega328 with Ethernet Shield (ATmega branch)
|
||||
- ATmega328 with enc28j60 (ATmega branch)
|
||||
- ATmega2560 with Ethernet Shield (ATmega branch)
|
||||
- ATmega2560 with enc28j60 (ATmega branch)
|
||||
|
||||
###### Note: ######
|
||||
|
||||
version 2.0 and up is not compatible with AVR/ATmega, check ATmega branch.
|
||||
|
||||
|
||||
Arduino for AVR not supports std namespace of c++.
|
||||
|
||||
|
||||
### wss / SSL ###
|
||||
supported for:
|
||||
- wss client on the ESP8266
|
||||
|
||||
- wss / SSL is not natively supported in WebSocketsServer however it is possible to achieve secure websockets
|
||||
by running the device behind an SSL proxy. See [Nginx](examples/Nginx/esp8266.ssl.reverse.proxy.conf) for a
|
||||
sample Nginx server configuration file to enable this.
|
||||
|
||||
### ESP Async TCP ###
|
||||
|
||||
This libary can run in Async TCP mode on the ESP.
|
||||
|
||||
The mode can be aktivated in the ```WebSockets.h``` (see WEBSOCKETS_NETWORK_TYPE define).
|
||||
The mode can be activated in the ```WebSockets.h``` (see WEBSOCKETS_NETWORK_TYPE define).
|
||||
|
||||
[ESPAsyncTCP](https://github.com/me-no-dev/ESPAsyncTCP) libary is required.
|
||||
|
||||
|
||||
### High Level Client API ###
|
||||
|
||||
- `begin` : Initiate connection sequence to the websocket host.
|
||||
```
|
||||
void begin(const char *host, uint16_t port, const char * url = "/", const char * protocol = "arduino");
|
||||
void begin(String host, uint16_t port, String url = "/", String protocol = "arduino");
|
||||
```
|
||||
- `onEvent`: Callback to handle for websocket events
|
||||
|
||||
```
|
||||
void onEvent(WebSocketClientEvent cbEvent);
|
||||
```
|
||||
|
||||
- `WebSocketClientEvent`: Handler for websocket events
|
||||
```
|
||||
void (*WebSocketClientEvent)(WStype_t type, uint8_t * payload, size_t length)
|
||||
```
|
||||
Where `WStype_t type` is defined as:
|
||||
```
|
||||
typedef enum {
|
||||
WStype_ERROR,
|
||||
WStype_DISCONNECTED,
|
||||
WStype_CONNECTED,
|
||||
WStype_TEXT,
|
||||
WStype_BIN,
|
||||
WStype_FRAGMENT_TEXT_START,
|
||||
WStype_FRAGMENT_BIN_START,
|
||||
WStype_FRAGMENT,
|
||||
WStype_FRAGMENT_FIN,
|
||||
} WStype_t;
|
||||
```
|
||||
|
||||
### Issues ###
|
||||
Submit issues to: https://github.com/Links2004/arduinoWebSockets/issues
|
||||
|
||||
|
83
examples/Nginx/esp8266.ssl.reverse.proxy.conf
Normal file
83
examples/Nginx/esp8266.ssl.reverse.proxy.conf
Normal file
@ -0,0 +1,83 @@
|
||||
# ESP8266 nginx SSL reverse proxy configuration file (tested and working on nginx v1.10.0)
|
||||
|
||||
# proxy cache location
|
||||
proxy_cache_path /opt/etc/nginx/cache levels=1:2 keys_zone=ESP8266_cache:10m max_size=10g inactive=5m use_temp_path=off;
|
||||
|
||||
# webserver proxy
|
||||
server {
|
||||
|
||||
# general server parameters
|
||||
listen 50080;
|
||||
server_name myDomain.net;
|
||||
access_log /opt/var/log/nginx/myDomain.net.access.log;
|
||||
|
||||
# SSL configuration
|
||||
ssl on;
|
||||
ssl_certificate /usr/builtin/etc/certificate/lets-encrypt/myDomain.net/fullchain.pem;
|
||||
ssl_certificate_key /usr/builtin/etc/certificate/lets-encrypt/myDomain.net/privkey.pem;
|
||||
ssl_session_cache builtin:1000 shared:SSL:10m;
|
||||
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
|
||||
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
|
||||
ssl_prefer_server_ciphers on;
|
||||
|
||||
location / {
|
||||
|
||||
# proxy caching configuration
|
||||
proxy_cache ESP8266_cache;
|
||||
proxy_cache_revalidate on;
|
||||
proxy_cache_min_uses 1;
|
||||
proxy_cache_use_stale off;
|
||||
proxy_cache_lock on;
|
||||
# proxy_cache_bypass $http_cache_control;
|
||||
# include the sessionId cookie value as part of the cache key - keeps the cache per user
|
||||
# proxy_cache_key $proxy_host$request_uri$cookie_sessionId;
|
||||
|
||||
# header pass through configuration
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# ESP8266 custom headers which identify to the device that it's running through an SSL proxy
|
||||
proxy_set_header X-SSL On;
|
||||
proxy_set_header X-SSL-WebserverPort 50080;
|
||||
proxy_set_header X-SSL-WebsocketPort 50081;
|
||||
|
||||
# extra debug headers
|
||||
add_header X-Proxy-Cache $upstream_cache_status;
|
||||
add_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
|
||||
# actual proxying configuration
|
||||
proxy_ssl_session_reuse on;
|
||||
# target the IP address of the device with proxy_pass
|
||||
proxy_pass http://192.168.0.20;
|
||||
proxy_read_timeout 90;
|
||||
}
|
||||
}
|
||||
|
||||
# websocket proxy
|
||||
server {
|
||||
|
||||
# general server parameters
|
||||
listen 50081;
|
||||
server_name myDomain.net;
|
||||
access_log /opt/var/log/nginx/myDomain.net.wss.access.log;
|
||||
|
||||
# SSL configuration
|
||||
ssl on;
|
||||
ssl_certificate /usr/builtin/etc/certificate/lets-encrypt/myDomain.net/fullchain.pem;
|
||||
ssl_certificate_key /usr/builtin/etc/certificate/lets-encrypt/myDomain.net/privkey.pem;
|
||||
ssl_session_cache builtin:1000 shared:SSL:10m;
|
||||
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
|
||||
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
|
||||
ssl_prefer_server_ciphers on;
|
||||
|
||||
location / {
|
||||
|
||||
# websocket upgrade tunnel configuration
|
||||
proxy_pass http://192.168.0.20:81;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "Upgrade";
|
||||
proxy_read_timeout 86400;
|
||||
}
|
||||
}
|
0
examples/ParticleWebSocketClient/.esp8266.skip
Normal file
0
examples/ParticleWebSocketClient/.esp8266.skip
Normal file
46
examples/ParticleWebSocketClient/application.cpp
Normal file
46
examples/ParticleWebSocketClient/application.cpp
Normal file
@ -0,0 +1,46 @@
|
||||
/* To compile using make CLI, create a folder under \firmware\user\applications and copy application.cpp there.
|
||||
* Then, copy src files under particleWebSocket folder.
|
||||
*/
|
||||
|
||||
#include "application.h"
|
||||
#include "particleWebSocket/WebSocketsClient.h"
|
||||
|
||||
WebSocketsClient webSocket;
|
||||
|
||||
void webSocketEvent(WStype_t type, uint8_t* payload, size_t length)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case WStype_DISCONNECTED:
|
||||
Serial.printlnf("[WSc] Disconnected!");
|
||||
break;
|
||||
case WStype_CONNECTED:
|
||||
Serial.printlnf("[WSc] Connected to URL: %s", payload);
|
||||
webSocket.sendTXT("Connected\r\n");
|
||||
break;
|
||||
case WStype_TEXT:
|
||||
Serial.printlnf("[WSc] get text: %s", payload);
|
||||
break;
|
||||
case WStype_BIN:
|
||||
Serial.printlnf("[WSc] get binary length: %u", length);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void setup()
|
||||
{
|
||||
Serial.begin(9600);
|
||||
|
||||
WiFi.setCredentials("[SSID]", "[PASSWORD]", WPA2, WLAN_CIPHER_AES_TKIP);
|
||||
WiFi.connect();
|
||||
|
||||
webSocket.begin("192.168.1.153", 85, "/ClientService/?variable=Test1212");
|
||||
webSocket.onEvent(webSocketEvent);
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
webSocket.sendTXT("Hello world!");
|
||||
delay(500);
|
||||
webSocket.loop();
|
||||
}
|
@ -17,71 +17,76 @@
|
||||
ESP8266WiFiMulti WiFiMulti;
|
||||
WebSocketsClient webSocket;
|
||||
|
||||
|
||||
#define USE_SERIAL Serial1
|
||||
|
||||
void webSocketEvent(WStype_t type, uint8_t * payload, size_t lenght) {
|
||||
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
|
||||
|
||||
switch(type) {
|
||||
case WStype_DISCONNECTED:
|
||||
USE_SERIAL.printf("[WSc] Disconnected!\n");
|
||||
break;
|
||||
case WStype_CONNECTED: {
|
||||
USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
|
||||
|
||||
switch(type) {
|
||||
case WStype_DISCONNECTED:
|
||||
USE_SERIAL.printf("[WSc] Disconnected!\n");
|
||||
break;
|
||||
case WStype_CONNECTED:
|
||||
{
|
||||
USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
|
||||
|
||||
// send message to server when Connected
|
||||
webSocket.sendTXT("Connected");
|
||||
}
|
||||
break;
|
||||
case WStype_TEXT:
|
||||
USE_SERIAL.printf("[WSc] get text: %s\n", payload);
|
||||
// send message to server when Connected
|
||||
webSocket.sendTXT("Connected");
|
||||
}
|
||||
break;
|
||||
case WStype_TEXT:
|
||||
USE_SERIAL.printf("[WSc] get text: %s\n", payload);
|
||||
|
||||
// send message to server
|
||||
// webSocket.sendTXT("message here");
|
||||
break;
|
||||
case WStype_BIN:
|
||||
USE_SERIAL.printf("[WSc] get binary lenght: %u\n", lenght);
|
||||
hexdump(payload, lenght);
|
||||
break;
|
||||
case WStype_BIN:
|
||||
USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
|
||||
hexdump(payload, length);
|
||||
|
||||
// send data to server
|
||||
// webSocket.sendBIN(payload, lenght);
|
||||
break;
|
||||
}
|
||||
// send data to server
|
||||
// webSocket.sendBIN(payload, length);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void setup() {
|
||||
// USE_SERIAL.begin(921600);
|
||||
USE_SERIAL.begin(115200);
|
||||
// USE_SERIAL.begin(921600);
|
||||
USE_SERIAL.begin(115200);
|
||||
|
||||
//Serial.setDebugOutput(true);
|
||||
USE_SERIAL.setDebugOutput(true);
|
||||
//Serial.setDebugOutput(true);
|
||||
USE_SERIAL.setDebugOutput(true);
|
||||
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
|
||||
for(uint8_t t = 4; t > 0; t--) {
|
||||
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
|
||||
USE_SERIAL.flush();
|
||||
delay(1000);
|
||||
}
|
||||
for(uint8_t t = 4; t > 0; t--) {
|
||||
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
|
||||
USE_SERIAL.flush();
|
||||
delay(1000);
|
||||
}
|
||||
|
||||
WiFiMulti.addAP("SSID", "passpasspass");
|
||||
WiFiMulti.addAP("SSID", "passpasspass");
|
||||
|
||||
//WiFi.disconnect();
|
||||
while(WiFiMulti.run() != WL_CONNECTED) {
|
||||
delay(100);
|
||||
}
|
||||
//WiFi.disconnect();
|
||||
while(WiFiMulti.run() != WL_CONNECTED) {
|
||||
delay(100);
|
||||
}
|
||||
|
||||
webSocket.begin("192.168.0.123", 81);
|
||||
//webSocket.setAuthorization("user", "Password"); // HTTP Basic Authorization
|
||||
webSocket.onEvent(webSocketEvent);
|
||||
// server address, port and URL
|
||||
webSocket.begin("192.168.0.123", 81, "/");
|
||||
|
||||
// event handler
|
||||
webSocket.onEvent(webSocketEvent);
|
||||
|
||||
// use HTTP Basic Authorization this is optional remove if not needed
|
||||
webSocket.setAuthorization("user", "Password");
|
||||
|
||||
// try ever 5000 again if connection has failed
|
||||
webSocket.setReconnectInterval(5000);
|
||||
|
||||
}
|
||||
|
||||
void loop() {
|
||||
webSocket.loop();
|
||||
webSocket.loop();
|
||||
}
|
||||
|
0
examples/WebSocketClientAVR/.esp8266.skip
Normal file
0
examples/WebSocketClientAVR/.esp8266.skip
Normal file
@ -0,0 +1,150 @@
|
||||
/*
|
||||
WebSocketClientSockJsAndStomp.ino
|
||||
|
||||
Example for connecting and maintining a connection with a SockJS+STOMP websocket connection.
|
||||
In this example we connect to a Spring application (see https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html).
|
||||
|
||||
Created on: 18.07.2017
|
||||
Author: Martin Becker <mgbckr>, Contact: becker@informatik.uni-wuerzburg.de
|
||||
*/
|
||||
|
||||
// PRE
|
||||
|
||||
#define USE_SERIAL Serial
|
||||
|
||||
|
||||
// LIBRARIES
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Hash.h>
|
||||
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <WebSocketsClient.h>
|
||||
|
||||
|
||||
// SETTINGS
|
||||
|
||||
const char* wlan_ssid = "yourssid";
|
||||
const char* wlan_password = "somepassword";
|
||||
|
||||
const char* ws_host = "the.host.net";
|
||||
const int ws_port = 80;
|
||||
|
||||
// base URL for SockJS (websocket) connection
|
||||
// The complete URL will look something like this(cf. http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-36):
|
||||
// ws://<ws_host>:<ws_port>/<ws_baseurl>/<3digits>/<randomstring>/websocket
|
||||
// For the default config of Spring's SockJS/STOMP support the default base URL is "/socketentry/".
|
||||
const char* ws_baseurl = "/socketentry/"; // don't forget leading and trailing "/" !!!
|
||||
|
||||
|
||||
// VARIABLES
|
||||
|
||||
WebSocketsClient webSocket;
|
||||
|
||||
|
||||
// FUNCTIONS
|
||||
|
||||
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
|
||||
|
||||
switch (type) {
|
||||
case WStype_DISCONNECTED:
|
||||
USE_SERIAL.printf("[WSc] Disconnected!\n");
|
||||
break;
|
||||
case WStype_CONNECTED:
|
||||
{
|
||||
USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
|
||||
}
|
||||
break;
|
||||
case WStype_TEXT:
|
||||
{
|
||||
// #####################
|
||||
// handle STOMP protocol
|
||||
// #####################
|
||||
|
||||
String text = (char*) payload;
|
||||
|
||||
USE_SERIAL.printf("[WSc] get text: %s\n", payload);
|
||||
|
||||
if (payload[0] == 'h') {
|
||||
|
||||
USE_SERIAL.println("Heartbeat!");
|
||||
|
||||
} else if (payload[0] == 'o') {
|
||||
|
||||
// on open connection
|
||||
char *msg = "[\"CONNECT\\naccept-version:1.1,1.0\\nheart-beat:10000,10000\\n\\n\\u0000\"]";
|
||||
webSocket.sendTXT(msg);
|
||||
|
||||
} else if (text.startsWith("a[\"CONNECTED")) {
|
||||
|
||||
// subscribe to some channels
|
||||
|
||||
char *msg = "[\"SUBSCRIBE\\nid:sub-0\\ndestination:/user/queue/messages\\n\\n\\u0000\"]";
|
||||
webSocket.sendTXT(msg);
|
||||
delay(1000);
|
||||
|
||||
// and send a message
|
||||
|
||||
msg = "[\"SEND\\ndestination:/app/message\\n\\n{\\\"user\\\":\\\"esp\\\",\\\"message\\\":\\\"Hello!\\\"}\\u0000\"]";
|
||||
webSocket.sendTXT(msg);
|
||||
delay(1000);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case WStype_BIN:
|
||||
USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
|
||||
hexdump(payload, length);
|
||||
|
||||
// send data to server
|
||||
// webSocket.sendBIN(payload, length);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void setup() {
|
||||
|
||||
// setup serial
|
||||
|
||||
// USE_SERIAL.begin(921600);
|
||||
USE_SERIAL.begin(115200);
|
||||
|
||||
// USE_SERIAL.setDebugOutput(true);
|
||||
|
||||
USE_SERIAL.println();
|
||||
|
||||
|
||||
// connect to WiFi
|
||||
|
||||
USE_SERIAL.print("Logging into WLAN: "); Serial.print(wlan_ssid); Serial.print(" ...");
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(wlan_ssid, wlan_password);
|
||||
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(500);
|
||||
USE_SERIAL.print(".");
|
||||
}
|
||||
USE_SERIAL.println(" success.");
|
||||
USE_SERIAL.print("IP: "); USE_SERIAL.println(WiFi.localIP());
|
||||
|
||||
|
||||
// #####################
|
||||
// create socket url according to SockJS protocol (cf. http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-36)
|
||||
// #####################
|
||||
String socketUrl = ws_baseurl;
|
||||
socketUrl += random(0, 999);
|
||||
socketUrl += "/";
|
||||
socketUrl += random(0, 999999); // should be a random string, but this works (see )
|
||||
socketUrl += "/websocket";
|
||||
|
||||
// connect to websocket
|
||||
webSocket.begin(ws_host, ws_port, socketUrl);
|
||||
webSocket.setExtraHeaders(); // remove "Origin: file://" header because it breaks the connection with Spring's default websocket config
|
||||
// webSocket.setExtraHeaders("foo: I am so funny\r\nbar: not"); // some headers, in case you feel funny
|
||||
webSocket.onEvent(webSocketEvent);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
webSocket.loop();
|
||||
}
|
113
examples/WebSocketClientSocketIO/WebSocketClientSocketIO.ino
Normal file
113
examples/WebSocketClientSocketIO/WebSocketClientSocketIO.ino
Normal file
@ -0,0 +1,113 @@
|
||||
/*
|
||||
* WebSocketClientSocketIO.ino
|
||||
*
|
||||
* Created on: 06.06.2016
|
||||
*
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266WiFiMulti.h>
|
||||
|
||||
#include <WebSocketsClient.h>
|
||||
|
||||
#include <Hash.h>
|
||||
|
||||
ESP8266WiFiMulti WiFiMulti;
|
||||
WebSocketsClient webSocket;
|
||||
|
||||
|
||||
#define USE_SERIAL Serial1
|
||||
|
||||
#define MESSAGE_INTERVAL 30000
|
||||
#define HEARTBEAT_INTERVAL 25000
|
||||
|
||||
uint64_t messageTimestamp = 0;
|
||||
uint64_t heartbeatTimestamp = 0;
|
||||
bool isConnected = false;
|
||||
|
||||
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
|
||||
|
||||
|
||||
switch(type) {
|
||||
case WStype_DISCONNECTED:
|
||||
USE_SERIAL.printf("[WSc] Disconnected!\n");
|
||||
isConnected = false;
|
||||
break;
|
||||
case WStype_CONNECTED:
|
||||
{
|
||||
USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
|
||||
isConnected = true;
|
||||
|
||||
// send message to server when Connected
|
||||
// socket.io upgrade confirmation message (required)
|
||||
webSocket.sendTXT("5");
|
||||
}
|
||||
break;
|
||||
case WStype_TEXT:
|
||||
USE_SERIAL.printf("[WSc] get text: %s\n", payload);
|
||||
|
||||
// send message to server
|
||||
// webSocket.sendTXT("message here");
|
||||
break;
|
||||
case WStype_BIN:
|
||||
USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
|
||||
hexdump(payload, length);
|
||||
|
||||
// send data to server
|
||||
// webSocket.sendBIN(payload, length);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void setup() {
|
||||
// USE_SERIAL.begin(921600);
|
||||
USE_SERIAL.begin(115200);
|
||||
|
||||
//Serial.setDebugOutput(true);
|
||||
USE_SERIAL.setDebugOutput(true);
|
||||
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
|
||||
for(uint8_t t = 4; t > 0; t--) {
|
||||
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
|
||||
USE_SERIAL.flush();
|
||||
delay(1000);
|
||||
}
|
||||
|
||||
WiFiMulti.addAP("SSID", "passpasspass");
|
||||
|
||||
//WiFi.disconnect();
|
||||
while(WiFiMulti.run() != WL_CONNECTED) {
|
||||
delay(100);
|
||||
}
|
||||
|
||||
webSocket.beginSocketIO("192.168.0.123", 81);
|
||||
//webSocket.setAuthorization("user", "Password"); // HTTP Basic Authorization
|
||||
webSocket.onEvent(webSocketEvent);
|
||||
|
||||
}
|
||||
|
||||
void loop() {
|
||||
webSocket.loop();
|
||||
|
||||
if(isConnected) {
|
||||
|
||||
uint64_t now = millis();
|
||||
|
||||
if(now - messageTimestamp > MESSAGE_INTERVAL) {
|
||||
messageTimestamp = now;
|
||||
// example socket.io message with type "messageType" and JSON payload
|
||||
webSocket.sendTXT("42[\"messageType\",{\"greeting\":\"hello\"}]");
|
||||
}
|
||||
if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
|
||||
heartbeatTimestamp = now;
|
||||
// socket.io heartbeat message
|
||||
webSocket.sendTXT("2");
|
||||
}
|
||||
}
|
||||
}
|
@ -18,7 +18,7 @@ WebSocketsServer webSocket = WebSocketsServer(81);
|
||||
|
||||
#define USE_SERIAL Serial1
|
||||
|
||||
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {
|
||||
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
|
||||
|
||||
switch(type) {
|
||||
case WStype_DISCONNECTED:
|
||||
@ -43,11 +43,11 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght
|
||||
// webSocket.broadcastTXT("message here");
|
||||
break;
|
||||
case WStype_BIN:
|
||||
USE_SERIAL.printf("[%u] get binary lenght: %u\n", num, lenght);
|
||||
hexdump(payload, lenght);
|
||||
USE_SERIAL.printf("[%u] get binary length: %u\n", num, length);
|
||||
hexdump(payload, length);
|
||||
|
||||
// send message to client
|
||||
// webSocket.sendBIN(num, payload, lenght);
|
||||
// webSocket.sendBIN(num, payload, length);
|
||||
break;
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,94 @@
|
||||
/*
|
||||
* WebSocketServer.ino
|
||||
*
|
||||
* Created on: 22.05.2015
|
||||
*
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266WiFiMulti.h>
|
||||
#include <WebSocketsServer.h>
|
||||
#include <Hash.h>
|
||||
|
||||
ESP8266WiFiMulti WiFiMulti;
|
||||
|
||||
WebSocketsServer webSocket = WebSocketsServer(81);
|
||||
|
||||
#define USE_SERIAL Serial
|
||||
|
||||
String fragmentBuffer = "";
|
||||
|
||||
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
|
||||
|
||||
switch(type) {
|
||||
case WStype_DISCONNECTED:
|
||||
USE_SERIAL.printf("[%u] Disconnected!\n", num);
|
||||
break;
|
||||
case WStype_CONNECTED: {
|
||||
IPAddress ip = webSocket.remoteIP(num);
|
||||
USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
|
||||
|
||||
// send message to client
|
||||
webSocket.sendTXT(num, "Connected");
|
||||
}
|
||||
break;
|
||||
case WStype_TEXT:
|
||||
USE_SERIAL.printf("[%u] get Text: %s\n", num, payload);
|
||||
break;
|
||||
case WStype_BIN:
|
||||
USE_SERIAL.printf("[%u] get binary length: %u\n", num, length);
|
||||
hexdump(payload, length);
|
||||
break;
|
||||
|
||||
// Fragmentation / continuation opcode handling
|
||||
// case WStype_FRAGMENT_BIN_START:
|
||||
case WStype_FRAGMENT_TEXT_START:
|
||||
fragmentBuffer = (char*)payload;
|
||||
USE_SERIAL.printf("[%u] get start start of Textfragment: %s\n", num, payload);
|
||||
break;
|
||||
case WStype_FRAGMENT:
|
||||
fragmentBuffer += (char*)payload;
|
||||
USE_SERIAL.printf("[%u] get Textfragment : %s\n", num, payload);
|
||||
break;
|
||||
case WStype_FRAGMENT_FIN:
|
||||
fragmentBuffer += (char*)payload;
|
||||
USE_SERIAL.printf("[%u] get end of Textfragment: %s\n", num, payload);
|
||||
USE_SERIAL.printf("[%u] full frame: %s\n", num, fragmentBuffer.c_str());
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void setup() {
|
||||
// USE_SERIAL.begin(921600);
|
||||
USE_SERIAL.begin(115200);
|
||||
|
||||
//Serial.setDebugOutput(true);
|
||||
USE_SERIAL.setDebugOutput(true);
|
||||
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
|
||||
for(uint8_t t = 4; t > 0; t--) {
|
||||
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
|
||||
USE_SERIAL.flush();
|
||||
delay(1000);
|
||||
}
|
||||
|
||||
WiFiMulti.addAP("SSID", "passpasspass");
|
||||
|
||||
while(WiFiMulti.run() != WL_CONNECTED) {
|
||||
delay(100);
|
||||
}
|
||||
|
||||
webSocket.begin();
|
||||
webSocket.onEvent(webSocketEvent);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
webSocket.loop();
|
||||
}
|
||||
|
@ -0,0 +1,86 @@
|
||||
/*
|
||||
* WebSocketServerHttpHeaderValidation.ino
|
||||
*
|
||||
* Created on: 08.06.2016
|
||||
*
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266WiFiMulti.h>
|
||||
#include <WebSocketsServer.h>
|
||||
#include <Hash.h>
|
||||
|
||||
ESP8266WiFiMulti WiFiMulti;
|
||||
|
||||
WebSocketsServer webSocket = WebSocketsServer(81);
|
||||
|
||||
#define USE_SERIAL Serial1
|
||||
|
||||
const unsigned long int validSessionId = 12345; //some arbitrary value to act as a valid sessionId
|
||||
|
||||
/*
|
||||
* Returns a bool value as an indicator to describe whether a user is allowed to initiate a websocket upgrade
|
||||
* based on the value of a cookie. This function expects the rawCookieHeaderValue to look like this "sessionId=<someSessionIdNumberValue>|"
|
||||
*/
|
||||
bool isCookieValid(String rawCookieHeaderValue) {
|
||||
|
||||
if (rawCookieHeaderValue.indexOf("sessionId") != -1) {
|
||||
String sessionIdStr = rawCookieHeaderValue.substring(rawCookieHeaderValue.indexOf("sessionId=") + 10, rawCookieHeaderValue.indexOf("|"));
|
||||
unsigned long int sessionId = strtoul(sessionIdStr.c_str(), NULL, 10);
|
||||
return sessionId == validSessionId;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* The WebSocketServerHttpHeaderValFunc delegate passed to webSocket.onValidateHttpHeader
|
||||
*/
|
||||
bool validateHttpHeader(String headerName, String headerValue) {
|
||||
|
||||
//assume a true response for any headers not handled by this validator
|
||||
bool valid = true;
|
||||
|
||||
if(headerName.equalsIgnoreCase("Cookie")) {
|
||||
//if the header passed is the Cookie header, validate it according to the rules in 'isCookieValid' function
|
||||
valid = isCookieValid(headerValue);
|
||||
}
|
||||
|
||||
return valid;
|
||||
}
|
||||
|
||||
void setup() {
|
||||
// USE_SERIAL.begin(921600);
|
||||
USE_SERIAL.begin(115200);
|
||||
|
||||
//Serial.setDebugOutput(true);
|
||||
USE_SERIAL.setDebugOutput(true);
|
||||
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
USE_SERIAL.println();
|
||||
|
||||
for(uint8_t t = 4; t > 0; t--) {
|
||||
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
|
||||
USE_SERIAL.flush();
|
||||
delay(1000);
|
||||
}
|
||||
|
||||
WiFiMulti.addAP("SSID", "passpasspass");
|
||||
|
||||
while(WiFiMulti.run() != WL_CONNECTED) {
|
||||
delay(100);
|
||||
}
|
||||
|
||||
//connecting clients must supply a valid session cookie at websocket upgrade handshake negotiation time
|
||||
const char * headerkeys[] = { "Cookie" };
|
||||
size_t headerKeyCount = sizeof(headerkeys) / sizeof(char*);
|
||||
webSocket.onValidateHttpHeader(validateHttpHeader, headerkeys, headerKeyCount);
|
||||
webSocket.begin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
webSocket.loop();
|
||||
}
|
||||
|
@ -26,7 +26,7 @@ ESP8266WiFiMulti WiFiMulti;
|
||||
ESP8266WebServer server = ESP8266WebServer(80);
|
||||
WebSocketsServer webSocket = WebSocketsServer(81);
|
||||
|
||||
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {
|
||||
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
|
||||
|
||||
switch(type) {
|
||||
case WStype_DISCONNECTED:
|
||||
@ -100,7 +100,7 @@ void setup() {
|
||||
// handle index
|
||||
server.on("/", []() {
|
||||
// send index.html
|
||||
server.send(200, "text/html", "<html><head><script>var connection = new WebSocket('ws://'+location.hostname+':81/', ['arduino']);connection.onopen = function () { connection.send('Connect ' + new Date()); }; connection.onerror = function (error) { console.log('WebSocket Error ', error);};connection.onmessage = function (e) { console.log('Server: ', e.data);};function sendRGB() { var r = parseInt(document.getElementById('r').value).toString(16); var g = parseInt(document.getElementById('g').value).toString(16); var b = parseInt(document.getElementById('b').value).toString(16); if(r.length < 2) { r = '0' + r; } if(g.length < 2) { g = '0' + g; } if(b.length < 2) { b = '0' + b; } var rgb = '#'+r+g+b; console.log('RGB: ' + rgb); connection.send(rgb); }</script></head><body>LED Control:<br/><br/>R: <input id=\"r\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/>G: <input id=\"g\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/>B: <input id=\"b\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/></body></html>");
|
||||
server.send(200, "text/html", "<html><head><script>var connection = new WebSocket('ws://'+location.hostname+':81/', ['arduino']);connection.onopen = function () { connection.send('Connect ' + new Date()); }; connection.onerror = function (error) { console.log('WebSocket Error ', error);};connection.onmessage = function (e) { console.log('Server: ', e.data);};function sendRGB() { var r = parseInt(document.getElementById('r').value).toString(16); var g = parseInt(document.getElementById('g').value).toString(16); var b = parseInt(document.getElementById('b').value).toString(16); if(r.length < 2) { r = '0' + r; } if(g.length < 2) { g = '0' + g; } if(b.length < 2) { b = '0' + b; } var rgb = '#'+r+g+b; console.log('RGB: ' + rgb); connection.send(rgb); }</script></head><body>LED Control:<br/><br/>R: <input id=\"r\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" /><br/>G: <input id=\"g\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" /><br/>B: <input id=\"b\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" /><br/></body></html>");
|
||||
});
|
||||
|
||||
server.begin();
|
||||
|
43
library.json
43
library.json
@ -1,19 +1,28 @@
|
||||
{
|
||||
"name": "WebSockets",
|
||||
"keywords": "wifi, http, web, server, client, websocket",
|
||||
"description": "WebSocket Server and Client for Arduino based on RFC6455",
|
||||
"repository":
|
||||
{
|
||||
"type": "git",
|
||||
"url": "https://github.com/Links2004/arduinoWebSockets.git"
|
||||
},
|
||||
"exclude": "tests",
|
||||
"frameworks": "arduino",
|
||||
"platforms": "*",
|
||||
"authors":
|
||||
{
|
||||
"name": "Markus Sattler",
|
||||
"url": "https://github.com/Links2004",
|
||||
"maintainer": true
|
||||
}
|
||||
"name": "WebSockets",
|
||||
"description": "WebSocket Server and Client for Arduino based on RFC6455",
|
||||
"keywords": "wifi, http, web, server, client, websocket",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Markus Sattler",
|
||||
"url": "https://github.com/Links2004",
|
||||
"maintainer": true
|
||||
}
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/Links2004/arduinoWebSockets.git"
|
||||
},
|
||||
"version": "2.0.9",
|
||||
"license": "LGPL-2.1",
|
||||
"export": {
|
||||
"exclude": [
|
||||
"tests"
|
||||
]
|
||||
},
|
||||
"frameworks": "arduino",
|
||||
"platforms": "*",
|
||||
"examples": [
|
||||
"examples/*/*.ino"
|
||||
]
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
name=WebSockets
|
||||
version=2.0.2
|
||||
version=2.0.9
|
||||
author=Markus Sattler
|
||||
maintainer=Markus Sattler
|
||||
maintainer=Markus Sattler
|
||||
sentence=WebSockets for Arduino (Server + Client)
|
||||
paragraph=use 2.x.x for ESP and 1.3 for AVR
|
||||
category=Communication
|
||||
|
@ -123,7 +123,7 @@ bool WebSockets::sendFrame(WSclient_t * client, WSopcode_t opcode, uint8_t * pay
|
||||
#ifdef WEBSOCKETS_USE_BIG_MEM
|
||||
// only for ESP since AVR has less HEAP
|
||||
// try to send data in one TCP package (only if some free Heap is there)
|
||||
if(!headerToPayload && ((length > 0) && (length < 1400)) && (ESP.getFreeHeap() > 6000)) {
|
||||
if(!headerToPayload && ((length > 0) && (length < 1400)) && (GET_FREE_HEAP > 6000)) {
|
||||
DEBUG_WEBSOCKETS("[WS][%d][sendFrame] pack to one TCP package...\n", client->num);
|
||||
uint8_t * dataPtr = (uint8_t *) malloc(length + WEBSOCKETS_MAX_HEADER_SIZE);
|
||||
if(dataPtr) {
|
||||
@ -233,18 +233,18 @@ bool WebSockets::sendFrame(WSclient_t * client, WSopcode_t opcode, uint8_t * pay
|
||||
// header has be added to payload
|
||||
// payload is forced to reserved 14 Byte but we may not need all based on the length and mask settings
|
||||
// offset in payload is calculatetd 14 - headerSize
|
||||
if(client->tcp->write(&payloadPtr[(WEBSOCKETS_MAX_HEADER_SIZE - headerSize)], (length + headerSize)) != (length + headerSize)) {
|
||||
if(write(client, &payloadPtr[(WEBSOCKETS_MAX_HEADER_SIZE - headerSize)], (length + headerSize)) != (length + headerSize)) {
|
||||
ret = false;
|
||||
}
|
||||
} else {
|
||||
// send header
|
||||
if(client->tcp->write(&buffer[0], headerSize) != headerSize) {
|
||||
if(write(client, &buffer[0], headerSize) != headerSize) {
|
||||
ret = false;
|
||||
}
|
||||
|
||||
if(payloadPtr && length > 0) {
|
||||
// send payload
|
||||
if(client->tcp->write(&payloadPtr[0], length) != length) {
|
||||
if(write(client, &payloadPtr[0], length) != length) {
|
||||
ret = false;
|
||||
}
|
||||
}
|
||||
@ -296,7 +296,7 @@ bool WebSockets::handleWebsocketWaitFor(WSclient_t * client, size_t size) {
|
||||
}
|
||||
|
||||
if(size > WEBSOCKETS_MAX_HEADER_SIZE) {
|
||||
DEBUG_WEBSOCKETS("[WS][%d][handleWebsocketWaitFor] size: %d to big!\n", client->num, size);
|
||||
DEBUG_WEBSOCKETS("[WS][%d][handleWebsocketWaitFor] size: %d too big!\n", client->num, size);
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -364,7 +364,7 @@ void WebSockets::handleWebsocketCb(WSclient_t * client) {
|
||||
}
|
||||
|
||||
if(buffer[0] != 0 || buffer[1] != 0 || buffer[2] != 0 || buffer[3] != 0) {
|
||||
// really to big!
|
||||
// really too big!
|
||||
header->payloadLen = 0xFFFFFFFF;
|
||||
} else {
|
||||
header->payloadLen = buffer[4] << 24 | buffer[5] << 16 | buffer[6] << 8 | buffer[7];
|
||||
@ -377,7 +377,7 @@ void WebSockets::handleWebsocketCb(WSclient_t * client) {
|
||||
DEBUG_WEBSOCKETS("[WS][%d][handleWebsocket] mask: %u payloadLen: %u\n", client->num, header->mask, header->payloadLen);
|
||||
|
||||
if(header->payloadLen > WEBSOCKETS_MAX_DATA_SIZE) {
|
||||
DEBUG_WEBSOCKETS("[WS][%d][handleWebsocket] payload to big! (%u)\n", client->num, header->payloadLen);
|
||||
DEBUG_WEBSOCKETS("[WS][%d][handleWebsocket] payload too big! (%u)\n", client->num, header->payloadLen);
|
||||
clientDisconnect(client, 1009);
|
||||
return;
|
||||
}
|
||||
@ -426,14 +426,15 @@ void WebSockets::handleWebsocketPayloadCb(WSclient_t * client, bool ok, uint8_t
|
||||
DEBUG_WEBSOCKETS("[WS][%d][handleWebsocket] text: %s\n", client->num, payload);
|
||||
// no break here!
|
||||
case WSop_binary:
|
||||
messageRecived(client, header->opCode, payload, header->payloadLen);
|
||||
case WSop_continuation:
|
||||
messageReceived(client, header->opCode, payload, header->payloadLen, header->fin);
|
||||
break;
|
||||
case WSop_ping:
|
||||
// send pong back
|
||||
sendFrame(client, WSop_pong, payload, header->payloadLen);
|
||||
sendFrame(client, WSop_pong, payload, header->payloadLen, true);
|
||||
break;
|
||||
case WSop_pong:
|
||||
DEBUG_WEBSOCKETS("[WS][%d][handleWebsocket] get pong (%s)\n", client->num, payload);
|
||||
DEBUG_WEBSOCKETS("[WS][%d][handleWebsocket] get pong (%s)\n", client->num, payload ? (const char*)payload : "");
|
||||
break;
|
||||
case WSop_close: {
|
||||
uint16_t reasonCode = 1000;
|
||||
@ -449,11 +450,7 @@ void WebSockets::handleWebsocketPayloadCb(WSclient_t * client, bool ok, uint8_t
|
||||
}
|
||||
clientDisconnect(client, 1000);
|
||||
}
|
||||
break;
|
||||
case WSop_continuation:
|
||||
// continuation is not supported
|
||||
clientDisconnect(client, 1003);
|
||||
break;
|
||||
break;
|
||||
default:
|
||||
clientDisconnect(client, 1002);
|
||||
break;
|
||||
@ -597,3 +594,55 @@ bool WebSockets::readCb(WSclient_t * client, uint8_t * out, size_t n, WSreadWait
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* write x byte to tcp or get timeout
|
||||
* @param client WSclient_t *
|
||||
* @param out uint8_t * data buffer
|
||||
* @param n size_t byte count
|
||||
* @return bytes send
|
||||
*/
|
||||
size_t WebSockets::write(WSclient_t * client, uint8_t *out, size_t n) {
|
||||
if(out == NULL) return 0;
|
||||
if(client == NULL) return 0;
|
||||
unsigned long t = millis();
|
||||
size_t len = 0;
|
||||
size_t total = 0;
|
||||
DEBUG_WEBSOCKETS("[write] n: %d t: %d\n", n, t);
|
||||
while(n > 0) {
|
||||
if(client->tcp == NULL) {
|
||||
DEBUG_WEBSOCKETS("[write] tcp is null!\n");
|
||||
break;
|
||||
}
|
||||
|
||||
if(!client->tcp->connected()) {
|
||||
DEBUG_WEBSOCKETS("[write] not connected!\n");
|
||||
break;
|
||||
}
|
||||
|
||||
if((millis() - t) > WEBSOCKETS_TCP_TIMEOUT) {
|
||||
DEBUG_WEBSOCKETS("[write] write TIMEOUT! %d\n", (millis() - t));
|
||||
break;
|
||||
}
|
||||
|
||||
len = client->tcp->write((const uint8_t*)out, n);
|
||||
if(len) {
|
||||
t = millis();
|
||||
out += len;
|
||||
n -= len;
|
||||
total += len;
|
||||
//DEBUG_WEBSOCKETS("write %d left %d!\n", len, n);
|
||||
} else {
|
||||
//DEBUG_WEBSOCKETS("write %d failed left %d!\n", len, n);
|
||||
}
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266)
|
||||
delay(0);
|
||||
#endif
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
size_t WebSockets::write(WSclient_t * client, const char *out) {
|
||||
if(client == NULL) return 0;
|
||||
if(out == NULL) return 0;
|
||||
return write(client, (uint8_t*)out, strlen(out));
|
||||
}
|
||||
|
@ -25,9 +25,23 @@
|
||||
#ifndef WEBSOCKETS_H_
|
||||
#define WEBSOCKETS_H_
|
||||
|
||||
#ifdef STM32_DEVICE
|
||||
#include <application.h>
|
||||
#define bit(b) (1UL << (b)) // Taken directly from Arduino.h
|
||||
#else
|
||||
#include <Arduino.h>
|
||||
#endif
|
||||
|
||||
#include <functional>
|
||||
|
||||
#ifndef NODEBUG_WEBSOCKETS
|
||||
#ifdef DEBUG_ESP_PORT
|
||||
#define DEBUG_WEBSOCKETS(...) DEBUG_ESP_PORT.printf( __VA_ARGS__ )
|
||||
#else
|
||||
//#define DEBUG_WEBSOCKETS(...) os_printf( __VA_ARGS__ )
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef DEBUG_WEBSOCKETS
|
||||
#define DEBUG_WEBSOCKETS(...)
|
||||
@ -37,9 +51,20 @@
|
||||
#ifdef ESP8266
|
||||
#define WEBSOCKETS_MAX_DATA_SIZE (15*1024)
|
||||
#define WEBSOCKETS_USE_BIG_MEM
|
||||
#define GET_FREE_HEAP ESP.getFreeHeap()
|
||||
// moves all Header strings to Flash (~300 Byte)
|
||||
//#define WEBSOCKETS_SAVE_RAM
|
||||
#else
|
||||
#ifdef STM32_DEVICE
|
||||
#define WEBSOCKETS_MAX_DATA_SIZE (15*1024)
|
||||
#define WEBSOCKETS_USE_BIG_MEM
|
||||
#define GET_FREE_HEAP System.freeMemory()
|
||||
#else
|
||||
//atmega328p has only 2KB ram!
|
||||
#define WEBSOCKETS_MAX_DATA_SIZE (1024)
|
||||
// moves all Header strings to Flash
|
||||
#define WEBSOCKETS_SAVE_RAM
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#define WEBSOCKETS_TCP_TIMEOUT (2000)
|
||||
@ -52,13 +77,16 @@
|
||||
// max size of the WS Message Header
|
||||
#define WEBSOCKETS_MAX_HEADER_SIZE (14)
|
||||
|
||||
#if !defined(WEBSOCKETS_NETWORK_TYPE)
|
||||
// select Network type based
|
||||
#if defined(ESP8266) || defined(ESP31B)
|
||||
#define WEBSOCKETS_NETWORK_TYPE NETWORK_ESP8266
|
||||
//#define WEBSOCKETS_NETWORK_TYPE NETWORK_ESP8266_ASYNC
|
||||
//#define WEBSOCKETS_NETWORK_TYPE NETWORK_W5100
|
||||
#else
|
||||
#define WEBSOCKETS_NETWORK_TYPE NETWORK_W5100
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
|
||||
|
||||
@ -96,10 +124,15 @@
|
||||
|
||||
#elif (WEBSOCKETS_NETWORK_TYPE == NETWORK_W5100)
|
||||
|
||||
#ifdef STM32_DEVICE
|
||||
#define WEBSOCKETS_NETWORK_CLASS TCPClient
|
||||
#define WEBSOCKETS_NETWORK_SERVER_CLASS TCPServer
|
||||
#else
|
||||
#include <Ethernet.h>
|
||||
#include <SPI.h>
|
||||
#define WEBSOCKETS_NETWORK_CLASS EthernetClient
|
||||
#define WEBSOCKETS_NETWORK_SERVER_CLASS EthernetServer
|
||||
#endif
|
||||
|
||||
#elif (WEBSOCKETS_NETWORK_TYPE == NETWORK_ENC28J60)
|
||||
|
||||
@ -111,6 +144,12 @@
|
||||
#error "no network type selected!"
|
||||
#endif
|
||||
|
||||
// moves all Header strings to Flash (~300 Byte)
|
||||
#ifdef WEBSOCKETS_SAVE_RAM
|
||||
#define WEBSOCKETS_STRING(var) F(var)
|
||||
#else
|
||||
#define WEBSOCKETS_STRING(var) var
|
||||
#endif
|
||||
|
||||
typedef enum {
|
||||
WSC_NOT_CONNECTED,
|
||||
@ -123,7 +162,11 @@ typedef enum {
|
||||
WStype_DISCONNECTED,
|
||||
WStype_CONNECTED,
|
||||
WStype_TEXT,
|
||||
WStype_BIN
|
||||
WStype_BIN,
|
||||
WStype_FRAGMENT_TEXT_START,
|
||||
WStype_FRAGMENT_BIN_START,
|
||||
WStype_FRAGMENT,
|
||||
WStype_FRAGMENT_FIN,
|
||||
} WStype_t;
|
||||
|
||||
typedef enum {
|
||||
@ -159,6 +202,8 @@ typedef struct {
|
||||
|
||||
WEBSOCKETS_NETWORK_CLASS * tcp;
|
||||
|
||||
bool isSocketIO; ///< client for socket.io server
|
||||
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266)
|
||||
bool isSSL; ///< run in ssl mode
|
||||
WiFiClientSecure * ssl;
|
||||
@ -170,6 +215,7 @@ typedef struct {
|
||||
bool cIsUpgrade; ///< Connection == Upgrade
|
||||
bool cIsWebsocket; ///< Upgrade == websocket
|
||||
|
||||
String cSessionId; ///< client Set-Cookie (session id)
|
||||
String cKey; ///< client Sec-WebSocket-Key
|
||||
String cAccept; ///< client Sec-WebSocket-Accept
|
||||
String cProtocol; ///< client Sec-WebSocket-Protocol
|
||||
@ -183,6 +229,11 @@ typedef struct {
|
||||
String base64Authorization; ///< Base64 encoded Auth request
|
||||
String plainAuthorization; ///< Base64 encoded Auth request
|
||||
|
||||
String extraHeaders;
|
||||
|
||||
bool cHttpHeadersValid; ///< non-websocket http header validity indicator
|
||||
size_t cMandatoryHeadersCount; ///< non-websocket mandatory http headers present count
|
||||
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
|
||||
String cHttpLine; ///< HTTP header lines
|
||||
#endif
|
||||
@ -202,7 +253,7 @@ class WebSockets {
|
||||
virtual void clientDisconnect(WSclient_t * client);
|
||||
virtual bool clientIsConnected(WSclient_t * client);
|
||||
|
||||
virtual void messageRecived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length);
|
||||
virtual void messageReceived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length, bool fin);
|
||||
|
||||
void clientDisconnect(WSclient_t * client, uint16_t code, char * reason = NULL, size_t reasonLen = 0);
|
||||
bool sendFrame(WSclient_t * client, WSopcode_t opcode, uint8_t * payload = NULL, size_t length = 0, bool mask = false, bool fin = true, bool headerToPayload = false);
|
||||
@ -219,6 +270,8 @@ class WebSockets {
|
||||
String base64_encode(uint8_t * data, size_t length);
|
||||
|
||||
bool readCb(WSclient_t * client, uint8_t *out, size_t n, WSreadWaitCb cb);
|
||||
virtual size_t write(WSclient_t * client, uint8_t *out, size_t n);
|
||||
size_t write(WSclient_t * client, const char *out);
|
||||
|
||||
|
||||
};
|
||||
|
@ -29,6 +29,7 @@
|
||||
WebSocketsClient::WebSocketsClient() {
|
||||
_cbEvent = NULL;
|
||||
_client.num = 0;
|
||||
_client.extraHeaders = WEBSOCKETS_STRING("Origin: file://");
|
||||
}
|
||||
|
||||
WebSocketsClient::~WebSocketsClient() {
|
||||
@ -63,6 +64,7 @@ void WebSocketsClient::begin(const char *host, uint16_t port, const char * url,
|
||||
_client.cVersion = 0;
|
||||
_client.base64Authorization = "";
|
||||
_client.plainAuthorization = "";
|
||||
_client.isSocketIO = false;
|
||||
|
||||
#ifdef ESP8266
|
||||
randomSeed(RANDOM_REG32);
|
||||
@ -73,6 +75,9 @@ void WebSocketsClient::begin(const char *host, uint16_t port, const char * url,
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
|
||||
asyncConnect();
|
||||
#endif
|
||||
|
||||
_lastConnectionFail = 0;
|
||||
_reconnectInterval = 500;
|
||||
}
|
||||
|
||||
void WebSocketsClient::begin(String host, uint16_t port, String url, String protocol) {
|
||||
@ -91,6 +96,27 @@ void WebSocketsClient::beginSSL(String host, uint16_t port, String url, String f
|
||||
}
|
||||
#endif
|
||||
|
||||
void WebSocketsClient::beginSocketIO(const char *host, uint16_t port, const char * url, const char * protocol) {
|
||||
begin(host, port, url, protocol);
|
||||
_client.isSocketIO = true;
|
||||
}
|
||||
|
||||
void WebSocketsClient::beginSocketIO(String host, uint16_t port, String url, String protocol) {
|
||||
beginSocketIO(host.c_str(), port, url.c_str(), protocol.c_str());
|
||||
}
|
||||
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266)
|
||||
void WebSocketsClient::beginSocketIOSSL(const char *host, uint16_t port, const char * url, const char * protocol) {
|
||||
begin(host, port, url, protocol);
|
||||
_client.isSocketIO = true;
|
||||
_client.isSSL = true;
|
||||
_fingerprint = "";
|
||||
}
|
||||
|
||||
void WebSocketsClient::beginSocketIOSSL(String host, uint16_t port, String url, String protocol) {
|
||||
beginSocketIOSSL(host.c_str(), port, url.c_str(), protocol.c_str());
|
||||
}
|
||||
#endif
|
||||
|
||||
#if (WEBSOCKETS_NETWORK_TYPE != NETWORK_ESP8266_ASYNC)
|
||||
/**
|
||||
@ -98,6 +124,10 @@ void WebSocketsClient::beginSSL(String host, uint16_t port, String url, String f
|
||||
*/
|
||||
void WebSocketsClient::loop(void) {
|
||||
if(!clientIsConnected(&_client)) {
|
||||
// do not flood the server
|
||||
if((millis() - _lastConnectionFail) < _reconnectInterval) {
|
||||
return;
|
||||
}
|
||||
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266)
|
||||
if(_client.isSSL) {
|
||||
@ -128,9 +158,11 @@ void WebSocketsClient::loop(void) {
|
||||
|
||||
if(_client.tcp->connect(_host.c_str(), _port)) {
|
||||
connectedCb();
|
||||
_lastConnectionFail = 0;
|
||||
} else {
|
||||
connectFailedCb();
|
||||
delay(10); //some little delay to not flood the server
|
||||
_lastConnectionFail = millis();
|
||||
|
||||
}
|
||||
} else {
|
||||
handleClientData();
|
||||
@ -199,6 +231,24 @@ bool WebSocketsClient::sendBIN(const uint8_t * payload, size_t length) {
|
||||
return sendBIN((uint8_t *) payload, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* sends a WS ping to Server
|
||||
* @param payload uint8_t *
|
||||
* @param length size_t
|
||||
* @return true if ping is send out
|
||||
*/
|
||||
bool WebSocketsClient::sendPing(uint8_t * payload, size_t length) {
|
||||
if(clientIsConnected(&_client)) {
|
||||
return sendFrame(&_client, WSop_ping, payload, length, true);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool WebSocketsClient::sendPing(String & payload) {
|
||||
return sendPing((uint8_t *) payload.c_str(), payload.length());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* disconnect one client
|
||||
* @param num uint8_t client id
|
||||
@ -234,6 +284,25 @@ void WebSocketsClient::setAuthorization(const char * auth) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* set extra headers for the http request;
|
||||
* separate headers by "\r\n"
|
||||
* @param extraHeaders const char * extraHeaders
|
||||
*/
|
||||
void WebSocketsClient::setExtraHeaders(const char * extraHeaders) {
|
||||
_client.extraHeaders = extraHeaders;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* set the reconnect Interval
|
||||
* how long to wait after a connection initiate failed
|
||||
* @param time in ms
|
||||
*/
|
||||
void WebSocketsClient::setReconnectInterval(unsigned long time) {
|
||||
_reconnectInterval = time;
|
||||
}
|
||||
|
||||
//#################################################################################
|
||||
//#################################################################################
|
||||
//#################################################################################
|
||||
@ -243,21 +312,24 @@ void WebSocketsClient::setAuthorization(const char * auth) {
|
||||
* @param client WSclient_t * ptr to the client struct
|
||||
* @param opcode WSopcode_t
|
||||
* @param payload uint8_t *
|
||||
* @param lenght size_t
|
||||
* @param length size_t
|
||||
*/
|
||||
void WebSocketsClient::messageRecived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t lenght) {
|
||||
void WebSocketsClient::messageReceived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length, bool fin) {
|
||||
WStype_t type = WStype_ERROR;
|
||||
|
||||
switch(opcode) {
|
||||
case WSop_text:
|
||||
type = WStype_TEXT;
|
||||
type = fin ? WStype_TEXT : WStype_FRAGMENT_TEXT_START;
|
||||
break;
|
||||
case WSop_binary:
|
||||
type = WStype_BIN;
|
||||
type = fin ? WStype_BIN : WStype_FRAGMENT_BIN_START;
|
||||
break;
|
||||
case WSop_continuation:
|
||||
type = fin ? WStype_FRAGMENT_FIN : WStype_FRAGMENT;
|
||||
break;
|
||||
}
|
||||
|
||||
runCbEvent(type, payload, lenght);
|
||||
runCbEvent(type, payload, length);
|
||||
|
||||
}
|
||||
|
||||
@ -305,6 +377,7 @@ void WebSocketsClient::clientDisconnect(WSclient_t * client) {
|
||||
client->cVersion = 0;
|
||||
client->cIsUpgrade = false;
|
||||
client->cIsWebsocket = false;
|
||||
client->cSessionId = "";
|
||||
|
||||
client->status = WSC_NOT_CONNECTED;
|
||||
|
||||
@ -373,12 +446,15 @@ void WebSocketsClient::handleClientData(void) {
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
/**
|
||||
* send the WebSocket header to Server
|
||||
* @param client WSclient_t * ptr to the client struct
|
||||
*/
|
||||
void WebSocketsClient::sendHeader(WSclient_t * client) {
|
||||
|
||||
static const char * NEW_LINE = "\r\n";
|
||||
|
||||
DEBUG_WEBSOCKETS("[WS-Client][sendHeader] sending header...\n");
|
||||
|
||||
uint8_t randomKey[16] = { 0 };
|
||||
@ -393,34 +469,66 @@ void WebSocketsClient::sendHeader(WSclient_t * client) {
|
||||
unsigned long start = micros();
|
||||
#endif
|
||||
|
||||
String handshake = "GET " + client->cUrl + " HTTP/1.1\r\n"
|
||||
"Host: " + _host + ":" + _port + "\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Origin: file://\r\n"
|
||||
"User-Agent: arduino-WebSocket-Client\r\n"
|
||||
"Sec-WebSocket-Version: 13\r\n"
|
||||
"Sec-WebSocket-Key: " + client->cKey + "\r\n";
|
||||
String handshake;
|
||||
bool ws_header = true;
|
||||
String url = client->cUrl;
|
||||
|
||||
if(client->cProtocol.length() > 0) {
|
||||
handshake += "Sec-WebSocket-Protocol: " + client->cProtocol + "\r\n";
|
||||
if(client->isSocketIO) {
|
||||
if(client->cSessionId.length() == 0) {
|
||||
url += WEBSOCKETS_STRING("&transport=polling");
|
||||
ws_header = false;
|
||||
} else {
|
||||
url += WEBSOCKETS_STRING("&transport=websocket&sid=");
|
||||
url += client->cSessionId;
|
||||
}
|
||||
}
|
||||
|
||||
if(client->cExtensions.length() > 0) {
|
||||
handshake += "Sec-WebSocket-Extensions: " + client->cExtensions + "\r\n";
|
||||
}
|
||||
handshake = WEBSOCKETS_STRING("GET ");
|
||||
handshake += url + WEBSOCKETS_STRING(" HTTP/1.1\r\n"
|
||||
"Host: ");
|
||||
handshake += _host + ":" + _port + NEW_LINE;
|
||||
|
||||
if(client->base64Authorization.length() > 0) {
|
||||
handshake += "Authorization: Basic " + client->base64Authorization + "\r\n";
|
||||
}
|
||||
if(ws_header) {
|
||||
handshake += WEBSOCKETS_STRING("Connection: Upgrade\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Sec-WebSocket-Version: 13\r\n"
|
||||
"Sec-WebSocket-Key: ");
|
||||
handshake += client->cKey + NEW_LINE;
|
||||
|
||||
if(client->plainAuthorization.length() > 0) {
|
||||
handshake += "Authorization: " + client->plainAuthorization + "\r\n";
|
||||
}
|
||||
if(client->cProtocol.length() > 0) {
|
||||
handshake += WEBSOCKETS_STRING("Sec-WebSocket-Protocol: ");
|
||||
handshake +=client->cProtocol + NEW_LINE;
|
||||
}
|
||||
|
||||
handshake += "\r\n";
|
||||
if(client->cExtensions.length() > 0) {
|
||||
handshake += WEBSOCKETS_STRING("Sec-WebSocket-Extensions: ");
|
||||
handshake +=client->cExtensions + NEW_LINE;
|
||||
}
|
||||
} else {
|
||||
handshake += WEBSOCKETS_STRING("Connection: keep-alive\r\n");
|
||||
}
|
||||
|
||||
client->tcp->write(handshake.c_str(), handshake.length());
|
||||
// add extra headers; by default this includes "Origin: file://"
|
||||
if (client->extraHeaders) {
|
||||
handshake += client->extraHeaders + NEW_LINE;
|
||||
}
|
||||
|
||||
handshake += WEBSOCKETS_STRING("User-Agent: arduino-WebSocket-Client\r\n");
|
||||
|
||||
if(client->base64Authorization.length() > 0) {
|
||||
handshake += WEBSOCKETS_STRING("Authorization: Basic ");
|
||||
handshake += client->base64Authorization + NEW_LINE;
|
||||
}
|
||||
|
||||
if(client->plainAuthorization.length() > 0) {
|
||||
handshake += WEBSOCKETS_STRING("Authorization: ");
|
||||
handshake += client->plainAuthorization + NEW_LINE;
|
||||
}
|
||||
|
||||
handshake += NEW_LINE;
|
||||
|
||||
DEBUG_WEBSOCKETS("[WS-Client][sendHeader] handshake %s", (uint8_t*)handshake.c_str());
|
||||
write(client, (uint8_t*)handshake.c_str(), handshake.length());
|
||||
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
|
||||
client->tcp->readStringUntil('\n', &(client->cHttpLine), std::bind(&WebSocketsClient::handleHeader, this, client, &(client->cHttpLine)));
|
||||
@ -441,30 +549,36 @@ void WebSocketsClient::handleHeader(WSclient_t * client, String * headerLine) {
|
||||
if(headerLine->length() > 0) {
|
||||
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] RX: %s\n", headerLine->c_str());
|
||||
|
||||
if(headerLine->startsWith("HTTP/1.")) {
|
||||
if(headerLine->startsWith(WEBSOCKETS_STRING("HTTP/1."))) {
|
||||
// "HTTP/1.1 101 Switching Protocols"
|
||||
client->cCode = headerLine->substring(9, headerLine->indexOf(' ', 9)).toInt();
|
||||
} else if(headerLine->indexOf(':')) {
|
||||
String headerName = headerLine->substring(0, headerLine->indexOf(':'));
|
||||
String headerValue = headerLine->substring(headerLine->indexOf(':') + 2);
|
||||
|
||||
if(headerName.equalsIgnoreCase("Connection")) {
|
||||
if(headerValue.equalsIgnoreCase("upgrade")) {
|
||||
if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Connection"))) {
|
||||
if(headerValue.equalsIgnoreCase(WEBSOCKETS_STRING("upgrade"))) {
|
||||
client->cIsUpgrade = true;
|
||||
}
|
||||
} else if(headerName.equalsIgnoreCase("Upgrade")) {
|
||||
if(headerValue.equalsIgnoreCase("websocket")) {
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Upgrade"))) {
|
||||
if(headerValue.equalsIgnoreCase(WEBSOCKETS_STRING("websocket"))) {
|
||||
client->cIsWebsocket = true;
|
||||
}
|
||||
} else if(headerName.equalsIgnoreCase("Sec-WebSocket-Accept")) {
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Sec-WebSocket-Accept"))) {
|
||||
client->cAccept = headerValue;
|
||||
client->cAccept.trim(); // see rfc6455
|
||||
} else if(headerName.equalsIgnoreCase("Sec-WebSocket-Protocol")) {
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Sec-WebSocket-Protocol"))) {
|
||||
client->cProtocol = headerValue;
|
||||
} else if(headerName.equalsIgnoreCase("Sec-WebSocket-Extensions")) {
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Sec-WebSocket-Extensions"))) {
|
||||
client->cExtensions = headerValue;
|
||||
} else if(headerName.equalsIgnoreCase("Sec-WebSocket-Version")) {
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Sec-WebSocket-Version"))) {
|
||||
client->cVersion = headerValue.toInt();
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Set-Cookie"))) {
|
||||
if (headerValue.indexOf(WEBSOCKETS_STRING("HttpOnly")) > -1) {
|
||||
client->cSessionId = headerValue.substring(headerValue.indexOf('=') + 1, headerValue.indexOf(";"));
|
||||
} else {
|
||||
client->cSessionId = headerValue.substring(headerValue.indexOf('=') + 1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Header error (%s)\n", headerLine->c_str());
|
||||
@ -490,6 +604,7 @@ void WebSocketsClient::handleHeader(WSclient_t * client, String * headerLine) {
|
||||
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] - cProtocol: %s\n", client->cProtocol.c_str());
|
||||
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] - cExtensions: %s\n", client->cExtensions.c_str());
|
||||
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] - cVersion: %d\n", client->cVersion);
|
||||
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] - cSessionId: %s\n", client->cSessionId.c_str());
|
||||
|
||||
bool ok = (client->cIsUpgrade && client->cIsWebsocket);
|
||||
|
||||
@ -498,12 +613,17 @@ void WebSocketsClient::handleHeader(WSclient_t * client, String * headerLine) {
|
||||
case 101: ///< Switching Protocols
|
||||
|
||||
break;
|
||||
case 200:
|
||||
if(client->isSocketIO) {
|
||||
break;
|
||||
}
|
||||
case 403: ///< Forbidden
|
||||
// todo handle login
|
||||
default: ///< Server dont unterstand requrst
|
||||
ok = false;
|
||||
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] serverCode is not 101 (%d)\n", client->cCode);
|
||||
clientDisconnect(client);
|
||||
_lastConnectionFail = millis();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@ -527,15 +647,19 @@ void WebSocketsClient::handleHeader(WSclient_t * client, String * headerLine) {
|
||||
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Websocket connection init done.\n");
|
||||
headerDone(client);
|
||||
|
||||
|
||||
runCbEvent(WStype_CONNECTED, (uint8_t *) client->cUrl.c_str(), client->cUrl.length());
|
||||
|
||||
} else {
|
||||
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] no Websocket connection close.\n");
|
||||
client->tcp->write("This is a webSocket client!");
|
||||
clientDisconnect(client);
|
||||
}
|
||||
}
|
||||
} else if(clientIsConnected(client) && client->isSocketIO && client->cSessionId.length() > 0) {
|
||||
sendHeader(client);
|
||||
} else {
|
||||
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] no Websocket connection close.\n");
|
||||
_lastConnectionFail = millis();
|
||||
if(clientIsConnected(client)) {
|
||||
write(client, "This is a webSocket client!");
|
||||
}
|
||||
clientDisconnect(client);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void WebSocketsClient::connectedCb() {
|
||||
|
@ -25,7 +25,6 @@
|
||||
#ifndef WEBSOCKETSCLIENT_H_
|
||||
#define WEBSOCKETSCLIENT_H_
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "WebSockets.h"
|
||||
|
||||
class WebSocketsClient: private WebSockets {
|
||||
@ -48,6 +47,14 @@ class WebSocketsClient: private WebSockets {
|
||||
void beginSSL(String host, uint16_t port, String url = "/", String fingerprint = "", String protocol = "arduino");
|
||||
#endif
|
||||
|
||||
void beginSocketIO(const char *host, uint16_t port, const char * url = "/socket.io/?EIO=3", const char * protocol = "arduino");
|
||||
void beginSocketIO(String host, uint16_t port, String url = "/socket.io/?EIO=3", String protocol = "arduino");
|
||||
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266)
|
||||
void beginSocketIOSSL(const char *host, uint16_t port, const char * url = "/socket.io/?EIO=3", const char * protocol = "arduino");
|
||||
void beginSocketIOSSL(String host, uint16_t port, String url = "/socket.io/?EIO=3", String protocol = "arduino");
|
||||
#endif
|
||||
|
||||
#if (WEBSOCKETS_NETWORK_TYPE != NETWORK_ESP8266_ASYNC)
|
||||
void loop(void);
|
||||
#else
|
||||
@ -66,10 +73,17 @@ class WebSocketsClient: private WebSockets {
|
||||
bool sendBIN(uint8_t * payload, size_t length, bool headerToPayload = false);
|
||||
bool sendBIN(const uint8_t * payload, size_t length);
|
||||
|
||||
bool sendPing(uint8_t * payload = NULL, size_t length = 0);
|
||||
bool sendPing(String & payload);
|
||||
|
||||
void disconnect(void);
|
||||
|
||||
void setAuthorization(const char * user, const char * password);
|
||||
void setAuthorization(const char * auth);
|
||||
|
||||
void setExtraHeaders(const char * extraHeaders = NULL);
|
||||
|
||||
void setReconnectInterval(unsigned long time);
|
||||
|
||||
protected:
|
||||
String _host;
|
||||
@ -82,7 +96,10 @@ class WebSocketsClient: private WebSockets {
|
||||
|
||||
WebSocketClientEvent _cbEvent;
|
||||
|
||||
void messageRecived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length);
|
||||
unsigned long _lastConnectionFail;
|
||||
unsigned long _reconnectInterval;
|
||||
|
||||
void messageReceived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length, bool fin);
|
||||
|
||||
void clientDisconnect(WSclient_t * client);
|
||||
bool clientIsConnected(WSclient_t * client);
|
||||
|
@ -40,6 +40,9 @@ WebSocketsServer::WebSocketsServer(uint16_t port, String origin, String protocol
|
||||
|
||||
_cbEvent = NULL;
|
||||
|
||||
_httpHeaderValidationFunc = NULL;
|
||||
_mandatoryHttpHeaders = NULL;
|
||||
_mandatoryHttpHeaderCount = 0;
|
||||
}
|
||||
|
||||
|
||||
@ -53,10 +56,14 @@ WebSocketsServer::~WebSocketsServer() {
|
||||
// TODO how to close server?
|
||||
#endif
|
||||
|
||||
if (_mandatoryHttpHeaders)
|
||||
delete[] _mandatoryHttpHeaders;
|
||||
|
||||
_mandatoryHttpHeaderCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* calles to init the Websockets server
|
||||
* called to initialize the Websocket server
|
||||
*/
|
||||
void WebSocketsServer::begin(void) {
|
||||
WSclient_t * client;
|
||||
@ -83,6 +90,7 @@ void WebSocketsServer::begin(void) {
|
||||
client->base64Authorization = "";
|
||||
|
||||
client->cWsRXsize = 0;
|
||||
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
|
||||
client->cHttpLine = "";
|
||||
#endif
|
||||
@ -118,7 +126,31 @@ void WebSocketsServer::onEvent(WebSocketServerEvent cbEvent) {
|
||||
_cbEvent = cbEvent;
|
||||
}
|
||||
|
||||
/**
|
||||
/*
|
||||
* Sets the custom http header validator function
|
||||
* @param httpHeaderValidationFunc WebSocketServerHttpHeaderValFunc ///< pointer to the custom http header validation function
|
||||
* @param mandatoryHttpHeaders[] const char* ///< the array of named http headers considered to be mandatory / must be present in order for websocket upgrade to succeed
|
||||
* @param mandatoryHttpHeaderCount size_t ///< the number of items in the mandatoryHttpHeaders array
|
||||
*/
|
||||
void WebSocketsServer::onValidateHttpHeader(
|
||||
WebSocketServerHttpHeaderValFunc validationFunc,
|
||||
const char* mandatoryHttpHeaders[],
|
||||
size_t mandatoryHttpHeaderCount)
|
||||
{
|
||||
_httpHeaderValidationFunc = validationFunc;
|
||||
|
||||
if (_mandatoryHttpHeaders)
|
||||
delete[] _mandatoryHttpHeaders;
|
||||
|
||||
_mandatoryHttpHeaderCount = mandatoryHttpHeaderCount;
|
||||
_mandatoryHttpHeaders = new String[_mandatoryHttpHeaderCount];
|
||||
|
||||
for (size_t i = 0; i < _mandatoryHttpHeaderCount; i++) {
|
||||
_mandatoryHttpHeaders[i] = mandatoryHttpHeaders[i];
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* send text data to client
|
||||
* @param num uint8_t client id
|
||||
* @param payload uint8_t *
|
||||
@ -251,6 +283,57 @@ bool WebSocketsServer::broadcastBIN(const uint8_t * payload, size_t length) {
|
||||
return broadcastBIN((uint8_t *) payload, length);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* sends a WS ping to Client
|
||||
* @param num uint8_t client id
|
||||
* @param payload uint8_t *
|
||||
* @param length size_t
|
||||
* @return true if ping is send out
|
||||
*/
|
||||
bool WebSocketsServer::sendPing(uint8_t num, uint8_t * payload, size_t length) {
|
||||
if(num >= WEBSOCKETS_SERVER_CLIENT_MAX) {
|
||||
return false;
|
||||
}
|
||||
WSclient_t * client = &_clients[num];
|
||||
if(clientIsConnected(client)) {
|
||||
return sendFrame(client, WSop_ping, payload, length);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool WebSocketsServer::sendPing(uint8_t num, String & payload) {
|
||||
return sendPing(num, (uint8_t *) payload.c_str(), payload.length());
|
||||
}
|
||||
|
||||
/**
|
||||
* sends a WS ping to all Client
|
||||
* @param payload uint8_t *
|
||||
* @param length size_t
|
||||
* @return true if ping is send out
|
||||
*/
|
||||
bool WebSocketsServer::broadcastPing(uint8_t * payload, size_t length) {
|
||||
WSclient_t * client;
|
||||
bool ret = true;
|
||||
for(uint8_t i = 0; i < WEBSOCKETS_SERVER_CLIENT_MAX; i++) {
|
||||
client = &_clients[i];
|
||||
if(clientIsConnected(client)) {
|
||||
if(!sendFrame(client, WSop_ping, payload, length)) {
|
||||
ret = false;
|
||||
}
|
||||
}
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266)
|
||||
delay(0);
|
||||
#endif
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool WebSocketsServer::broadcastPing(String & payload) {
|
||||
return broadcastPing((uint8_t *) payload.c_str(), payload.length());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* disconnect all clients
|
||||
*/
|
||||
@ -279,9 +362,8 @@ void WebSocketsServer::disconnect(uint8_t num) {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* set the Authorizatio for the http request
|
||||
/*
|
||||
* set the Authorization for the http request
|
||||
* @param user const char *
|
||||
* @param password const char *
|
||||
*/
|
||||
@ -386,21 +468,24 @@ bool WebSocketsServer::newClient(WEBSOCKETS_NETWORK_CLASS * TCPclient) {
|
||||
* @param client WSclient_t * ptr to the client struct
|
||||
* @param opcode WSopcode_t
|
||||
* @param payload uint8_t *
|
||||
* @param lenght size_t
|
||||
* @param length size_t
|
||||
*/
|
||||
void WebSocketsServer::messageRecived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t lenght) {
|
||||
void WebSocketsServer::messageReceived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length, bool fin) {
|
||||
WStype_t type = WStype_ERROR;
|
||||
|
||||
switch(opcode) {
|
||||
case WSop_text:
|
||||
type = WStype_TEXT;
|
||||
type = fin ? WStype_TEXT : WStype_FRAGMENT_TEXT_START;
|
||||
break;
|
||||
case WSop_binary:
|
||||
type = WStype_BIN;
|
||||
type = fin ? WStype_BIN : WStype_FRAGMENT_BIN_START;
|
||||
break;
|
||||
case WSop_continuation:
|
||||
type = fin ? WStype_FRAGMENT_FIN : WStype_FRAGMENT;
|
||||
break;
|
||||
}
|
||||
|
||||
runCbEvent(client->num, type, payload, lenght);
|
||||
runCbEvent(client->num, type, payload, length);
|
||||
|
||||
}
|
||||
|
||||
@ -446,6 +531,7 @@ void WebSocketsServer::clientDisconnect(WSclient_t * client) {
|
||||
client->cIsWebsocket = false;
|
||||
|
||||
client->cWsRXsize = 0;
|
||||
|
||||
#if (WEBSOCKETS_NETWORK_TYPE == NETWORK_ESP8266_ASYNC)
|
||||
client->cHttpLine = "";
|
||||
#endif
|
||||
@ -461,7 +547,7 @@ void WebSocketsServer::clientDisconnect(WSclient_t * client) {
|
||||
/**
|
||||
* get client state
|
||||
* @param client WSclient_t * ptr to the client struct
|
||||
* @return true = conneted
|
||||
* @return true = connected
|
||||
*/
|
||||
bool WebSocketsServer::clientIsConnected(WSclient_t * client) {
|
||||
|
||||
@ -492,7 +578,7 @@ bool WebSocketsServer::clientIsConnected(WSclient_t * client) {
|
||||
}
|
||||
#if (WEBSOCKETS_NETWORK_TYPE != NETWORK_ESP8266_ASYNC)
|
||||
/**
|
||||
* Handle incomming Connection Request
|
||||
* Handle incoming Connection Request
|
||||
*/
|
||||
void WebSocketsServer::handleNewClients(void) {
|
||||
|
||||
@ -569,46 +655,74 @@ void WebSocketsServer::handleClientData(void) {
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
* returns an indicator whether the given named header exists in the configured _mandatoryHttpHeaders collection
|
||||
* @param headerName String ///< the name of the header being checked
|
||||
*/
|
||||
bool WebSocketsServer::hasMandatoryHeader(String headerName) {
|
||||
for (size_t i = 0; i < _mandatoryHttpHeaderCount; i++) {
|
||||
if (_mandatoryHttpHeaders[i].equalsIgnoreCase(headerName))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* handle the WebSocket header reading
|
||||
* @param client WSclient_t * ptr to the client struct
|
||||
* handles http header reading for WebSocket upgrade
|
||||
* @param client WSclient_t * ///< pointer to the client struct
|
||||
* @param headerLine String ///< the header being read / processed
|
||||
*/
|
||||
void WebSocketsServer::handleHeader(WSclient_t * client, String * headerLine) {
|
||||
|
||||
static const char * NEW_LINE = "\r\n";
|
||||
|
||||
headerLine->trim(); // remove \r
|
||||
|
||||
if(headerLine->length() > 0) {
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] RX: %s\n", client->num, headerLine->c_str());
|
||||
|
||||
// websocket request starts allways with GET see rfc6455
|
||||
// websocket requests always start with GET see rfc6455
|
||||
if(headerLine->startsWith("GET ")) {
|
||||
|
||||
// cut URL out
|
||||
client->cUrl = headerLine->substring(4, headerLine->indexOf(' ', 4));
|
||||
|
||||
//reset non-websocket http header validation state for this client
|
||||
client->cHttpHeadersValid = true;
|
||||
client->cMandatoryHeadersCount = 0;
|
||||
|
||||
} else if(headerLine->indexOf(':')) {
|
||||
String headerName = headerLine->substring(0, headerLine->indexOf(':'));
|
||||
String headerValue = headerLine->substring(headerLine->indexOf(':') + 2);
|
||||
|
||||
if(headerName.equalsIgnoreCase("Connection")) {
|
||||
if(headerValue.indexOf("Upgrade") >= 0) {
|
||||
if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Connection"))) {
|
||||
headerValue.toLowerCase();
|
||||
if(headerValue.indexOf(WEBSOCKETS_STRING("upgrade")) >= 0) {
|
||||
client->cIsUpgrade = true;
|
||||
}
|
||||
} else if(headerName.equalsIgnoreCase("Upgrade")) {
|
||||
if(headerValue.equalsIgnoreCase("websocket")) {
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Upgrade"))) {
|
||||
if(headerValue.equalsIgnoreCase(WEBSOCKETS_STRING("websocket"))) {
|
||||
client->cIsWebsocket = true;
|
||||
}
|
||||
} else if(headerName.equalsIgnoreCase("Sec-WebSocket-Version")) {
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Sec-WebSocket-Version"))) {
|
||||
client->cVersion = headerValue.toInt();
|
||||
} else if(headerName.equalsIgnoreCase("Sec-WebSocket-Key")) {
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Sec-WebSocket-Key"))) {
|
||||
client->cKey = headerValue;
|
||||
client->cKey.trim(); // see rfc6455
|
||||
} else if(headerName.equalsIgnoreCase("Sec-WebSocket-Protocol")) {
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Sec-WebSocket-Protocol"))) {
|
||||
client->cProtocol = headerValue;
|
||||
} else if(headerName.equalsIgnoreCase("Sec-WebSocket-Extensions")) {
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Sec-WebSocket-Extensions"))) {
|
||||
client->cExtensions = headerValue;
|
||||
} else if(headerName.equalsIgnoreCase("Authorization")) {
|
||||
} else if(headerName.equalsIgnoreCase(WEBSOCKETS_STRING("Authorization"))) {
|
||||
client->base64Authorization = headerValue;
|
||||
} else {
|
||||
client->cHttpHeadersValid &= execHttpHeaderValidation(headerName, headerValue);
|
||||
if (_mandatoryHttpHeaderCount > 0 && hasMandatoryHeader(headerName)) {
|
||||
client->cMandatoryHeadersCount++;
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
DEBUG_WEBSOCKETS("[WS-Client][handleHeader] Header error (%s)\n", headerLine->c_str());
|
||||
}
|
||||
@ -618,8 +732,8 @@ void WebSocketsServer::handleHeader(WSclient_t * client, String * headerLine) {
|
||||
client->tcp->readStringUntil('\n', &(client->cHttpLine), std::bind(&WebSocketsServer::handleHeader, this, client, &(client->cHttpLine)));
|
||||
#endif
|
||||
} else {
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] Header read fin.\n", client->num);
|
||||
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] Header read fin.\n", client->num);
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cURL: %s\n", client->num, client->cUrl.c_str());
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cIsUpgrade: %d\n", client->num, client->cIsUpgrade);
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cIsWebsocket: %d\n", client->num, client->cIsWebsocket);
|
||||
@ -628,6 +742,8 @@ void WebSocketsServer::handleHeader(WSclient_t * client, String * headerLine) {
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cExtensions: %s\n", client->num, client->cExtensions.c_str());
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cVersion: %d\n", client->num, client->cVersion);
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - base64Authorization: %s\n", client->num, client->base64Authorization.c_str());
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cHttpHeadersValid: %d\n", client->num, client->cHttpHeadersValid);
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] - cMandatoryHeadersCount: %d\n", client->num, client->cMandatoryHeadersCount);
|
||||
|
||||
bool ok = (client->cIsUpgrade && client->cIsWebsocket);
|
||||
|
||||
@ -641,20 +757,22 @@ void WebSocketsServer::handleHeader(WSclient_t * client, String * headerLine) {
|
||||
if(client->cVersion != 13) {
|
||||
ok = false;
|
||||
}
|
||||
if(!client->cHttpHeadersValid) {
|
||||
ok = false;
|
||||
}
|
||||
if (client->cMandatoryHeadersCount != _mandatoryHttpHeaderCount) {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
|
||||
if(_base64Authorization.length() > 0) {
|
||||
if(client->base64Authorization.length() > 0) {
|
||||
String auth = "Basic ";
|
||||
auth += _base64Authorization;
|
||||
if(auth != client->base64Authorization) {
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] HTTP Authorization failed!\n", client->num);
|
||||
handleAuthorizationFailed(client);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
ok = false;
|
||||
}
|
||||
String auth = WEBSOCKETS_STRING("Basic ");
|
||||
auth += _base64Authorization;
|
||||
if(auth != client->base64Authorization) {
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] HTTP Authorization failed!\n", client->num);
|
||||
handleAuthorizationFailed(client);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if(ok) {
|
||||
@ -668,32 +786,30 @@ void WebSocketsServer::handleHeader(WSclient_t * client, String * headerLine) {
|
||||
|
||||
client->status = WSC_CONNECTED;
|
||||
|
||||
client->tcp->write("HTTP/1.1 101 Switching Protocols\r\n"
|
||||
String handshake = WEBSOCKETS_STRING("HTTP/1.1 101 Switching Protocols\r\n"
|
||||
"Server: arduino-WebSocketsServer\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Version: 13\r\n"
|
||||
"Sec-WebSocket-Accept: ");
|
||||
client->tcp->write(sKey.c_str(), sKey.length());
|
||||
handshake += sKey + NEW_LINE;
|
||||
|
||||
if(_origin.length() > 0) {
|
||||
String origin = "\r\nAccess-Control-Allow-Origin: ";
|
||||
origin += _origin;
|
||||
origin += "\r\n";
|
||||
client->tcp->write(origin.c_str(), origin.length());
|
||||
handshake += WEBSOCKETS_STRING("Access-Control-Allow-Origin: ");
|
||||
handshake +=_origin + NEW_LINE;
|
||||
}
|
||||
|
||||
if(client->cProtocol.length() > 0) {
|
||||
String protocol = "\r\nSec-WebSocket-Protocol: ";
|
||||
protocol += _protocol;
|
||||
protocol += "\r\n";
|
||||
client->tcp->write(protocol.c_str(), protocol.length());
|
||||
} else {
|
||||
client->tcp->write("\r\n");
|
||||
handshake += WEBSOCKETS_STRING("Sec-WebSocket-Protocol: ");
|
||||
handshake +=_protocol + NEW_LINE;
|
||||
}
|
||||
|
||||
// header end
|
||||
client->tcp->write("\r\n");
|
||||
handshake += NEW_LINE;
|
||||
|
||||
DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] handshake %s", client->num, (uint8_t*)handshake.c_str());
|
||||
|
||||
write(client, (uint8_t*)handshake.c_str(), handshake.length());
|
||||
|
||||
headerDone(client);
|
||||
|
||||
|
@ -25,7 +25,6 @@
|
||||
#ifndef WEBSOCKETSSERVER_H_
|
||||
#define WEBSOCKETSSERVER_H_
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "WebSockets.h"
|
||||
|
||||
#define WEBSOCKETS_SERVER_CLIENT_MAX (5)
|
||||
@ -33,13 +32,15 @@
|
||||
|
||||
|
||||
|
||||
class WebSocketsServer: private WebSockets {
|
||||
class WebSocketsServer: protected WebSockets {
|
||||
public:
|
||||
|
||||
#ifdef __AVR__
|
||||
typedef void (*WebSocketServerEvent)(uint8_t num, WStype_t type, uint8_t * payload, size_t length);
|
||||
typedef bool (*WebSocketServerHttpHeaderValFunc)(String headerName, String headerValue);
|
||||
#else
|
||||
typedef std::function<void (uint8_t num, WStype_t type, uint8_t * payload, size_t length)> WebSocketServerEvent;
|
||||
typedef std::function<bool (String headerName, String headerValue)> WebSocketServerHttpHeaderValFunc;
|
||||
#endif
|
||||
|
||||
WebSocketsServer(uint16_t port, String origin = "", String protocol = "arduino");
|
||||
@ -55,6 +56,10 @@ public:
|
||||
#endif
|
||||
|
||||
void onEvent(WebSocketServerEvent cbEvent);
|
||||
void onValidateHttpHeader(
|
||||
WebSocketServerHttpHeaderValFunc validationFunc,
|
||||
const char* mandatoryHttpHeaders[],
|
||||
size_t mandatoryHttpHeaderCount);
|
||||
|
||||
|
||||
bool sendTXT(uint8_t num, uint8_t * payload, size_t length = 0, bool headerToPayload = false);
|
||||
@ -75,6 +80,12 @@ public:
|
||||
bool broadcastBIN(uint8_t * payload, size_t length, bool headerToPayload = false);
|
||||
bool broadcastBIN(const uint8_t * payload, size_t length);
|
||||
|
||||
bool sendPing(uint8_t num, uint8_t * payload = NULL, size_t length = 0);
|
||||
bool sendPing(uint8_t num, String & payload);
|
||||
|
||||
bool broadcastPing(uint8_t * payload = NULL, size_t length = 0);
|
||||
bool broadcastPing(String & payload);
|
||||
|
||||
void disconnect(void);
|
||||
void disconnect(uint8_t num);
|
||||
|
||||
@ -90,16 +101,19 @@ protected:
|
||||
String _origin;
|
||||
String _protocol;
|
||||
String _base64Authorization; ///< Base64 encoded Auth request
|
||||
String * _mandatoryHttpHeaders;
|
||||
size_t _mandatoryHttpHeaderCount;
|
||||
|
||||
WEBSOCKETS_NETWORK_SERVER_CLASS * _server;
|
||||
|
||||
WSclient_t _clients[WEBSOCKETS_SERVER_CLIENT_MAX];
|
||||
|
||||
WebSocketServerEvent _cbEvent;
|
||||
WebSocketServerHttpHeaderValFunc _httpHeaderValidationFunc;
|
||||
|
||||
bool newClient(WEBSOCKETS_NETWORK_CLASS * TCPclient);
|
||||
|
||||
void messageRecived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length);
|
||||
void messageReceived(WSclient_t * client, WSopcode_t opcode, uint8_t * payload, size_t length, bool fin);
|
||||
|
||||
void clientDisconnect(WSclient_t * client);
|
||||
bool clientIsConnected(WSclient_t * client);
|
||||
@ -111,7 +125,6 @@ protected:
|
||||
|
||||
void handleHeader(WSclient_t * client, String * headerLine);
|
||||
|
||||
|
||||
/**
|
||||
* called if a non Websocket connection is coming in.
|
||||
* Note: can be override
|
||||
@ -136,8 +149,7 @@ protected:
|
||||
* @param client WSclient_t * ptr to the client struct
|
||||
*/
|
||||
virtual void handleAuthorizationFailed(WSclient_t *client) {
|
||||
|
||||
client->tcp->write("HTTP/1.1 401 Unauthorized\r\n"
|
||||
client->tcp->write("HTTP/1.1 401 Unauthorized\r\n"
|
||||
"Server: arduino-WebSocket-Server\r\n"
|
||||
"Content-Type: text/plain\r\n"
|
||||
"Content-Length: 45\r\n"
|
||||
@ -162,6 +174,30 @@ protected:
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Called at client socket connect handshake negotiation time for each http header that is not
|
||||
* a websocket specific http header (not Connection, Upgrade, Sec-WebSocket-*)
|
||||
* If the custom httpHeaderValidationFunc returns false for any headerName / headerValue passed, the
|
||||
* socket negotiation is considered invalid and the upgrade to websockets request is denied / rejected
|
||||
* This mechanism can be used to enable custom authentication schemes e.g. test the value
|
||||
* of a session cookie to determine if a user is logged on / authenticated
|
||||
*/
|
||||
virtual bool execHttpHeaderValidation(String headerName, String headerValue) {
|
||||
if(_httpHeaderValidationFunc) {
|
||||
//return the value of the custom http header validation function
|
||||
return _httpHeaderValidationFunc(headerName, headerValue);
|
||||
}
|
||||
//no custom http header validation so just assume all is good
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
/*
|
||||
* returns an indicator whether the given named header exists in the configured _mandatoryHttpHeaders collection
|
||||
* @param headerName String ///< the name of the header being checked
|
||||
*/
|
||||
bool hasMandatoryHeader(String headerName);
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
24
travis/common.sh
Normal file
24
travis/common.sh
Normal file
@ -0,0 +1,24 @@
|
||||
#!/bin/bash
|
||||
|
||||
function build_sketches()
|
||||
{
|
||||
local arduino=$1
|
||||
local srcpath=$2
|
||||
local platform=$3
|
||||
local sketches=$(find $srcpath -name *.ino)
|
||||
for sketch in $sketches; do
|
||||
local sketchdir=$(dirname $sketch)
|
||||
if [[ -f "$sketchdir/.$platform.skip" ]]; then
|
||||
echo -e "\n\n ------------ Skipping $sketch ------------ \n\n";
|
||||
continue
|
||||
fi
|
||||
echo -e "\n\n ------------ Building $sketch ------------ \n\n";
|
||||
$arduino --verify $sketch;
|
||||
local result=$?
|
||||
if [ $result -ne 0 ]; then
|
||||
echo "Build failed ($1)"
|
||||
return $result
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
Reference in New Issue
Block a user