# mPy - RTC driver for DS3231
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-08-06  initial release

# DS3231 datasheet: https://www.analog.com/media/en/technical-documentation/data-sheets/ds3231.pdf

# microPython RTC
# from machine import RTC
# rtc = RTC()
# rtc.datatime((YYYY, M, D, DOW, h, m, s, 0))		# set datetime, DOW=0 for monday
# rtc.datatime()									# get datetime (YYYY, M, D, DOW, h, m, s, 0)

from	machine	import	Pin, RTC, I2C

# ========================== RtcEx ===========================

# Class RTC extended
class RtcEx(RTC):
    
    # get datetime as [YYYY, M, D, h, m, s]
    def get(self):
        dt = list(self.datetime())
        return dt[:3] + dt[4:7]				# remove DOW and subseconds
        
    
    # set RTC from [YYYY, M, D, h, m, s]
    def set(self, t):
        dt = t[:3] + [0] + t[3:] + [0]		# insert DOW and subseconds
        self.datetime(dt)
  
# ========================== tests ===========================

if __name__ == '__main__':
    
    import	time
    import	json
    from	drivers	import	nbInput
    
    # set RTC to 2026-08-06 Thursday 01:02:03 and print it
    def test1():
        rtc = RTC()
        rtc.datetime((2026, 8, 6, 3, 1, 2, 3, 0))
        print(rtc.datetime())
        
        
    # set RTC to 2026-08-06 01:02:03 and print it
    def test2():
        rtc = RtcEx()
        rtc.set([2026, 8, 6, 1, 2, 3])
        print(rtc.get())
        
        
    # CLI interface with RTC
    # get datetime: time<cr>
    # set datetime: time=[YYYY, M, D, h, m, s] ex. [2026, 8, 7, 10, 11, 12]
    def test3():
        rtc = RtcEx()
        while True:
            if s := nbInput():
                if   s == 'time': print(rtc.get())
                elif s.startswith('time='):
                    dt = json.loads(s[5:])
                    rtc.set(dt)
            time.sleep_ms(100)
            print('*', end='')
        

    test1()

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