基於 : http://softbugbug.blogspot.com/2015/10/python.html
要有全域變數 HH, MM, SS
timer 要數時間
此段程式碼功能為 連上網路更新 HH, MM, SS 的數值
-- ['gettime.lua']
-- get time from web
-- update NodeMCU time base on get from web
url = "http://time.artjoey.com/js/basetime.php"
site = "time.artjoey.com"
loc = "/js/basetime.php"
data = "GET "
..loc.." HTTP/1.1\r\nHost: "
..site.."\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n"
sk=net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c)
print("receive")
print(c)
get={string.find(c,"baseTime=")}
--If GET value exist,
if get[2] ~= nil then
print("P:")
print(get[2] ) -- print the start location of serch string
basetime = string.sub(c, get[2]+1, -7) -- last char are 000;CrLf. get basetime
-- example basetime = 1443789637
-- NodeMCU max value 2147483647
print(basetime)
print("before:"..HH..":"..MM..":"..SS)
esp_update()
print("after:"..HH..":"..MM..":"..SS)
end
end )
sk:on("disconnection", function(sck, c)
print("disconnection")
print(c)
end )
sk:on("connection", function(sck, c)
print("connection")
print(c)
end )
sk:connect(80,ip)
sk:send(data)
function esp_update()
twsec = basetime + 28800 -- 60 * 60 * 8 add 8Hr (tw: GMT + 8)
daysec = twsec % 86400 -- 60 * 60 * 24
HH = daysec / 3600 -- 60 * 60
MM = (daysec / 60) % 60
SS = daysec % 60
-- webs() -- run http_server after update time
end
題外話:
NodeMCU 的字串連接式為 ..
ex:
str1 = "Hellow"
str2 = str1..123 -- 數值型態的資料在此會自動轉為字串
print(str2)
Hellow123
謝謝你文章內的string.find(c,"baseTime=")
回覆刪除提供線索解開NODEMCU 網頁控制服務的問題點XD