# SPDX-License-Identifier: MIT """The SaveKey: a 24LC256 serial EEPROM on a joystick port, spoken to over I2C. **The chip** (DOC: Microchip, *24AA256/24LC256/24FC256 Data Sheet*, DS20001203W, 2019; pinned in ``scripts/pinned_files.json``, cited below as *DS* with its section). 32,768 bytes; a two-wire bus where the master (the 6507, bit-banging the RIOT's port A) owns the clock: - a Start is SDA falling while SCL is high, a Stop SDA rising while SCL is high (DS 4.0); a bit is sampled while SCL is high, so SDA changes only while SCL is low; - the first byte after a Start is the control byte ``1010 A2 A1 A0 R/W`` (DS 5.0); the chip acknowledges on the ninth clock by pulling SDA low; - a write sends two address bytes (A14-A8 with the top bit "don't care", then A7-A0) and up to 64 data bytes into a page buffer; the six low address bits count within the page and roll over inside it (DS 6.1, 6.2); the Stop starts the internal write cycle, at most 5 ms (DS Table 1-2, parameter 17, TWC), during which the chip acknowledges nothing (DS 7.0); - a read returns the byte at the address pointer and moves it on by one, rolling over from $7FFF to $0000; the master acknowledges each byte it wants followed by another and ends with no acknowledge and a Stop (DS 8.0). **The wiring** (the cartridges' own code, restart rule 4: Go Fish!'s I2C routine, $FA73-$FAC0 of its NTSC dump, clocks SWCHA D3 and drives D2 through SWACNT, sends $A0/$A1 as control bytes, and reads its answers back on D2). So on the right port SDA is pin 3 (SWCHA D2) and SCL pin 4 (SWCHA D3), and the chip select pins read 000. A program drives SDA low by making D2 an output with SWCHA D2 = 0, and releases it by making D2 an input; the line then floats high through the SaveKey's pull-up (DOC: danjovic's SaveKey Plus circuit description, "the pins are pulled up through 10K resistors": a compatible board, cited for the pull-ups only). A SaveKey on the left port would use pins 3 and 4 there (SWCHA D6, D7); no permitted source shows a program doing so (HYPOTHESIS by symmetry of the connector, docs/start-here.md "Controllers"). **Levels.** Each line is the wired AND of what the RIOT leaves on its pin (:attr:`RIOT.port_a_listener`'s argument) and what the chip pulls low; the chip's pull shows on the RIOT's input, so a program reads its acknowledges and data on SWCHA D2. Choices no permitted source decides, each a HYPOTHESIS: - a fresh chip reads $FF everywhere (an erased EEPROM; settled by reading a new 24LC256); - the write cycle takes the data sheet's maximum, 5 ms of CPU time (real chips are faster; a program that polls for the acknowledge, DS 7.0, would show the real time on a console); - the chip sees the lines only when the RIOT changes them, so the bus is evaluated at port writes, which is when the levels can change. **Saves** go to ``$XDG_DATA_HOME/a2600-python`` (default ``~/.local/share/a2600-python``), never beside a ROM; ``path=None`` keeps the chip in memory only. """ from __future__ import annotations import os from pathlib import Path SIZE = 0x8000 # DOC: DS 1.0, 256 Kbit PAGE = 64 # DOC: DS 6.2, the page write buffer CONTROL_CODE = 0xA0 # DOC: DS 5.0, "1010" CHIP_SELECT = 0 # DOC (the cartridges' own code): Go Fish! sends $A0/$A1, A2-A0 = 000 WRITE_CYCLE_S = 0.005 # DOC: DS parameter 17, TWC maximum; HYPOTHESIS that a chip takes all of it # Bus states. IDLE, CONTROL, ADDRESS_HIGH, ADDRESS_LOW, WRITING, READING = range(6) def default_path() -> Path: """Where the SaveKey's 32 KB live between runs.""" base = os.environ.get("XDG_DATA_HOME") or str(Path.home() / ".local" / "share") return Path(base) / "a2600-python" / "savekey.bin" class EEPROM24LC256: """The chip's I2C state machine, driven by the two line levels.""" def __init__(self, cpu_hz: float, path: Path | None = None) -> None: self.path = path self.memory = bytearray(b"\xff") * SIZE # HYPOTHESIS: an erased chip reads $FF if path is not None and path.is_file(): data = path.read_bytes()[:SIZE] self.memory[: len(data)] = data self.write_cycles = round(WRITE_CYCLE_S * cpu_hz) self.scl = True self.sda = True self.pull_low = False # the chip pulls SDA low (acknowledge or a 0 data bit) self.state = IDLE self.bits = 0 # bits shifted in or out of the byte in hand self.shift = 0 self.ack_phase = False # the ninth clock of a byte self.pointer = 0 self.page: dict[int, int] = {} # page-buffer address -> byte, for the write in hand self.busy_until = -1 # cycle the internal write cycle ends # -- the two lines ------------------------------------------------------- def lines(self, scl: bool, sda: bool, cycle: int) -> None: """New line levels (``sda`` as the master leaves it; the chip's pull is applied here).""" sda = sda and not self.pull_low if scl and self.scl and sda != self.sda: # SDA changing while SCL is high: a Start (falling) or a Stop (rising). self.sda = sda if sda: self._stop(cycle) else: self._start(cycle) return rising = scl and not self.scl falling = self.scl and not scl self.scl, self.sda = scl, sda if rising: self._clock_high(sda) elif falling: self._clock_low(cycle) def _start(self, cycle: int) -> None: self.state = CONTROL if cycle >= self.busy_until else IDLE self.bits = self.shift = 0 self.ack_phase = False self.pull_low = False # A Start in place of the Stop drops the page buffer (HYPOTHESIS: DS 6.2 # writes it only "once the master has transmitted a Stop condition"). self.page = {} def _stop(self, cycle: int) -> None: if self.state == WRITING and self.page: for address, value in self.page.items(): self.memory[address] = value self.page = {} self.busy_until = cycle + self.write_cycles self._save() self.state = IDLE self.pull_low = False self.ack_phase = False def _clock_high(self, sda: bool) -> None: if self.state == IDLE: return if self.ack_phase: if self.state == READING and sda: self.state = IDLE # the master's no-acknowledge: the read is over return if self.state != READING: self.shift = ((self.shift << 1) | sda) & 0xFF self.bits += 1 def _clock_low(self, cycle: int) -> None: if self.state == IDLE: self.pull_low = False return if self.ack_phase: # The ninth clock is over: release the line, or put out the next byte. self.ack_phase = False self.pull_low = False self.bits = self.shift = 0 if self.state == READING: self._send_next() return if self.state == READING: self.bits += 1 if self.bits == 8: self.pull_low = False # release for the master's acknowledge self.ack_phase = True else: self.pull_low = not (self.shift >> (7 - self.bits)) & 1 return if self.bits == 8: self.pull_low = self._byte(self.shift) self.ack_phase = True def _send_next(self) -> None: self.shift = self.memory[self.pointer] self.pointer = (self.pointer + 1) % SIZE self.bits = 0 self.pull_low = not self.shift & 0x80 def _byte(self, value: int) -> bool: """A received byte; returns whether the chip acknowledges it.""" state = self.state if state == CONTROL: if value & 0xF0 != CONTROL_CODE or (value >> 1) & 7 != CHIP_SELECT: self.state = IDLE return False if value & 1: self.state = READING # the first byte goes out after the acknowledge else: self.state = ADDRESS_HIGH return True if state == ADDRESS_HIGH: self.pointer = (value & 0x7F) << 8 self.state = ADDRESS_LOW return True if state == ADDRESS_LOW: self.pointer |= value self.page = {} self.state = WRITING return True # WRITING: into the page buffer; the low six bits count and roll over. self.page[self.pointer] = value base = self.pointer & ~(PAGE - 1) self.pointer = base | ((self.pointer + 1) & (PAGE - 1)) return True def _save(self) -> None: if self.path is None: return self.path.parent.mkdir(parents=True, exist_ok=True) self.path.write_bytes(self.memory) class SaveKey: """A SaveKey on a joystick port (``port`` 1, the right, as the cartridges use it).""" def __init__(self, riot, cpu_hz: float, *, port: int = 1, path: Path | None = None) -> None: self.riot = riot self.chip = EEPROM24LC256(cpu_hz, path) shift = 0 if port == 1 else 4 self.sda_bit = 1 << (shift + 2) # pin 3 self.scl_bit = 1 << (shift + 3) # pin 4 riot.port_a_listener = self.port_changed def port_changed(self, levels: int, cycle: int) -> None: chip = self.chip chip.lines(bool(levels & self.scl_bit), bool(levels & self.sda_bit), cycle) riot = self.riot value = riot.input_a | self.sda_bit if chip.pull_low: value &= ~self.sda_bit if value != riot.input_a: riot.set_input_a(value)