1 Star 0 Fork 5

dazuo0312/Lua808

forked from Lawson1990s/Lua808 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
ntp_demo.lua 2.27 KB
一键复制 编辑 原始数据 按行查看 历史
MicroScale 提交于 2023-04-09 11:36 . 格式化文件
-- 实现ntp校准时间
-- 通过回调的方式进行演示
local function netCB(netc, event, param)
if event == socket.LINK and param == 0 then
sys.publish("NTP_ENABLE_LINK")
elseif event == socket.ON_LINE and param == 0 then
socket.tx(netc, "\xE3\x00\x06\xEC" .. string.rep("\x00", 44))
socket.wait(netc) -- 这样才会有接收消息的回调
elseif event == socket.EVENT and param == 0 then
local rbuf = zbuff.create(512)
socket.rx(netc, rbuf)
if rbuf:used() >= 48 then
local tamp = rbuf:query(40, 4, true)
if tamp - 0x83aa7e80 > 0 then
-- rtc.set(tamp - 0x83aa7e80 + 8 * 3600)
else
-- 2036年后,当前ntp协议会回滚
log.info("ntp 时间戳回滚")
-- rtc.set(0x7C558180 + tamp + 8 * 3600)
end
log.info(os.date())
sys.publish("NTP_FINISH")
rbuf:resize(4)
end
end
end
local function ntpTask()
local server = {
"ntp1.aliyun.com", "ntp2.aliyun.com", "ntp3.aliyun.com",
"ntp4.aliyun.com", "ntp5.aliyun.com", "ntp6.aliyun.com",
"ntp7.aliyun.com", "194.109.22.18", "210.72.145.44"
}
local msg
local netc = socket.create(nil, netCB)
socket.debug(netc, true)
socket.config(netc, nil, true) -- 配置成UDP,自动分配本地端口
local isError, result = socket.linkup(netc)
if isError then
log.info("unkown error")
return false
end
if not result then
result, msg = sys.waitUntil("NTP_ENABLE_LINK")
else
log.info("already online")
end
for k, v in pairs(server) do
log.info("尝试", v)
isError, result = socket.connect(netc, v, 123)
if isError then
log.info("unkown error")
else
result, msg = sys.waitUntil("NTP_FINISH", 5000)
if result then
log.info("ntp 完成")
socket.close(netc)
socket.release(netc)
return
end
end
socket.close(netc)
end
log.info("ntp 失败")
socket.release(netc)
return
end
function ntpDemo() sys.taskInit(ntpTask) end
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/dazuo0312/lua808.git
git@gitee.com:dazuo0312/lua808.git
dazuo0312
lua808
Lua808
master

搜索帮助

D67c1975 1850385 1daf7b77 1850385