Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serial (Link Cable) support #232

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions pyboy/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@ def valid_file_path(path):
parser.add_argument("--sound", action="store_true", help="Enable sound (beta)")
parser.add_argument("--no-renderer", action="store_true", help="Disable rendering (internal use)")

parser.add_argument("--serial-bind", action="store_true", help="Bind to this TCP addres for using Link Cable")
parser.add_argument(
"--serial-address", default=None, type=str, help="Connect (or bind) to this TCP address for using Link Cable"
)
parser.add_argument(
"--serial-interrupt-based", action="store_true", help="Use only interrupt-based transfers for using Link Cable"
)

gameboy_type_parser = parser.add_mutually_exclusive_group()
gameboy_type_parser.add_argument(
"--dmg", action="store_const", const=False, dest="cgb", help="Force emulator to run as original Game Boy (DMG)"
Expand All @@ -106,6 +114,9 @@ def valid_file_path(path):
def main():
argv = parser.parse_args()

if (argv.serial_bind or argv.serial_interrupt_based) and not argv.serial_address:
parser.error("--serial-bind and --serial-interrupt-based requires --serial-address")

print(
"""
The Game Boy controls are as follows:
Expand Down
2 changes: 1 addition & 1 deletion pyboy/core/mb.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ from pyboy.utils cimport IntIOInterface, WindowEvent
cdef Logger logger

cdef uint16_t STAT, LY, LYC
cdef short VBLANK, LCDC, TIMER, SERIAL, HIGHTOLOW
cdef int INTR_VBLANK, INTR_LCDC, INTR_TIMER, INTR_SERIAL, INTR_HIGHTOLOW
cdef int STATE_VERSION

Expand All @@ -36,6 +35,7 @@ cdef class Motherboard:
cdef pyboy.core.timer.Timer timer
cdef pyboy.core.sound.Sound sound
cdef pyboy.core.cartridge.base_mbc.BaseMBC cartridge
cdef object serial
cdef bint bootrom_enabled
cdef char[1024] serialbuffer
cdef uint16_t serialbuffer_count
Expand Down
26 changes: 23 additions & 3 deletions pyboy/core/mb.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from pyboy import utils
from pyboy.utils import STATE_VERSION

from . import bootrom, cartridge, cpu, interaction, lcd, ram, sound, timer
from . import bootrom, cartridge, cpu, interaction, lcd, ram, serial, sound, timer

INTR_VBLANK, INTR_LCDC, INTR_TIMER, INTR_SERIAL, INTR_HIGHTOLOW = [1 << x for x in range(5)]
OPCODE_BRK = 0xDB
Expand All @@ -27,6 +27,9 @@ def __init__(
sound_emulated,
cgb,
randomize=False,
serial_address=None,
serial_bind=None,
serial_interrupt_based=False,
):
if bootrom_file is not None:
logger.info("Boot-ROM file provided")
Expand All @@ -42,6 +45,7 @@ def __init__(
self.bootrom = bootrom.BootROM(bootrom_file, cgb)
self.ram = ram.RAM(cgb, randomize=randomize)
self.cpu = cpu.CPU(self)
self.serial = serial.Serial(serial_address, serial_bind, serial_interrupt_based)

if cgb:
self.lcd = lcd.CGBLCD(
Expand Down Expand Up @@ -204,6 +208,7 @@ def buttonevent(self, key):

def stop(self, save):
self.sound.stop()
self.serial.stop()
if save:
self.cartridge.stop()

Expand Down Expand Up @@ -298,10 +303,11 @@ def tick(self):
min(
self.lcd.cycles_to_interrupt(),
self.timer.cycles_to_interrupt(),
# self.serial.cycles_to_interrupt(),
self.serial.cycles_to_transmit(),
mode0_cycles
)
)
cycles = 4

#TODO: Support General Purpose DMA
# https://gbdev.io/pandocs/CGB_Registers.html#bit-7--0---general-purpose-dma
Expand All @@ -315,6 +321,8 @@ def tick(self):

if self.timer.tick(cycles):
self.cpu.set_interruptflag(INTR_TIMER)
if self.serial.tick(cycles):
self.cpu.set_interruptflag(INTR_SERIAL)

lcd_interrupt = self.lcd.tick(cycles)
if lcd_interrupt:
Expand Down Expand Up @@ -364,7 +372,13 @@ def getitem(self, i):
elif 0xFEA0 <= i < 0xFF00: # Empty but unusable for I/O
return self.ram.non_io_internal_ram0[i - 0xFEA0]
elif 0xFF00 <= i < 0xFF4C: # I/O ports
if i == 0xFF04:
if i == 0xFF01:
logger.info(f"get SB {self.serial.SB}")
return self.serial.SB
elif i == 0xFF02:
logger.info(f"get SC {self.serial.SC}")
return self.serial.SC
elif i == 0xFF04:
return self.timer.DIV
elif i == 0xFF05:
return self.timer.TIMA
Expand Down Expand Up @@ -478,10 +492,16 @@ def setitem(self, i, value):
if i == 0xFF00:
self.ram.io_ports[i - 0xFF00] = self.interaction.pull(value)
elif i == 0xFF01:
self.serial.SB = value
logger.info(f"SB: {value:02x}")

self.serialbuffer[self.serialbuffer_count] = value
self.serialbuffer_count += 1
self.serialbuffer_count &= 0x3FF
self.ram.io_ports[i - 0xFF00] = value
elif i == 0xFF02:
self.serial.SC = value
logger.info(f"SC: {value:02x}")
elif i == 0xFF04:
self.timer.reset()
elif i == 0xFF05:
Expand Down
144 changes: 144 additions & 0 deletions pyboy/core/serial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import logging
import os
import queue
import socket
import sys
import threading

logger = logging.getLogger(__name__)

SERIAL_FREQ = 8192 # Hz
CPU_FREQ = 4213440 # Hz

async_recv = queue.Queue()


def async_comms(socket):
while True:
item = socket.recv(1)
async_recv.put(item)


class Serial:
def __init__(self, serial_address, serial_bind, serial_interrupt_based):
self.SB = 0
self.SC = 0
self.connection = None

self.trans_bits = 0
self.cycles_count = 0
self.cycles_target = CPU_FREQ // SERIAL_FREQ
self.serial_interrupt_based = serial_interrupt_based

if not serial_address:
logger.info("No serial address supplied. Link Cable emulation disabled.")
return

if not serial_address.count(".") == 3 and serial_address.count(":") == 1:
logger.info("Only IP-addresses of the format x.y.z.w:abcd is supported")
return

address_ip, address_port = serial_address.split(":")
address_tuple = (address_ip, int(address_port))

if serial_bind:
self.binding_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.binding_connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
logger.info(f"Binding to {serial_address}")
self.binding_connection.bind(address_tuple)
self.binding_connection.listen(1)
self.connection, _ = self.binding_connection.accept()
logger.info(f"Client has connected!")
else:
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
logger.info(f"Connecting to {serial_address}")
self.connection.connect(address_tuple)
logger.info(f"Connection successful!")

# if self.serial_interrupt_based:
# logger.info("Interrupt-based serial emulation active!")
# self.recv_thread = threading.Thread(target=async_comms, args=(self.connection,))
# self.recv_thread.start()

def tick(self, cycles):
if self.connection is None:
return

# self.cycles_count += 1

if self.serial_interrupt_based:
if self.SC & 0x80 == 0: # Performance optimization. Games might not set this on slave
return False

self.cycles_count += 1

if (self.cycles_to_transmit() == 0):
if self.SC & 1: # Master
if self.SC & 0x80:
logger.info(f"Master sending!")
self.connection.send(bytes([self.SB]))
data = self.connection.recv(1)
self.SB = data[0]
self.SC &= 0b0111_1111
self.cycles_count = 0
return True
else:
# try:
# data = async_recv.get(block=False)
# except queue.Empty:
# return False
try:
data = self.connection.recv(1, socket.MSG_DONTWAIT)
except BlockingIOError:
return False

logger.info(f"Slave recv!")
self.connection.send(bytes([self.SB]))
# data = self.connection.recv(1)
self.SB = data[0]
self.SC &= 0b0111_1111
self.cycles_count = 0
return True
return False
else:
# Check if serial is in progress
if self.SC & 0x80 == 0:
return False

self.cycles_count += 1

if (self.cycles_to_transmit() == 0):
# if self.SC & 1: # Master
send_bit = bytes([(self.SB >> 7) & 1])
self.connection.send(send_bit)

data = self.connection.recv(1)
self.SB = ((self.SB << 1) & 0xFF) | data[0] & 1

logger.info(f"recv sb: {self.SB:08b}")
self.trans_bits += 1

self.cycles_count = 0

if self.trans_bits == 8:
self.trans_bits = 0
self.SC &= 0b0111_1111
return True
return False
return False

def cycles_to_transmit(self):
if self.connection:
if self.SC & 0x80:
return max(self.cycles_target - self.cycles_count, 0)
# return CPU_FREQ // SERIAL_FREQ
else:
return 1 << 16
else:
return 1 << 16

def stop(self):
if self.connection:
self.connection.close()
# if self.serial_interrupt_based and self.recv_thread:
# self.recv_thread.kill()
6 changes: 6 additions & 0 deletions pyboy/pyboy.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ def __init__(
sound_emulated=False,
cgb=None,
log_level=defaults["log_level"],
serial_address=None,
serial_bind=None,
serial_interrupt_based=False,
**kwargs
):
"""
Expand Down Expand Up @@ -143,6 +146,9 @@ def __init__(
sound_emulated,
cgb,
randomize=randomize,
serial_address=serial_address,
serial_bind=serial_bind,
serial_interrupt_based=serial_interrupt_based,
)

# Validate all kwargs
Expand Down
Loading