whitecatboard / Lua-RTOS-ESP32

Lua RTOS for ESP32
Other
1.2k stars 221 forks source link

Feature request: websocket support. #213

Open xopxe opened 5 years ago

xopxe commented 5 years ago

It would be great if we could use websockets. That would allow to have complex client side UI, portably, and some light API on the microcontroller side. Do you have any plans? As alternatives I suppose we could deploy a websocket server in parallel on a separate port (like this one https://github.com/Molorius/esp32-websocket). But the ideal solution is to use an http server with websocket support, or integrate support into httpsrv.c

the0ne commented 5 years ago

The integration of https://github.com/Molorius/esp32-websocket into the httpsrv isn't easy as the esp32-websocket module works on netconn only.

But I made progress by adding an interface in sockets.h to get the socket's netconn and providing that to ws_server_add_client. netconn_write doesn't seem to work on that but using netconn_write_partial it seems to work.

I'm not yet sure whether to implement as:

  1. one lua callback for all websocket or
  2. separate lua files for websocket request depending on the request url like for "normal" http(s) requests

Probably 1. will be easier to implement and provide faster runtime...

xopxe commented 5 years ago

Yes, probably having a single Lua callback will be good enough. You can pass the URL to the handler so it can discriminate between services if needed from inside the Lua code. The handler will also need the socket so it can stream data into the connection with a thread.

the0ne commented 5 years ago

the callback will have the following globals set:

http_method
http_uri
http_request
http_cookies
http_language
http_agent
http_port
http_secure
http_remote_addr

the following values will be given as parameters: length of the message the message the message type (which can be text or bin)

sample callback:

    function websocket_callback(len, msg, type)
        -- os.syslog("lua got msg: "..msg)
        local print = net.service.http.print_websocket
        print("you sent: "..msg) --this is sent directly to the client
    end
    net.service.http.start(80, 0, nil, nil, nil, websocket_callback)

also, it will be possible to send a message to all connected websocket clients from any lua script on the system by using net.service.http.print_websockets("your_message_here")

xopxe commented 5 years ago

Nice!

the0ne commented 5 years ago

Good news here. I recently managed to rip-out-again some functionality (serving static files in separate threads) that I had added for speed testing and optimization. Still, some more cleanup will be done before creating a PR.

bazooka07 commented 4 years ago

Hello, Are websockets working now with the http server ?