# mPy - Serial UART client updating RTC
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-07-09  initial release

from	drivers	import	Serial
import	time
from	machine	import	RTC

# ======================== test UART communication ============================

# get time from USB time server as:
#    [year, month, day, hours, minutes, seconds, weekday, yearday, utc_offs]
def getTime(rx, tx):
    comm = Serial(rx=rx, tx=tx)
    time.sleep_ms(100)
    comm.writeLn('\ntime')
    for _ in range(10):
        if x := comm.readLn():
            return x
        time.sleep(0.1)
    print('getTime: no response from time server')
        
# ============================ UpdateTime ====================================

# update RTC datetime
def updateTime():
    rtc	= RTC()
    print(rtc.datetime())
    rtc.datetime([2000 ,1, 1, 0, 0, 0, 0, 0])		# destroy RTC datetime as Thonny sets it
#    print(rtc.datetime())
    if x := getTime(rx=16, tx=17):					# year, month, day, hours, minutes, seconds, weekday, yearday, utc_offs
#       print('Rx:', x)        
        x = x[:3] + [x[6]] + x[3:7]					# year, month, day, weekday, hours, minutes, seconds, usec
        rtc.datetime(x)
        print('RTC is now:', rtc.datetime())


updateTime()

# ================================== end =====================================
