pcengine_rust/cpu_io/
io_port.rs

1//! The I/O port ($1000-$13FF, one register) and what answers on the pad pins
2//! (`cpu_io/io_port.py`).
3//!
4//! [hw: pcetech 4] Reads: D7 CD-unit sense (1 = not attached; C6 records sgxtech's opposite
5//! sentence), D6 country (1 = PC Engine, 0 = TurboGrafx-16), D5-D4 always 1, D3-D0 the pad pins.
6//! Writes: D1 = CLR, D0 = SEL. The port never returns buffer bits, but a read does load the buffer.
7//!
8//! [mfr: HuC6280 hardware manual 2.5, 2.6] The CPU's output port (port O, O0-O7) is a latch that
9//! reads back nothing and is driven high by a system reset, so SEL and CLR both power up *high*;
10//! the eight bits are kept because the SuperGrafx's S-EXP port uses O2-O7. Port K (K0-K7) is the
11//! input the pad pins and the CD sense reach.
12
13use crate::sockets::ControllerPort;
14
15pub struct IoPort {
16    pub country_pc_engine: bool,
17    pub device: Option<Box<dyn ControllerPort>>,
18    /// [mfr: HuC6280 manual 2.5] "H level is output to the output port"
19    pub latch: u8,
20}
21
22impl IoPort {
23    pub fn new(country_pc_engine: bool, device: Option<Box<dyn ControllerPort>>) -> IoPort {
24        IoPort {
25            country_pc_engine,
26            device,
27            latch: 0xFF,
28        }
29    }
30
31    pub fn sel(&self) -> bool {
32        self.latch & 1 != 0
33    }
34
35    pub fn clr(&self) -> bool {
36        self.latch & 2 != 0
37    }
38
39    pub fn reset(&mut self) {
40        self.latch = 0xFF;
41    }
42
43    pub fn read(&mut self, cd_attached: bool) -> u8 {
44        // Pins pulled up on an empty port: every pad bit reads 1 (docs: controller-info
45        // "all inputs default to high"; pcetech: unconnected controllers return $0F).
46        let (sel, clr) = (self.sel(), self.clr());
47        let nibble = match self.device.as_mut() {
48            None => 0x0F,
49            Some(device) => device.read(sel, clr) & 0x0F,
50        };
51        let mut value = 0x30 | nibble;
52        if !cd_attached {
53            value |= 0x80;
54        }
55        if self.country_pc_engine {
56            value |= 0x40;
57        }
58        value
59    }
60
61    pub fn write(&mut self, value: u8) {
62        self.latch = value;
63        let (sel, clr) = (self.sel(), self.clr());
64        if let Some(device) = self.device.as_mut() {
65            device.write(sel, clr);
66        }
67    }
68}