Ask Google for the time with an ESP8266

This is an example of how to connect to Google and retrieve just the HEAD information, which happens to include the current time.

It would be possible to do this with NTP, but that would require more coding. The results wouldn’t be any more accurate. I am pretty sure Google keeps the time on their servers well synchronized with the actual time.

— retrieve the current time from Google
— tested on NodeMCU 0.9.5 build 20150108

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)
print(‘\nRetrieved in ‘..((tmr.now()-t)/1000)..’ milliseconds’)
print(‘Google says it is ‘..string.sub(payload,string.find(payload,”Date: “)
+6,string.find(payload,”Date: “)+35))
conn:close()
end)
t = tmr.now()
conn:connect(80,’google.com’)

The program can be saved to a file, google.lua. Then, dofile(‘google.lua’) will retrieve and print the time. From this location, the normal elapsed time from requesting to printing was under one tenth of a second. Pretty good.

google

Simple scripts like this are easy to enter and test with LuaLoader.

Advertisements

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: