NodeMCU ESP32 Lua WebSocket Library

From Drake Panzer

Right now, the NodeMCU ESP32 Lua firmware has no WebSocket library. There was a pull request back in 2019 by chilipeppr to add a pure Lua WebSocket library but the maintainers got distracted and never merged it.

Here's the Lua library: File:Websocket.lua

You have to upload it to your ESP32 and run node.compile('websocket.lua') to compile it to websocket.lc.

Example Code

ws = require('websocket')
ws.on("receive", function(data, fin)
  -- fin of 1 or nil means you got all data
  -- fin of 0 means extended data will come in
  print("Got data:" .. data .. ", fin:", fin)
end)
ws.on("connection", function(host, port, path)
  print("Websocket connected to host:", host, "port:", port, "path:", path)
  ws.send("list")
end)
ws.on("disconnection", function()
  print("Websocket got disconnect from:", ws.wsUrl)
end)
ws.on("pingsend", function()
  print("Ping")
end)
ws.on("pongrecv", function()
  print("Got pong. We're alive.")
end)

-- Make sure you are connected to wifi
-- This sample websocket connects to Serial Port JSON server
-- Set this to your own 2nd SPJS, not the local one, or you'll get loopbacks
-- ws.connect("ws://10.0.0.201:8989/ws")
-- Or, example public websocket server
ws.connect("ws://demos.kaazing.com/echo")