Uploading a Lua script to NodeMCU using Wifi

user2518618 picture user2518618 · Dec 14, 2015 · Viewed 7.7k times · Source

Is it possible to upload a Lua script to a NodeMCU using the Wifi interface instead of serial?

The tutorials and examples that I have found all use the serial interface, i.e. a cable, to program the NodeMCU, but I would like to change the program without connecting anything (using a smartphone or a browser)

Answer

Eyal picture Eyal · Dec 20, 2015

I upload all the modules over wifi. I first upload a bootstrap.lua program in the usual way (over USB). This program can then be used to upload the real (larger) payload. Here is the bootstrap program:

ip, mask, host = wifi.sta.getip()
port, path, pgm = 80, "/upload", "u.lc"
file.remove(pgm) ; file.open(pgm, "w+") payloadFound = false
local conn = net.createConnection(net.TCP, 0)
conn:on("connection", function(conn)
        conn:send("GET "..path.."/"..pgm.." HTTP/1.0\r\n".."Host: "..host.."\r\nConnection: close\r\nAccept: */*\r\n\r\n") end)
conn:on("receive", function(conn, payload)
        if (payloadFound) then file.write(payload) file.flush()
        else payloadOffset = string.find(payload, "\r\n\r\n")
                if (payloadOffset) then
                        file.write(string.sub(payload, payloadOffset + 4)) file.flush() payloadFound = true
                end end end)
conn:on("disconnection", function(conn) file.close() dofile(pgm) end) conn:connect(port,host)

The first line uses the gateway server as the web server from which programs are uploaded. The second line sets the port (80), path (/upload) and name (u.lc) of the program to upload. It then GETs the file and finally runs it (last line).

You must have your wireless connection active before running this, and your web server should be active of course, with your payload in /upload/u.lc.

Naturally you can change the hardwired values, or even make them dynamic.

Heading ##This Should be a simple starting point for what you want.

BTW, the condensed format is there to make the initial upload fast, I upload with luatool.py using the --dofile option.

Updating your program (u.lc) later is a simple repeat of dofile("bootstrap.lua").

My u.lc is a stage 2 bootstrap that uploads a long list of files (mostly .lc). Probably too involved for this short answer.

Finally, I should mention that this is loosely based on https://github.com/Manawyrm/ESP8266-HTTP/

HTH