diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c567c06..288ba30 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -114,10 +114,17 @@ jobs: run: PLAYERS=4 LOCAL_A=2 LOCAL_B=2 KEYS=tests/recordings/dm4.bnr QUIET=1 STACK_MIN=150 build/venv/bin/python tools/lockstep_zx.py 600 - name: Spectrum 128K match, 4 players, stack watermark run: A_BUILD=build/zx128 B_BUILD=build/zx128 PLAYERS=4 LOCAL_A=2 LOCAL_B=2 KEYS=tests/recordings/dm4.bnr QUIET=1 STACK_MIN=100 build/venv/bin/python tools/lockstep_zx.py 600 - - name: Spectrum link gone silent mid-match, 48K and 128K (both end with CONNECTION LOST in about 10 s) + - name: ZX Spectrum Next matches (the 128K build on a Next with its ESP) + run: | + A_BUILD=build/zx128 B_BUILD=build/zx128 A_NEXT=1 B_NEXT=1 PLAYERS=4 LOCAL_A=2 LOCAL_B=2 KEYS=tests/recordings/dm4.bnr QUIET=1 STACK_MIN=100 build/venv/bin/python tools/lockstep_zx.py 600 + A_BUILD=build/zx128 B_BUILD=build/zx128 A_NEXT=1 B_NEXT=1 NEXT_TIMING=7 QUIET=1 build/venv/bin/python tools/lockstep_zx.py 200 + A_BUILD=build/zx128 B_BUILD=build/zx QUIET=1 A_NEXT=1 build/venv/bin/python tools/lockstep_zx.py 200 + A_BUILD=build/zx128 B_BUILD=build/zx128 B_NEXT=1 QUIET=1 build/venv/bin/python tools/lockstep_zx.py 200 + - name: Spectrum link gone silent mid-match, 48K, 128K and Next (both end with CONNECTION LOST in about 10 s) run: | CUT_AT=200 QUIET=1 build/venv/bin/python tools/lockstep_zx.py 600 CUT_AT=200 A_BUILD=build/zx128 B_BUILD=build/zx128 QUIET=1 build/venv/bin/python tools/lockstep_zx.py 600 + CUT_AT=200 A_BUILD=build/zx128 B_BUILD=build/zx128 A_NEXT=1 B_NEXT=1 QUIET=1 build/venv/bin/python tools/lockstep_zx.py 600 - name: CPC match run: build/venv/bin/python tools/lockstep_cpc.py 300 - name: against BomberNet 0.2.0, both ways diff --git a/README.md b/README.md index 066d049..dd7f8cb 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ joysticks, or on several machines over the network, in any mix. | Browser (phone, tablet or computer) | nothing more | | Sharp MZ-800 (the MZ-700 plays locally) | an [MZPico](https://mzpico.com/) with a Pico W and Wi-Fi enabled in its configuration; or a Unicard with the NET firmware, on a home network with a relay of your own | | ZX Spectrum 48K or larger | a Spectranet or Spectranext; on a 128K, an ESP-01 Wi-Fi module | +| ZX Spectrum Next (untried on hardware) | its own Wi-Fi | | Amstrad CPC | an M4 board | | Atari XL/XE | a FujiNet | | Commodore 64 | a WiC64, or an Ultimate 64 / Ultimate-II+ | diff --git a/c/common/netdev_soft.c b/c/common/netdev_soft.c index 31a815d..0e9649b 100644 --- a/c/common/netdev_soft.c +++ b/c/common/netdev_soft.c @@ -29,12 +29,17 @@ uint8_t net_device; #else #define BIN_ARG "" #endif -#ifdef NET_PLATFORM /* plat_config.h: which machine this is, for the relay's statistics */ +#if defined(NET_PLATFORM_AT) /* the "&pf=" a driver wrote at this address (the 128K tape: bank6.c) */ +#define PF_ARG "" +#define PF_PUT(p) put_s(p, (const char *)NET_PLATFORM_AT) +#elif defined(NET_PLATFORM) /* plat_config.h: which machine this is, for the relay's statistics */ #define PF_ARG "&pf=" NET_PLATFORM +#define PF_PUT(p) (p) #else #define PF_ARG "" +#define PF_PUT(p) (p) #endif -/* The longest: /net?game=16974&code=ABCD&bin=1&pf=element-zx-128k */ +/* The longest: /net?game=16974&code=ABCD&bin=1&pf=zx-spectrum-next */ static char path[52]; #define MSGQ 4 #define E_BUILD 6 @@ -341,7 +346,7 @@ uint8_t net_create(uint16_t build, uint8_t slots, const uint8_t *settings, uint8 uint8_t r; if (slots < 1 || slots > NET_SLOTS) return E_PARAM; if (len > 16) len = 16; - p = put_u(put_s(path, "/net?game="), NET_GAME_ID); put_s(p, "&create=1" BIN_ARG PF_ARG)[0] = 0; + p = put_u(put_s(path, "/net?game="), NET_GAME_ID); PF_PUT(put_s(p, "&create=1" BIN_ARG PF_ARG))[0] = 0; p = put_u(put_s(out, "{\"op\":\"create\",\"game\":"), NET_GAME_ID); p = put_u(put_s(p, ",\"build\":"), build); p = put_u(put_s(p, ",\"slots\":"), slots); @@ -357,7 +362,7 @@ uint8_t net_create(uint16_t build, uint8_t slots, const uint8_t *settings, uint8 uint8_t net_join(uint16_t build, const char *code, uint8_t *slot, uint8_t *slots, uint8_t *settings, uint8_t *len) { char *p; uint8_t r; - p = put_u(put_s(path, "/net?game="), NET_GAME_ID); put_s(put_s(put_s(p, "&code="), code), BIN_ARG PF_ARG)[0] = 0; + p = put_u(put_s(path, "/net?game="), NET_GAME_ID); PF_PUT(put_s(put_s(put_s(p, "&code="), code), BIN_ARG PF_ARG))[0] = 0; p = put_u(put_s(out, "{\"op\":\"join\",\"game\":"), NET_GAME_ID); p = put_u(put_s(p, ",\"build\":"), build); put_s(put_s(put_s(p, ",\"code\":\""), code), "\"}")[0] = 0; diff --git a/c/platform/zx/bank6.c b/c/platform/zx/bank6.c index 8c98220..e720fb6 100644 --- a/c/platform/zx/bank6.c +++ b/c/platform/zx/bank6.c @@ -7,6 +7,7 @@ * top, so it must not touch the game's memory above C000h; the game passes * data through its staging buffer below C000h. */ #include +#include #include "tcp.h" const char bank6_signature[4] = {'B', 'N', 'B', '6'}; /* checked by the game before the first call */ @@ -43,12 +44,56 @@ static uint8_t esp01_machine(void) __naked { ret __endasm; } + +/* Is this a ZX Spectrum Next (or a Next core on another FPGA board)? Its + * ESP Wi-Fi module sits behind a UART at the same ports, 133Bh/143Bh, which + * the eLeMeNt's follows. Told by nextreg 7Fh, a user register: written + * through 243Bh/253Bh, it reads back on a Next only (a 128K, +2 or +3 + * decodes neither port: A1 = 1, A0 = 1). Its value is kept. A ZX Printer + * decodes them (A2 = 0) and starts its motor on 5Ah: on a machine that is + * not a Next, 04h stops it again. -> L = 1 */ +static uint8_t next_machine(void) __naked { + __asm + ld bc,0x243b ; nextreg select: 7Fh, user register 0 + ld a,0x7f + out (c),a + inc b ; 253Bh: its value + in e,(c) + ld a,0x5a + out (c),a + in a,(c) + cp 0x5a + jr nz,nm_no + ld a,0xa5 + out (c),a + in a,(c) + out (c),e ; the user value back + cp 0xa5 + jr nz,nm_no + ld hl,1 + ret +nm_no: + ld a,4 ; not a Next: a ZX Printer on these ports, motor off + out (c),a + ld hl,0 + ret + __endasm; +} +extern uint8_t esp_next; /* tcp_esp01_at.c: the Next's UART and reset, not the ZXi's */ #endif -/* the game's tcp_present, through bank6_entries.h */ +/* the game's tcp_present, through bank6_entries.h; the machine's name for + * the relay goes above the game's staging buffer (NET_PLATFORM_AT, 5DAAh: + * the game reads it there when it opens a room) */ +#define PF_AT ((char *)0x5daa) uint8_t bank6_present(void) { #ifdef BANK6_ESP01 - if (!esp01_machine()) return 0; + strcpy(PF_AT, "&pf=element-zx-128k"); + if (esp01_machine()) esp_next = 0; + else if (next_machine()) { esp_next = 1; strcpy(PF_AT, "&pf=zx-spectrum-next"); } + else return 0; +#else + PF_AT[0] = 0; /* the Spectranet test build: no name (the machine is unknown) */ #endif return tcp_present(); } diff --git a/c/platform/zx/plat_config.h b/c/platform/zx/plat_config.h index 225f4ac..bce760d 100644 --- a/c/platform/zx/plat_config.h +++ b/c/platform/zx/plat_config.h @@ -14,7 +14,7 @@ #define NET_BINARY_INPUT 1 /* input lines as binary messages (the relay's bin=1): about 7 bytes, not 50 */ #define PLAT_ASM_TEXT 1 /* print_string, hud_text, title_text* in cpu/z80/loops.c */ #ifdef ZX128 /* the relay's statistics: &pf= (docs/net-protocol.md) */ -#define NET_PLATFORM "element-zx-128k" +#define NET_PLATFORM_AT 0x5daa /* bank 6 writes "&pf=element-zx-128k" or "&pf=zx-spectrum-next" there */ #else #define NET_PLATFORM "zx-spectrum-48k" #endif diff --git a/c/platform/zx/tcp_bank6.c b/c/platform/zx/tcp_bank6.c index 459ce20..1a22c82 100644 --- a/c/platform/zx/tcp_bank6.c +++ b/c/platform/zx/tcp_bank6.c @@ -3,19 +3,21 @@ * * This file is linked first, so all of it is below C000h: the code and the * page and stack state stay visible while bank 6 replaces bank 0 at C000h. - * Data in and out goes through the staging buffer at 5D00h-5DBFh, as the + * Data in and out goes through the staging buffer at 5D00h-5DA9h, as the * game's own buffers and its stack may be above C000h: the BASIC loader's * area below the game, free once the game runs (it never returns). A * call runs on bank 6's own stack (from its top down) and returns to the * caller's page and stack; BANKM (5B5Ch) is kept with the port, as the * ROM expects. The entry addresses come from bank 6's map (bank6_entries.h, - * written by tools/zx128_entries.py). */ + * written by tools/zx128_entries.py). Above the buffer, 5DAAh-5DBFh, bank 6 + * leaves the machine's name for the relay, "&pf=" (NET_PLATFORM_AT in + * plat_config.h): an eLeMeNt's or a Next's, as it finds. */ #include #include #include "tcp.h" #include "bank6_entries.h" -#define STAGE_SIZE 192 +#define STAGE_SIZE 170 /* 5DAAh-5DBFh: the machine's name (bank6.c) */ #define b6_stage ((uint8_t *)0x5d00) static uint8_t b6_state; /* 0 not checked, 1 ready, 2 no bank 6 driver */ diff --git a/c/platform/zx/tcp_esp01_at.c b/c/platform/zx/tcp_esp01_at.c index fd53cf7..c2e816c 100644 --- a/c/platform/zx/tcp_esp01_at.c +++ b/c/platform/zx/tcp_esp01_at.c @@ -9,12 +9,23 @@ * receive, 703Bh/713Bh register 5 bit 0 the module's power, 7C3Bh/7D3Bh the * FIFO reset. Timeouts count the ROM's frame counter (5C78h). * + * On a ZX Spectrum Next (esp_next, set by bank6.c) the same UART ports + * serve its ESP; the eLeMeNt's ZXi registers become the Next's: es_init + * selects the ESP's UART (153Bh), 8N1 without flow control (163Bh), 115200 + * Bd from the video timing's clock (nextreg 11h; 143Bh takes the + * prescaler), the UART's ports on (nextreg 83h bit 4), and releases the + * module's reset; the power cycle holds nextreg 02h bit 7 (the ESP's and + * the expansion bus's reset) instead; the FIFO reset is 163Bh bit 7. Its + * status bits 0-2 mean what the driver reads them as: a byte waiting, the + * transmit buffer full, the receive buffer overflowed. + * * His notes: * Fast banked sccz80 TCP backend. Same passive protocol as the C reference. * Receive chunks are 192 bytes. No next read while the local chunk is held. * All UART polling is bounded; synchronous operations have 10s deadlines. */ #include "tcp.h" +uint8_t esp_next; /* 1 on a ZX Spectrum Next */ uint8_t tcp_present(void) __naked { __asm call es_init @@ -39,6 +50,17 @@ uint8_t tcp_present(void) __naked { es_present_power: ; A fixed-length payload state may still require module power recovery. ; Cycle only module power, keeping baud and persistent Wi-Fi credentials. + ld a,(_esp_next) + or a + jr z,es_power_zxi + ld bc,0x243b ; the Next: hold the ESP in reset, es_init releases it + ld a,2 + out (c),a + inc b + ld a,0x80 + out (c),a + jr es_power_off +es_power_zxi: ld bc,0x703b ld a,5 out (c),a @@ -46,6 +68,7 @@ uint8_t tcp_present(void) __naked { in a,(c) res 0,a out (c),a +es_power_off: ld de,50 call es_pause call es_init @@ -401,6 +424,9 @@ static void esp_engine(void) __naked { __asm ; BIOS 2.0 turn_sub/turnon_wifi1 and byte UART semantics, only required services. es_init: + ld a,(_esp_next) + or a + jr nz,es_init_next ld bc,0x703b ld a,5 out (c),a @@ -409,6 +435,55 @@ static void esp_engine(void) __naked { set 0,a out (c),a ret +; The Next: its ESPs UART at 115200 8N1, the UARTs ports on, the module +; out of reset. +es_init_next: + ld bc,0x153b + ld a,0x10 ; the ESP UART; prescaler bits 16:14 = 0 + out (c),a + ld b,0x16 ; 163Bh: 8 bits, no parity, one stop bit, no flow control + ld a,0x18 + out (c),a + ld bc,0x243b + ld a,0x02 ; release the ESP reset + out (c),a + inc b + xor a + out (c),a + dec b + ld a,0x83 ; internal port decoding: the UART on + out (c),a + inc b + in a,(c) + or 0x10 + out (c),a + dec b + ld a,0x11 ; video timing: which 28 MHz clock + out (c),a + inc b + in a,(c) + and 7 + add a,a + ld e,a + ld d,0 + ld hl,es_next_baud + add hl,de + ld a,(hl) + inc hl + ld h,(hl) + ld l,a ; the prescaler: the clock / 115200 + ld bc,0x143b + ld a,l + and 0x7f + out (c),a ; bits 6:0 + add hl,hl + ld a,h + and 0x7f + or 0x80 + out (c),a ; bits 13:7 + ret +es_next_baud: ; nextreg 11h 0-6 (VGA 28.0 .. 33.0 MHz), 7 (HDMI, 27 MHz) + defw 243,248,256,260,269,278,286,234 ; Reset parser/transaction state, preserving host and port arguments. es_clear: ld hl,es_busy @@ -422,6 +497,16 @@ static void esp_engine(void) __naked { ret ; Discard old replies only when no transaction is active. Bounded 2048 bytes. es_drain: + ld a,(_esp_next) + or a + jr z,es_drain_zxi + ld bc,0x163b ; the Next: reset the UART, empty its FIFOs, 8N1 again + ld a,0x98 + out (c),a + ld a,0x18 + out (c),a + jr es_drain_fifo +es_drain_zxi: ; BIOS 2.0 hardware FIFO reset. Also clears an old overflow condition. ld bc,0x7c3b ld a,0x30 @@ -429,6 +514,7 @@ static void esp_engine(void) __naked { inc b ld a,1 out (c),a +es_drain_fifo: ld de,2048 ld l,4 es_drain_loop: diff --git a/docs/development.md b/docs/development.md index ba02edd..8da2988 100644 --- a/docs/development.md +++ b/docs/development.md @@ -54,7 +54,7 @@ c/platform/ one directory per machine: mz, zx, host (the PC simulator) | `c/cpu/z80/` | faster Z80 versions of shared C (playfield copy, hash loop, text and digits, the network's input lines), used where `plat_config.h` asks; the C stays the reference (`portability.md`) | | `c/platform/mz/` | Sharp MZ-700/800: keyboard matrix, joysticks, tones through the monitor, 8253 frame limiter, screen flush through the display-code tables; `uc_mz.c` is the card transport on ports 50h/51h | | `c/platform/zx/` | ZX Spectrum 48K: keys and joysticks, frame sync on the ROM's frame counter, beeper, the 6 x 8 pixel screen routine in assembly; `tcp_spectranet.c` is `tcp.h` over the Spectranet socket calls | -| `c/platform/zx/bank6.c`, `tcp_bank6.c`, `tcp_esp01*.c` | the 128K build (`PLATFORM=zx128`, `port-zx128-esp01.md`): the network driver in RAM bank 6 (the ESP-01's, by Milan Stava, or the Spectranet's), the game's `tcp.h` pages it in | +| `c/platform/zx/bank6.c`, `tcp_bank6.c`, `tcp_esp01*.c` | the 128K build (`PLATFORM=zx128`, `port-zx128-esp01.md`): the network driver in RAM bank 6 (the ESP-01's, by Milan Stava, or the Spectranet's), the game's `tcp.h` pages it in; the same build on a ZX Spectrum Next (`port-zx-next.md`) | | `c/platform/cpc/` | Amstrad CPC (port in progress, `port-amstrad-cpc.md`): Mode 1 in four inks, cells rendered in advance from the MZ characters (`tools/make_cpc_tables.py`), keyboard and joysticks through the PPI, AY tones | | `c/platform/host/` | the PC: `sim.c` (the whole game with a key bot, recording, replay and a stub network card), `tcp_posix.c` and `softnet_test.c` (the software network device on a PC) | | `c/platform/*/tables.c/.h` | generated: logical cell codes to the machine's characters and colours (`tools/make_zx_tables.py` for the Spectrum) | @@ -185,4 +185,5 @@ changed on purpose and how fast it runs: `original.md`. | `port-web.md` | the game compiled to WebAssembly for the browser (no emulator): plan, results, the page on mzpico.com | | `portability.md` | the rules that keep one C game for Z80, 6502 and 68000 machines | | `port-zx128-esp01.md` | the 128K Spectrum with an ESP-01 (Milan Stava's port, brought in step by step): plan and progress | +| `port-zx-next.md` | the ZX Spectrum Next: the 128K build and its ESP driver on the Next's UART; plan and progress | | `../PLAN.md` | the multiplayer plan the C port followed | diff --git a/docs/net-protocol.md b/docs/net-protocol.md index f701931..b33475b 100644 --- a/docs/net-protocol.md +++ b/docs/net-protocol.md @@ -113,9 +113,14 @@ One socket per device. JSON frames: **Which machine** (`&pf=` in the URL, optional): the machine's name for the production relay's statistics, the id of its port in the catalog (`c64`, `amiga`, `atari-xl`, `atari-st`, `amstrad-cpc`, `pc-dos`, `zx-spectrum-48k`, -`element-zx-128k`, `browser`). It changes nothing in a game; the production +`element-zx-128k`, `zx-spectrum-next`, `browser`). It changes nothing in a game; the production relay counts an unknown id as if there were none, and `relay/relay.py` ignores -it. `NET_PLATFORM` in a platform's `plat_config.h` sets it; the MZ-800 needs +it. `NET_PLATFORM` in a platform's `plat_config.h` sets it. The 128K build +sets `NET_PLATFORM_AT` instead, which takes precedence: the game reads the +`&pf=` that its bank 6 driver wrote at that address +(`platform/zx/bank6.c`, `bank6_present`): `element-zx-128k` or +`zx-spectrum-next`, as the driver finds, none in the Spectranet test +variant; the names are changed there. The MZ-800 needs none, because the MZPico firmware makes the connection and names itself. Rooms die 10 minutes after their last message (a host may wait a while). Codes are 4 letters from a diff --git a/docs/port-zx-next.md b/docs/port-zx-next.md new file mode 100644 index 0000000..aafbe24 --- /dev/null +++ b/docs/port-zx-next.md @@ -0,0 +1,130 @@ +# BomberNet on the ZX Spectrum Next: plan and progress + +The Next runs the 128K build (`PLATFORM=zx128`, docs/port-zx128-esp01.md) +in its 128K mode: the same game, the same network driver in RAM bank 6. Its +ESP Wi-Fi module sits behind a UART whose ports, 133Bh and 143Bh, the +eLeMeNt ZX's copied, so Milan Stava's ESP-01 driver talks to it unchanged. +What differs is around the UART, and it is a few branches in that driver. + +## Steps + +1. **The driver on a Next**: tell the Next apart, select its ESP's UART at + 115200 Bd, its module reset and FIFO reset. Done, see below. +2. **The Next in the test emulator**: `tools/zxemu.py` with + `esp01='next'`; the lockstep and cross-play tests with Next machines, + in CI. Done, see below. +3. **A real emulator**: the tape loaded under NextZXOS and matches played + on a whole emulated Next (ZEsarUX). Done, see below. +4. **Hardware test** on a Next, then the release (the 128K tape under a + Next name as well, a catalog card, a setup guide). +5. Optional: the Next's 28 MHz (nextreg 07h) gives it the time for the + run-ahead of docs/rollback-plan.md, the only Z80 machine that has it. + The 128K tape has no memory left for it (below), so it would be a Next + build of its own (z88dk's `+zxn`, a `.nex` file). + +## Step 1: the driver + +From the core's own documents (gitlab.com/SpectrumNext/ +ZX_Spectrum_Next_FPGA, `cores/zxnext/ports.txt` and `nextreg.txt`): + +- **Which machine.** `bank6.c` asks for the eLeMeNt or the MB03+ first, as + before, then for a Next: nextreg 7Fh (a user register, through 243Bh and + 253Bh) written 5Ah and A5h must read back each. A 128K, +2 or +3 decodes + neither port (A1 = 1, A0 = 1); on a Next the register's value is put + back. A ZX Printer decodes both (A2 = 0) and its motor starts on 5Ah: on + a machine that is not a Next the check ends by writing 04h, motor off. The + machine ID (nextreg 00h) is not used: 0Ah on a Next, other values on the + Next cores of other FPGA boards and in emulators. +- **The UART.** 153Bh bit 6 = 0 selects the ESP's UART (the other is the + Pi's), with bit 4 the prescaler's top bits 16:14 = 0; 163Bh = 18h, 8 bits, + no parity, one stop bit, no flow control; nextreg 83h bit 4 keeps the + UART's ports decoded. 115200 Bd: the prescaler is the system clock / the + baud rate, the clock from the video timing (nextreg 11h: 28.0 to 33.0 MHz + for VGA 0 to 6, 27 MHz for HDMI), so 243 to 286, or 234; 143Bh takes its + bits 6:0, then bits 13:7 with bit 7 set. The eLeMeNt's driver keeps the + speed it finds; on the Next it is set, as the module's AT firmware starts + at 115200 after a reset. +- **The status bits** of 133Bh mean what the driver reads them as: bit 0 a + byte waiting, bit 1 the transmit buffer full (64 bytes), bit 2 the + receive buffer overflowed (cleared by the read; the driver's error 5). + The receive buffer holds 512 bytes, the eLeMeNt's 2048. +- **The module's reset.** Where the eLeMeNt switches the module's power + (ZXi register 5), the Next holds nextreg 02h bit 7, which resets the ESP + and the expansion bus, and the driver's `es_init` releases it. +- **The FIFO reset.** 163Bh bit 7 empties both FIFOs (the eLeMeNt's ZXi + register 30h). + +The game's program is the same (but for the name, below); bank 6 grows by +259 bytes (11231, about 4.6 KB free below its stack). The eLeMeNt's paths +are unchanged. + +## Step 2: the test emulator + +`tools/zxemu.py` class `NextEsp`, from the same documents: the nextregs +above (00h, 02h, 11h, 7Fh, 83h), the UART's four ports, the status bits, +a 512-byte receive buffer that counts what it loses, a 64-byte transmit +buffer. The module hears the Spectrum only with the ESP's UART selected, +its ports on, 8-bit frames and a prescaler within 2 % of 115200 Bd at the +video timing's clock (`NEXT_TIMING`, default 0); else what is sent is lost +and counted. The eLeMeNt's ZXi ports read FFh, as on a Next. + +- `tools/lockstep_zx.py`: `A_NEXT=1`, `B_NEXT=1` make that machine a Next; + a byte lost in an ESP's receive buffer now fails the test. +- `tools/crossplay.py`: the machine `next`. +- CI (test.yml): two Nexts with four players on the dm4 keys and the stack + watermark, two Nexts on HDMI timing, a Next against a 48K Spectranet, an + eLeMeNt against a Next. + +Results, each with 0 mismatches, no abort and no byte lost in an ESP's +receive buffer; the local relay unless noted: + +| Match | Frames | Notes | +|---|---|---| +| Next against Next, 4 players (2 + 2) on the dm4 keys | 240 | 139 bytes of stack left above the program | +| Next against Next, HDMI timing (27 MHz clock, prescaler 234) | 240 | | +| Next host, 48K Spectranet joiner, and the reverse | 240 each | | +| Next host, eLeMeNt joiner, and the reverse | 240 each | | +| Next against Next, BREAK after 60 | | both leave; the module back to commands, the Next hosts a new room | +| Next against CPC, both ways (`tools/crossplay.py`) | 160 each | playfields identical | +| Next against MZ-800, both ways | 160 each | playfields identical | +| Next host, 48K joiner, production relay | 200 | the module resolves and connects to api.mzpico.com itself | + +The emulation is written from the documents, not from a real Next: the +loading, the module's real timing and replies, and the 512-byte receive +buffer at the relay's real pace are the hardware test's to check (step 4). + +## Step 3: a whole emulated Next + +ZEsarUX (built from source in `~/src/zesarux`, git 4d86ac8) emulates the +Next with its SD card and NextZXOS, and can bridge its UART to a host +character device; `tools/ci/zesarux-uartbridge.patch` adds the option +`--uartbridge ` (otherwise a menu setting). `tools/next_esp.py` +puts an ESP's AT firmware on a pseudo-terminal, connected to the local +relay. `tools/next_zesarux.py host|join` boots the Next from ZEsarUX's SD +image (NextZXOS 2.06H, 2020) with the tape added, through the video mode +test and the welcome into the Browser, opens the tape with the TAP +loader's "128K mode" as a player would, and plays against the 48K of +`tools/zxemu.py`: the Next hosts, or types the 48K's room code. + +- The tape loads in 128K mode from the Browser; the title's NETWORK row + reads OFF and can be changed (not dimmed as NONE): the game found the + Next, set its UART and the module answered. +- Next hosting, 48K joining: 600 frames, no abort (the game compares the + hashes every 16 frames; a difference would end it with DESYNC). +- 48K hosting, Next joining by its keyboard: 600 frames, no abort. +- The relay sees `pf=zx-spectrum-next`. + +ZEsarUX's UART status has only bit 0 (a byte waiting), its transmit never +busy, and the nextreg 02h reset does not reach the module: those parts are +covered by `tools/zxemu.py` above, not here. + +## The machine's name for the relay + +The relay's statistics take `&pf=` (docs/net-protocol.md). The 128K +tape is the same file on an eLeMeNt and a Next, so the name is chosen at +run time: bank 6's `bank6_present` writes `&pf=element-zx-128k` or +`&pf=zx-spectrum-next` into 5DAAh-5DBFh, above the staging buffer (which +is now 170 bytes, 5D00h-5DA9h), and the game copies it from there into the +room's URL (`NET_PLATFORM_AT` in plat_config.h). The game program grows by +1 byte (FE76h, 42 bytes under its limit); doing the same in the game +itself cost 57 to 60 bytes, more than it had. diff --git a/docs/setup/README.md b/docs/setup/README.md index f9387a8..c47c401 100644 --- a/docs/setup/README.md +++ b/docs/setup/README.md @@ -11,6 +11,7 @@ runs in the browser. | Sharp MZ-800 (the MZ-700 plays locally) | [mz-800.md](mz-800.md) | | ZX Spectrum 48K and up | [zx-spectrum-48k.md](zx-spectrum-48k.md) | | eLeMeNt ZX in 128K mode, with an ESP-01 | [element-zx-128k-esp01.md](element-zx-128k-esp01.md) | +| ZX Spectrum Next (untried on hardware) | [zx-spectrum-next.md](zx-spectrum-next.md) | | Amstrad CPC | [amstrad-cpc.md](amstrad-cpc.md) | | Atari XL/XE | [atari-xl.md](atari-xl.md) | | Commodore 64 | [c64.md](c64.md) | @@ -90,7 +91,7 @@ Then point each machine at that PC (say 192.168.1.10): | Message | Meaning | |---|---| -| NETWORK row greyed out, or missing | no network device was found when the game started; see the platform's guide | +| NETWORK row dimmed, reading NONE | no network device was found when the game started; see the platform's guide | | NO CONNECTION | the relay did not answer: no network, no DHCP, a wrong relay address, or a Wi-Fi device not joined to its network | | ROOM NOT FOUND | no room has that code (rooms close when everybody leaves) | | BUILD MISMATCH | the other machine runs a BomberNet whose game logic or protocol differs: the two must carry the same build id, which changes only with those (0.2.0 and 0.3.0 share it and play together) | diff --git a/docs/setup/amiga.md b/docs/setup/amiga.md index 03a6886..f30c683 100644 --- a/docs/setup/amiga.md +++ b/docs/setup/amiga.md @@ -22,7 +22,7 @@ stack provides. Start your stack before the game: Roadshow, AmiTCP, Miami, Genesis, over any Ethernet or Wi-Fi hardware they support. The game needs no settings of its own. -Without a stack running, the title screen has no NETWORK row. +Without a stack running, the title screen shows the NETWORK row dimmed, as NONE. For a relay of your own, rewrite the `.adf` or the program's relay address with `tools/set_relay.py` from the sources (see the diff --git a/docs/setup/amstrad-cpc.md b/docs/setup/amstrad-cpc.md index 34d47b4..80406f8 100644 --- a/docs/setup/amstrad-cpc.md +++ b/docs/setup/amstrad-cpc.md @@ -19,7 +19,7 @@ M4 must be joined to your Wi-Fi first, as its manual describes (its configuration on the SD card, or its web page). Nothing in the game to set. -Without an M4, the title screen has no NETWORK row. +Without an M4, the title screen shows the NETWORK row dimmed, as NONE. For a relay of your own, rewrite the `.dsk` or the `.cpc` file's relay address with `tools/set_relay.py` from the sources (see the diff --git a/docs/setup/atari-st.md b/docs/setup/atari-st.md index bc5e789..a24a4cf 100644 --- a/docs/setup/atari-st.md +++ b/docs/setup/atari-st.md @@ -24,7 +24,7 @@ to your Wi-Fi as its manual describes. The game talks to it at 19,200 bps, translation), then `ATDT relay:port` to connect. Set the modem to 19,200 bps if it is not there already; nothing else in the game to set. -Without a modem answering, the title screen has no NETWORK row. +Without a modem answering, the title screen shows the NETWORK row dimmed, as NONE. For a relay of your own, rewrite the `.st` or the `.prg` file's relay address with `tools/set_relay.py` from the sources (see the diff --git a/docs/setup/atari-xl.md b/docs/setup/atari-xl.md index 7a1aa9a..2223445 100644 --- a/docs/setup/atari-xl.md +++ b/docs/setup/atari-xl.md @@ -18,7 +18,7 @@ keyboard and the serial bus itself; a reset brings the OS back. serial bus, at the FujiNet's high speed. The FujiNet must be joined to your Wi-Fi, which its CONFIG program does once; nothing in the game to set. -Without a FujiNet answering, the title screen has no NETWORK row. +Without a FujiNet answering, the title screen shows the NETWORK row dimmed, as NONE. **Not tried on real hardware yet.** The network has been tested only in an emulated chain (Altirra, FujiNet-PC and the NetSIO hub), which runs far diff --git a/docs/setup/c64.md b/docs/setup/c64.md index ea4fd44..30cdca4 100644 --- a/docs/setup/c64.md +++ b/docs/setup/c64.md @@ -23,7 +23,7 @@ Two devices work; the game finds whichever answers at start. interface (under its cartridge or software settings) and have the Ultimate on your network; the game then opens its connections through it. -Without either, the title screen has no NETWORK row. +Without either, the title screen shows the NETWORK row dimmed, as NONE. For a relay of your own, rewrite the `.d64` or the `.prg` file's relay address with `tools/set_relay.py` from the sources (see the diff --git a/docs/setup/element-zx-128k-esp01.md b/docs/setup/element-zx-128k-esp01.md index 0339c97..db67c95 100644 --- a/docs/setup/element-zx-128k-esp01.md +++ b/docs/setup/element-zx-128k-esp01.md @@ -22,7 +22,7 @@ board's own tools, as the eLeMeNt's documentation describes; the game does not store Wi-Fi credentials. At start the game probes the module and recovers it if it is in a bad state. -Without a module answering, the title screen has no NETWORK row. +Without a module answering, the title screen shows the NETWORK row dimmed, as NONE. For a relay of your own, rewrite the tape's relay address with `tools/set_relay.py` from the sources (see the [setup page](README.md#the-relay)). diff --git a/docs/setup/mz-800.md b/docs/setup/mz-800.md index 0a1b70d..0fbfb83 100644 --- a/docs/setup/mz-800.md +++ b/docs/setup/mz-800.md @@ -29,7 +29,7 @@ it is known to work. In `/unicard/network.cfg`: `NETRELAYADDR` is that PC's address, `NETRELAYPORT` 8766. -Without either, the title screen has no NETWORK row. +Without either, the title screen shows the NETWORK row dimmed, as NONE. ## Keys diff --git a/docs/setup/zx-spectrum-48k.md b/docs/setup/zx-spectrum-48k.md index 483b587..31d0e12 100644 --- a/docs/setup/zx-spectrum-48k.md +++ b/docs/setup/zx-spectrum-48k.md @@ -22,7 +22,7 @@ on a plain 48K. configuration (its ROM's setup utility). Nothing in the game to set. - **Spectranext:** the same interface; set up as its manual describes. -Without a Spectranet or Spectranext, the title screen has no NETWORK row. +Without a Spectranet or Spectranext, the title screen shows the NETWORK row dimmed, as NONE. For a relay of your own, rewrite the tape's relay address with `tools/set_relay.py` from the sources (see the [setup page](README.md#the-relay)). diff --git a/docs/setup/zx-spectrum-next.md b/docs/setup/zx-spectrum-next.md new file mode 100644 index 0000000..5b5d74f --- /dev/null +++ b/docs/setup/zx-spectrum-next.md @@ -0,0 +1,49 @@ +# BomberNet on the ZX Spectrum Next + +**Runs on:** a ZX Spectrum Next, or a Next core on another FPGA board, with +its ESP Wi-Fi module, in its ZX Spectrum 128K mode. It is the same game and +the same tape as for the eLeMeNt ZX: the game tells the two machines apart +and drives the Next's own Wi-Fi. + +**Not tried on a real Next yet.** The game has been tested on emulated +Nexts only: loaded under NextZXOS and played over the network in a whole +emulated Next, and matched against every other machine on a model built +from the Next's hardware documents. Reports from real Nexts are welcome. + +**File:** the 128K tape, `bombernet--zx-spectrum-128k-esp01.tap`. + +## Loading + +Copy the tape to the SD card, open it in NextZXOS's Browser and choose +**1, 128K mode** in the TAP loader's menu. The game uses the 128K's extra +memory (the network driver lives in a RAM bank) and the AY for its tones. + +## Network play + +The Next's ESP module must be on your Wi-Fi first: join it with the Next's +own Wi-Fi setup, as its manual describes, so that the module keeps the +network and joins it again by itself after a reset (the AT firmware's +saved network and automatic connection, the usual setting). The game never +asks for the network, and when it resets an unresponsive module it relies +on that. At start the game selects the ESP's +serial port, sets it to 115200 Bd (the module's AT firmware speed after a +reset) for whichever video mode the Next runs, probes the module, and +resets it if it does not answer. + +Without a module answering, the title screen shows the NETWORK row dimmed, as NONE. + +For a relay of your own, rewrite the tape's relay address with +`tools/set_relay.py` from the sources (see the [setup page](README.md#the-relay)). + +## Keys + +As on the 48K: Q A O P and SPACE (M when two share the keyboard), the +Sinclair keys, Kempston, Fuller or Cursor joysticks; BREAK leaves a match. + +## In an emulator + +ZEsarUX runs it under NextZXOS and plays through the relay when its Next's +serial port is connected to a Wi-Fi module emulated on the host +(`tools/next_esp.py` from the sources, with ZEsarUX patched as +`docs/port-zx-next.md` describes). CSpect emulates the ESP's AT commands +itself; it has not been tried. diff --git a/tools/ci/zesarux-uartbridge.patch b/tools/ci/zesarux-uartbridge.patch new file mode 100644 index 0000000..22fedc5 --- /dev/null +++ b/tools/ci/zesarux-uartbridge.patch @@ -0,0 +1,30 @@ +diff --git a/src/start.c b/src/start.c +index 6556d5a..f9dedfa 100644 +--- a/src/start.c ++++ b/src/start.c +@@ -52,6 +52,7 @@ + + + #include "start.h" ++#include "uartbridge.h" + #include "cpu.h" + #include "scrnull.h" + #include "operaciones.h" +@@ -4204,6 +4205,17 @@ int parse_cmdline_options(int desde_commandline) + tbblue_fast_boot_mode.v=1; + } + ++ else if (!strcmp(argv[puntero_parametro],"--uartbridge")) { ++ /* BomberNet test bench: the Next's ESP UART on a host character device (a pty) */ ++ siguiente_parametro_argumento(); ++ if (strlen(argv[puntero_parametro]) >= PATH_MAX) { ++ printf("--uartbridge: device path too long\n"); ++ exit(1); ++ } ++ strcpy(uartbridge_name,argv[puntero_parametro]); ++ uartbridge_enable(); ++ } ++ + else if (!strcmp(argv[puntero_parametro],"--random-r-register")) { + cpu_random_r_register.v=1; + } diff --git a/tools/crossplay.py b/tools/crossplay.py index 597c69a..3070b33 100755 --- a/tools/crossplay.py +++ b/tools/crossplay.py @@ -10,8 +10,9 @@ C64 runs in VICE with a WiC64 (tools/vice.py), in real time on its own: its TV frame is 20 ms of waiting, and it stands still while it is read. - tools/crossplay.py [steps] [host] [joiner] machines: mz, zx, cpc, esp, c64, amiga, st, pc, web; default mz zx - (esp: build/zx128, an eLeMeNt with its ESP-01) + tools/crossplay.py [steps] [host] [joiner] machines: mz, zx, cpc, esp, next, c64, amiga, st, pc, web; default mz zx + (esp: build/zx128, an eLeMeNt with its ESP-01; + next: the same build on a ZX Spectrum Next) (the second argument alone: mz or zx hosts the other) PLAYERS=3 LOCAL_HOST=2 LOCAL_JOIN=1 seats: players in total, local players per machine MODE=0 co-op (default 1, deathmatch) @@ -69,8 +70,8 @@ class Spectrum: def __init__(self): self.S = {n: sym_from_map(self.build + '/bomber.map', n) for n in NAMES} - if self.kind == 'ESP': - self.z = ZX(esp01=True, bank6=self.build + '/bank6', relay=('127.0.0.1', 8765)) + if self.kind in ('ESP', 'NEXT'): + self.z = ZX(esp01='next' if self.kind == 'NEXT' else True, bank6=self.build + '/bank6', relay=('127.0.0.1', 8765)) else: self.z = ZX(spectranet=True, relay=('127.0.0.1', 8765)) self.z.load(self.build + '/bomber') @@ -95,7 +96,12 @@ def close(self): pass class Element(Spectrum): """The 128K build with its ESP-01 driver, on an emulated eLeMeNt ZX.""" kind = 'ESP' - build = 'build/zx128' + build = os.environ.get('ZX128_BUILD', 'build/zx128') + + +class Next(Element): + """The same build on an emulated ZX Spectrum Next with its ESP.""" + kind = 'NEXT' class Amstrad: @@ -468,7 +474,7 @@ def until(cond, limit, *ms): t0 = time.time() -MACHINES = {'mz': MZ, 'zx': Spectrum, 'cpc': Amstrad, 'esp': Element, 'c64': Commodore, 'amiga': Amiga, 'st': AtariST, 'pc': IBMPC, 'web': WebPage} +MACHINES = {'mz': MZ, 'zx': Spectrum, 'cpc': Amstrad, 'esp': Element, 'next': Next, 'c64': Commodore, 'amiga': Amiga, 'st': AtariST, 'pc': IBMPC, 'web': WebPage} host, join = MACHINES[HOST](), MACHINES[JOIN]() both = (host, join) run(90, *both) # both titles up and settled @@ -501,8 +507,10 @@ def until(cond, limit, *ms): for m in both: if m.kind == 'C64': m.reset_net() if not os.environ.get('NOWALK'): host.press('walk'); join.press('walk') # inputs cross between the machines -seen = {m.kind: {} for m in both} -maps = {m.kind: {} for m in both} # frame -> the map: compared at a frame both have (the logs give them every 16th) +H, J = (host.kind, join.kind) if host.kind != join.kind else (host.kind + ' host', join.kind + ' join') +KEY = {id(host): H, id(join): J} # the two machines' results apart, also when both are of one kind +seen = {H: {}, J: {}} +maps = {H: {}, J: {}} # frame -> the map: compared at a frame both have (the logs give them every 16th) start = [m.r16('_frame_no') for m in both] @@ -511,17 +519,17 @@ def collect(m): or (the MZ, read between TV frames) from its current frame.""" if hasattr(m, 'flushes'): for f, h in m.flushes: - if f % HP: seen[m.kind][(f // HP) * HP] = h + if f % HP: seen[KEY[id(m)]][(f // HP) * HP] = h m.flushes.clear() else: f = m.r16('_frame_no') - if f % HP: seen[m.kind][(f // HP) * HP] = m.r16('_state_hash') - if hasattr(m, 'maps'): maps[m.kind].update(m.maps); m.maps.clear() + if f % HP: seen[KEY[id(m)]][(f // HP) * HP] = m.r16('_state_hash') + if hasattr(m, 'maps'): maps[KEY[id(m)]].update(m.maps); m.maps.clear() else: # read from memory: the map at the frames the logs keep (f % 16 == 1) f = m.r16('_frame_no') - if f % HP == 1 and f not in maps[m.kind]: + if f % HP == 1 and f not in maps[KEY[id(m)]]: mp = m.rd('_map_layer', 1000) - if mp: maps[m.kind][f] = bytes(mp) + if mp: maps[KEY[id(m)]][f] = bytes(mp) GAP = int(os.environ.get('GAP', 0)) # GAP=n: at game frame n the C64 stops polling for 5 s @@ -543,7 +551,6 @@ def collect(m): m.gap(5, *[o for o in both if o is not m]); GAP = 0 for m in both: collect(m) if host.r8('_net_abort') or join.r8('_net_abort'): break -H, J = host.kind, join.kind common = sorted(set(seen[H]) & set(seen[J]) - {0}) mism = [f for f in common if seen[H][f] != seen[J][f]] for f in common: print(f'frame {f}: {H} {seen[H][f]:04x} {J} {seen[J][f]:04x} {"MISMATCH" if f in mism else "ok"}') diff --git a/tools/lockstep_zx.py b/tools/lockstep_zx.py index 92e4331..dd229e1 100755 --- a/tools/lockstep_zx.py +++ b/tools/lockstep_zx.py @@ -9,6 +9,8 @@ B_BUILD=build/v020/build/zx ... B runs another build (its bomber and bomber.map) A_BUILD=build/zx128 ... A too; a build with a bank6 file is a 128K Spectrum, an eLeMeNt with an ESP-01 when that is its driver + A_NEXT=1, B_NEXT=1 ... that machine is a ZX Spectrum Next with its ESP instead + (NEXT_TIMING=7: its video timing, HDMI; default 0) KEYS=build/ref/dm4.bnr ... the players' keys from a recording (A's local players are its players 1 and 2, B's 3 and 4): a busy match QUIET=1 ... tones off @@ -44,9 +46,11 @@ def g8(z, addr): return gr(z, addr, 1)[0] def g16(z, addr): return int.from_bytes(gr(z, addr, 2), 'little') def gp(z, addr, data, page=0): z.poke(addr, data, page=page) -def inst(build): +def inst(build, next_=False): b6 = os.path.join(build, 'bank6') esp = os.path.exists(b6) and 'stream_rx' in open(b6 + '.map').read() # the ESP-01 driver in bank 6 + if next_ and not esp: sys.exit(f'{build}: a Next needs the ESP driver in bank 6 (A_NEXT/B_NEXT)') + if esp and next_: esp = 'next' z = ZX(spectranet=not esp, esp01=esp, relay=relay, bank6=b6 if os.path.exists(b6) else None) z.load(os.path.join(build, 'bomber')) return z @@ -62,7 +66,7 @@ def tap(z, key, n=3, *others): t0 = time.time() stack_short = False # STACK_MIN=n: fail when the stack left fewer bytes unused -a, b = inst(A_BUILD), inst(B_BUILD) +a, b = inst(A_BUILD, os.environ.get('A_NEXT') == '1'), inst(B_BUILD, os.environ.get('B_NEXT') == '1') FB, TMB, SHB, FNB, NSB, NAB_B, NDLY_B = (SB(n) for n in ('_flush_screen', '_title_mode', '_state_hash', '_frame_no', '_net_slot', '_net_abort', '_net_delay')) BSS = {a: S('__BSS_END_tail'), b: SB('__BSS_END_tail')} @@ -168,7 +172,8 @@ def step_a(): # A's own quanta, to time its f'{a.sn_calls + b.sn_calls} Spectranet calls; {time.time() - t0:.0f} s') a.screenshot('build/zx_net_A.png'); b.screenshot('build/zx_net_B.png') for name, z in (('A', a), ('B', b)): - if z.esp: print(f'{name}: ESP-01 receive FIFO, bytes lost: {z.esp.lost}') + if z.esp: z.esp._deliver() + if z.esp: print(f'{name}: ESP receive FIFO, bytes lost: {z.esp.lost}' + (f', sent with the UART set wrong: {z.esp.garbled}' if hasattr(z.esp, 'garbled') else '')) m = z.read(BSS[z], TOP[z] - BSS[z], page=0) used_from = next((BSS[z] + i for i, v in enumerate(m) if v != 0xa5), TOP[z]) print(f'{name}: stack reached {used_from:04x} (marked up to {TOP[z]:04x}), {used_from - BSS[z]} bytes above the program left unused') @@ -195,8 +200,11 @@ def step_a(): # A's own quanta, to time its again = gr(a, NC, 4) != before print('A hosts again: room', gr(a, NC, 4).decode() if again else 'none') sys.exit(0 if aborts[0] == 7 and aborts[1] and not mism and again else 1) +for z in (a, b): + if z.esp: z.esp._deliver() # bytes due since the last read: into the FIFO, or lost +lost = any(z.esp and z.esp.lost for z in (a, b)) # an ESP receive buffer overflowed if CUT_AT: print(f'link cut at frame {CUT_AT}: A abort {aborts[0]} after {cut_after if cut_after is None else round(cut_after, 1)} s, ' f'B abort {aborts[1]} (9 = CONNECTION LOST)') - sys.exit(0 if aborts == (9, 9) and cut_after and 9 <= cut_after <= 12 and not mism else 1) -sys.exit(1 if mism or any(aborts) or not common or stack_short else 0) + sys.exit(0 if aborts == (9, 9) and cut_after and 9 <= cut_after <= 12 and not mism and not lost else 1) +sys.exit(1 if mism or any(aborts) or not common or stack_short or lost else 0) diff --git a/tools/next_esp.py b/tools/next_esp.py new file mode 100644 index 0000000..7e96a54 --- /dev/null +++ b/tools/next_esp.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""An ESP8266 with its AT firmware on a pseudo-terminal: the ZX Spectrum +Next's Wi-Fi module for an emulator whose Next UART is bridged to a host +character device (ZEsarUX's --uartbridge, patched in by tools/ci/ +zesarux-uartbridge.patch). + + tools/next_esp.py LINK [--log file] [--relay host:port] [--trace] + +LINK becomes a symlink to the pty's slave side. The firmware is what +tools/zxemu.py's Esp01 answers, in real time: AT, ATE0 (echo until then), +AT+CIPMUX/CIPDINFO/CIPRECVMODE/CIPMODE, AT+CIPSTART="TCP","host",port (a +real connection; --relay sends it there instead, the local relay in the +tests), AT+CIPCLOSE, AT+CIPSEND in CIPMODE=1: transparent, every byte to +the socket and back, until "+++" alone (20 ms of silence before and +after). Anything else answers ERROR. Bytes to the Next are paced at +115200 Bd (11520 a second). The log has every command and connection +(--trace: the bytes too).""" +import os, re, select, socket, sys, termios, time, tty + +link = sys.argv[1] +logf = open(sys.argv[sys.argv.index('--log') + 1], 'a') if '--log' in sys.argv else None +relay = None +if '--relay' in sys.argv: + h, _, p = sys.argv[sys.argv.index('--relay') + 1].rpartition(':') + relay = (h, int(p)) +TRACE = '--trace' in sys.argv +RATE = 11520.0 # bytes a second at 115200 Bd, 8N1 +GUARD = 0.020 + + +def log(msg): + if logf: logf.write(f'{time.time():.3f} {msg}\n'); logf.flush() + + +master, slave = os.openpty() +tty.setraw(slave) +attrs = termios.tcgetattr(slave) +attrs[3] &= ~termios.ECHO +termios.tcsetattr(slave, termios.TCSANOW, attrs) +if os.path.lexists(link): os.remove(link) +os.symlink(os.ttyname(slave), link) # the slave kept open here: the emulator closing it never hangs up the pty +log(f'pty {os.ttyname(slave)} as {link}') + +sock, echo, cipmode, transparent = None, True, 0, False + +line = bytearray() +to_next = bytearray() +budget, last_pace = 0.0, time.time() +plus, last_rx = 0, 0.0 + + +def say(text): + to_next.extend(text.encode() if isinstance(text, str) else text) + + +def close(): + global sock + if sock: sock.close(); sock = None + + +def command(c): + global echo, cipmode, transparent, sock, plus + log(f'command {c!r}') + ok = '\r\nOK\r\n' + if c == 'AT': say(ok) + elif c == 'ATE0': echo = False; say(ok) + elif c in ('AT+CIPMUX=0', 'AT+CIPDINFO=0', 'AT+CIPRECVMODE=0', 'AT+CIPRECVMODE=1'): say(ok) + elif c in ('AT+CIPMODE=0', 'AT+CIPMODE=1'): cipmode = int(c[-1]); say(ok) + elif c == 'AT+CIPCLOSE': + if sock: close(); say('CLOSED\r\n' + ok) + else: say('\r\nERROR\r\n') + elif c.startswith('AT+CIPSTART="TCP","'): + m = re.match(r'AT\+CIPSTART="TCP","([^"]+)",(\d+)$', c) + if not m: say('\r\nERROR\r\n'); return # malformed: refused, as the firmware does, relay or not + try: + s = socket.create_connection(relay if relay else (m.group(1), int(m.group(2))), timeout=10) + s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + s.settimeout(5) # sends wait for room; reads only after select says there is data + close(); sock = s; say('CONNECT\r\n' + ok); log(f'connected to {s.getpeername()}') + except OSError as e: + log(f'connect: {e}'); say('\r\nERROR\r\nCLOSED\r\n') + elif c == 'AT+CIPSEND' and cipmode == 1 and sock: + say(ok + '\r\n>'); transparent = True; plus = 0 + else: say('\r\nERROR\r\n') + + +def from_next(data): + global plus, last_rx, transparent + for b in data: + now = time.time() + if transparent: + if b == 0x2b and (plus or now - last_rx >= GUARD) and plus < 3: + plus += 1 # perhaps the escape: held back + else: + out = b'+' * plus + bytes([b]); plus = 0 + if sock: + try: sock.sendall(out) + except OSError: close() + last_rx = now + continue + last_rx = now + if echo: say(bytes([b])) + if b == 10: + c = line.decode('latin-1').strip(); line.clear() + if c: command(c) + else: line.append(b) + + +while True: + now = time.time() + budget = min(budget + (now - last_pace) * RATE, 64.0); last_pace = now + if to_next and budget >= 1: + n = min(int(budget), len(to_next)) + os.write(master, bytes(to_next[:n])); del to_next[:n]; budget -= n + if plus and time.time() - last_rx >= GUARD: + if plus == 3: transparent = False; log('+++: back to commands') + elif sock: # a + or ++ that ended a payload: data after all + try: sock.sendall(b'+' * plus) + except OSError: close() + plus = 0 + rl = [master] + ([sock] if sock and transparent and len(to_next) < 512 else []) + r, _, _ = select.select(rl, [], [], 0.002) + if master in r: + d = os.read(master, 4096) + if TRACE: log(f'from the Next {d!r}') + from_next(d) + if sock and sock in r: + try: d = sock.recv(4096) + except OSError: d = b'' + if d: + if TRACE: log(f'to the Next {d!r}') + say(d) + else: + log('the far end closed'); close(); transparent = False; say('CLOSED\r\n') diff --git a/tools/next_zesarux.py b/tools/next_zesarux.py new file mode 100644 index 0000000..b4b2a69 --- /dev/null +++ b/tools/next_zesarux.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""The 128K tape on a whole emulated ZX Spectrum Next (ZEsarUX) against the +emulated 48K Spectrum of tools/zxemu.py, through the local relay. + + tools/next_zesarux.py host|join [frames] default 600 + +The Next boots from the Next system's SD card image (ZEsarUX's tbblue.mmc, +copied to build/next with BOMBER.TAP from build/zx128 added), past the +video mode test and the welcome, into NextZXOS's Browser, and loads the +tape with the TAP loader's "128K mode", as a player would. Its UART is +bridged to tools/next_esp.py, an ESP's AT firmware on a pseudo-terminal +that connects to the local relay. host: the Next hosts and the 48K joins; +join: the 48K hosts and the Next types the room code. Then both walk for +the frames given; the game checks the hashes itself (DESYNC would end the +match), and the verdict is that neither machine aborted. Screenshots of +the Next: build/next/*.bmp. + +Needs ZEsarUX built in ~/src/zesarux/src (ZESARUX) with +tools/ci/zesarux-uartbridge.patch (its --uartbridge option), Xvfb on :97 +(NEXT_DISPLAY), the local relay on 8765, mtools, and build/zx128 and +build/zx (or ZX48_BUILD). ZEsarUX's remote protocol on port 10123.""" +import os, socket, subprocess, sys, time +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from zxemu import ZX, sym_from_map + +ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) +OUT = os.path.join(ROOT, 'build', 'next') +ZDIR = os.environ.get('ZESARUX', os.path.expanduser('~/src/zesarux/src')) +ZX48 = os.environ.get('ZX48_BUILD', os.path.join(ROOT, 'build', 'zx')) +PORT = 10123 +ROLE = sys.argv[1] if len(sys.argv) > 1 else 'host' +N = int(sys.argv[2]) if len(sys.argv) > 2 else 600 +K_SPACE, K_ENTER, K_DOWN = 128, 129, 144 # ZEsarUX's util_teclas + + +def zrcp(*lines, wait=0.6): + """send commands to ZEsarUX's remote protocol; their replies, the prompts left out""" + s = socket.create_connection(('127.0.0.1', PORT)); s.settimeout(3) + def reply(): + got = b'' + try: + while not got.endswith(b'command> '): + d = s.recv(65536) + if not d: raise ConnectionError('ZEsarUX closed its remote protocol connection') + got += d + except socket.timeout: pass + return got[:-len(b'command> ')] if got.endswith(b'command> ') else got + reply() # the welcome + out = '' + for l in lines: + s.sendall(l.encode() + b'\n'); time.sleep(wait); out += reply().decode('latin-1') + s.close() + return out + + +def key(code, n=1): + for _ in range(n): + zrcp(f'send-keys-event {code} 1', wait=0.15); zrcp(f'send-keys-event {code} 0', wait=0.35) + + +def shot(name): zrcp(f'save-screen {OUT}/{name}.bmp') + + +def next_var(name, n=1): + """n bytes of the Next's game: BANKM (5B5Ch) and the bytes in one read, one instant, and counted only with + bank 0 at C000h (bank 6 may stand in there); 255 (or None for n > 1) when no read had bank 0 in""" + a = sym_from_map(os.path.join(ROOT, 'build', 'zx128', 'bomber.map'), name) + for _ in range(50): + d = bytes.fromhex(zrcp(f'read-memory 23388 {a - 23388 + n}').split()[0]) + if len(d) == a - 23388 + n and (a < 0xc000 or d[0] & 7 == 0): return d[-1] if n == 1 else d[-n:] + time.sleep(0.05) + return 255 if n == 1 else None + + +os.makedirs(OUT, exist_ok=True) +mmc = os.path.join(OUT, 'tbblue.mmc') +subprocess.run(['cp', os.path.join(ZDIR, 'tbblue.mmc'), mmc], check=True) +subprocess.run(['mcopy', '-o', '-i', mmc + '@@1048576', os.path.join(ROOT, 'build', 'zx128', 'bomber.tap'), '::/BOMBER.TAP'], check=True) +esp = subprocess.Popen([sys.executable, os.path.join(ROOT, 'tools', 'next_esp.py'), os.path.join(OUT, 'esp.pty'), + '--log', os.path.join(OUT, 'esp.log'), '--relay', '127.0.0.1:8765']) +time.sleep(1) +emu = subprocess.Popen(['./zesarux', '--noconfigfile', '--machine', 'TBBlue', '--enable-mmc', '--enable-divmmc-ports', + '--mmc-file', mmc, '--mmc-no-persistent-writes', '--tbblue-autoconfigure-sd-already-asked', + '--enable-remoteprotocol', '--remoteprotocol-port', str(PORT), '--uartbridge', os.path.join(OUT, 'esp.pty'), + '--vo', 'xwindows', '--ao', 'null', '--nosplash', '--disablefooter'], cwd=ZDIR, + env=dict(os.environ, DISPLAY=os.environ.get('NEXT_DISPLAY', ':97')), + stdout=open(os.path.join(OUT, 'zesarux.log'), 'w'), stderr=subprocess.STDOUT) +try: + time.sleep(10) + key(K_ENTER); time.sleep(30) # the video mode test; NextZXOS boots + key(K_SPACE); time.sleep(8) # past the welcome + key(K_ENTER); time.sleep(10) # the menu: Browser, given time to list the card + key(K_DOWN, 16); time.sleep(1) # down to BOMBER.TAP (the card's root: 15 entries above it) + key(K_ENTER); time.sleep(3) # the TAP loader's menu + zrcp('send-keys-ascii 150 49'); time.sleep(25) # 1: 128K mode + shot('title') + if next_var('_title_mode') != 1: sys.exit('the Next is not at the title (or its memory reads wrong)') + + M = os.path.join(ZX48, 'bomber.map'); S = lambda n: sym_from_map(M, n) + z = ZX(spectranet=True, relay=('127.0.0.1', 8765)); z.load(os.path.join(ZX48, 'bomber')) + F = S('_flush_screen'); z.set_breakpoint(F) + def frames(n): + for _ in range(n): z.run_until(F, max_seconds=30) + def frames_for(sec): + t = time.time() + while time.time() - t < sec: frames(1) + def tap(k, n=4): z.press(k); frames(n); z.release(k); frames(1) + def ntap(c, pause=0.6): zrcp(f'send-keys-ascii 200 {c}'); frames_for(pause) # the 48K keeps running meanwhile + g8 = lambda n: z.read(S(n), 1)[0]; g16 = lambda n: int.from_bytes(z.read(S(n), 2), 'little') + frames(4) + if ROLE == 'host': + ntap(97); ntap(112) # the Next: A (down to NETWORK), P (HOST) + ntap(32, 12) # SPACE: the room + shot('lobby') + nc = sym_from_map(os.path.join(ROOT, 'build', 'zx128', 'bomber.map'), '_net_code') + for _ in range(20): # the Next's room code, from its memory (retried: bank 6 may be + code = bytes.fromhex(zrcp(f'read-memory {nc} 4').split()[0][:8]).decode('latin-1') # paged in at C000h) + if len(code) == 4 and code.isalpha() and code.isupper(): break + frames_for(0.3) + z.poke(S('_menu_net'), bytes([2])); z.poke(S('_net_code'), code.encode()) + tap('SPACE'); frames(4); tap('SPACE') + for _ in range(600): + if g8('_net_slot') == 1: break + frames(1) + frames_for(3) + tap('SPACE'); ntap(32, 1) # the 48K ready, then the Next (the host last) + else: + z.poke(S('_menu_mode'), bytes([1])); z.poke(S('_menu_players'), bytes([2])) + z.poke(S('_menu_net'), bytes([1])); z.poke(S('_menu_local'), bytes([1])) + before = z.read(S('_net_code'), 4) + tap('SPACE') + for _ in range(600): + if z.read(S('_net_code'), 4) != before: break + frames(1) + code = z.read(S('_net_code'), 4).decode() + ntap(97); ntap(112); ntap(112) # the Next: A, P, P (JOIN) + ntap(32, 2) # the code screen + for ch in code: ntap(ord(ch.lower())) + typed = next_var('_net_code', 4) + if typed != code.encode(): # a key press lost in the emulator's queue: the code put right + print(f'the Next typed {typed!r}, not {code}: corrected in its memory', flush=True) + a = sym_from_map(os.path.join(ROOT, 'build', 'zx128', 'bomber.map'), '_net_code') + zrcp(f'write-memory {a} ' + ' '.join(str(c) for c in code.encode())) + ntap(32, 4) # join + for _ in range(600): + if g8('_s_members') >= 2: break + frames(1) + if g8('_s_members') < 2: + shot('join'); sys.exit(f'the Next did not join room {code} (build/next/join.bmp)') + frames_for(3) + ntap(32, 1); tap('SPACE') # the Next ready, then the 48K (the host last) + print('room', code, flush=True) + for k in range(1500): # ready taps repeated until both are in the game (a tap that + if g8('_title_mode') == 0 and (k % 25 or next_var('_title_mode') == 0): break # lands in the lobby's redraw is lost) + frames(1) + if k % 150 == 149: + if g8('_title_mode'): tap('SPACE') + if next_var('_title_mode'): ntap(32, 0.5) + print('in game: title_mode', g8('_title_mode'), 'Next', next_var('_title_mode'), 'delay', g8('_net_delay'), flush=True) + z.press('P' if ROLE == 'join' else 'O'); zrcp('send-keys-event 111 1') # both walk + for i in range(N): + frames(1) + if g8('_net_abort'): break + if i == N // 2: shot('game') + frames_for(1) # the Next's own verdict too: an abort it saw last may not have reached the 48K + next_abort = next_var('_net_abort') + ok = g8('_net_abort') == 0 and g8('_title_mode') == 0 and next_abort == 0 + print(f'end: 48K frame {g16("_frame_no")}, abort {g8("_net_abort")}, Next abort {next_abort}: {"passed" if ok else "FAILED"}', flush=True) + zrcp('send-keys-event 111 0') +finally: + emu.terminate(); esp.terminate() +sys.exit(0 if ok else 1) diff --git a/tools/zxemu.py b/tools/zxemu.py index bd4f22c..f2db643 100644 --- a/tools/zxemu.py +++ b/tools/zxemu.py @@ -19,7 +19,9 @@ With esp01=True the machine is an eLeMeNt ZX with its ESP-01 (class Esp01): the ZXi ID register, the UART and an ESP8266 AT firmware behind it, enough -for the build/zx128 driver (platform/zx/tcp_esp01*.c), which runs unchanged.""" +for the build/zx128 driver (platform/zx/tcp_esp01*.c), which runs unchanged. +With esp01='next' it is a ZX Spectrum Next in 128K mode with its ESP (class +NextEsp): the Next's registers, its UART and the same firmware.""" import os, re, select, socket, struct, time, zlib import zx from zx._device import KeyStroke @@ -56,6 +58,7 @@ class Esp01: emulated millisecond, so that the relay's timeouts mean something.""" BYTE_T = 3500000 * 10 // 115200 GUARD_T = 70000 # 20 ms + FIFO = 2048 # the receive FIFO def __init__(self, z, relay): self.z, self.relay = z, relay @@ -67,6 +70,7 @@ def __init__(self, z, relay): self.tx_free = 0 self.sleep_t = 0 self.lost = 0 + self.overflow = False self.reset() def reset(self): @@ -93,12 +97,16 @@ def _deliver(self): except OSError: self.sock = None while self.out and self.out_t <= now: - if len(self.fifo) < 2048: self.fifo.append(self.out[0]) - else: self.lost += 1 + if len(self.fifo) < self.FIFO: self.fifo.append(self.out[0]) + else: self.lost += 1; self.overflow = True del self.out[0] self.out_t += self.BYTE_T - if self.plus == 3 and now - self.last_tx >= self.GUARD_T: - self.plus = 0; self.transparent = False # +++ alone: back to commands, the connection stays + if self.plus and now - self.last_tx >= self.GUARD_T: + if self.plus == 3: self.transparent = False # +++ alone: back to commands, the connection stays + elif self.sock and not self.z.cut: # a + or ++ that ended a payload: data after all + try: self.sock.sendall(b'+' * self.plus) + except OSError: self.sock = None + self.plus = 0 if not self.fifo and not self.out and self.transparent and now - self.sleep_t > 3500: self.sleep_t = now if self.sock: select.select([self.sock], [], [], 0.002) @@ -176,6 +184,101 @@ def port_out(self, addr, v): self.fifo = bytearray() +class NextEsp(Esp01): + """The ZX Spectrum Next's ESP UART and the registers around it, from the + core's ports.txt and nextreg.txt (gitlab.com/SpectrumNext/ + ZX_Spectrum_Next_FPGA, cores/zxnext): + - nextregs through 243Bh (select) and 253Bh (value): 00h the machine ID + (0Ah), 02h bit 7 holds the ESP in reset (released: a fresh module after + its start-up text), 11h the video timing (which 28 MHz clock; timing= + chooses it), 7Fh a user register, 83h bit 4 the UART's ports. + - 133Bh read: bit 0 a byte waiting, 1 the 64-byte transmit buffer full, + 2 the receive buffer overflowed (cleared by the read), 3 it is 3/4 + full, 4 the transmit buffer empty; 143Bh write: the prescaler's bits + 6:0 (bit 7 = 0) or 13:7 (bit 7 = 1); 153Bh: bit 6 the Pi's UART + instead of the ESP's, bit 4 with bits 2:0 the prescaler's bits 16:14; + 163Bh: bits 4:3 the frame (11 = 8 bits), bit 7 empties the FIFOs. + The receive buffer holds 512 bytes; a byte written to a full + transmit buffer is lost (counted with garbled). With the Pi's UART + selected the ESP's bytes are neither seen nor sent. + The module hears the Spectrum only with the ESP's UART selected, its + ports on, 8 bits a frame and a prescaler within 2 % of 115200 Bd at the + clock of the video timing; else what is sent is lost (the module + answers nothing). The eLeMeNt's ZXi ports read FFh.""" + FIFO = 512 + CLK = (28000000, 28571429, 29464286, 30000000, 31000000, 32000000, 33000000, 27000000) + + def __init__(self, z, relay, timing=0): + self.nr_sel = 0 + self.nregs = {0x00: 0x0a, 0x02: 0x00, 0x07: 0x00, 0x11: timing, 0x7f: 0xff, 0x83: 0xff} + self.uart_sel, self.frame, self.prescaler = 0x00, 0x18, 0 + self.garbled = 0 # bytes sent while the UART was set wrong + super().__init__(z, relay) + + def baud_ok(self): + if not self.prescaler: return False + return abs(self.CLK[self.nregs[0x11] & 7] / self.prescaler - 115200) < 115200 * 0.02 + + def heard(self): + return (not self.uart_sel & 0x40 and self.nregs[0x83] & 0x10 and (self.frame & 0x18) == 0x18 + and self.baud_ok()) + + def status(self): + if self.uart_sel & 0x40: return 0x10 # the Pi's UART: nothing there, transmit empty + self._deliver() + n, now = len(self.fifo), self.z.now() + ov, self.overflow = self.overflow, False + return ((1 if n else 0) | (2 if self.tx_free - now > 63 * self.BYTE_T else 0) | (4 if ov else 0) | + (8 if n >= self.FIFO * 3 // 4 else 0) | (16 if now >= self.tx_free else 0)) + + def read(self): + if self.uart_sel & 0x40: return 0x00 # the Pi's UART: empty + return super().read() + + def write(self, b): + now = self.z.now() + if self.tx_free - now > 63 * self.BYTE_T: # the 64-byte transmit buffer full: the byte is lost + self.garbled += 1; return + if self.uart_sel & 0x40: self.tx_free = max(now, self.tx_free) + self.BYTE_T; return # to the Pi's UART + if self.heard(): return super().write(b) + self.tx_free = max(now, self.tx_free) + self.BYTE_T + self.garbled += 1 + + def port_in(self, addr): + hi = addr >> 8 + if hi == 0x13: return self.status() + if hi == 0x14: return self.read() + if hi == 0x15: return self.uart_sel & 0x47 + if hi == 0x16: return self.frame + if hi == 0x25: return self.nregs.get(self.nr_sel, 0x00) + return 0xff + + def port_out(self, addr, v): + hi = addr >> 8 + if hi == 0x13: self.write(v) + elif hi == 0x14: + if v & 0x80: self.prescaler = (self.prescaler & ~0x3f80) | (v & 0x7f) << 7 + else: self.prescaler = (self.prescaler & ~0x7f) | (v & 0x7f) + elif hi == 0x15: + self.uart_sel = v + if v & 0x10: self.prescaler = (self.prescaler & 0x3fff) | (v & 7) << 14 + elif hi == 0x16: + self.frame = v & 0x7f + if v & 0x80: # both FIFOs emptied: what had arrived by now goes with them + self._deliver(); self.fifo = bytearray(); self.overflow = False; self.tx_free = self.z.now() + elif hi == 0x24: self.nr_sel = v + elif hi == 0x25: + r = self.nr_sel + if r in (0x00, 0x01, 0x0e, 0x0f, 0x11): return # read only (11h: in config mode only) + if r == 0x02: + if v & 0x80: self.reg5 = 0 # held in reset + elif self.nregs[0x02] & 0x80: # released: a fresh module after its start-up text + self.reset(); self.reg5 = 1 + self.out_t = self.z.now() + 3500000 // 2; self.out = bytearray(b'\r\nready\r\n') + self.nregs[0x02] = v & 0x80 + else: self.nregs[r] = v + + class ZX(zx.Spectrum): IXCALL = 0x3ffd @@ -194,7 +297,8 @@ def __init__(self, spectranet=False, relay=('127.0.0.1', 8765), bank6=None, esp0 # (a Wi-Fi lost under the modem): nothing in, nothing out self.socks = {} self.sn_calls = 0 - self.esp = Esp01(self, relay) if esp01 else None + self.esp = (NextEsp(self, relay, int(os.environ.get('NEXT_TIMING', 0))) if esp01 == 'next' + else Esp01(self, relay) if esp01 else None) self.set_on_input_callback(self._input) if esp01: self.set_on_output_callback(self._output) self.reset_and_wait() # ROM start-up: system variables, IM 1, IY