# SPDX-License-Identifier: MIT """The save device from the ID strings in the ROM (docs/cartridge.md "Choosing the save device"). "Nintendo didn't include a backup-type entry in the ROM header, however, the required type can be detected by ID strings in the ROM-image" (GBATEK §GBA Cart Backup IDs; DOC), stored word-aligned. A ROM naming more than one family is counted under the first in the census order (Flash 1M, Flash 512, Flash, EEPROM, SRAM_F, SRAM), which is the board's choice too (U-CART-1, HYPOTHESIS; a per-game override is offered). The clock: ``SIIRTC_V`` is the ID string of the RTC library, found word-aligned in 60 ROMs of the census, Pokémon Emerald among them (docs/cartridge.md; OBSERVED in the ROM images, not a document). The board fits the GPIO port and the RTC when it is present (HYPOTHESIS: that the library's presence means the chip is on the board, as for the save IDs; an override is offered). """ from __future__ import annotations from gba_python.cartridge.backup import EEPROM, FLASH_CHIPS, SRAM, Flash, NoBackup ORDER = ( (b"FLASH1M_V", "flash128"), (b"FLASH512_V", "flash64"), (b"FLASH_V", "flash64"), (b"EEPROM_V", "eeprom"), (b"SRAM_F_V", "sram"), (b"SRAM_V", "sram"), ) KINDS = ("none", "sram", "flash64", "flash128", "eeprom", "eeprom512", "eeprom8k") def find_aligned(rom: bytes, needle: bytes) -> bool: start = rom.find(needle) while start != -1: if start % 4 == 0: return True start = rom.find(needle, start + 1) return False def detect_kind(rom: bytes) -> str: for needle, kind in ORDER: if find_aligned(rom, needle): return kind return "none" def detect_rtc(rom: bytes) -> bool: return find_aligned(rom, b"SIIRTC_V") def make_backup(kind: str, data: bytes | None = None): """``kind`` is one of KINDS; a Flash kind may name its chip: ``flash64:sst``, ``flash64:macronix``, ``flash64:panasonic``, ``flash64:atmel``, ``flash128:sanyo``, ``flash128:macronix128`` (backup.FLASH_CHIPS).""" kind, _, chip = kind.partition(":") if chip and (not kind.startswith("flash") or chip not in FLASH_CHIPS): raise ValueError(f"unknown save chip {kind}:{chip}") if kind == "sram": return SRAM(data) if kind == "flash64": return Flash(0x10000, data, chip or None) if kind == "flash128": return Flash(0x20000, data, chip or None) if kind == "eeprom": return EEPROM(None, data) if kind == "eeprom512": return EEPROM(0x200, data) if kind == "eeprom8k": return EEPROM(0x2000, data) if kind == "none": return NoBackup() raise ValueError(f"unknown save type {kind}")