import network
import utime as time
import ntptime


connect_status_4g = False 

#----------------------------------4G网----------------------------
lte = network.LTE()
def connect_4g():
    global connect_status_4g, iccid,version 
    if not lte.isconnected():
        print("Connecting to 4g...")
        lte.active(True)
        lte.connect()
        time.sleep(1)   #不能删除
        # 循环等待直到连接成功
        connect_cnt = 0
        while True:
            connect_cnt+=1
            if lte.isconnected():
                connect_status_4g = True
                print("4G connected:", lte.status())
                version = lte.version()
                iccid = lte.iccid() 
                print('''version:{}\niccid:{}'''.format(version,iccid))
                break
            else:
                if(connect_cnt>1):
                    connect_status_4g = False 
                    print(f"connect time {connect_cnt}")
                    break
    return connect_status_4g
    
    
def synchronous_timer():
    # 设置NTP服务器地址，阿里服务器时间"time.aliyun.com"
    ntptime.host = "pool.ntp.org"
    bSync = False 
    try: 
        ntptime.settime()  # 使用默认的NTP服务器校时
        bSync = True 
    except OSError as e:
        print(f"NTP failed:{e} \r")
    else:
        print("NTP校时成功")
        # 打印当前系统时间
    current_time = time.localtime()
    print("localtime:", current_time)
    return bSync

def Sync_Timer():    
    #同步时间    
    ret = connect_4g()    #4G
    print('net = ',ret) 
    if ret:
        ret = synchronous_timer()     
    return ret










if __name__ == '__main__': 
    Sync_Timer()
        