Post your best Lua script examples here

User avatar
By DidymusRex
#7916 First, I am completely new to Lua, but not to programming in general. This seems like it should be very simple from the examples in the forum but it has me completely stumped.

What I find is if I run the commands below (after defining the listAP function) the wifi.sta.getap() never sees my AP - I always wind up in the "No AP in range" branch. BUT! if I run them separately by hand (using lualoader) it picks up the AP withing a few seconds (that's why I put the tmr.delay(3000000) in and will allow me to connect. Why doesn't the delay work? Eventually I want the ESP to start up on it's own and communicate via http but on it's own I can't get it to reliably connect to the network. I've been beating on this for hours and hours and tried three different ESP-01 chips to no avail.

Code: Select all-- declare function listAP
print("declaring listAP")
function listAP(tbl)
    print("begin listAP")
    local k
    local v
    if tbl then
        -- do I recognize the network?
        for k, v in pairs(tbl) do
            print(k .. " : " .. v)
            if k == "home" then
                ssid = k
                pswd = "password b"
            elseif k == "work" then
                ssid = k
                pswd = "password y"
            end
        end
    else
        print("No AP in range")
    end
end

wifi.sta.setmode(wifi.STATION)
wifi.sta.getap(listAP)
tmr.delay(3000000)

wifi.sta.config(ssid, pswd)
wifi.sta.connect()
print(wifi.sta.status())
User avatar
By DidymusRex
#8253 So it appears from the GitHub forum that the tmr.delay() is blocking the network stack. That would match the behaviour I see. What I found, though, was when I put the wifi.sta.getap in a timer it runs asynchronously so the config and connect lines are allowed to run before the AP is identified. I guess I'll need to put each of these in their own timer that checks the status of it's pre-reqs? Seems a little counter-intuitive but I'm willing to give it a whirl.