# DS3231 MicroPython Library
# Supports reading and writing time on the DS3231 RTC module

from machine import I2C

DS3231_I2C_ADDR = 0x68

class DS3231:
    def __init__(self, i2c, addr=DS3231_I2C_ADDR):
        self.i2c = i2c
        self.addr = addr

    def _bcd_to_dec(self, bcd):
        return (bcd // 16) * 10 + (bcd % 16)

    def _dec_to_bcd(self, dec):
        return (dec // 10) * 16 + (dec % 10)

    def datetime(self):
        """Reads the current date and time from the RTC."""
        data = self.i2c.readfrom_mem(self.addr, 0x00, 7)
        second = self._bcd_to_dec(data[0] & 0x7F)
        minute = self._bcd_to_dec(data[1])
        hour = self._bcd_to_dec(data[2] & 0x3F)  # 24-hour mode
        day = self._bcd_to_dec(data[4])
        month = self._bcd_to_dec(data[5] & 0x1F)
        year = self._bcd_to_dec(data[6]) + 2000
        return (year, month, day, hour, minute, second)

    def set_datetime(self, year, month, day, hour, minute, second):
        """Sets the RTC date and time."""
        data = bytearray([
            self._dec_to_bcd(second),
            self._dec_to_bcd(minute),
            self._dec_to_bcd(hour),
            0,  # Day of the week (ignored)
            self._dec_to_bcd(day),
            self._dec_to_bcd(month),
            self._dec_to_bcd(year - 2000)
        ])
        self.i2c.writeto_mem(self.addr, 0x00, data)
