-1

I'm pretty new to the ESP8266. I'm trying to add the WebSockets to the Lua code, but everytime I try to use the WebSocket looking at the documentation, the device throws error as attempt to index global websocket (a nil value). I'm not really sure if there is something to be imported, can anyone please help me with this.

function connectToSocket()
    print ("Connect to socket called, OK.")
    local ws_client = websocket.createClient()
end

wifi.setphymode(wifi.PHYMODE_N)
wifi.setmode(wifi.STATION)
wifi.sta.config("SSID","PWD")
wifi.sta.eventMonReg(wifi.STA_IDLE, function() print("IDLE") end)
wifi.sta.eventMonReg(wifi.STA_CONNECTING, function() print("CONNECTING...") end)
wifi.sta.eventMonReg(wifi.STA_WRONGPWD, function() print("WRONG PASSWORD!!!") end)
wifi.sta.eventMonReg(wifi.STA_APNOTFOUND, function() print("NO SUCH SSID FOUND") end)
wifi.sta.eventMonReg(wifi.STA_FAIL, function() print("FAILED TO CONNECT") end)
wifi.sta.eventMonReg(wifi.STA_GOTIP, function() 
    print("GOT IP "..wifi.sta.getip()) 
    connectToSocket()
end)
wifi.sta.eventMonStart()
wifi.sta.connect()
gre_gor
  • 6,669
  • 9
  • 47
  • 52
maheshgupta024
  • 7,657
  • 3
  • 20
  • 18
  • 1
    How did you configure your NodeMCU firmware build? (https://nodemcu-build.com/) Did you try to put `websocket = require("websocket")` as the first line of the script? – Maximilian Gerhardt Sep 22 '17 at 19:23

1 Answers1

0

I see three problems with the above code.

The main issue appears to be that your firmware is missing the websocket module. Uncomment https://github.com/nodemcu/nodemcu-firmware/blob/master/app/include/user_modules.h#L75 if you happen to build it manually.

Furthermore, all event handlers need to be registered before the respective events have a chance to be fired. I see you intend to do exactly that. However, by default wifi.sta.config uses auto connect=true in which case the WiFi registration process starts before the event monitor is started.

Lastly, the signature for wifi.sta.config changed a few months ago (see docs for details). Now you'd have to say wifi.sta.config{"SSID","PWD"} thereby passing a Lua table.

Marcel Stör
  • 22,695
  • 19
  • 92
  • 198
  • You are absolutely correct, when I observed the message after the reboot, the websocket module is missing. Then I made another build with websockets. Thanks @Marcel – maheshgupta024 Sep 27 '17 at 20:01