// 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 the reference's `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 //! (`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-rust` (default //! `~/.local/share/a2600-rust`), never beside a ROM; `path=None` keeps the //! chip in memory only. //! //! Rust-forced differences (a2600-python `savekey.py` at 28fb095): the save //! directory is named after this crate (`a2600-rust`) as the reference's is //! after itself; the chip is shared (`Rc>`) between the //! [`SaveKey`] and the listener it installs on the RIOT, which is handed the //! RIOT to answer through; the page buffer (a dictionary) is an ordered map; //! Python's `round` (half to even) is [`round_half_even`]. use std::cell::RefCell; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::rc::Rc; use serde::{Deserialize, Serialize}; use crate::riot::RIOT; pub const SIZE: usize = 0x8000; // DOC: DS 1.0, 256 Kbit pub const PAGE: usize = 64; // DOC: DS 6.2, the page write buffer pub const CONTROL_CODE: u8 = 0xA0; // DOC: DS 5.0, "1010" pub const CHIP_SELECT: u8 = 0; // DOC (the cartridges' own code): Go Fish! sends $A0/$A1, A2-A0 = 000 pub const WRITE_CYCLE_S: f64 = 0.005; // DOC: DS parameter 17, TWC maximum; HYPOTHESIS that a chip takes all of it // Bus states. pub const IDLE: u8 = 0; pub const CONTROL: u8 = 1; pub const ADDRESS_HIGH: u8 = 2; pub const ADDRESS_LOW: u8 = 3; pub const WRITING: u8 = 4; pub const READING: u8 = 5; /// Python's `round()`: to the nearest integer, ties to even. pub fn round_half_even(x: f64) -> i64 { let r = x.round(); // half away from zero if (x - x.trunc()).abs() == 0.5 && (r as i64) % 2 != 0 { (r - x.signum()) as i64 } else { r as i64 } } /// Where the SaveKey's 32 KB live between runs. pub fn default_path() -> PathBuf { let base = match std::env::var("XDG_DATA_HOME") { Ok(v) if !v.is_empty() => PathBuf::from(v), _ => PathBuf::from(std::env::var("HOME").unwrap_or_default()) .join(".local") .join("share"), }; base.join("a2600-rust").join("savekey.bin") } /// The chip's I2C state machine, driven by the two line levels. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct EEPROM24LC256 { pub path: Option, pub memory: Vec, pub write_cycles: i64, pub scl: bool, pub sda: bool, pub pull_low: bool, // the chip pulls SDA low (acknowledge or a 0 data bit) pub state: u8, pub bits: u32, // bits shifted in or out of the byte in hand pub shift: u8, pub ack_phase: bool, // the ninth clock of a byte pub pointer: usize, pub page: BTreeMap, // page-buffer address -> byte, for the write in hand pub busy_until: i64, // cycle the internal write cycle ends } impl EEPROM24LC256 { pub fn new(cpu_hz: f64, path: Option) -> EEPROM24LC256 { let mut memory = vec![0xFF; SIZE]; // HYPOTHESIS: an erased chip reads $FF if let Some(p) = path.as_deref() { if p.is_file() { if let Ok(data) = std::fs::read(p) { let n = data.len().min(SIZE); memory[..n].copy_from_slice(&data[..n]); } } } EEPROM24LC256 { path, memory, write_cycles: round_half_even(WRITE_CYCLE_S * cpu_hz), scl: true, sda: true, pull_low: false, state: IDLE, bits: 0, shift: 0, ack_phase: false, pointer: 0, page: BTreeMap::new(), busy_until: -1, } } // -- the two lines ------------------------------------------------------- /// New line levels (`sda` as the master leaves it; the chip's pull is applied here). pub fn lines(&mut self, scl: bool, sda: bool, cycle: u64) { let cycle = cycle as i64; let sda = sda && !self.pull_low; if scl && self.scl && 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; } let rising = scl && !self.scl; let falling = self.scl && !scl; self.scl = scl; self.sda = sda; if rising { self.clock_high(sda); } else if falling { self.clock_low(); } } fn start(&mut self, cycle: i64) { self.state = if cycle >= self.busy_until { CONTROL } else { IDLE }; self.bits = 0; 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.clear(); } fn stop(&mut self, cycle: i64) { if self.state == WRITING && !self.page.is_empty() { for (&address, &value) in self.page.iter() { self.memory[address] = value; } self.page.clear(); self.busy_until = cycle + self.write_cycles; self.save(); } self.state = IDLE; self.pull_low = false; self.ack_phase = false; } fn clock_high(&mut self, sda: bool) { if self.state == IDLE { return; } if self.ack_phase { if self.state == READING && sda { self.state = IDLE; // the master's no-acknowledge: the read is over } return; } if self.state != READING { self.shift = (self.shift << 1) | sda as u8; self.bits += 1; } } fn clock_low(&mut self) { 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 = 0; 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 = (self.shift >> (7 - self.bits)) & 1 == 0; } return; } if self.bits == 8 { self.pull_low = self.byte(self.shift); self.ack_phase = true; } } fn send_next(&mut self) { self.shift = self.memory[self.pointer]; self.pointer = (self.pointer + 1) % SIZE; self.bits = 0; self.pull_low = self.shift & 0x80 == 0; } /// A received byte; returns whether the chip acknowledges it. fn byte(&mut self, value: u8) -> bool { let state = self.state; if state == CONTROL { if value & 0xF0 != CONTROL_CODE || (value >> 1) & 7 != CHIP_SELECT { self.state = IDLE; return false; } if value & 1 != 0 { 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) as usize) << 8; self.state = ADDRESS_LOW; return true; } if state == ADDRESS_LOW { self.pointer |= value as usize; self.page.clear(); self.state = WRITING; return true; } // WRITING: into the page buffer; the low six bits count and roll over. self.page.insert(self.pointer, value); let base = self.pointer & !(PAGE - 1); self.pointer = base | ((self.pointer + 1) & (PAGE - 1)); true } fn save(&self) { let Some(path) = self.path.as_deref() else { return }; if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); } let _ = std::fs::write(path, &self.memory); } } /// A SaveKey on a joystick port (`port` 1, the right, as the cartridges use it). #[derive(Clone)] pub struct SaveKey { pub chip: Rc>, pub sda_bit: u8, pub scl_bit: u8, } impl SaveKey { pub fn new(riot: &mut RIOT, cpu_hz: f64, port: usize, path: Option<&Path>) -> SaveKey { let chip = Rc::new(RefCell::new(EEPROM24LC256::new(cpu_hz, path.map(Path::to_path_buf)))); SaveKey::with_chip(riot, chip, port) } /// A SaveKey around an existing chip (a restored state's). pub fn with_chip(riot: &mut RIOT, chip: Rc>, port: usize) -> SaveKey { let shift = if port == 1 { 0 } else { 4 }; let key = SaveKey { chip, sda_bit: 1 << (shift + 2), // pin 3 scl_bit: 1 << (shift + 3), // pin 4 }; let listener = key.clone(); riot.port_a_listener = Some(Box::new(move |riot: &mut RIOT, levels: u8, cycle: u64| { listener.port_changed(riot, levels, cycle) })); key } pub fn port_changed(&self, riot: &mut RIOT, levels: u8, cycle: u64) { let mut chip = self.chip.borrow_mut(); chip.lines(levels & self.scl_bit != 0, levels & self.sda_bit != 0, cycle); let mut 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); } } }