Post your best Lua script examples here

User avatar
By trackerj
#31571 Another Example for Google time fetch. Can be used also for RTC time sync if NTP not available:

Code: Select all getTime = function()
     conn=net.createConnection(net.TCP, 0)
     conn:on("connection",function(conn, payload)
            conn:send("HEAD / HTTP/1.1\r\n"..
                      "Host: google.com\r\n"..
                      "Accept: */*\r\n"..
                      "User-Agent: Mozilla/4.0 (compatible; esp8266 Lua;)"..
                      "\r\n\r\n")
            end)           
     conn:on("receive", function(conn, payload)
          tstamp = string.sub(payload,string.find(payload,"Date: ")+6,string.find(payload,"Date: ")+35)
          --print('Timestamp : '..tstamp)
          conn:close()
     end)
    conn:connect(80,'google.com')
    conn = nil

    t = {}
    i=0
    for token in string.gmatch(tstamp, "[^%s]+") do
       t[i] = token
       --print(t[i])
       i=i+1
    end

    wkd = {["Sun"]=1, ["Mon"]=2, ["Tue"]=3, ["Wed"]=4, ["Thu"]=5, ["Fri"]=6, ["Sat"]=7 }
    mnt = {["Jan"]=1, ["Feb"]=2, ["Mar"]=3, ["Apr"]=4, ["May"]=5, ["Jun"]=6, ["Jul"]=7, ["Aug"]=8, ["Sep"]=9, ["Oct"]=10, ["Nov"]=11,["Dec"]=12}
    wk1=string.sub(t[0],0,3)
    dtd=wkd[wk1]
    d1=t[1]
    mn1=t[2]
    mnl=mnt[mn1]
    y1=string.sub(t[3],3,4)
    h1=2+string.sub(t[4],0,2)
    m1=string.sub(t[4],4,5)
    s1=string.sub(t[4],7,8)

    --print("Date : "..wk1..", "..d1.."/"..mn1.."/"..t[3])
    --print("Time : "..h1..":"..m1..":"..s1)

    return s1,m1,h1,d1,dtd,mnl,y1
end


For more details : RTC + NTP + Google time - a practical example