Tuesday, 2 August 2016

Sockets in NodeMCU with Lua

I started this project with Php Socket Server and NodeMcu Lua Client in Mind.. But i have hardtime getting it working.. So I replace the Php socket server with Python Socket server running in raspberry pi

So I used the Python Socket Server running in the Raspberry pi and NodeMcu with Lua as socket Client using port 12346 in Intranet.

 NodeMcu Side 
I Normally used REPL (Read Evaluate and Print Loop) to send the Commands than Execute it as File.

Configure your wifi in station mode
               wifi.setmode(wifi.STATION)

connect to access point
                                 wifi.sta.config("SSID","PASSWORD")
               wifi,sta.connect()
               ip = wifi.sta.get.ip()

use print(ip) to print the ip of your nodeMCU. if it returns NULL, then use
                               print(wifi,sta.status())
it will return number from 0 -5
0 - STA_IDLE
1 - STA_Connecting
2 - STA_wrong Password
3 - STA_AP Not Found
4 - STA_FAIL
5 - STA_GOT_IP

Normally it will take couple of seconds to connect the Access Point. So the return value will be 1 after couple of seconds you will get 5.

To create the Socket connection we can use built-in module name net
                                        sk=net.createConnection(net.TCP, 0)
this will create the TCP socket client and return the handler which is assigned to sk
                                      sk:on("connection", function(sck,c)
                     sk:send("HELLO")end)
it is used to specify the callback function when the connection is established
same goes for receive and send also

finally .. sk:connect(12346,"192.168.1.199") is used to connect the socket

You can find the all source Code on My Github Repositories https://github.com/anilkunchalaece/NodeMcuLuaSocketwithPython

No comments:

Post a Comment