Try   HackMD

適用於 MicroPython 和 ESP32 的 ntptime 模組

tags: MicroPython ESP32

PaoyungJun 03, 2022

ℳ𝒾𝒸𝓇ℴ𝒫𝓎𝓉𝒽ℴ𝓃 隨手記

ntptime module

MicroPython因為開源之故,所以有多種版本,因此在一些模組的操作與在網路上找到的使用範例並不一致。以 ntptime 這個模組來說,為了校正時差想到的屬性就是 timezone,但目前從官網下載的 ESP32 v1.18 firmware 並沒有 ntptime.timezone,可以用 help 指令得知:

>>> help(ntptime)
object <module 'ntptime' from 'ntptime.py'> is of type module
  socket -- <module 'usocket'>
  NTP_DELTA -- 3155673600
  struct -- <module 'ustruct'>
  __name__ -- ntptime
  __file__ -- ntptime.py
  host -- pool.ntp.org
  time -- <function time at 0x3ffe5410>
  settime -- <function settime at 0x3ffe5420>
>>>

timezone

雖沒找到 timezone 但却發現 NTP_DELTA 這個值 3155673600 有點莫名,查看原始檔 ntptime.py

#... # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60 NTP_DELTA = 3155673600 #...

原來 ntp 的秒數是從 1900/01/01 開始起算,而 MicroPython 是從 2000/01/01 起算,所以要做差值才能正確的計算,而台灣是 UTC+8 亦即提早 28800 秒,因此把 NTP_DELTA 改為 3155644800 就會是台灣的當地時間。

ntp server

再則在執行 ntptime.settime() 偶爾會出現 timeout 的異常,從原始檔中得知 ntptime.host 預設值為 pool.ntp.org,既然在台灣就用台灣的 ntp server 吧!若擔心 timeout 異常造成對時不成功,可以下參數 must=True 強制對時,就把以上這些寫成 function,以利日後使用。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
記得要先連上網路 不然下了 must=True 就變成大迴圈了

# name: tw_ntp.py, version: 0.1.0, author: paoyung.chang@gmail.com
# Copyright (c) 2022 Paoyung Chang. See the file LICENSE for copying permission.
# License link: https://gist.github.com/paoyung/7e465ad984a6cf24024508831ec54516
import time
import ntptime
def tw_ntp(host='clock.stdtime.gov.tw', must=False):
"""
host: 台灣可用的 ntp server 如下可任選,未指定預設為 clock.stdtime.gov.tw
tock.stdtime.gov.tw
watch.stdtime.gov.tw
time.stdtime.gov.tw
clock.stdtime.gov.tw
tick.stdtime.gov.tw
must: 是否非對到不可
"""
ntptime.NTP_DELTA = 3155644800 # UTC+8 的 magic number
ntptime.host = host
count = 1
if must:
count = 100
for _ in range(count):
try:
ntptime.settime()
except:
time.sleep(1)
continue
else:
return True
return False
"""
example:
tw_ntp() # 使用預設值
tw_ntp(must=True) # 非對到時不可
tw_ntp(must=1) # 同上
tw_ntp('tick.stdtime.gov.tw', 1) # 指定server,並強制對時
"""
view raw tw_ntp.py hosted with ❤ by GitHub

三點不一樣
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

  • 已 UTC+8
  • 台灣 NTP Server
  • 可要求強制對時

關於作者  

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

我是 𝙋𝙖𝙤𝙮𝙪𝙣𝙜,是 MicroPythonEspruino 的愛好者,一直認為:

「Maker 應該把重心放在應用上,而不該被語言工具限制了創意」

所以想藉由較為簡捷且詳細的解說讓更多人可以學習進而自由發揮,而非淪為只能將程式碼複製貼上的複製人,如果你認同這樣的理念,請一起為此目標努力,如果我的文章內容對你有幫助,請轉發或協助需要的人。

若有專案需求,請利用 連絡我,謝謝!