Hi3861下使用micropython更新系统时间 原创

发布于 2022-3-3 16:54
浏览
1收藏

在Hi3861上移植了micropython,因为一些应用需要时间功能,所以,实现了一下该功能。
1、移植unetwork和usocket库。
2、rtc_time函数实现

STATIC mp_obj_t mod_rtc_time(size_t n_args, const mp_obj_t *args) {
    if(n_args == 0)
    {
        return mp_obj_new_int((mp_int_t)hi_get_real_time());
    }
    else
    {
        int set_time = mp_obj_get_int(args[0]);
        hi_set_real_time(set_time);
        return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_rtc_time_obj,0,1,mod_rtc_time);

3、联网py脚本

import network
import time

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
#wlan.scan()
wlan.connect("harmony", "88888888")
while True:
    if(wlan.isconnected()):
        break
    time.sleep(1)
time.sleep(1)
wlan.ifconfig()

4、更新时间py脚本


try:
    import usocket as socket
except:
    import socket
try:
    import ustruct as struct
except:
    import struct
import time

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

# The NTP host can be configured at runtime by doing: ntptime.host = 'myhost.org'
host = "pool.ntp.org"

def ntime():
    NTP_QUERY = bytearray(48)
    NTP_QUERY[0] = 0x1B
    addr = socket.getaddrinfo(host, 123)[0][-1]
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(1000)
    try:
        s.settimeout(1)
        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
    return val - UNIX_DELTA


# There's currently no timezone support in MicroPython, so
# utime.localtime() will return UTC time (as if it was .gmtime())
def settime():
    #t = time()
    #import machine
    #import utime

    #tm = utime.localtime(t)
    #machine.RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
    time.rtctime(1641379744)


## test
t = ntime()
#print(t)
time.rtctime(t)
print(time.localtime(time.rtctime()))

'''
参考用例
https://blog.csdn.net/zld_555/article/details/106238482
'''

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
2
收藏 1
回复
举报
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐