Giter Site home page Giter Site logo

links2004 / arduinowebsockets Goto Github PK

View Code? Open in Web Editor NEW
1.8K 89.0 547.0 646 KB

arduinoWebSockets

License: GNU Lesser General Public License v2.1

C++ 83.51% C 9.31% HTML 0.81% JavaScript 1.19% Shell 2.60% Python 2.58%
arduino-library websocket-server wss ws websocket websockets websocket-client esp8266 esp

arduinowebsockets's Introduction

WebSocket Server and Client for Arduino Build Status

a WebSocket Server and Client for Arduino based on RFC6455.

Supported features of RFC6455
  • text frame
  • binary frame
  • connection close
  • ping
  • pong
  • 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 for more info and a potential workaround.
  • wss / SSL is not possible.
Supported Hardware
  • ESP8266 Arduino for ESP8266
  • ESP32 Arduino for ESP32
  • ESP31B
  • Raspberry Pi Pico W Arduino for Pico
  • 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.0 and up is not compatible with AVR/ATmega, check ATmega branch.

version 2.3.0 has API changes for the ESP8266 BareSSL (may brakes existing code)

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 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 activated in the WebSockets.h (see WEBSOCKETS_NETWORK_TYPE define).

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_PING,
    WStype_PONG,
} WStype_t;

Issues

Submit issues to: https://github.com/Links2004/arduinoWebSockets/issues

Join the chat at https://gitter.im/Links2004/arduinoWebSockets

License and credits

The library is licensed under LGPLv2.1

libb64 written by Chris Venter. It is distributed under Public Domain see LICENSE.

arduinowebsockets's People

Contributors

amrbekhit avatar bebo-dot-dev avatar brtiberio avatar carlosrdomin avatar chemicstry avatar d-a-v avatar hasenradball avatar itay7564 avatar ivankravets avatar jc19000 avatar jesben avatar kenkeiras avatar kenkus-futurice avatar links2004 avatar lucalas avatar matth-x avatar maurus95 avatar mavyfaby avatar mgbckr avatar mvermand22 avatar nerochiaro avatar ninban avatar shrynshjn avatar simap avatar sovcik avatar ssh2go avatar tony763 avatar urish avatar wnemay avatar yacubane avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

arduinowebsockets's Issues

Can't compile

Hi,
This library sounds great, but I can't compile on Arduino IDE. It gives me

fatal error: core_esp8266_features.h: No such file or directory
I have esp8266 core version 2.0, and it's working fine.

Error

Arduino: 1.6.7 (Mac OS X), Board: "Arduino/Genuino Uno"

/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp: In member function 'void WebSockets::sendFrame(WSclient_t_, WSopcode_t, uint8_t_, size_t, bool, bool, bool)':
/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:182:34: warning: right shift count >= width of type [enabled by default]
*headerPtr = ((length >> 24) & 0xFF);

                              ^

/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:184:34: warning: right shift count >= width of type [enabled by default]
*headerPtr = ((length >> 16) & 0xFF);

                              ^

/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp: In member function 'bool WebSockets::handleWebsocketWaitFor(WSclient_t*, size_t)':
/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:299:87: error: 'bind' is not a member of 'std'
readCb(client, &client->cWsHeader[client->cWsRXsize], (size - client->cWsRXsize), std::bind([](WebSockets * server, size_t size, WSclient_t * client, bool ok) {

                                                                                   ^

/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:310:25: error: 'std::placeholders' has not been declared
}, this, size, std::placeholders::_1, std::placeholders::_2));

                     ^

/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:310:48: error: 'std::placeholders' has not been declared
}, this, size, std::placeholders::_1, std::placeholders::_2));

                                            ^

/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp: In member function 'void WebSockets::handleWebsocketCb(WSclient_t*)':
/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:359:32: warning: large integer implicitly truncated to unsigned type [-Woverflow]
header->payloadLen = 0xFFFFFFFF;

                            ^

/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:361:47: warning: left shift count >= width of type [enabled by default]
header->payloadLen = buffer[4] << 24 | buffer[5] << 16 | buffer[6] << 8 | buffer[7];

                                           ^

/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:361:65: warning: left shift count >= width of type [enabled by default]
header->payloadLen = buffer[4] << 24 | buffer[5] << 16 | buffer[6] << 8 | buffer[7];

                                                             ^

/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:394:53: error: 'bind' is not a member of 'std'
readCb(client, payload, header->payloadLen, std::bind(&WebSockets::handleWebsocketPayloadCb, this, placeholders::_1, std::placeholders::_2, payload));

                                                 ^

/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:394:108: error: 'placeholders' has not been declared
readCb(client, payload, header->payloadLen, std::bind(&WebSockets::handleWebsocketPayloadCb, this, placeholders::_1, std::placeholders::_2, payload));

                                                                                                        ^

/Users/iMohammad/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:394:131: error: 'std::placeholders' has not been declared
readCb(client, payload, header->payloadLen, std::bind(&WebSockets::handleWebsocketPayloadCb, this, placeholders::_1, std::placeholders::_2, payload));

                                                                                                                               ^

exit status 1
Error compiling.
Error downloading http://downloads.arduino.cc/libraries/library_index.json
java.lang.RuntimeException: java.lang.Exception: Error downloading http://downloads.arduino.cc/libraries/library_index.json
at cc.arduino.contributions.libraries.ui.LibraryManagerUI.lambda$onUpdatePressed$13(LibraryManagerUI.java:205)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.Exception: Error downloading http://downloads.arduino.cc/libraries/library_index.json
at cc.arduino.contributions.DownloadableContributionsDownloader.download(DownloadableContributionsDownloader.java:113)
at cc.arduino.contributions.JsonDownloader.download(JsonDownloader.java:49)
at cc.arduino.contributions.GZippedJsonDownloader.download(GZippedJsonDownloader.java:59)
at cc.arduino.contributions.libraries.LibraryInstaller.updateIndex(LibraryInstaller.java:66)
at cc.arduino.contributions.libraries.ui.LibraryManagerUI.lambda$onUpdatePressed$13(LibraryManagerUI.java:202)
... 1 more
Caused by: java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:792)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:789)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1536)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at cc.arduino.utils.network.FileDownloader.downloadFile(FileDownloader.java:166)
at cc.arduino.utils.network.FileDownloader.download(FileDownloader.java:123)
at cc.arduino.contributions.DownloadableContributionsDownloader.download(DownloadableContributionsDownloader.java:111)
... 5 more

This report would have more information with
"Show verbose output during compilation"
enabled in File > Preferences.

Esp+ smartphone

hey there. I would like to use this awesome project. can you clarify some things for me as Im a beginner. I want to:

  1. run websocket server on esp8266 which also acts as an AP but there is no internet connection.
  2. run websocket client on smartphone which connects to AP on esp and communicates values to the esp
    Is this possible? again sorry for the newbie questions. how do I proceed? write webserver sketch to esp using arduino IDE and run client as a webapp either from phone or pc? thanks for your support

Getting disconnected after 1 or 2 messages if sent from input interrupt handler

I am testing WebSocketClient.ino on Adafruit HUZZAH ESP8266 breakout using node webSocketServer. I modified WebSocketClient.ino to add input interrupt from push button which sends a text message. First message works and then it disconnects.

Here is the code:

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <WebSocketsClient.h>

#include <Hash.h>

ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;


void webSocketEvent(WStype_t type, uint8_t * payload, size_t lenght) {


    switch(type) {
        case WStype_DISCONNECTED:
            Serial.printf("[WSc] Disconnected!\n");
            break;
        case WStype_CONNECTED:
            {
                Serial.printf("[WSc] Connected to url: %s\n",  payload);

                // send message to server when Connected
                webSocket.sendTXT("Connected");
            }
            break;
        case WStype_TEXT:
            Serial.printf("[WSc] get text: %s\n", payload);

            // send message to server
            // webSocket.sendTXT("message here");
            break;
        case WStype_BIN:
            Serial.printf("[WSc] get binary lenght: %u\n", lenght);
            hexdump(payload, lenght);

            // send data to server
            // webSocket.sendBIN(payload, lenght);
            break;
    }

}


void inputChanged() {
   Serial.printf("inputChanged\n");
   webSocket.sendTXT("inputChanged");
}

void setup() {

    Serial.begin(115200);

    Serial.setDebugOutput(true);

    for(uint8_t t = 4; t > 0; t--) {
        Serial.printf("[SETUP] BOOT WAIT %d...\n", t);
        Serial.flush();
        delay(1000);
    }


    WiFiMulti.addAP("KWN", "xxxxxxxx");


    //WiFi.disconnect();
    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
    }

    webSocket.begin("192.168.0.10", 81);
    webSocket.onEvent(webSocketEvent);

    pinMode(0, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(0), inputChanged, RISING);

}



void loop() {
    webSocket.loop();

}

Here is what i get from serial monitor:

[SETUP] BOOT WAIT 4...
scandone
state: 0 -> 2 (b0)
[SETUP] BOOT WAIT 3...
reconnect
state: 2 -> 0 (0)
f 0, [SETUP] BOOT WAIT 2...
scandone
state: 0 -> 2 (b0)
[SETUP] BOOT WAIT 1...
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 4
cnt 

connected with KWN, channel 11
dhcp client start...
state: 5 -> 0 (0)
rm 0
f 0, scandone
f 0, scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 4
cnt 

connected with KWN, channel 11
dhcp client start...
ip:192.168.0.16,mask:255.255.255.0,gw:192.168.0.1
[WSc] Connected to url: /
[WSc] get text: Hallo Client!
[WSc] get text: Connected
inputChanged
[WSc] get text: inputChanged
inputChanged
inputChanged
[WSc] Disconnected!

Here is what i see on the server side:

Thu Dec 17 2015 03:35:57 GMT-0600 (Central Standard Time) Connection accepted.
Received Message: Connected
Received Message: inputChanged
Thu Dec 17 2015 03:37:25 GMT-0600 (Central Standard Time) Peer ::ffff:192.168.0.16 disconnected.

sendTXT works fine if i placed it in loop as shown below and it doesn't get disconnected.

void loop() {
    webSocket.loop();


        static unsigned long last = 0;

        if(abs(millis() - last) > 1000) {
        webSocket.sendTXT(String(millis()));
        last = millis();

}

But if i press the button it disconnects. If i remove the sendTXT from button interrupt handler , connection stays alive.

Any idea what could be causing this issue?

use of websockets within wifimesh

Dear,

Your library seems really good, especially after reviewing some of the test results (messages/second) between two instances (pc and esp8266).

Do you think that your code running on 20/30 esp8266 (each node being both server and client, connected to all of the other nodes and connected to a router (for ntp e.g.)) is capable of handling 20/30 active ws connections on each of the nodes (and about 1 message per second per connection), without the use of wss, so normal wc over TCP?

Thank you so much in advance!

ps, am I correct when I claim that an (extra) ws connection doesn't require much resources if no messages are being pushed over the channel (except from the ping/pong)?

problem compiling your examples

I'm learning about websockets to use in my project.
Your example :WebSocketServer_LEDcontrol.ino seems to be just what I need! Thank you!
But: trying to compile (win10, Arduino 1.6.7) I keep getting this error:

Arduino: 1.6.7 (Windows 10), Board:"NodeMCU 0.9 (ESP-12 Module), 80 MHz, Serial, 115200, 4M (3M SPIFFS)"
C:\Users\Ton\Documents\Arduino\libraries\arduinoWebSockets\src\WebSockets.cpp:28:35: fatal error: core_esp8266_features.h: No such file or directory

include <core_esp8266_features.h>

                                                         ^

compilation terminated.
exit status 1

What can I do?
Thank you for helping me out ...

Ton

Example with both server and client with ESP8266

I am trying to create on 2 nodeMCU's a socket connection.
On one I install the server example on the other the client example.
How do I send a message from my client to the server. The IP's are correct and I added in the loop a simple sendTXT but all I get is messages that the buffer is overflowing. Is there an example containing my question? If I use the browser and change it to the server IP the browser test works great,

use web-socket as secure single connection

hi Markus , I have webserver sketch which is serve about 500 kb html file in SPIFF, if I use the only HTTP webserver , the latency is long , the download is so slow and somehow the module cant understand which client is main and chocked by request of other clients, however your suggestion to using ESPAsyncTCP & ESPAsyncWebServer was not successful so I thought maybe we could use webserver to create the secure long stand single connection with client and whereas the connection is live the module can check sensor status in loop
any replay appreciated

Websocket freezes - LmacRxBlk:1

Hi,

So I've been using your code for quite sometime and found it very nice.
However, I've encountered a "timing" problem: When I try to send data from the ESP8266 but its "receiving buffer" is still not empty, the code sometime stuck and stop working, solved only with reset.

Don't know if it is my fault for using it wrong or if not what is the best way to fix it - But at least in my case I wrote a small patch which solved the issue (I'm not the best coder).

On WebSocketServer.cpp, on the "WebSocketsServer::sendTXT" function I've added just before the "sendFrame" function this code:

if(client->tcp.available() > 0) {
    DEBUG_WEBSOCKETS("[WS-Server][%d][handleHeader] SEND: Buffer is not empty, cancelling respond");
    return;
}

which cancels the sending in case the buffer is not empty.

If I'm not the first one reporting this issue please let me know if there's a better solution.

Thanks,
Amir

Maximum number of connections?

Hello, I'm using esp8266 and my project requires that more computer are connected to my esp websocket server. But maximum number of connections I can achieve is 4.
If more computers try to connect it refuses. Any ideas what is wrong?

handle authentification

if using WebSocketClient on arduino with a non arduino Socket server, what's the best way to handle authentification ?
Can an example be provided ? ( or just explain and i will write a PR for this )

about #define USE_SERIAL Serial1

dear friend,
first,when I use your client from example, I don't know yours "Serial1" is from which library? how can read serial data.
secondly, I used nodemcu0.9 module, take ch340g connected mcu's rx(D9),tx(D10), received lots of messy code.
may you help me. thanks.

error: 'WiFiClientSecure' does not name a type WiFiClientSecure * ssl;

when i add this library it throws me this error when i verify it.

In file included from C:\Program Files (x86)\Arduino\libraries\arduinoWebSockets-master\src/WebSocketsServer.h:29:0,
             from WiFiMulti.ino:8:
C:\Program Files (x86)\Arduino\libraries\arduinoWebSockets-master\src/WebSockets.h:120:9: error: 'WiFiClientSecure' does not name a type
     WiFiClientSecure * ssl;
     ^
Error compiling.

Compilation error

Just try to compile WebSocketClient example

Arduino: 1.6.7 (Mac OS X), Плата:"Generic ESP8266 Module, Serial, 80 MHz, 40MHz, DIO, 921600, 4M (3M SPIFFS), ck"

/Users/artem/Documents/Arduino/libraries/WebSockets/src/WebSockets.cpp:28:35: fatal error: core_esp8266_features.h: No such file or directory
#include <core_esp8266_features.h>

compilation terminated.
exit status 1

`

Compilation issue

This is probably more a doc request, but anyway...

I installed the library by cloning it under ~/Arduino/libraries

Compiling sketches that #include <WebSocketsServer.h> fail with:
/home/fabrice/Arduino/libraries/arduinoWebSockets/src/WebSockets.cpp:28:35: fatal error: core_esp8266_features.h: No such file or directory
#include <core_esp8266_features.h>

core_esp8266_features.h is present at ~/soft/arduino-1.6.7/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_features.h

What am I doing wrong?

core_esp8266_main.cpp issue

Hi there,
When I compile examples I get this error:

/Users/xxxxx/Documents/Arduino/libraries/esp8266/core_esp8266_main.cpp: In function 'void esp_schedule()':
/Users/xxxxx/Documents/Arduino/libraries/esp8266/core_esp8266_main.cpp:76:38: error: 'ets_post' was not declared in this scope
     ets_post(LOOP_TASK_PRIORITY, 0, 0);
                                      ^
/Users/xxxx/Documents/Arduino/libraries/esp8266/core_esp8266_main.cpp: In function 'void user_init()':
/Users/xxxxx/Documents/Arduino/libraries/esp8266/core_esp8266_main.cpp:149:24: error: 'ets_task' was not declared in this scope
         LOOP_QUEUE_SIZE);
                        ^
Error compiling.

Please help

implement WStype_BAD_REQUEST in WebSocketServer

It would be nice to implement a WStype_BAD_REQUEST for non-websocket connections and allow user to send a different response rather than the hard-coded one ( HTTP/1.1 400 Bad Request ) . This also can be used to handle simple non-websocket requests.
_cbEvent(client->num, WStype_BAD_REQUEST, (uint8_t *) client->cUrl.c_str(), client->cUrl.length());
If after calling the event connection is still open , or some variable is set , then fall -back to same hard-coded message as it is now at the end of WebSocketsServer.cpp file. I could fork this , but I think it would be a nice feature to the base code :)

Usage inside a c++ class

I have problems using onEvent inside another c++ class. Can you help me?

void Connection::connect(String host, int port, String fingerprint, String token) {
  Serial.println(String("Connect to ws://")+host+":"+port+" with token "+token);
  this->host = host;
  this->port = port;
  this->fingerprint = fingerprint;
  this->token = token;

  this->ws.protocol = "io-json-v1";
  this->ws.beginSSL(this->host, this->port, "/channel", this->fingerprint);

// attempt 1
//  this->ws.onEvent(std::bind(&Connection::onWebSocketEvent, this));

// attempt 2
  this->ws.onEvent([&](WStype_t type, uint8_t* payload, size_t length) {
    this->onWebSocketEvent(type, payload, length);
  });
}

void Connection::onWebSocketEvent(WStype_t type, uint8_t* payload, size_t length) {
  // ...
}

On my first attempt I get this error:

IO.cpp: In member function 'void Connection::connect(String, int, String, String)':
IO.cpp:16: error: no matching function for call to 'WebSocketsClient::onEvent(std::_Bind_helper<false, void (Connection::*)(WStype_t, unsigned char*, unsigned int), Connection* const>::type)'
   this->ws.onEvent(std::bind(&Connection::onWebSocketEvent, this));
                                                                  ^
IO.cpp:16:66: note: candidate is:
In file included from IO.h:7:0,
                 from IO.cpp:1:
/Users/chris/Documents/Arduino/libraries/arduinoWebSockets/src/WebSocketsClient.h:50:14: note: void WebSocketsClient::onEvent(WebSocketsClient::WebSocketClientEvent)
         void onEvent(WebSocketClientEvent cbEvent);
              ^
/Users/chris/Documents/Arduino/libraries/arduinoWebSockets/src/WebSocketsClient.h:50:14: note:   no known conversion for argument 1 from 'std::_Bind_helper<false, void (Connection::*)(WStype_t, unsigned char*, unsigned int), Connection* const>::type {aka std::_Bind<std::_Mem_fn<void (Connection::*)(WStype_t, unsigned char*, unsigned int)>(Connection*)>}' to 'WebSocketsClient::WebSocketClientEvent {aka void (*)(WStype_t, unsigned char*, unsigned int)}'
no matching function for call to 'WebSocketsClient::onEvent(std::_Bind_helper<false, void (Connection::*)(WStype_t, unsigned char*, unsigned int), Connection* const>::type)'

On the second:

IO.cpp: In member function 'void Connection::connect(String, int, String, String)':
IO.cpp:20: error: no matching function for call to 'WebSocketsClient::onEvent(Connection::connect(String, int, String, String)::__lambda0)'
   });
    ^
IO.cpp:20:4: note: candidate is:
In file included from IO.h:7:0,
                 from IO.cpp:1:
/Users/chris/Documents/Arduino/libraries/arduinoWebSockets/src/WebSocketsClient.h:50:14: note: void WebSocketsClient::onEvent(WebSocketsClient::WebSocketClientEvent)
         void onEvent(WebSocketClientEvent cbEvent);
              ^
/Users/chris/Documents/Arduino/libraries/arduinoWebSockets/src/WebSocketsClient.h:50:14: note:   no known conversion for argument 1 from 'Connection::connect(String, int, String, String)::__lambda0' to 'WebSocketsClient::WebSocketClientEvent {aka void (*)(WStype_t, unsigned char*, unsigned int)}'
no matching function for call to 'WebSocketsClient::onEvent(Connection::connect(String, int, String, String)::__lambda0)'

Unable to compile examples with ESP Arduino v2.0.0

I seem to be unable to compile any of the examples with v2.0.0. The error I get is

\Arduino\libraries\arduinoWebSockets\src\WebSockets.cpp:28:35: fatal error:core_esp8266_features.h: No such file or directory  #include <core_esp8266_features.h>

I am a bit new to git, so I am using this library with Arduino 1.6.5 along with the board manager.
But according to commit 92a63e9, it should work right?

Closed connection not noticed by WebSocketClient

Hi!

Thank you for coding such a great websocket library! It works like a charm!
However, I am running into the following issue...
I have an ESP8266 websocket client running your code and it connects to a php ratchet websocket server (latest version: 0.3.3). The ESP2866 waits for commands from other websocket clients to do something. This works perfectly, however, after a while (more than 20-30 minutes) the connection closes (most likely initiated by the client). This shows up in the ratchet log BUT the websocket client still says _client.tcp.connected() == true. I checked whether it was ratchet falsely claiming the connection was closed, but after running "netstat -natp" on the websocket server it became clear that indeed there is no active connection anymore between the ratchet server and the ESP8266 client while _client.tcp.connected() in the loop function still returns true :-(...

I checked online and found this on https://www.arduino.cc/en/Reference/WiFiClientConnected:

"Note that a client is considered connected if the connection has been closed but there is still unread data."

So maybe there is still unread data in the connection somehow? Or perhaps a bug in the ESP's tcp stack?

Thanx!

Jeroen

More than 10 messages a second gives error LmacRxBlk:1

Using the server example and the html in the test subfolder, the updates (time messages) come in at 1 update every second. If I lower the html polling interval to <100ms it crashes with a message LmacRxBlk:1, which as I understand is a full buffer, but can't find a way to circumvent this. Is this maybe a bug?

I can't figure out what is wrong. Any help appreciated!
I tried to attach the html code but can't. Below the html with all <> replaced by []

[html]
[head]

[script]
var connection = new WebSocket('ws://192.168.0.13:81/test', ['arduino']);

connection.onopen = function () {
connection.send('Message from Browser to ESP8266 yay its Working!! ' + new Date());
connection.send('ping');
setTimeout(refresh,3000);
};

connection.onerror = function (error) {
console.log('WebSocket Error ', error);
};

connection.onmessage = function (e) {
console.log('Server: ', e.data);
};

function refresh(){
connection.send('Time: ' + new Date());
setTimeout(refresh,50);
}
[/script]

[/head]
[body]
Test Websocket.
[/body]
[/html]

Wrong data sent to C++ libWebSockets server

I' m using esp8266 with this library to connect as a client to a C++ websocket server.
With "WebSocketClient" example, connection and handshake complete successfully, but when I send a simple text message (like "hello"), the C++ server receive the "hello" text, plus some incomprehnsible characters.
In addition, my server crash because the message is always bigger than buffer of server, whatever the size.
All libs are RFC6455 (websocket v13) compilant.
Here part of ESP8266 log:

[WS-Client][handleHeader] Websocket connection init done.
[WS][0][headerDone] Header Handling Done (0us).
Connection: Upgrade
[WS-Client][handleHeader] RX: Sec-WebSocket-Accept: wF4RQ16RitGys2E5mhs0fSeme] fin: 1 opCode: 2 mask: 1 length: 1 headerToPayload: 0
[WS][0][sendFrame] pack to one TCP package...
JUSM=
[WS-Client][handleHeader] RX: Sec-WebSocket-Protocol: instruction_protocol
[WS-Client][handleHeader] Header read fin.
[WS-Client][handleHeader] Client[WSc] Connected to url: /
[WS][0][sendFrame] ------- send massage frame -------
[WS][0][sendFra[WS][0][sendFrame] sending Frame Done (42313us).
[WS-Client] connection lost.
[WS-Client] client disconnected.
[WSc] Disconnected!

And here C++ Server

[1454767129:5654] NOTICE: Libwebsockets version: 1.6.0 5086597
[1454767129:5654] NOTICE: IPV6 not compiled in
[1454767129:5654] NOTICE: libev support not compiled in
[1454767129:5654] NOTICE: Threads: 1 each 4096 fds
[1454767129:5654] NOTICE: mem: platform fd map: 32768 bytes
[1454767129:5654] NOTICE: mem: per-conn: 368 bytes + protocol rx buf
[1454767129:5655] NOTICE: canonical_hostname = teo-laptop
[1454767129:5655] NOTICE: Compiled with OpenSSL support
[1454767129:5655] NOTICE: Using non-SSL mode
[1454767129:5669] NOTICE: Listening on port 9002
Client connected. Ip: 192.168.1.9 Name: ESP_D56E95
Instr: size=3002370 and cont=s
RUN FINISHED; Aborted; real time: 4s; user: 0ms; system: 0ms

Someone can help me ?

Error compiling

Hi,
Try to compile WebSocketClient, I got this message. Could you help me?
I am using ESP8266 Arduino IDE and ESP-12Module on MAC.
thanks.

WebSocket/WebSockets.cpp.o:(.text+0x1c): undefined reference to base64_init_encodestate' WebSocket/WebSockets.cpp.o:(.text+0x20): undefined reference tobase64_encode_block'
WebSocket/WebSockets.cpp.o:(.text+0x24): undefined reference to base64_encode_blockend' WebSocket/WebSockets.cpp.o: In functionWebSockets::base64_encode(unsigned char*, unsigned int)':
WebSockets.cpp:(.text+0x6b): undefined reference to base64_init_encodestate' WebSockets.cpp:(.text+0x79): undefined reference tobase64_encode_block'
WebSockets.cpp:(.text+0x83): undefined reference to `base64_encode_blockend'
collect2: error: ld returned 1 exit status
Error compiling.

LmacRxBlk:1 when receiving messages too fast

I'm using this library for exchanging JSON messages between ESP8266 and servers. But it is very frustrating to see my ESP freeze when I try to send messages too fast.
What I'm trying to do is to send is 73 characters long JSON message every three seconds from server to ESP. ESP also broadcasts JSON message to servers every two seconds.

After some time (few seconds) I get LmacRxBlk:1 message and my ESP freezes for few seconds and sometimes even resets.

I'm using esp8266 core version: 2.1.0-rc2.
Any idea to prevent ESP crashing if it receives too many messages from server?

Problem with using two ESP8266 and websockets

I use this websocket server on my ESP8266 and I'm trying to connect from my PC in order to read sensor data. Sometimes websocket connection fails but when I click reconnect on my PC it connects again... it is not major problem
But when I connect another ESP8266 at the same network both ESP freezes. Main loop is executing but websocket server freezes. Nothing helps but restart.

Any ideas to solve this problem? What causes freezing when another websocket server is active at the same network?

Header names are case sensitive.

After two days of debugging to try and figure out why my luvit websocket client couldn't connect, I discovered that my header names had Websocket while browsers had WebSocket. A proper websocket server should do a case insensitive check.

It's up to you if you think it's worth the extra code and performance cost to do all header keys case insensitive. In this case I just changed my client to better match what browsers send so I'm not blocked by this.

luvit/lit@4dacac1

How to enable Debug and Ratchet?

Sorry for the noob question.

I see many times in issues the line for enable debug. In line 30 in WebSockets.h
But, i dont understand what i need put in line 30 for debug works.
I tried Serial, Serial1, Serial2, Serial3... But no ones works. In all cases i got an error in compilation.

I need to debug because Arduino is not connecting the WebSocket server made in Ratchet (PHP).
I see the connection in Ratchet console, but Arduino disconnects immediately following.

Anyone Can help me?

How to send sensor status from the arduino?

Great library! None of the examples I can find, try to initiate a message from the Arduino. How do you do that? I would imagine something like this (which doesn't compile):

void loop() {
    webSocket.loop();
    server.handleClient();

    if (digitalRead(SENSOR) == HIGH) {
        webSocket.sendTXT("Sensor has spotted something");
    }
}

EDIT: Sorry - saw in your src that I forgot to supply num, payload, length to the command.

missing Hash.h

Trying to compile the WebsocketServer example I get: fatal error: Hash.h: No such file or directory

webSocket.sendTXT

Hopefully I am doing something wrong, but it looks like it takes around 400 milliseconds to transmit simple messages.

My code for the ESP8266:

void loop() 
{
  webSocket.loop();
  webSocket.sendTXT("1");
}

The websocket that it is connecting to is a simple NodeJS script that measures time between messages. It shows an average duration between messages of 400 milliseconds. I can send data from a web browser and have it received with no noticeable latency.

It seems like I should be able to send data much faster than this. Can you advise?

Thanks.

Fatal exception (28):

It compiles and uploads just fine but, something goes quite wrong when running...
Any idea of what it could be?

Running W7, Arduino IDE 1.6.5 and downloaded the sources for both ESP8266/Arduino and the arduinoWebSockets today 2015-07-15 so new sources.

[SETUP] BOOT WAIT 4...
scandone
[SETUP] BOOT WAIT 3...
add 0
aid 3
pm open phy_2,type:2 0 0
cnt

connected with TP-LINK_CB4DE8, channel 6
dhcp client start...
ip:192.168.1.100,mask:255.255.255.0,gw:192.168.1.1
[SETUP] BOOT WAIT 2...
[SETUP] BOOT WAIT 1...
Fatal exception (28):
epc1=0x40102180, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00001c20, depc=0x00000000
Fatal exception (28):
epc1=0x40102052, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00001c24, depc=0x00000000
Fatal exception (28):
epc1=0x40102052, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00001c24, depc=0x00000000
Fatal exception (28):
epc1=0x40102052, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00001c24, depc=0x00000000
Fatal exception (28):
epc1=0x40102052, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00001c24, depc=0x00000000
Fatal exception (28):
epc1=0x40102052, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00001c24, depc=0x00000000
Fatal exception (28):
epc1=0x40102052, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00001c24, depc=0x00000000
Fatal exception (28):
epc1=0x40102052, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00001c24, depc=0x00000000
Fatal exception (28):
epc1=0x40102052, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00001c24, depc=0x00000000
$�epc1
ets Jan 8 2013,rst cause:4, boot mode:(3,0)

wdt reset

Some warnings

warning: deprecated conversion from string constant to 'char_' [-Wwrite-strings]
bool connect(char hostname[], char path[] = "/", int port = 80);
^
warning: deprecated conversion from string constant to 'char_' [-Wwrite-strings]
bool connect(char hostname[], char path[] = "/", int port = 80);
^
WebSocketClient.cpp:51:29: note: in expansion of macro 'pgm_read_word'
strcpy_P(buffer, (char*)pgm_read_word(&(WebSocketClientStringTable[index])));

Arduino 1.6.7

Websockets compatibility/Implementation HTML5 vs Socket.io

Hi Markus,
I developed my test environment with my html/javascript and nodejs server to be easier to test my html/js code before putting it into ESP8266. I used websocket socket.io library. All on my environment is working fine, but now I'm trying to put all thing into ESP and here is my problem :

although your sample code html/js are working fine with ESP8266, as soon as I'm trying to connect to ESP8266 with socket.io it does not work or even connect.
I was thinking websockets was "standard" but it seems libraries may have different implementation.
At startup I wanted to use the HTML5 one on client side (the native one in browser, same as your examples) but for the same reason I didn't not succeed to connect with this one from my client broswer to my nodejs server running socket.io

I love socket.io because it implements all disconnect/reconnect mechanism (and other) but Im' afraid may be I need to use the basic HTML5 one to get it working with you lib ?

Any hints or explanation would be useful for my understanding because I'm lost on websocket jungle.
Thanks for your help

WebSockets Performance Issues

I have noticed that I have to have my web socket server send a response to the client for every message the the client sends in order to get good performance. Is this expected?

For example, the loop below runs on the client. This loop takes 2-3 seconds if the web socket server sends a response for every message that it receives.

If the server doesn't send a response for each message received then the loop below takes 200-300 seconds.

Loop running on the client:
uint32_t numMsgs = 1000; for(int i = 0; i < numMsgs; ++i) { webSocket.loop(); webSocket.sendTXT("Test Message"); }

I noticed this behavior when I was sending large files with your webSockets library. Do you have an example that shows the optimal method for sending large amounts of data?

Increase performance

Hello again!
I've tested your WebSocketClient sketch and it's pretty fast. However, if I send many messages they pile up and take some time to be printed. Is there any way to make it faster?

Missing core_esp8266_features.h

The examples do not compile. Here is the error:

Arduino: 1.6.7 (Windows 7), Board: "Generic ESP8266 Module, Serial, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck"

C:\Users\matt\Documents\Arduino\libraries\arduinoWebSockets-master\src\WebSockets.cpp:28:35: fatal error: core_esp8266_features.h: No such file or directory

 #include <core_esp8266_features.h>

                                   ^

compilation terminated.

exit status 1
Error compiling.

Delay() inside of "for" loops fail after socket connection is made

Using the async branch, delay()s inside of "for" loops aren't honored after a websockets connection is established. The same loop performs as expected before the ws connection is made. Is this expected behavior? Is there a workaround?

Hardware

Generic ESP-12E board

Sketch

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsClient.h>
#include <Hash.h>

ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;

void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {

    // Immediately exits the for loop and prints 1-255 in the console
    for(uint8_t c = 255; c > 0; c--) {
          Serial.println(c);
        delay(1000);
    }

}

void setup() {
    Serial.begin(115200);

    WiFiMulti.addAP("myNetworkName", "myPassword");

    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
    }

    webSocket.begin("192.168.1.119", 1440);
    webSocket.onEvent(webSocketEvent);


    // Works as expected
    for(uint8_t c = 255; c > 0; c--) {
        Serial.println(c);
        delay(1000);
    }


}

void loop() {

}

Watch Dog Timer keeps firing

Have been trying to create a simple server/client communications scheme with arduinoWebSockets but the WDT keeps firing on the server and client? The basic difference is that I'm trying to use access point mode without the multi.

While testing WebSocketsServer and WebSocketsClient on the ESP in Access mode I ran across an issue that is still unresolved. More than likely something wrong on my part but if someone has an idea please let me know!

The issue is that the WDT keeps firing...

The server code: ****************************

include

include

include

include "WebSockets.h"

include "WebSocketsServer.h"

define ssid "racemaster"

define pass "00112233445566778899aabbcc"

WebSocketsServer webSocket = WebSocketsServer(81);

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {

switch (type) {
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\n", num);
break;
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(num);
Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
}
break;
case WStype_TEXT:
Serial.printf("[%u] get Text: %s\n", num, payload);

// echo data back to browser
webSocket.sendTXT(num, payload, lenght);

// send data to all connected clients
webSocket.broadcastTXT(payload, lenght);
break;
case WStype_BIN:
Serial.printf("[%u] get binary lenght: %u\n", num, lenght);
hexdump(payload, lenght);

// echo data back to browser
webSocket.sendBIN(num, payload, lenght);
break;
}

}
IPAddress netServerIp = { 192, 168, 10, 1 };
IPAddress netSubNetIp = { 255, 255, 255, 0 };
void setup() {
Serial.begin(115200);

WiFi.disconnect();
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(netServerIp, netServerIp, netSubNetIp);

WiFi.softAP(ssid, pass);

webSocket.begin();
webSocket.onEvent(webSocketEvent);
}

void loop() {
webSocket.loop();
delay(5);
}

The client code:****************************

include

include

include <WebSockets/src/WebSocketsClient.h>

include

define ssid "racemaster"

define pass "00112233445566778899aabbcc"

WebSocketsClient webSocket;

void webSocketEvent(WStype_t type, uint8_t * payload, size_t lenght) {
switch (type) {
case WStype_DISCONNECTED:
Serial.printf("[WSc] Disconnected!\n");
break;
case WStype_CONNECTED:
{
Serial.printf("[WSc] Connected to url: %s\n", payload);
}
break;
case WStype_TEXT:
Serial.printf("[WSc] get text: %s\n", lenght);

// send data to back to Server
webSocket.sendTXT(payload, lenght);
break;
case WStype_BIN:
Serial.printf("[WSc] get binary lenght: %u\n", lenght);
hexdump(payload, lenght);

// echo data back to Server
webSocket.sendBIN(payload, lenght);
break;
}
}

void setup() {
Serial.begin(115200);

WiFi.disconnect();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);

while (WiFi.status() != WL_CONNECTED){
//Wait for client to connect
Serial.print(".");
delay(500);
}

Serial.println();
Serial.print("Connected:");
Serial.println(WiFi.localIP());

webSocket.begin("192.168.10.1", 81);
webSocket.onEvent(webSocketEvent);
}

unsigned long lastSentMsg = millis();
void loop() {
webSocket.loop();

//Send a message to the server every 5 seconds
if ((millis() - lastSentMsg) > 5000){
webSocket.sendTXT("testing",7);
lastSentMsg = millis();
}
delay(5);
}

Pass a class member function to onEvent?

My skills are kind of limited in C++. A code being better than a thousand words:

MyClass.h

#ifndef MyClass_h
#define MyClass_h

#include <WebSocketsServer.h>
#include <Hash.h>

class MyClass {
  public:
    MyClass();
    ~MyClass();
  private:
    WebSocketsServer* wss;
    int needToAccessThisValue;
    void onWsEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length);
};

#endif

MyClass.cpp

#include "MyClass.h"

MyClass::MyClass()  {
  this->wss = new WebSocketsServer(81);
  this->wss->onEvent(/* this->onWsEvent */);
  this->needToAccessThisValue = 123;
}

MyClass::~MyClass() {
  delete this->wss;
}

void MyClass::onWsEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
  Serial.println(this->needToAccessThisValue);
}

How can I pass onWsEvent to the onEvent method? I can't make onWsEvent static because I need to access properties from this function (static would not allow a this).

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.