# SPDX-License-Identifier: MIT """Rung 7: the serial port's audio-affecting parts (B7.x in docs/behaviour.md), AHRM 5.6.""" from __future__ import annotations from pokey_python import POKEY from pokey_python.chip import AUDCTL, AUDF1, AUDF2, SKCTL, STIMER AUDF4 = 6 def setup(skctl: int, audctl: int = 0x40, audf1: int = 0, audf2: int = 255) -> POKEY: chip = POKEY() for register, value in ((AUDCTL, audctl), (AUDF1, audf1), (AUDF2, audf2), (SKCTL, skctl)): chip.write(register, value) chip.tick() return chip def fires(chip: POKEY, ch: int, cycles: int, stimer: bool = True) -> list[int]: """Fire ticks of channel ch, counted from a STIMER write at T = 0.""" if stimer: chip.write(STIMER, 0) chip.tick() out = [] for t in range(1, cycles): chip.tick() if chip.fired[ch]: out.append(t) return out def test_two_tone_resync_stretches_timer_1(): # B7.2: AHRM 5.6 "Two-tone resync timing": IRQST at 8, 14, 20 instead of 8, 12, 16 # (fire ticks one earlier: 7, 13, 19) assert fires(setup(0x0B), 0, 22) == [7, 13, 19] def test_without_two_tone_timer_1_runs_free(): assert fires(setup(0x03), 0, 22) == [7, 11, 15, 19] def test_force_break_takes_timer_1_out_of_the_resync(): # B7.2: force break forces the data bit to 0: only timer 2 resyncs assert fires(setup(0x8B), 0, 22) == [7, 11, 15, 19] def test_timer_2_resync_preempts_a_slower_timer_1(): # B7.2: timer 2 pulses always resync, so a faster timer 2 keeps timer 1 from firing # (channels 1 and 2 at 1.79 MHz: channel 2 is clocked by channel 1 only when joined, # so timer 2 here runs on the 64 kHz clock with AUDF2 = 0 and timer 1 has AUDF1 = 200) chip = setup(0x8B, audctl=0x40, audf1=200, audf2=0) assert fires(chip, 0, 3000) == [] def test_async_receive_holds_timers_3_and_4(): # B7.3: AHRM 5.6 "Asynchronous receive mode": held while waiting for a start bit chip = setup(0x13, audctl=0x00) chip.write(AUDF4, 0) chip.tick() assert fires(chip, 3, 2000) == [] chip.write(SKCTL, 0x03) chip.tick() assert fires(chip, 3, 200, stimer=False) def test_clock_pins(): # B7.4: Table 10: mode 010 drives both clocks from channel 4; mode 000 makes them inputs chip = setup(0x23, audctl=0x20) # channel 3 at 1.79 MHz; channel 4 on 64 kHz chip.write(AUDF4, 0) chip.tick() seen = set() for _ in range(400): chip.tick() seen.add((chip.oclk, chip.bclk_out)) assert {(0, 0), (1, 1)} <= seen chip.write(SKCTL, 0x03) chip.tick() chip.bclk_in = 0 assert chip.bclk_out is None and chip.oclk == 0 assert chip.oclk_ff == 0 and chip.bclk_ff == 0 # reset by bits 6-4 = 000 def test_sod_and_force_break(): # B7.1: the held bit (1 at power-on), 0 while force break is set chip = setup(0x03) assert chip.sod == 1 chip.write(SKCTL, 0x83) chip.tick() assert chip.sod == 0