# SPDX-License-Identifier: MIT """The cart EEPROM (milestone 7) driven through the cart port the way the BLL kit's ``eeprom.inc`` drives it: CS = A7, CLK = A1 (counter bits, stepped by RCART accesses, cleared by the address strobe), DI/DO = AUDIN.""" from __future__ import annotations from lynx_python.cart.eeprom import Eeprom from lynx_python.cart.port import CartPort class Driver: """The BLL routine's moves, on a CartPort with an EEPROM attached.""" def __init__(self, port: CartPort) -> None: self.port = port def cs_low(self): # stx $fd87 with 3 then 2: strobe high clears the counter self.port.set_strobe(1) self.port.set_strobe(0) def cs_high(self): # 128 accesses of $FCB2: counter bit 7 set for _ in range(128): self.port.write(0, 0) def clock(self): # two accesses: A1 up, two more: A1 down for _ in range(4): self.port.write(0, 0) def send(self, value: int, bits: int): self.cs_low() self.cs_high() for i in reversed(range(bits)): self.port.set_audin((value >> i) & 1) self.clock() def command(self, opcode: int, address: int, address_bits: int = 6): self.send((1 << (2 + address_bits)) | (opcode << address_bits) | address, 3 + address_bits) def read_word(self, address: int) -> int: self.command(0b10, address) self.port.set_audin(1) # AUDIN to input word = 0 for _ in range(16): self.clock() word = (word << 1) | self.port.audin_pin() self.cs_low() return word def write_word(self, address: int, value: int): self.command(0b00, 0b110000) # EWEN self.command(0b01, address) for i in reversed(range(16)): self.port.set_audin((value >> i) & 1) self.clock() self.cs_low() # programming starts here self.cs_high() assert self.port.audin_pin() == 1 # ready self.command(0b00, 0) # EWDS self.cs_low() def test_write_then_read_back(tmp_path): port = CartPort(bytes(1024), 1024) port.eeprom = Eeprom("93C46", path=tmp_path / "save.eep") bus = Driver(port) assert bus.read_word(5) == 0xFFFF # erased bus.write_word(5, 0x1234) bus.write_word(63, 0xBEEF) assert bus.read_word(5) == 0x1234 and bus.read_word(63) == 0xBEEF image = (tmp_path / "save.eep").read_bytes() assert len(image) == 128 and image[10:12] == b"\x12\x34" def test_save_survives_a_new_console(tmp_path): path = tmp_path / "save.eep" port = CartPort(bytes(1024), 1024) port.eeprom = Eeprom("93C46", path=path) Driver(port).write_word(7, 0x0A0B) again = CartPort(bytes(1024), 1024) again.eeprom = Eeprom("93C46", path=path) assert Driver(again).read_word(7) == 0x0A0B def test_write_needs_ewen(tmp_path): port = CartPort(bytes(1024), 1024) port.eeprom = Eeprom("93C46", path=tmp_path / "save.eep") bus = Driver(port) bus.command(0b01, 3) for _ in range(16): port.set_audin(0) bus.clock() bus.cs_low() assert bus.read_word(3) == 0xFFFF assert not (tmp_path / "save.eep").exists()