"""The serial port with nothing plugged in (no link partner in the first build, decision 7). Registers as NanoBoyAdvance keeps them (``bus/io.cpp``): SIOCNT, RCNT, and the data registers stored as written. Setting SIOCNT's start bit (7) runs a normal-mode transfer with the internal clock: it ends 512/64/2048/256 cycles later (256 KHz or 2 MHz clock, 8- or 32-bit), clears the start bit and raises the serial IRQ if enabled. The mGBA suite's SIO groups and alyosha-tas ``Serial/*`` judge this; NBA passes few of them (C9), so neither is a rung 0-2 gate. """ from __future__ import annotations from gba_python.irq import IRQ, SERIAL from gba_python.scheduler import Scheduler TRANSFER_CYCLES = (512, 64, 2048, 256) # [32-bit << 1 | 2 MHz clock] class Serial: def __init__(self, scheduler: Scheduler, irq: IRQ) -> None: self.scheduler = scheduler self.irq = irq self.siocnt = 0 self.rcnt = 0 self.data = [0] * 8 # 4000120-400012E: SIODATA32/SIOMULTI0-3, SIOMLT_SEND as halfwords self.joy = [0] * 6 # JOYCNT, JOY_RECV low/high, JOY_TRANS low/high, JOYSTAT def write_siocnt(self, value: int, mask: int) -> None: value = self.siocnt & ~mask | value & mask starting = not self.siocnt & 0x80 and value & 0x80 self.siocnt = self.siocnt & 0x80 | value & ~0x80 if starting: self.siocnt |= 0x80 cycles = TRANSFER_CYCLES[(self.siocnt >> 1 & 1) | (self.siocnt >> 11 & 2)] self.scheduler.add(cycles, self._done) def write_joycnt(self, value: int, mask: int) -> None: """JOYCNT: bits 0-2 are event flags that a 1 acknowledges, as in IF; bit 6 enables the reset IRQ; the rest are unused (GBATEK "JOYCNT"). With nothing on the JOY bus no event sets a flag, so the BIOS's read-and-acknowledge sees 0.""" value &= mask flags = self.joy[0] & 7 & ~value self.joy[0] = flags | (self.joy[0] & ~mask | value) & 0x40 def _done(self, _: int) -> None: if self.siocnt & 0x4000: self.irq.raise_(SERIAL) self.siocnt &= ~0x80