"""The two controller ports (docs/controllers.md). A device drives five inputs per segment (pins 1, 4, 2, 3 and 6, all active low) and, if it has a spinner, two quadrature phases (pin 9 and pin 7). The console adds the rest: bit 4 is its one-shot's node, bit 5 pin 7 read directly, bit 7 the pulse-shaping NAND's output, and the shaped pin-9 edges pulse the Z80's /INT. That console circuitry lives in the board (:class:`colecovision_python.board.Board`); devices here only say what their pins do. Segments: 0 = joystick (selected by a write to $C0-$DF), 1 = keypad ($80-$9F). """ from __future__ import annotations from typing import Protocol JOYSTICK, KEYPAD = 0, 1 #: The keypad's four-bit codes (pins 1, 4, 2, 3 as bits 0-3), checked against OS-7's #: DEC_KBD_TBL (docs/controllers.md). "blue" and "purple" are the Super Action #: Controller's extra buttons, read as keypad codes 4 and 8. KEY_CODES = { "0": 0x0A, "1": 0x0D, "2": 0x07, "3": 0x0C, "4": 0x02, "5": 0x03, "6": 0x0E, "7": 0x05, "8": 0x01, "9": 0x0B, "*": 0x09, "#": 0x06, "blue": 0x04, "purple": 0x08, } # fmt: skip #: Joystick directions as bits 0-3. DIRECTIONS = {"up": 0x01, "right": 0x02, "down": 0x04, "left": 0x08} class ControllerPort(Protocol): """What the board asks of a device on a 9-pin port.""" def read(self, segment: int) -> int: """Pins 1, 4, 2, 3 as bits 0-3 and pin 6 as bit 6, active low; other bits ignored.""" ... def spinner_edges(self, until: int) -> list[tuple[int, bool]]: """Rising edges of pin 9 up to CPU clock ``until``, each as (clock, pin-7 level at that edge), oldest first, each reported once. Empty for devices without a spinner.""" ... def pin7(self, clock: int) -> bool: """Pin 7 (the second spinner phase) at ``clock``: True is high (pulled up).""" ... class Unplugged: """Nothing in the port: every input floats high on its pull-up.""" def read(self, segment: int) -> int: return 0x7F def spinner_edges(self, until: int) -> list[tuple[int, bool]]: return [] def pin7(self, clock: int) -> bool: return True class HandController: """Coleco's standard controller: joystick, left and right fire, 12-key pad. Set the state between frames: ``directions`` (a set of "up", "right", "down", "left"), ``keys`` (a set of keypad names), ``left_fire``, ``right_fire``. Two keys pressed together read as the AND of their codes: the pad is a diode matrix on four wires (docs/controllers.md; MAME's comment and code, tier 5). """ def __init__(self) -> None: self.directions: set[str] = set() self.keys: set[str] = set() self.left_fire = False self.right_fire = False def read(self, segment: int) -> int: if segment == JOYSTICK: low = 0x0F for name in self.directions: low &= ~DIRECTIONS[name] fire = self.left_fire else: low = 0x0F for name in self.keys: low &= KEY_CODES[name] fire = self.right_fire return 0x30 | low | (0 if fire else 0x40) def spinner_edges(self, until: int) -> list[tuple[int, bool]]: return [] def pin7(self, clock: int) -> bool: return True class Spinner: """A quadrature encoder on pins 9 (phase A) and 7 (phase B). ``rate`` is in full quadrature cycles per second: positive turns "right" (OS-7's word: at each triggering edge of pin 9, pin 7 is high), negative "left", 0 still. The console's shaper fires on each falling edge of pin 9 (a capacitor couples the edge into the NAND [DB sheet 3; SCH sheet 6]); that edge is what :meth:`spinner_edges` reports. Pin 7 leads or lags by a quarter cycle. """ def __init__(self, cpu_clock_hz: int = 3_579_545) -> None: self.cpu_clock_hz = cpu_clock_hz self.rate = 0.0 self._next: float | None = None self._last_edge: float | None = None self._clock = 0 def spinner_edges(self, until: int) -> list[tuple[int, bool]]: rate = self.rate if rate == 0: self._next = None self._clock = until return [] period = self.cpu_clock_hz / abs(rate) if self._next is None: self._next = self._clock + period # a full cycle after it begins turning edges = [] while self._next <= until: edges.append((int(self._next), rate > 0)) self._last_edge = self._next self._next += period self._clock = until return edges def pin7(self, clock: int) -> bool: if self.rate == 0 or self._last_edge is None: return True # at rest: pulled up (the encoder's resting phase is arbitrary) period = self.cpu_clock_hz / abs(self.rate) phase = ((clock - self._last_edge) / period) % 1.0 near_edge = phase < 0.25 or phase >= 0.75 return near_edge if self.rate > 0 else not near_edge class SpinnerHandController(HandController): """A hand controller whose port also carries a spinner (``spinner.rate``).""" has_spinner = True def __init__(self) -> None: super().__init__() self.spinner = Spinner() def spinner_edges(self, until: int) -> list[tuple[int, bool]]: return self.spinner.spinner_edges(until) def pin7(self, clock: int) -> bool: return self.spinner.pin7(clock) class SuperActionController(SpinnerHandController): """Coleco's Super Action Controller: joystick, 12-key pad, four action buttons and a spinner. Yellow is the joystick segment's fire (``left_fire``), orange the keypad segment's (``right_fire``); purple and blue read as keypad codes 8 and 4 (put "purple" or "blue" in ``keys``) [docs/controllers.md; MAME's coleco_m.cpp, tier 5].""" class RollerController: """The Roller Controller (a trackball): X drives port 1's spinner pins, Y port 2's; two hand controllers plug into it. Plug ``ports[0]`` and ``ports[1]``; set ``x`` and ``y`` in quadrature cycles per second.""" def __init__(self) -> None: self.ports = (SpinnerHandController(), SpinnerHandController()) @property def x(self) -> float: return self.ports[0].spinner.rate @x.setter def x(self, rate: float) -> None: self.ports[0].spinner.rate = rate @property def y(self) -> float: return self.ports[1].spinner.rate @y.setter def y(self, rate: float) -> None: self.ports[1].spinner.rate = rate class DrivingModule(SpinnerHandController): """Expansion Module 2: a steering wheel on port 1's spinner pins (``spinner.rate``) and a pedal that is a switch on the joystick segment's fire line (``pedal``); the player's hand controller goes in port 2 [MAME's coleco.cpp header, tier 5].""" @property def pedal(self) -> bool: return self.left_fire @pedal.setter def pedal(self, down: bool) -> None: self.left_fire = down