# SPDX-License-Identifier: MIT """The cartridge's GPIO port and the Seiko S-3511 real-time clock behind it. Sources: GBATEK §GBA Cart I/O Port (GPIO), §GBA Cart Real-Time Clock (RTC) and the §DS Real-Time Clock it points to ("The RTC chip is (almost) the same as used in NDS consoles"); all DOC unless tagged. docs/cartridge.md "GPIO port and the S-3511 RTC" restates them; the open questions are U-CART-4 and U-CART-5 in docs/undocumented-behavior.md. **The port.** Three halfwords in the ROM chip: 080000C4 data (bits 0-3), 080000C6 direction (1 = out), 080000C8 control (bit 0: 1 = the three registers read back, 0 = write-only, when "reads return 00h (or possible other data, if the rom contains non-zero data at that location)", so the board returns the ROM's halfword there). Wired to the RTC as bit 0 SCK, bit 1 SIO, bit 2 CS (Boktai's column of GBATEK's "Connection Examples"). The port answers on the cartridge bus, so at the same cartridge addresses in all three ROM windows (HYPOTHESIS: the chip sees only the cartridge's address lines). **The serial protocol** (§DS Real-Time Clock, "Serial Transfer Flowchart"): CS low with SCK high, then CS high starts a transfer; a command byte and its parameter bytes follow; CS low ends it. The chip takes SIO on SCK's rising edge ("Output /SCK=LOW and SIO=databit ... Output /SCK=HIGH") and drives SIO on the falling edge ("data is output on (or immediately after) falling edge"). Bits go LSB first on the wire for parameters. The command byte's eight bits, in the order sent, are the fixed code 0, 1, 1, 0, a 3-bit register number (most significant first: GBATEK's "Rev" column), then the direction (1 = read). GBATEK's "Fwd" and "Rev" columns are the same eight wire bits read in the two orders, so the chip has one order. **Registers** (§GBA Cart Real-Time Clock, "Comparision of RTC Registers", mapping the DS names by their "Rev" numbers): 0 force reset (no parameters), 1 control (1 byte), 2 date and time (7: year, month, day, weekday, hour, minute, second, BCD), 3 time (3), 6 force IRQ (no parameters), 4, 5 and 7 "always FFh". **The clock** is a board convention: the RTC holds a date and time set when the board is built (the host's local time, unless given) and counts emulated time from there, one second per 2**24 cycles (the GBA clock is 16.78 MHz, 2**24 Hz: GBATEK §GBA Technical Data; DOC), so a run is deterministic for a given start. The real chip runs from its own 32.768 kHz crystal. """ from __future__ import annotations import datetime SECOND = 1 << 24 # cycles per second of the GBA clock (DOC: 16.78 MHz = 2**24 Hz) DATA, DIRECTION, CONTROL = 0x62, 0x63, 0x64 # halfword indexes of 080000C4, C6, C8 SCK, SIO, CS = 1, 2, 4 # GPIO bits (DOC: Boktai's wiring) REG_RESET, REG_CONTROL, REG_DATETIME, REG_TIME, REG_IRQ = 0, 1, 2, 3, 6 PARAMETER_BYTES = {REG_RESET: 0, REG_CONTROL: 1, REG_DATETIME: 7, REG_TIME: 3, REG_IRQ: 0} # Control register bits that software can write (DOC: 1 "IRQ duty/hold related?", 3 per-minute # IRQ, 5 "Unknown?", 6 12/24-hour mode; 7 power-off is read-only, cleared on read). CONTROL_WRITABLE = 0x6A CONTROL_24H = 0x40 CONTROL_POWER_OFF = 0x80 # "Setting after Battery-Shortcut is 82h. Setting after Force-Reset is 00h." (DOC) CONTROL_AFTER_BATTERY_LOSS = 0x82 EPOCH = datetime.datetime(2000, 1, 1) # BCD year 00 is 2000 (DS table: "00h..99h = 2000..2099") def bcd(value: int) -> int: return ((value // 10) << 4) | (value % 10) def from_bcd(value: int) -> int | None: high, low = value >> 4, value & 0xF if high > 9 or low > 9: return None return high * 10 + low class RTC: """The S-3511 as the three wires see it.""" def __init__(self, start: datetime.datetime | None = None, battery_lost: bool = False): if start is None: start = datetime.datetime.now().replace(microsecond=0) self.seconds = int((start - EPOCH).total_seconds()) # at cycle ``since`` self.since = 0 # A fresh cartridge's clock keeps time with the power-off flag clear and 24-hour mode # (HYPOTHESIS, a board convention: a cartridge whose battery is good; Nintendo's RTC # games set 24-hour mode). ``battery_lost`` gives GBATEK's 82h instead. self.control = CONTROL_AFTER_BATTERY_LOSS if battery_lost else CONTROL_24H if battery_lost: self.force_reset(0) self.control = CONTROL_AFTER_BATTERY_LOSS # The wires as last driven, and the transfer under way. self.cs = 0 self.sck = 0 self.sio_out = 1 # the chip's SIO output level (HYPOTHESIS: high when idle) self.active = False self.bit_count = 0 self.shift = 0 self.register = -1 # -1 while the command byte is coming self.reading = False self.out_bytes: list[int] = [] self.in_bytes: list[int] = [] self.out_bit = 0 # ------------------------------------------------------------------------------ # The clock def now_seconds(self, now: int) -> int: return self.seconds + (now - self.since) // SECOND def set_seconds(self, seconds: int, now: int) -> None: # Keep the fraction of a second already counted (HYPOTHESIS: a write does not restart # the chip's 1 Hz divider; no document says). fraction = (now - self.since) % SECOND self.seconds = seconds self.since = now - fraction def date_bytes(self, now: int) -> list[int]: moment = EPOCH + datetime.timedelta(seconds=self.now_seconds(now)) return [ bcd(moment.year - 2000), bcd(moment.month), bcd(moment.day), # Weekday: "00h..06h, custom assignment" (DS table; DOC); the board counts 0 for # the weekday of 2000-01-01 plus days (HYPOTHESIS: software sets it, the chip only # counts it). Stored as an offset so a written weekday is kept. (self.weekday_offset + (moment - EPOCH).days) % 7, *self.time_bytes(now), ] weekday_offset = 6 # 2000-01-01 was a Saturday; 0 = Sunday by default (HYPOTHESIS) def time_bytes(self, now: int) -> list[int]: moment = EPOCH + datetime.timedelta(seconds=self.now_seconds(now)) hour = moment.hour if self.control & CONTROL_24H: # 24-hour mode: the AM/PM flag reads 1 from 12h to 23h ("AM/PM flag moved from # hour.bit6 (NDS) to hour.bit7 (GBA)"; the DS's 24h rule; DOC). value = bcd(hour) | (0x80 if hour >= 12 else 0) else: # 12-hour mode: 00h..11h with the AM/PM flag ("12 o'clock is defined as 00h"; DOC). value = bcd(hour % 12) | (0x80 if hour >= 12 else 0) return [value, bcd(moment.minute), bcd(moment.second)] def write_date(self, data: list[int], now: int) -> None: """Year, month, day, weekday, then the time. A value that is not a valid BCD date is ignored whole (HYPOTHESIS, U-CART-5: what the chip does with one is unknown).""" year, month, day = (from_bcd(v) for v in data[:3]) if year is None or month is None or day is None: return try: moment = datetime.datetime(2000 + year, month, day) except ValueError: return seconds = self.time_seconds(data[4:7]) if seconds is None: return total = int((moment - EPOCH).total_seconds()) + seconds self.set_seconds(total, now) self.weekday_offset = ((data[3] & 7) - (moment - EPOCH).days) % 7 def time_seconds(self, data: list[int]) -> int | None: hour = from_bcd(data[0] & 0x3F) minute = from_bcd(data[1] & 0x7F) second = from_bcd(data[2] & 0x7F) if hour is None or minute is None or second is None: return None if not self.control & CONTROL_24H: if hour > 11: return None hour += 12 if data[0] & 0x80 else 0 if hour > 23 or minute > 59 or second > 59: return None return hour * 3600 + minute * 60 + second def write_time(self, data: list[int], now: int) -> None: seconds = self.time_seconds(data) if seconds is None: return day = self.now_seconds(now) // 86400 * 86400 self.set_seconds(day + seconds, now) def force_reset(self, now: int) -> None: """ "all used registers become 00h, except day/month which become 01h" (DOC): control 00h, 2000-01-01 00:00:00, weekday 0.""" self.control = 0 self.set_seconds(0, now) self.weekday_offset = 0 # ------------------------------------------------------------------------------ # The wires def drive(self, sck: int, sio: int, cs: int, now: int) -> None: """New levels on the three wires from the GPIO port (an input pin's level is what the chip itself drives, given as ``sio`` = its own output).""" if not cs: if self.active: self.finish(now) self.active = False elif not self.cs: # CS rising starts a transfer (DOC: "Init CS=LOW and /SCK=HIGH ... Switch CS=HIGH"). # HYPOTHESIS: SCK's level at that moment is not checked. self.active = True self.bit_count = 0 self.shift = 0 self.register = -1 self.reading = False self.in_bytes = [] self.out_bytes = [] elif self.active: if sck and not self.sck: self.rising(sio, now) elif self.sck and not sck: self.falling() self.cs, self.sck = cs, sck def rising(self, sio: int, now: int) -> None: if self.register >= 0 and self.reading: return # the chip is driving SIO; host levels are not taken if self.register < 0: # The command byte: bits kept in the order sent, first bit most significant. self.shift = (self.shift << 1) | sio else: self.shift |= sio << self.bit_count # parameters: LSB first (DOC) self.bit_count += 1 if self.bit_count < 8: return byte, self.shift, self.bit_count = self.shift, 0, 0 if self.register < 0: self.command(byte, now) else: self.in_bytes.append(byte) self.received(now) def falling(self) -> None: if self.register < 0 or not self.reading: return # "data is output on (or immediately after) falling edge" (DOC), LSB first. if not self.out_bytes: self.sio_out = 1 # past the register's bytes (HYPOTHESIS: reads 1, like FFh) return self.sio_out = (self.out_bytes[0] >> self.out_bit) & 1 self.out_bit += 1 if self.out_bit == 8: self.out_bit = 0 self.out_bytes.pop(0) def command(self, byte: int, now: int) -> None: if byte >> 4 != 0b0110: # Not the fixed code: the chip ignores the transfer (HYPOTHESIS, U-CART-5). self.active = False return self.register = (byte >> 1) & 7 self.reading = bool(byte & 1) self.out_bit = 0 register = self.register if register == REG_RESET: # "strobed by ANY access to them, ie. by both writing to, as well as reading # from these registers" (DOC). self.force_reset(now) elif register == REG_IRQ: # "drag the IRQ output LOW for a short moment" (DOC): not modelled; the cartridge # /IRQ is not wired to the board's Game Pak interrupt yet (U-CART-5). pass if self.reading: if register == REG_CONTROL: self.out_bytes = [self.control] self.control &= ~CONTROL_POWER_OFF # "auto cleared on read" (DOC) elif register == REG_DATETIME: self.out_bytes = self.date_bytes(now) elif register == REG_TIME: self.out_bytes = self.time_bytes(now) elif register in (4, 5, 7): self.out_bytes = [0xFF] * 8 # "always FFh" (DOC) else: self.out_bytes = [] def received(self, now: int) -> None: register = self.register data = self.in_bytes if register == REG_CONTROL and len(data) == 1: self.control = (self.control & CONTROL_POWER_OFF) | (data[0] & CONTROL_WRITABLE) elif register == REG_DATETIME and len(data) == 7: self.write_date(data, now) elif register == REG_TIME and len(data) == 3: self.write_time(data, now) def finish(self, now: int) -> None: self.register = -1 self.reading = False # ------------------------------------------------------------------------------ # Battery-file state (docs/cartridge.md "Battery files") def state(self, now: int) -> dict: moment = EPOCH + datetime.timedelta(seconds=self.now_seconds(now)) return { "datetime": moment.isoformat(), "control": self.control, "weekday_offset": self.weekday_offset, "host_time": datetime.datetime.now().replace(microsecond=0).isoformat(), } def load_state(self, state: dict, now: int, host_now: datetime.datetime | None = None): """The clock kept running while the console was off: add the host time elapsed since the file was written (board convention).""" moment = datetime.datetime.fromisoformat(state["datetime"]) if host_now is None: host_now = datetime.datetime.now().replace(microsecond=0) elapsed = host_now - datetime.datetime.fromisoformat(state["host_time"]) moment += max(elapsed, datetime.timedelta(0)) self.set_seconds(int((moment - EPOCH).total_seconds()), now) self.control = state["control"] & 0xFF self.weekday_offset = state.get("weekday_offset", self.weekday_offset) class GPIO: """The ROM chip's 4-bit port with the RTC on bits 0-2.""" def __init__(self, rtc: RTC) -> None: self.rtc = rtc self.data = 0 # levels written to the data register self.direction = 0 # 1 = out self.readable = False # control bit 0 def read(self, index: int, now: int) -> int | None: """The halfword the port drives at halfword index ``index``, or None for the ROM's.""" if not self.readable: return None if index == DATA: # An output pin reads back what was written; an input pin reads the device # (HYPOTHESIS: GBATEK gives no read-back rule). Only SIO has a driver on the RTC # side; SCK and CS inputs and bit 3 read 0 (HYPOTHESIS). value = self.data & self.direction if not self.direction & SIO: value |= self.rtc.sio_out << 1 return value & 0xF if index == DIRECTION: return self.direction return 1 # CONTROL: bit 0 set, or the port would not be readable def write(self, index: int, value: int, now: int) -> None: if index == DATA: self.data = value & 0xF elif index == DIRECTION: self.direction = value & 0xF else: self.readable = bool(value & 1) return self.update(now) def update(self, now: int) -> None: out = self.data & self.direction sio = (out >> 1) & 1 if self.direction & SIO else self.rtc.sio_out self.rtc.drive(out & SCK, sio, (out >> 2) & 1, now)