# https://gist.github.com/aallan/581ecf4dc92cd53e3a415b7c33a1147c
from machine import Pin
import network
import utime
import sys
import ntptime
import wlan
try:
import usocket as socket
except:
import socket
try:
import ustruct as struct
except:
import struct
INTERVAL = 1000 # millisecond
"""
Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
(date(1970, 1, 1) - date(1900, 1, 1)).days * 24*60*60
(70*365+17)*24*60*60 = 2208988800 =>UTC0
28800 = 8*60*60
2208960000 = 2208988800-28800
"""
# Optional UTC+8 offset time (seconds), if not set, UTC0
UTC_OFFSET = 28800 # 8 * 60 * 60
# NTP_DELTA = 2208988800 + UTC_OFFSET
# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
# host = "pool.ntp.org"
host = "tw.pool.ntp.org"
# ntptime.host = "time.nist.gov"
# ntptime.host = "pool.ntp.org"
ntptime.host = "tw.pool.ntp.org"
# ntptime.host = "ntp.aliyun.com"
# ntptime.host = "time.google.com"
if(sys.platform=="esp8266"):
led = Pin(2, Pin.OUT)
elif(sys.platform=="esp32"):
led = Pin(2, Pin.OUT)
elif(sys.platform=="rp2"):
led = Pin("LED", Pin.OUT)
def gettime():
NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x1B
addr = socket.getaddrinfo(host, 123)[0][-1]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.settimeout(10.0)
res = s.sendto(NTP_QUERY, addr)
msg = s.recv(48)
finally:
s.close()
val = struct.unpack("!I", msg[40:44])[0]
return val - NTP_DELTA
def settime():
t = gettime()
tm = utime.gmtime(t)
machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
def sync_time_with_retry():
try:
print("Syncing with NTP server...")
# settime()
ntptime.settime()
print("Time synchronized.")
except OSError as e:
# print("Error syncing time:", e)
if e.args[0] == 110: # ETIMEDOUT
print("ETIMEDOUT error during time sync. Retrying in 5 seconds...")
utime.sleep(5)
sync_time_with_retry() # Recursive call to retry
else:
print(f"An unexpected error occurred: {e}")
# Start Function
if __name__ == '__main__':
wlan.connect_wifi() # Connecting to WiFi Router
utime.sleep_ms(1000)
led.on()
sync_time_with_retry() # Synchronize the time
print("NTP 時間同步完成!")
led.off()
lastTime = utime.ticks_ms()
while True:
try:
currTime = utime.ticks_ms()
if (currTime - lastTime > INTERVAL):
lastTime = currTime
led.toggle()
# 獲取並顯示本地時間 (台灣時區 +8)
# utime.localtime() 取得 UTC 時間,所以要加上 8 小時
local_time_tuple = utime.localtime(utime.time() + UTC_OFFSET)
print(f"目前本地時間 (UTC+8): {local_time_tuple}")
# 也可以直接格式化輸出
# print("本地時間:", time.strftime("%Y-%m-%d %H:%M:%S", local_time_tuple))
utime.sleep_ms(100)
except KeyboardInterrupt:
print("Stop")
break