diff --git a/changelog/2026-11-19-digitone-ii-link.md b/changelog/2026-11-19-digitone-ii-link.md new file mode 100644 index 0000000000..dc90e51232 --- /dev/null +++ b/changelog/2026-11-19-digitone-ii-link.md @@ -0,0 +1 @@ +Digitone II: development bases now carry a read-only USB link for diagnostics, in the Analog Rytm MKII link's format: the unit's link status, memory reads and a picture of its screen. Release bases do not have it. diff --git a/changelog/2026-11-25-digitone-ii-link-bounded.md b/changelog/2026-11-25-digitone-ii-link-bounded.md new file mode 100644 index 0000000000..3d2ecc9cf7 --- /dev/null +++ b/changelog/2026-11-25-digitone-ii-link-bounded.md @@ -0,0 +1 @@ +Digitone II: the development link no longer reads memory at an address the computer names. It answers only with its own counters and the screen, sent as one frame even while the display changes. Release bases do not have the link. diff --git a/docs/MACHINE_RECIPE.md b/docs/MACHINE_RECIPE.md index 87ec33b9ac..4a86169faf 100644 --- a/docs/MACHINE_RECIPE.md +++ b/docs/MACHINE_RECIPE.md @@ -42,7 +42,7 @@ Read this before you plan a core, a base or the first modules for any machine ot | Analog Four MKII | research | elekloader core-a4 0.2 | not started | none known | as the Rytm: same platform | | Digitakt II | preview | Modwerk base from core-dt2 1.1's source (elekloader#221 at `0df8409`), with sequencer and project hooks | started: the site builds the [pinned base](../sdk/machines/digitakt-ii/elekloader/README.md) `8650bb8a` (`e88273ed`, which passed on one unit on 17 November 2026, with kit data ended before the project archive); downloads off. The USB link is not started (SysEx over USB MIDI, from the Rytm's) | digikit (emulator only) | the exact build on a second unit, then the USB link ([goal](../sdk/machines/digitakt-ii/GOAL.md)) | | Syntakt | research | Modwerk boot probe | not started | digiemu's port (open upstream pull request; emulator only) | the core stage, planned as the base | -| Digitone II | preview | core-dn2 0.3, with the Digitakt II 1.1 additions, in toonst's elekloader fork: boots and its six UI events run on units (18 November 2026) | started: Modwerk's builder carries the device (`machine:base` and the site's kit), and `machine:base` builds a base from the Digitakt II's source at core-dn2 0.3's addresses (19 November 2026), which ran on a unit and is bound (`base-binding.json`, the site's catalog); the page builds it for beta users, and Modwerk's packer keeps images under the unit's 2 MiB update limit | digikit (the author's; emulator only) | the Modwerk base, reusing the Digitakt II's with its own recipe as the Rytm MKI does, then flashing from the site and the link ([goal](../sdk/machines/digitone-ii/GOAL.md)) | +| Digitone II | preview | core-dn2 0.3, with the Digitakt II 1.1 additions, in toonst's elekloader fork: boots and its six UI events run on units (18 November 2026) | started: Modwerk's builder carries the device (`machine:base` and the site's kit), and `machine:base` builds a base from the Digitakt II's source at core-dn2 0.3's addresses (19 November 2026), which ran on a unit and is bound (`base-binding.json`, the site's catalog); the page builds it for beta users, and Modwerk's packer keeps images under the unit's 2 MiB update limit. The development link started over USB MIDI SysEx in development bases: the link's counters and the screen, no address a client names ([LINK.md](../sdk/machines/digitone-ii/LINK.md)) | digikit (the author's; emulator only) | the Modwerk base, reusing the Digitakt II's with its own recipe as the Rytm MKI does, then flashing from the site and the link ([goal](../sdk/machines/digitone-ii/GOAL.md)) | | Model:Cycles | research | Modwerk base from core-mc 0.3's source (Elekloader v0.11.0) plus a key-LED hook ([events.json](../sdk/machines/model-cycles/events.json)) | started: built by `npm run machine:base`; runs on a unit with a test module on the LED hook; the USB link started over USB MIDI SysEx: in every base the identity, the audio load, a diagnostics log in the Octatrack's layout and the Octatrack's runtime loader (modules on trial, kept, undone, refused while playing), on a unit flashed with the release base (24 November 2026); development bases add memory reads, keys, encoder turns and a RAM boot ([LINK.md](../sdk/machines/model-cycles/LINK.md)); the site builds the pinned base from the owner's OS file as a local preview, downloads off; the MCP's `device_status` reads its identity, `device_load` the audio load, `device_log` the log, and its trial tools load modules (24 November 2026) | digiemu (emulator only) | the first module, Control All Config ([guide](../sdk/machines/model-cycles/README.md)) | | Analog Keys | research | none | not started | none known | the machine steps first ([add a machine](ADD_A_MACHINE.md)) | | Zoom MultiStomp | preview (MS-70CDR); research (MS-50G, MS-60B, G1on) | MIDISTOMP on the MS-70CDR; the MS-50G and MS-60B need builds from their own OS | browser base build and flash over Web MIDI. Shared MCP status and load tools use the same link. Load needs the MIDISTOMP SysEx load reply. | Ziddle (emulator only) | Prove a RAM-only effect trial and rollback on the MS-70CDR before wiring review, trial, Keep and Undo. See the [plan](ZOOM_MULTISTOMP.md#plan). | diff --git a/docs/verification/2026-11-19-digitone-ii-link-on-a-unit.md b/docs/verification/2026-11-19-digitone-ii-link-on-a-unit.md new file mode 100644 index 0000000000..986b53356f --- /dev/null +++ b/docs/verification/2026-11-19-digitone-ii-link-on-a-unit.md @@ -0,0 +1,14 @@ +# Digitone II: the development link answers over USB, 19 November 2026 + +Stage one of the Digitone II development link (`sdk/machines/digitone-ii/LINK.md`, #1763) on OS 1.12, flashed with Elektron Transfer. Contributor's Digitone II (@prodbysmolec), on the same unit as the [base record](2026-11-19-digitone-ii-base-on-a-unit.md). + +- **Stock file:** `Digitone_II_OS1.12.syx`, `7e5b8a73…2ceb35`. Elektron Transfer 1.10.3 on macOS, closed before the host ran. +- **Build:** `npm run machine:base -- digitone-ii --dev`, development package `7b14964a…` (.run 4,712, .bss 3,572 bytes; 15 sites), linked with `hello-marker-dn2` 1.0 by Elekloader 0.11.0's patcher and verified (sections 2, 4, 5, 7 and 8 byte for byte, the in-place depack, under the unit's update limit): `.syx` `8e87168ee2dd6d8b150d6ca364cb8e3a8ef9634ce66dd42320651636386aeecd`. +- **Host:** `sdk/machines/digitone-ii/tools/dn2_link.py` with mido 1.3.3 and python-rtmidi 1.5.8 on macOS; the unit's USB port shows as "Elektron Digitone II". +- **Boot:** it flashed and booted; the marker square showed top right (`hello-marker-dn2`). +- **`ident`:** answered every request: `link 1, received 1, dropped 0, ticks 1496`, then `received 2 … ticks 1502`, and `received 6, dropped 0, ticks 1681` after the requests below. The link counts each request, drops none, and its tick count rises with stock's UI task. +- **`mem 0x47f00000 64`:** returned 64 bytes. They are the start of the development package's `.run` section as it was built, with the boot loader's relocation filled in (the first absolute address reads `0x47f012b4`, inside the package's own area). The bytes are not recorded here, because `.run` carries stock bytes the package copies. +- **Refusals:** `mem 0x0 16` (outside DDR and SRAM) and `mem 0x47f00000 200` (over 128 bytes) each came back with status 4, out of range. +- **Second build, the same day:** the link waits a tick while stock's USB MIDI receive parser is mid-SysEx (its status byte at 0x445090ac, LINK.md). Development package `3ef5b3f0f7fb53cf44e64330256fb42c4b8395e982e949f11f53dcaf4c02ce96` (.run 4,724, .bss 3,572 bytes; 15 sites), linked with `hello-marker-dn2` 1.0 by Elekloader 0.11.0's patcher and verified as above: `.syx` `f580bf70d28f3e212e36ed2e7ea62bd0275817407df8eae74fc04e20b3cb88e1`. It flashed and booted with the marker, and sounds played normally; `ident` answered (`received 1, dropped 0, ticks 215`, then `received 5 … ticks 246`), `mem 0x47f00000 16` returned the start of `.run`, `mem 0x445090ac 4` read the status byte as 0x00 between messages, and `mem 0x0 4` was refused, out of range. +- **Screen:** `dn2_link.py screen` on the second build read the frame pointer (0x44623fc8) and the frame through `mem` and showed the unit's screen as it was: pattern A01, UNTITLED, tempo 120.0, the SYN 4 page with its envelope and filter, the marker top right. +- **Not tested:** a link request while other SysEx arrives on USB (a host cannot interleave two SysEx messages on one USB cable, so the wait was not seen to hold an answer back), a request over MIDI DIN (the link must ignore it), long sessions with the development base. diff --git a/docs/verification/2026-12-05-digitone-ii-dev-stack-on-a-unit.md b/docs/verification/2026-12-05-digitone-ii-dev-stack-on-a-unit.md new file mode 100644 index 0000000000..aa5186f618 --- /dev/null +++ b/docs/verification/2026-12-05-digitone-ii-dev-stack-on-a-unit.md @@ -0,0 +1,86 @@ +# Digitone II: the development link stack on a unit, 5 December 2026 + +The development link stack (#1763 link, #1817 keys, #1820 diagnostics, #1821 RAM boot, #1842 loader) on the contributor's Digitone II (@prodbysmolec), OS 1.12, in two sittings on one image: the first without a person at the unit, the second with the developer at the unit for the cases that need a person's YES or NO. It ran on the stack's top head after `base/digitone-ii-next` was merged up through it. This is the session the owner's checklist on #1763 asks for. The earlier records (19 and 20 November) come from builds that still read memory through `mem`. They are kept for their history, but do not qualify this package. + +- **Built from:** #1842 at `5a9aa0137`, with `npm run machine:base -- digitone-ii --dev`. The heads then: #1763 `5b4c19ea3`, #1817 `b955b0470`, #1820 `e85be0631`, #1821 `962aed3a4`, #1842 `5a9aa0137`. +- **Package:** the development package `a158dc917c68d70c61d895085da9f6451dafa6c54ee198a27a50dd061a641583` (HELLO base `44f3088784d0a8e7…`, `.run` and `.bss` as built, 18 sites). +- **Image:** linked by Elekloader 0.11.0's patcher to `.syx` `436b2afe93075f937142da2face861bc140b7611729f3e868c1f95afbdabfb1b` (main OS CRC `f0aebc69`) and flashed over USB; the developer pressed YES. +- **The last head builds the same package.** #1842's head `4ef2c9abd` rebuilt `a158dc917c68d70c61d895085da9f6451dafa6c54ee198a27a50dd061a641583` on 5 December. Since `5a9aa0137` only `LINK.md`, the host tool `dn2_link.py` and its test `test_dn2_link.py` changed, then this record and `GOAL.md`: nothing that goes into the base. +- **Test module:** `examples/corner_dot.c`, built with `sdk/runtime/loader/build.py` (module `aee18e5a`, package `ace8db2d…`). +- **Who did what:** the agent sent every request from the host. The developer flashed the image (YES), power-cycled the unit and pressed the keys at UPGRADE OS NOW?. Where a row needs a person at the unit, it says so. + +## The fixed steps + +The steps of [the test procedure](../TEST_PROCEDURE.md), in its order. The runner has no Digitone II steps yet: `npm run test:procedure -- --base digitone-ii --plan` marks steps 2 to 10 not run, with "Digitone II has no USB link the procedure drives yet". So the steps a tool exists for ran by hand. + +| # | Step | Run | What | +| --- | --- | --- | --- | +| 1 | Software checks | run | `npm run check -- --base upstream/base/digitone-ii-next` on each head of the stack, with `sdk:check`, before each push | +| 2 | Beside every other module | not run | `modules:compat` compares the Octatrack's modules only. The base ran alone, with the loader's test module beside it in step 7's place | +| 3 | Name the build | run, by hand | the package and `.syx` above, built from `5a9aa0137`. The runner would want `--package` or `--stock` with `--elemod` | +| 4 | DSP cost model | not run | the cycle scan models the Octatrack's DSP only | +| 5 | Emulator rehearsal | not run | there is no Digitone II emulator rehearsal | +| 6 | Read the unit | run, by hand | `dn2_link.py ident` at the start: `boot 0` (the flashed OS), live set `44f30887…`, no module live | +| 7 | Scripted unit pass | not run as a step | there are no Digitone II cases for the runner. Each PR's own cases ran by hand instead (below) | +| 8 | Soak | not run | there is no soak for the Digitone II. The nearest is the host that sends without reading, 60 s with the pattern playing (below) | +| 9 | Cost on the unit | not run | there is no price tool for the Digitone II. The only load figures are the UI ticks and frame counter read during the floods (below) | +| 10 | Put back | run, by hand | after the RAM boots, a power cycle brought the flashed base back (`boot 0`, its own HELLO); the loader's removal left no module live; the person's YES at the last prompt flashed the same image again, and the base came back armed | +| 11 | Agent by hand | run | screenshots over the link (`screen --png`) of each prompt and page the rows name. Audio: the unit's USB audio during a control flood and during a RAM boot, later the same day (below) | +| 12 | Submitter's own stage | run | the developer flashed, power-cycled, pressed YES and NO at the prompts and saw the unit freeze during the large flood. Listening: chords on this package with Voice Spread sounded good to the developer (below) | + +## Run without a person at the unit + +| PR | Check | Result | +| --- | --- | --- | +| #1763 | `screen 128` right after boot, before any part 0 | status 4 | +| #1763 | `ident`; `screen --png` | answers; a whole frame, eight parts of one copy | +| #1763 | the old `mem` (0x21) | status 2 | +| #1763 | `screen 64` (not a multiple of 128) | status 4 | +| #1817 | `hold TRK`, then `disarm` | `posted` +1 for the press, +1 for the release, then nothing for 3 s; a key afterwards: status 1, not armed | +| #1820 | `diag --save`, then `parseDeviceLog` | 7,304 bytes, version 2, START read. **The first image paged only 6,148 bytes, and `parseDeviceLog` read nothing.** Fixed in `e85be0631` (LOG pages the whole version 2 image, the records zero). That is why the session runs on this, the second image | +| #1820 | `log` 7304, 7424 (past the end) and 64 (between parts); the last part, 7296 | status 4, 4, 4; 0 | +| #1820 | `freeze 7` with nobody at the panel | a FREEZE incident (10,550 frames). The frame counter went on, 59,297 → 70,152, while the UI ticks moved by 8 | +| #1821 | `ramboot` of the image, four times in a row (three of them from a RAM-booted base) | each `boot 1` with CRC `f0aebc69`, about 30 s each with the upload. `bootdiag`: MWBT and its check word, the marks `4d57001d` and stage 6 (the container copied). On two runs the host tool ended with rtmidi's `InvalidPortError` while it waited after the reset; the RAM boot itself had gone through each time. Fixed in the tool, host only (`19eab8081`) | +| #1821 | a RAM boot whose boot gate fails: the unpacked CRC one bit off | status 0, then `boot 8` (the unpacked image was wrong, so a reset to the flashed OS): the flashed base came back with its own HELLO, and nothing was written | +| #1821 | at UPGRADE OS NOW?, `ramboot` with a container CRC that does not match the staged upload | status 7, and the prompt still waits (screenshot). A correct `ramboot` then answered it from RAM (`boot 1`, about 22 s), with nothing flashed | +| #1821 | the CRC over the full 1.9 MB container | the status 7 reply came after 0.22 s, the OK after 0.39 s. While UPGRADE OS NOW? waits, stock's frame counter already stands still. The sound, measured later on 5 December on a flashed development base that carries this stack and two follow-ups (the reboot, #2685, and the store fix, #2684; its RAM boot code is this stack's): with the pattern playing, the unit's USB audio (inputs 0/1, the main out) recorded on the host had trigs until 3.46 s, and `ramboot` had started the upload, through stock's OS upload path, at 2.9 s. Silence from then until about 30 s, when the unit reset into the RAM-booted OS; the CRC at UPGRADE OS NOW? comes at the end of that silence. Sound again after the RAM boot. So stock stops the sound as soon as an OS upload begins, well before the prompt: nothing plays during the CRC, however long it runs, and the link adds no silence of its own beyond stock's upload | +| #1842 | a trial, rolled back after 5 s | one module live during it, none after | +| #1842 | a trial kept, with `--base` naming the build's `.identity` | kept; `corner_dot`'s 3x3 dot in the screen's corner, which was empty before | +| #1842 | the kept module's removal, kept | none live | +| #1842 | `--base` with another build's identity | refused by the host before anything is sent | +| #1842 | PLAY from the link, then a trial | refused: "unsafe (the unit plays: stop it)" | +| all | a host that sends without reading: 60 s of `ident`, `screen` and `diag` with no input port open, while the pattern played | 67,992 requests, about 1,130 a second. `ident` before: received 132, dropped 0, ticks 2124. After: received 68,126, dropped 60,784, ticks 3947, so 4 answered a tick, and the UI tick kept about 29.4 a second. The frame counter went on, and no incident was logged. `ident` and `screen` answered normally afterwards. **Limit:** macOS's USB MIDI driver keeps draining the endpoint, so this shows the link's load and not USB backpressure, which a Mac host cannot produce | + +## With the developer at the unit + +The same image, after a power cycle (link armed). Each row's upload is the same `.syx` (`436b2afe…`), so a YES flashes the image already on the unit. + +| PR | Check | Result | +| --- | --- | --- | +| #1817 | at UPGRADE OS NOW?, `press YES` and `turn A 3` from the link | status 6 both; `refused` 2, `posted` 0; the prompt still waits (screenshot) | +| #1817 | the person's NO at the prompt | stock restarts (counters back to zero, normal screen, nothing flashed). It did so each time, with and without the link holding a key, so this is stock's answer to NO | +| #1817 | the link holds TRK, the upload, then the person's NO | the same restart; nothing flashed | +| #1817 | the link holds YES through the upload, then `let YES` at the prompt | status 6; `posted` stays 1, `refused` +1; the prompt still waits (screenshot) | +| #1817 | then, at the same prompt with YES still held, `release` | accepted: the YES release is queued (`posted` 2) and taken before stock (`refused` 2); the prompt still waits (screenshot). On 26 November, on a build of #1817 before `5d37e3f2c`, this release started the flash | +| #1817 | then the person's YES | flashed (the same image), the base came back armed | +| #1817 | the link holds TRK, the upload, then the person's YES | flashed, the base came back armed | +| #1817 | after the prompts, `press FUNC`, `press YES`, `hold FUNC` / `let FUNC` on normal screens | accepted, `posted` 6, `refused` 0; with FUNC held the page shows its FUNC labels (screenshot). So YES and FUNC behave normally after the held-back YES release | +| #1820 | `freeze 3` asked every 0.27 s from the moment a person pressed NO on a normal screen | status 5 up to 1.67 s after the press, accepted at 1.93 s: the window is 60 UI ticks, about 2 s, not the 3 s link.c's comment and the guide said (the guide and the tool now say 2 s; link.c's comment follows with its next code change, as it is part of the base's identity) | +| all | a host that queues 3.5 million `ident`/`screen`/`diag` requests in 30 s while the pattern plays | the Mac's MIDI driver delivered all of them (`received` 3,500,597, `dropped` 3,500,578), about 29,000 a second, and the developer saw the unit freeze until they were through: a FREEZE incident of 144,831 frames (96 s). Afterwards the developer said the pattern ran in time again. Audio: not recorded on this run; measured on the 250,000 control instead (two rows down) | +| all | control: 250,000 nine-byte SysEx the link ignores (`MWX`), then 250,000 `ident` requests, the pattern playing | FREEZE 10,069 frames (6.7 s) and 10,207 frames (6.8 s); the link answered again 7.2 s and 6.9 s after the first. So it is stock's MIDI task taking every SysEx before the UI runs, whoever the SysEx is for; the link adds nothing measurable. The first sitting's flood (about 1,130 a second) froze nothing | +| all | audio during a flood, later the same day: the unit's USB audio (inputs 0/1, the main out, 48 kHz) recorded for 22 s, the pattern playing with trigs on steps 1, 5, 9 and 13, and 250,000 nine-byte SysEx the link ignores sent 4 s in. The unit then ran a RAM-booted development base with a store fix (#2684) and Voice Spread; its link is this stack's, the same code | the link answered again 6.4 s after the first. All 37 intervals between trigs were 0.48 to 0.52 s, apart from the pattern's own 1.0 s gap every 8 trigs, the same before, during and after the flood. So the sound and the sequencer go on in time while the UI stands still | + +## Listening + +The developer listened to four Voice Spread chords on this package linked with Voice Spread (`9ce8ff19`, `.syx` `ef14a48c…`) and said "es hat sich gut angehört" (it sounded good). This stack changes no sound path. Its own sound was not judged apart from that: normal playback during the session, and the flood and RAM boot measurements above. + +## Not yet + +- **The sound during a loader trial:** not listened to or measured. +- **The 3.5 million flood's own audio:** not recorded. The measurement ran on the 250,000 control. + +## Not tested + +- The late case at UPGRADE OS NOW? (#1817): a link event stock dispatches after the link gave it up. It is covered by the host test only (`dn2_link_host.c`, a lag before and during the prompt, for a key and a turn). +- A host that stops reading at the USB level (see the first flood's limit above). +- A request over DIN, and long sessions. diff --git a/sdk/machines/digitone-ii/GOAL.md b/sdk/machines/digitone-ii/GOAL.md index 5657d1b91d..56cf3c09a4 100644 --- a/sdk/machines/digitone-ii/GOAL.md +++ b/sdk/machines/digitone-ii/GOAL.md @@ -16,7 +16,7 @@ This is the Octatrack's stack ([machine recipe](../../../docs/MACHINE_RECIPE.md) | Build path | Started: Modwerk's linker (`LINK_DEVICES`, `ELE3_DEVICES`) knows OS 1.12 and links core-dn2 0.3 and 0.4, alone and with elekloader's examples, to the same main OS as elekloader, byte for byte. It takes the core's DSP bridge and refuses mods with DSP code. The pinned Elekloader kit stays as it is (owner, 19 November 2026): Modwerk's builder carries the device ([`device.json`](elekloader/device.json)), which `npm run machine:base` registers with the kit's Python SDK and the site with the browser kit; both read stock 1.12 and rewrite it, sealed, byte for byte. What is left is the base itself | [`elemod.ts`](../../../src/engine/elektron/elemod.ts), [`machine-base.py`](../../../scripts/machine-base.py), [`carried-devices.ts`](../../../src/engine/elekloader/carried-devices.ts) | | Base | Started: the Digitakt II base's core-dt2 1.1 source at core-dn2 0.3's Digitone II addresses, with copies of three files; `npm run machine:base` builds it. It ran on a unit with its hooks, and a project kept a change across a power cycle ([19 November 2026](../../../docs/verification/2026-11-19-digitone-ii-base-on-a-unit.md)), and about five hours of playing. `base-binding.json` records that identity (`7a60d82e`), its package is in the site's catalog, and the machine's SDK profile ([`core-profile`](../../digitone-ii/core-profile/interface.json), budgets) describes it. Modwerk's packer keeps its images under the unit's 2 MiB update limit | [`elekloader/`](elekloader/README.md) | | Flashing from the site | Started: the unit refuses an upgrade over about 2 MiB decoded (`update_max` in [`device.json`](elekloader/device.json)), so `fitUpdate` packs a larger build's main OS again with Modwerk's optimal packer, under the limit, and refuses one that still does not fit. The machine page builds the base alone for beta users (a core build preview, no module yet; downloads off until the owner turns them on); the OS upgrade over USB MIDI (`os-upgrade.ts`) ran on a unit and is not on the page yet. Today the owner sends a `.syx` with Elektron Transfer | [`fit-update.ts`](../../../src/engine/elekloader/fit-update.ts); the MS-70CDR's [`ZoomBaseDialog.tsx`](../../../src/components/ZoomBaseDialog.tsx) in [`BaseDialogFrame.tsx`](../../../src/components/BaseDialogFrame.tsx) | -| USB link and diagnostics | Not started | the Rytm's [link](../analog-rytm-mkii/LINK.md), the Octatrack's [`diag.c`](../octatrack/elekloader/diag.c) and [`device-log.ts`](../../../src/engine/elekloader/device-log.ts) | +| USB link and diagnostics | Started: development bases carry a read-only link in the Rytm link's format whose requests return only what the unit chooses: the link's counters (`ident`) and the screen (`screen`), no address a client names ([LINK.md](LINK.md)). It ran on a unit, `screen` and the refusals included ([5 December 2026](../../../docs/verification/2026-12-05-digitone-ii-dev-stack-on-a-unit.md)); the 19 November [run](../../../docs/verification/2026-11-19-digitone-ii-link-on-a-unit.md) was on an earlier build that still read memory through `mem` | the Rytm's [link](../analog-rytm-mkii/LINK.md), the Octatrack's [`diag.c`](../octatrack/elekloader/diag.c) and [`device-log.ts`](../../../src/engine/elekloader/device-log.ts) | | Loading without a reflash | Not started | [porting the runtime loader](../../runtime/loader/README.md#porting-to-another-machine) | | Base updates over USB | Not started | [two-slot base](../../../docs/OCTATRACK_TWO_SLOT_BASE.md) | | MCP device tools, machine page | Not started; the page shows status only | [device tools](../../../docs/FRONTEND_MCP.md#then-test-the-connected-device), [`OctatrackHub.tsx`](../../../src/components/OctatrackHub.tsx) | diff --git a/sdk/machines/digitone-ii/LINK.md b/sdk/machines/digitone-ii/LINK.md new file mode 100644 index 0000000000..778985ef08 --- /dev/null +++ b/sdk/machines/digitone-ii/LINK.md @@ -0,0 +1,49 @@ +# Digitone II development link + +Stage one of piece 4 of the [goal](GOAL.md): read-only diagnostics over USB MIDI SysEx, in the +[Analog Rytm MKII link's](../analog-rytm-mkii/LINK.md) wire format, so one host can speak to both. It is in +development bases only (`npm run machine:base -- digitone-ii --dev`, base.json's `dev`), never in a release. + +```sh +python3 sdk/machines/digitone-ii/tools/dn2_link.py ident +python3 sdk/machines/digitone-ii/tools/dn2_link.py screen --png screen.png +``` + +| Request | cmd | What comes back | +| --- | --- | --- | +| `ident` | 0x01 | the link's own counters: link version, link messages received, dropped (ring full or too long), ticks | +| `screen OFF` | 0x20 | OFF, the copy's number, then 128 bytes of the frame on the screen from OFF (0, 128 … 896) | + +**The unit chooses what each request returns.** No request names an address, so a USB client reads the link's counters +and the screen and nothing else of the instrument's state. Every other command, the earlier `mem` (0x21) included, is +refused with status 2 and nothing but the status. + +`screen 0` copies the frame on the screen and sends its first part; `screen 128` to `screen 896` send the rest of that +copy, each with the copy's number, so the eight parts are one frame even if stock draws in between, and the host checks +the number. A part before any `screen 0`, an offset past the frame or between parts, or a frame pointer that does not +lie wholly in DDR is refused with status 4. Stock keeps two frame pointers side by side at 0x402a10c8 and sends the +first to the display, then swaps them (0x40131fd2), so the frame on the screen is the second; 128x64 pixels, 1 bit each, +in the Analog Rytm MKII's layout. + +Status 0 ok, 2 bad request, 4 out of range. USB only: a link message from DIN is never acted on. + +`sdk/tests/dn2_link_host.c` compiles `link.c` for the host and checks both requests and every refusal +(`test_dn2_link.py` runs it). This version ran on a unit over USB: `ident`, a whole frame through `screen`, and the +refusals, `mem` included ([5 December 2026](../../../docs/verification/2026-12-05-digitone-ii-dev-stack-on-a-unit.md)). +The first version's `mem` answered on 19 November +([record](../../../docs/verification/2026-11-19-digitone-ii-link-on-a-unit.md)). + +## Where it runs (OS 1.12) + +- **Receive.** `link.s` observes stock's SysEx router at 0x4012197a (MIDI task), the site core-dn2 0.3's `ev_sysex` + uses: the message in a1, its length in d1, the source in d2 (2 or 4 USB). The link copies its own messages + (`F0 7D 'MWL'`) into a ring; every register comes back as it was and stock routes every message as before. +- **Work.** `ev_tick` (UI task) answers up to four a tick through stock's `sysex_send` (0x401236d2) on USB. +- **Waits for stock.** A tick answers nothing while stock is mid-SysEx on USB: the status byte of stock's USB MIDI + receive parser (0x4011f3c0, the function the USB driver is given) at 0x445090ac reads 0xF0 then. The Rytm's is a word. +- **A host that floods.** Stock's MIDI task takes every SysEx before the UI task runs again, so SysEx arriving at full + USB speed stands the UI still for as long as it comes in, whoever it is for. On a unit (5 December 2026), 250,000 + nine-byte messages, about 29,000 a second, stood it still 6.7 s when the link ignored them and 6.8 s when they were + link requests. The link drops what its ring cannot hold and answers four a tick; `dn2_link.py` waits for every + answer, so it never floods. +- **Not yet.** The Rytm link's keys, encoders, remote YES and RAM boot. diff --git a/sdk/machines/digitone-ii/README.md b/sdk/machines/digitone-ii/README.md index 9ef4e3b90c..2b4c8416a7 100644 --- a/sdk/machines/digitone-ii/README.md +++ b/sdk/machines/digitone-ii/README.md @@ -6,7 +6,7 @@ What a module developer needs on the Digitone II: the base's hooks, what the uni ## Modwerk stack -The Digitone II follows the Octatrack's stack ([recipe](../../../docs/MACHINE_RECIPE.md)). Where it stands: the base, the Digitakt II base's core-dt2 1.1 source at the Digitone II's addresses ([`elekloader/`](elekloader/README.md)), runs on a unit and is the cumulative draft #1767; the USB link and the runtime loader are in review; flashing from the site, base updates over USB and the machine page are not built ([goal](GOAL.md)). Its contract is [`sdk/digitone-ii/core-profile/interface.json`](../../digitone-ii/core-profile/interface.json): a module uses those events, tables and exports and nothing else. The development link (SysEx over USB MIDI: memory reads, key presses, screenshots, RAM boots) is in review (#1763, #1842); the reads below were made with it. +The Digitone II follows the Octatrack's stack ([recipe](../../../docs/MACHINE_RECIPE.md)). Where it stands: the base, the Digitakt II base's core-dt2 1.1 source at the Digitone II's addresses ([`elekloader/`](elekloader/README.md)), runs on a unit and is the cumulative draft #1767; the USB link and the runtime loader are in review; flashing from the site, base updates over USB and the machine page are not built ([goal](GOAL.md)). Its contract is [`sdk/digitone-ii/core-profile/interface.json`](../../digitone-ii/core-profile/interface.json): a module uses those events, tables and exports and nothing else. The development link (SysEx over USB MIDI: the link's counters, screenshots, key presses, RAM boots) is in review (#1763, #1842). It reads no address a client names; the addresses below were read with research builds of it that still could. ## Core hooks diff --git a/sdk/machines/digitone-ii/elekloader/README.md b/sdk/machines/digitone-ii/elekloader/README.md index 235ced38c7..9ea3b7a28f 100644 --- a/sdk/machines/digitone-ii/elekloader/README.md +++ b/sdk/machines/digitone-ii/elekloader/README.md @@ -24,6 +24,9 @@ One variant, `plain`: none of the Digitakt II base's sequencer and project addit are not found yet. No DSP bridge either: the base links mods for the ColdFire only, and Modwerk's linker refuses a mod that brings DSP code. +A development base (`--dev`) also carries the read-only development link ([LINK.md](../LINK.md)): `base/link.c` and +`link.s`, at stock's SysEx router. + ## Build it ```sh diff --git a/sdk/machines/digitone-ii/elekloader/base.json b/sdk/machines/digitone-ii/elekloader/base.json index 92b5782f64..f88a80a7c2 100644 --- a/sdk/machines/digitone-ii/elekloader/base.json +++ b/sdk/machines/digitone-ii/elekloader/base.json @@ -170,5 +170,36 @@ "requires", "conflicts" ] + }, + "dev": { + "about": "The development link (base/link.c, link.s), stage one: read-only diagnostics over USB MIDI SysEx in the Analog Rytm MKII link's wire format: ident (link version, messages received and dropped, ticks) and screen (the frame on the screen in eight parts of 128 bytes, copied when the first is asked for). The device chooses what each request returns: no request names an address. Its receive site observes stock's SysEx router at 0x4012197a, where core-dn2 0.3's ev_sysex sits; replies go through stock's sysex_send on USB from ev_tick. Development bases only.", + "sources": [ + "../base/link.c", + "../base/link.s" + ], + "sites": [ + { + "addr": "0x4012197a", + "len": 6, + "stockSha256": "d8acd0e6e84b3d17d530cf3e5621bc1d0a1e5062f8c0a62a79113c0d9548fc33", + "op": "jsr", + "target": "mw_link_router" + } + ], + "cflags": [ + "-DSYSEX_SEND_AT=0x401236d2", + "-DUSB_SYSEX_STATE_AT=0x445090ac", + "-DFRAME_POINTERS_AT=0x402a10c8" + ], + "defsym": { + "SYSEX_TABLE": "0x40207f9e" + }, + "subscribe": [ + { + "event": "ev_tick", + "fn": "mw_link_tick", + "order": 240 + } + ] } } diff --git a/sdk/machines/digitone-ii/elekloader/base/link.c b/sdk/machines/digitone-ii/elekloader/base/link.c new file mode 100644 index 0000000000..b4502d21b7 --- /dev/null +++ b/sdk/machines/digitone-ii/elekloader/base/link.c @@ -0,0 +1,188 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// The Digitone II's development link, stage one: read-only diagnostics over USB MIDI SysEx, in the Analog Rytm MKII +// link's wire format (sdk/machines/analog-rytm-mkii/LINK.md), so one host speaks to both. Development bases only. +// Requests and replies are F0 7D 'M' 'W' 'L' version seq cmd ... F7; a reply's cmd has 0x40 set, then a status. +// Numbers are u32 as five 7-bit bytes, least significant first; byte blocks are 7-bit packed, the first byte's top +// bit in bit 6 of the group's leading byte. +// ident 0x01 -> link version, messages received, messages dropped, ticks (the link's own counters) +// screen 0x20 OFF -> 128 bytes of the frame on the screen from OFF (0, 128 ... 896), with the frame's number +// The device chooses what each request returns: there is no request for an address the host names, so a client +// reads the link's counters and the screen and nothing else of the unit. +// Receive (link.s): stock's SysEx router, MIDI task; the link's own messages from USB go into a ring, the router goes +// on as stock. Work: ev_tick (UI task) takes the ring and replies through stock's sysex_send on USB. +#include +#define COLD __attribute__((cold, noinline)) + +#define LINK_VERSION 1 +#define SYSEX_SEND ((int (*)(const uint8_t *, int, const uint8_t *, int))SYSEX_SEND_AT) // stock, OS 1.12 +// The status byte of stock's USB MIDI receive parser (OS 1.12, 0x4011f3c0, which the USB driver is given): 0xF0 +// while a SysEx message is arriving on USB. One byte here; the Rytm's is a word. +#define USB_SYSEX_STATE (*(volatile uint8_t *)USB_SYSEX_STATE_AT) + +#define USB 2 +#define AUTO_USB 4 +#define ST_OK 0 +#define ST_BAD 2 +#define ST_RANGE 4 +#define CMD_IDENT 0x01 +#define CMD_SCREEN 0x20 +#define HEADER 8 // F0 7D M W L ver seq cmd +#define RING 8 // requests waiting for the UI task +#define CMD_BYTES 32 // a request's bytes, F0..F7 (screen, the longest, is 14) +#define PER_TICK 4 // requests answered in one tick +#define FRAME_BYTES 1024 // 128x64 pixels, 1 bit each +#define SCREEN_PART 128 // a screen reply's bytes +// Stock keeps two frame pointers side by side (OS 1.12, FRAME_POINTERS_AT 0x402a10c8): it sends the one it drew to +// the display, then swaps them (0x40131fd2), so the frame on the screen is the second. +#define FRAME_ON_SCREEN (((uint8_t *const volatile *)FRAME_POINTERS_AT)[1]) +#ifndef DDR_START // a host test names its own +#define DDR_START 0x40000000u +#define DDR_END 0x48000000u +#endif + +static uint8_t ring[RING][CMD_BYTES]; +static uint8_t ring_len[RING]; +static volatile uint32_t ring_head, ring_tail, ring_drops, rx_count; +static uint32_t ticks; + +// From link.s, in the MIDI task, for every SysEx stock's router gets. +void mw_link_rx(const uint8_t *msg, uint32_t len, uint32_t source) +{ + uint32_t h; + uint32_t i; + if (len < HEADER + 1 || msg[0] != 0xF0 || msg[1] != 0x7D || msg[2] != 'M' || msg[3] != 'W' || msg[4] != 'L') + return; + if (source != USB && source != AUTO_USB) + return; // ours, but not from USB: never acted on + rx_count++; + h = ring_head; + if (h - ring_tail >= RING || len > CMD_BYTES) { + ring_drops++; + return; + } + for (i = 0; i < len; i++) + ring[h % RING][i] = msg[i]; + ring_len[h % RING] = (uint8_t)len; + __asm__ volatile("" ::: "memory"); // the bytes before the index, also for the compiler + ring_head = h + 1; // published last: the UI task reads it after the bytes +} + +static uint8_t reply[HEADER + 1 + 5 + 5 + (SCREEN_PART / 7 + 1) * 8 + 1]; +// The frame as it was when OFF 0 was asked for: the later parts come from this copy, so the eight parts are one frame. +static uint8_t frame[FRAME_BYTES]; +static uint32_t frame_number; // 0 until the first copy + +static uint8_t *put32(uint8_t *p, uint32_t v) +{ + int i; + for (i = 0; i < 5; i++, v >>= 7) + *p++ = v & 0x7f; + return p; +} + +static uint32_t get32(const uint8_t *p) +{ + return p[0] | (uint32_t)p[1] << 7 | (uint32_t)p[2] << 14 | (uint32_t)p[3] << 21 | (uint32_t)(p[4] & 0x0f) << 28; +} + +static uint8_t *pack(uint8_t *p, const volatile uint8_t *src, int n) +{ + int i, k; + for (i = 0; i < n; i += 7) { + uint8_t *top = p++; + *top = 0; + for (k = 0; k < 7 && i + k < n; k++) { + uint8_t b = src[i + k]; + if (b & 0x80) + *top |= 0x40 >> k; + *p++ = b & 0x7f; + } + } + return p; +} + +static uint8_t *begin(int seq, int cmd, int status) +{ + uint8_t *p = reply; + *p++ = 0xF0; + *p++ = 0x7D; + *p++ = 'M'; + *p++ = 'W'; + *p++ = 'L'; + *p++ = LINK_VERSION; + *p++ = (uint8_t)seq; + *p++ = (uint8_t)(cmd | 0x40); + *p++ = (uint8_t)status; + return p; +} + +static void send(uint8_t *end) +{ + *end++ = 0xF7; + SYSEX_SEND(reply, end - reply, 0, USB); +} + +// OFF 0 copies the frame on the screen, if stock's pointer to it lies wholly in DDR; 0 when it does not. +static int take_frame(void) +{ + const uint8_t *fb = FRAME_ON_SCREEN; + int i; + if ((uintptr_t)fb < DDR_START || (uintptr_t)fb > DDR_END - FRAME_BYTES) + return 0; + for (i = 0; i < FRAME_BYTES; i++) + frame[i] = fb[i]; + frame_number++; + return 1; +} + +static void COLD act(const uint8_t *m, int len) +{ + int seq = m[6], cmd = m[7], n = len - HEADER - 1; + uint8_t *p; + if (m[5] != LINK_VERSION || m[len - 1] != 0xF7) { + send(begin(seq, cmd, ST_BAD)); + return; + } + switch (cmd) { + case CMD_IDENT: + p = begin(seq, cmd, ST_OK); + p = put32(p, LINK_VERSION); + p = put32(p, rx_count); + p = put32(p, ring_drops); + p = put32(p, ticks); + send(p); + return; + case CMD_SCREEN: + if (n < 5) { + send(begin(seq, cmd, ST_BAD)); + return; + } else { + uint32_t off = get32(m + HEADER); + if (off >= FRAME_BYTES || off % SCREEN_PART || (off == 0 ? !take_frame() : !frame_number)) { + send(begin(seq, cmd, ST_RANGE)); + return; + } + p = begin(seq, cmd, ST_OK); + p = put32(p, off); + p = put32(p, frame_number); + p = pack(p, frame + off, SCREEN_PART); + send(p); + } + return; + default: // anything else, the old mem (0x21) included + send(begin(seq, cmd, ST_BAD)); + } +} + +void mw_link_tick(void) +{ + int done; + ticks++; + for (done = 0; done < PER_TICK && ring_tail != ring_head; done++) { + uint32_t t = ring_tail; + if (USB_SYSEX_STATE == 0xF0) + break; // stock is mid-SysEx on USB: next tick + act(ring[t % RING], ring_len[t % RING]); + ring_tail = t + 1; + } +} diff --git a/sdk/machines/digitone-ii/elekloader/base/link.s b/sdk/machines/digitone-ii/elekloader/base/link.s new file mode 100644 index 0000000000..814f607d9b --- /dev/null +++ b/sdk/machines/digitone-ii/elekloader/base/link.s @@ -0,0 +1,22 @@ +| SPDX-License-Identifier: GPL-3.0-or-later +| Development bases only (base.json's dev, machine:base --dev): the Digitone II link's receive site (link.c). + + .section .run, "ax" + +| ---- stock's SysEx router, OS 1.12 0x4012197a (MIDI task) ------------------------- +| The site is the router's lea SYSEX_TABLE,a3 (6 bytes), with the message in a1, its length in d1 and the source in +| d2 (2 or 4 USB, 8 or 16 DIN), as core-dn2 0.3's ev_sysex finds them. mw_link_rx copies the link's own messages into +| its ring; every register comes back as it was and stock routes the message as before, so the site only observes. + .globl mw_link_router +mw_link_router: + lea -16(%sp), %sp + movem.l %d0-%d1/%a0-%a1, (%sp) + move.l %d2, -(%sp) | source + move.l %d1, -(%sp) | length + move.l %a1, -(%sp) | message + jsr mw_link_rx + lea 12(%sp), %sp + movem.l (%sp), %d0-%d1/%a0-%a1 + lea 16(%sp), %sp + lea SYSEX_TABLE, %a3 | the instruction the site replaced + rts diff --git a/sdk/machines/digitone-ii/machine.json b/sdk/machines/digitone-ii/machine.json index 54715766e1..e8e732a4b6 100644 --- a/sdk/machines/digitone-ii/machine.json +++ b/sdk/machines/digitone-ii/machine.json @@ -28,7 +28,8 @@ "mods": "done" }, "stack": { - "base": "started" + "base": "started", + "link": "started" }, "research": [ { diff --git a/sdk/machines/digitone-ii/tools/dn2_link.py b/sdk/machines/digitone-ii/tools/dn2_link.py new file mode 100644 index 0000000000..6b28051c44 --- /dev/null +++ b/sdk/machines/digitone-ii/tools/dn2_link.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""The Digitone II development link's host, stage one: read-only (sdk/machines/digitone-ii/elekloader/base/link.c). + + dn2_link.py ident # link version, messages received and dropped, ticks + dn2_link.py screen [--png F] # the frame on the screen, as text (and a PNG) + +The unit chooses what each request returns: there is no request for an address. + +Needs a development base on the unit (npm run machine:base -- digitone-ii --dev) and mido with a MIDI backend. +The wire format is the Analog Rytm MKII link's (sdk/machines/analog-rytm-mkii/LINK.md).""" +import argparse +import binascii +import struct +import sys +import time +import zlib + +HEADER = bytes([0xF0, 0x7D, ord('M'), ord('W'), ord('L'), 1]) +CMD = {'ident': 0x01, 'screen': 0x20} +STATUS = {0: 'ok', 2: 'bad request', 4: 'out of range'} + + +def u32(v): + return bytes((v >> (7 * i)) & 0x7f for i in range(5)) + + +def get32(b, at): + return b[at] | b[at + 1] << 7 | b[at + 2] << 14 | b[at + 3] << 21 | (b[at + 4] & 0x0f) << 28 + + +def unpack7(b): + out = bytearray() + for i in range(0, len(b), 8): + top = b[i] + for k, c in enumerate(b[i + 1:i + 8]): + out.append(c | (0x80 if top & (0x40 >> k) else 0)) + return bytes(out) + + +# A frame is 128x64 pixels, 1 bit each, 1024 bytes; the unit sends it in eight parts. It copies the frame when part 0 +# is asked for and sends every part from that copy, each with the copy's number. +FRAME_BYTES = 1024 +SCREEN_PART = 128 + + +def frame_rows(fb): + """The 1024-byte frame as 64 rows of 128 pixels, top row first (the Analog Rytm MKII's layout).""" + return [[(fb[(7 - y // 8) + 8 * x] >> (y % 8)) & 1 for x in range(128)] for y in range(64)] + + +def ascii_art(rows): + chars = {(1, 1): '\u2588', (1, 0): '\u2580', (0, 1): '\u2584', (0, 0): ' '} + return '\n'.join(''.join(chars[(a, b)] for a, b in zip(rows[y], rows[y + 1])) for y in range(0, len(rows), 2)) + + +def png(rows, scale=3): + raw = b''.join((bytes([0]) + bytes(255 if px else 0 for px in row for _ in range(scale))) * scale for row in rows) + def chunk(t, d): + return struct.pack('>I', len(d)) + t + d + struct.pack('>I', binascii.crc32(t + d) & 0xffffffff) + head = struct.pack('>IIBBBBB', len(rows[0]) * scale, len(rows) * scale, 8, 0, 0, 0, 0) + return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', head) + chunk(b'IDAT', zlib.compress(raw, 9)) + chunk(b'IEND', b'') + + +def request(seq, name, *values): + return HEADER + bytes([seq & 0x7f, CMD[name]]) + b''.join(u32(v) for v in values) + b'\xF7' + + +def parse(msg): + """A reply's (seq, cmd, status, payload) or None.""" + if len(msg) < len(HEADER) + 4 or msg[:len(HEADER)] != HEADER or msg[-1] != 0xF7 or not msg[len(HEADER) + 1] & 0x40: + return None + return msg[6], msg[7] & 0x3f, msg[8], msg[9:-1] + + +class LinkError(Exception): + """No acceptable reply: the caller decides whether that ends the command.""" + + +# The sequence number: advanced for every request, so a late reply to an earlier one (this run or the last) never +# matches the current one. Seeded from the clock so two runs in a row start apart. +_seq = [int(time.time() * 10)] + + +class MidiLine: + """The unit's USB MIDI pair, through mido.""" + + def __init__(self, port): + import mido + self.mido = mido + pick = lambda names: [n for n in names if port.lower() in n.lower()] + ins, outs = pick(mido.get_input_names()), pick(mido.get_output_names()) + if len(ins) != 1 or len(outs) != 1: + sys.exit('Need exactly one MIDI input and output named like %r.' % port) + self.inp, self.out = mido.open_input(ins[0]), mido.open_output(outs[0]) + + def drain(self): + for _ in self.inp.iter_pending(): + pass + + def send(self, frame): + self.out.send(self.mido.Message('sysex', data=frame[1:-1])) + + def poll(self): + """The next SysEx message as F0..F7 bytes, or None.""" + m = self.inp.poll() + while m is not None and m.type != 'sysex': + m = self.inp.poll() + return None if m is None else bytes([0xF0]) + bytes(m.data) + b'\xF7' + + def close(self): + self.inp.close() + self.out.close() + + +def exchange(line, name, *values, timeout=2.0, accept=None): + """Send one request on line and return the first reply with its sequence number, its command and, if given, + accept(reply) true. Anything else (a late reply to an earlier request, a short reply) is skipped.""" + _seq[0] += 1 + seq = _seq[0] & 0x7f + line.drain() + line.send(request(seq, name, *values)) + end = time.time() + timeout + while time.time() < end: + msg = line.poll() + if msg is None: + time.sleep(0.002) + continue + got = parse(msg) + if got and got[0] == seq and got[1] == CMD[name] and (accept is None or accept(got)): + return got + raise LinkError('No answer: is a development base with the link on the unit, and USB MIDI connected?') + + +def ask(name, *values, port='Digitone II', timeout=2.0, accept=None, line=None): + own = line is None + line = MidiLine(port) if own else line + try: + return exchange(line, name, *values, timeout=timeout, accept=accept) + except LinkError as e: + sys.exit(str(e)) + finally: + if own: + line.close() + + +def packed_len(n): + """The length of n bytes packed 7 in 8, as link.c's pack() writes them.""" + return n + (n + 6) // 7 + + +def screen_reply_fits(off, number=None): + """A screen reply is this request's only if it echoes off, carries exactly one part and, after part 0, the number + of part 0's copy (or is a refusal).""" + def fits(got): + _, _, status, p = got + if status: + return True + return len(p) == 10 + packed_len(SCREEN_PART) and get32(p, 0) == off and (number is None or get32(p, 5) == number) + return fits + + +def screen_part(off, port, line=None, number=None): + """(the copy's number, the part's bytes).""" + _, _, status, p = ask('screen', off, port=port, accept=screen_reply_fits(off, number), line=line) + if status: + sys.exit('refused: ' + STATUS.get(status, str(status))) + return get32(p, 5), unpack7(p[10:])[:SCREEN_PART] + + +def screen(port, line=None): + """The frame on the screen: part 0 makes the unit copy it, the other seven come from that copy, so it never tears.""" + own = line is None + line = MidiLine(port) if own else line + try: + number, first = screen_part(0, port, line) + return first + b''.join(screen_part(at, port, line, number)[1] for at in range(SCREEN_PART, FRAME_BYTES, SCREEN_PART)) + finally: + if own: + line.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--port', default='Digitone II') + sub = parser.add_subparsers(dest='cmd', required=True) + sub.add_parser('ident') + shot = sub.add_parser('screen') + shot.add_argument('--png', help='also write the frame as a PNG here') + a = parser.parse_args() + if a.cmd == 'screen': + rows = frame_rows(screen(a.port)) + print(ascii_art(rows)) + if a.png: + open(a.png, 'wb').write(png(rows)) + return + _, _, status, p = ask('ident', port=a.port) + if status: + sys.exit('refused: ' + STATUS.get(status, str(status))) + print('link %d, received %d, dropped %d, ticks %d' % tuple(get32(p, 5 * i) for i in range(4))) + + +if __name__ == '__main__': + main() diff --git a/sdk/tests/dn2_link_host.c b/sdk/tests/dn2_link_host.c new file mode 100644 index 0000000000..45b5488e14 --- /dev/null +++ b/sdk/tests/dn2_link_host.c @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// The Digitone II link (base/link.c) on the host, with stock's sysex_send, USB parser state and frame pointers +// stubbed: run by test_dn2_link.py. Exit 0 and "ok" when every check holds; a failed check prints its line. +#include +#include +#include + +static uint8_t last_reply[512]; +static int last_len, sent_count, sent_bytes, send_result; // send_result: what stock's send returns (refused: -1) +static int stub_sysex_send(const uint8_t *m, int n, const uint8_t *b, int s) +{ + (void)b; (void)s; + sent_bytes += n; + if (n > (int)sizeof last_reply) + n = (int)sizeof last_reply; + memcpy(last_reply, m, (size_t)n); + last_len = n; + sent_count++; + return send_result; +} +static uint8_t usb_state; +// "DDR" for the test: the frame on the screen and, around it, bytes no reply may carry. +static uint8_t ddr[8192]; +static uint8_t outside[64]; +static uint8_t *frame_pointers[2]; + +#define SYSEX_SEND_AT ((uintptr_t)stub_sysex_send) +#define USB_SYSEX_STATE_AT ((uintptr_t)&usb_state) +#define FRAME_POINTERS_AT ((uintptr_t)frame_pointers) +#define DDR_START ((uintptr_t)ddr) +#define DDR_END ((uintptr_t)ddr + sizeof ddr) +#include "../machines/digitone-ii/elekloader/base/link.c" + +static int failed; +#define CHECK(c) do { if (!(c)) { printf("failed at line %d: %s\n", __LINE__, #c); failed = 1; } } while (0) + +static uint32_t at32(const uint8_t *p) { return get32(p); } + +/* Sends one request with `words` u32 values and returns the reply's status (-1: no reply). */ +static int request(int cmd, int words, uint32_t a, uint32_t b) +{ + uint8_t m[32] = { 0xF0, 0x7D, 'M', 'W', 'L', LINK_VERSION, 3, (uint8_t)cmd }; + uint8_t *p = m + HEADER; + int before = sent_count; + if (words > 0) + p = put32(p, a); + if (words > 1) + p = put32(p, b); + *p++ = 0xF7; + act(m, (int)(p - m)); + return sent_count == before ? -1 : last_reply[8]; +} + +static void unpack(const uint8_t *src, uint8_t *dst, int n) // as dn2_link.py's unpack7 +{ + int i, k, o = 0; + for (i = 0; o < n; i += 8) + for (k = 0; k < 7 && o < n; k++) + dst[o++] = (uint8_t)(src[i + 1 + k] | (src[i] & (0x40 >> k) ? 0x80 : 0)); +} + +/* The part of the frame in the last reply: OFF, the copy's number, then 128 packed bytes and F7. */ +static int part_fits(uint32_t off, uint32_t *number, uint8_t *out) +{ + int expected = HEADER + 1 + 5 + 5 + SCREEN_PART + (SCREEN_PART + 6) / 7 + 1; + if (last_len != expected || last_reply[last_len - 1] != 0xF7 || at32(last_reply + 9) != off) + return 0; + *number = at32(last_reply + 14); + unpack(last_reply + 19, out, SCREEN_PART); + return 1; +} + +// ---- a host that keeps asking and never reads: what the link sends stays bounded ---- +// The host's half of the TX contract: whatever a host sends, the link answers at most PER_TICK requests a tick, +// queues no more than its ring, drops the rest, never retries a send stock refused, sends nothing while stock is +// mid-SysEx on USB, and answers again once the host stops. Stock's own waits below sysex_send are not modelled here: +// they need the unit (the shared design's bounded native send). +static void backpressure_checks(void) +{ + static const uint8_t ident[] = { 0xF0, 0x7D, 'M', 'W', 'L', LINK_VERSION, 5, CMD_IDENT, 0xF7 }; + uint8_t screen[HEADER + 6] = { 0xF0, 0x7D, 'M', 'W', 'L', LINK_VERSION, 6, CMD_SCREEN }; + uint32_t drops0 = ring_drops, head0 = ring_head, tail0 = ring_tail, ticks0 = ticks; + int t, k, sends0 = sent_count, most = 0, most_bytes = 0, quiet = 0; + put32(screen + HEADER, 0)[0] = 0xF7; + + for (t = 0; t < 300; t++) { // ten seconds of 30 requests a tick, never read + int s0 = sent_count, b0 = sent_bytes; + send_result = t & 1 ? -1 : 0; // every other tick stock refuses the send + for (k = 0; k < 30; k++) { + if (k & 1) + mw_link_rx(screen, sizeof screen, USB); + else + mw_link_rx(ident, sizeof ident, AUTO_USB); + CHECK(ring_head - ring_tail <= RING); + } + mw_link_tick(); + if (sent_count - s0 > most) + most = sent_count - s0; + if (sent_bytes - b0 > most_bytes) + most_bytes = sent_bytes - b0; + } + send_result = 0; + CHECK(most == PER_TICK); + CHECK(most_bytes <= PER_TICK * (int)sizeof reply); + CHECK(sent_count - sends0 == (int)(ring_tail - tail0)); // one send per request taken: nothing retried + CHECK(ring_drops - drops0 == 300 * 30 - (ring_head - head0)); + CHECK(ticks - ticks0 == 300); + + usb_state = 0xF0; // stock mid-SysEx on USB: the link waits, the ring holds + for (k = 0; k < 2 * RING; k++) + mw_link_rx(ident, sizeof ident, USB); + { + int s0 = sent_count; + for (t = 0; t < 30; t++) + mw_link_tick(); + CHECK(sent_count == s0 && ring_head - ring_tail == RING); + } + usb_state = 0; + while (ring_head != ring_tail && quiet++ < RING) // the host has stopped: the backlog drains in a few ticks + mw_link_tick(); + CHECK(ring_head == ring_tail && quiet <= RING / PER_TICK); + CHECK(request(CMD_IDENT, 0, 0, 0) == ST_OK); // and the link answers as before +} + +int main(void) +{ + uint8_t got[FRAME_BYTES], part[SCREEN_PART]; + uint32_t number = 0, n2 = 0, off; + int i; + + for (i = 0; i < (int)sizeof ddr; i++) + ddr[i] = (uint8_t)(0xA5 ^ i); // what lies around the frame + memset(outside, 0x5A, sizeof outside); + frame_pointers[0] = ddr; // the frame stock draws next + frame_pointers[1] = ddr + 2048; // the frame on the screen + for (i = 0; i < FRAME_BYTES; i++) + frame_pointers[1][i] = (uint8_t)(i * 7 + 1); + + // ident: the link's own counters. + CHECK(request(CMD_IDENT, 0, 0, 0) == ST_OK); + CHECK(at32(last_reply + 9) == LINK_VERSION); + + // A part before any part 0 has no copy to come from. + CHECK(request(CMD_SCREEN, 1, 128, 0) == ST_RANGE); + CHECK(last_len == HEADER + 2); + + // The whole frame: part 0 copies it, the rest come from the copy even if stock draws meanwhile. + CHECK(request(CMD_SCREEN, 1, 0, 0) == ST_OK); + CHECK(part_fits(0, &number, got)); + CHECK(number == 1); + for (i = 0; i < FRAME_BYTES; i++) + frame_pointers[1][i] ^= 0xFF; // a draw between the parts + for (off = SCREEN_PART; off < FRAME_BYTES; off += SCREEN_PART) { + CHECK(request(CMD_SCREEN, 1, off, 0) == ST_OK); + CHECK(part_fits(off, &n2, got + off)); + CHECK(n2 == number); + } + for (i = 0; i < FRAME_BYTES; i++) + CHECK(got[i] == (uint8_t)(i * 7 + 1)); // one frame, not torn + CHECK(request(CMD_SCREEN, 1, 0, 0) == ST_OK); // a new part 0 takes the new frame + CHECK(part_fits(0, &n2, part)); + CHECK(n2 == 2 && part[0] == (uint8_t)(1 ^ 0xFF)); + + // Refusals: no offset past the frame or between parts, and nothing but the status goes back. + { + uint32_t bad[] = { 1, 64, 127, 129, FRAME_BYTES, FRAME_BYTES + SCREEN_PART, 0x7FFFFFFF, 0xFFFFFF80 }; + for (i = 0; i < (int)(sizeof bad / sizeof bad[0]); i++) { + CHECK(request(CMD_SCREEN, 1, bad[i], 0) == ST_RANGE); + CHECK(last_len == HEADER + 2); + } + } + CHECK(request(CMD_SCREEN, 0, 0, 0) == ST_BAD); // no offset at all + + // A frame pointer that does not lie wholly in DDR is never read. + frame_pointers[1] = outside; + CHECK(request(CMD_SCREEN, 1, 0, 0) == ST_RANGE); + frame_pointers[1] = ddr + sizeof ddr - FRAME_BYTES + 1; + CHECK(request(CMD_SCREEN, 1, 0, 0) == ST_RANGE); + frame_pointers[1] = 0; + CHECK(request(CMD_SCREEN, 1, 0, 0) == ST_RANGE); + CHECK(request(CMD_SCREEN, 1, SCREEN_PART, 0) == ST_OK); // the earlier copy stays as it was + CHECK(part_fits(SCREEN_PART, &n2, part) && n2 == 2); + + // The old mem request and every other command: refused, whatever address they name. + { + uint32_t addrs[] = { (uint32_t)(uintptr_t)ddr, 0x40000000, 0x47f00000, 0x80000000, 0x402a10c8, 0 }; + for (i = 0; i < (int)(sizeof addrs / sizeof addrs[0]); i++) { + CHECK(request(0x21, 2, addrs[i], 16) == ST_BAD); + CHECK(last_len == HEADER + 2); + } + for (i = 0; i < 0x40; i++) + if (i != CMD_IDENT && i != CMD_SCREEN) { + CHECK(request(i, 2, 0x40000000, 128) == ST_BAD); + CHECK(last_len == HEADER + 2); + } + } + + // A request in another link version is refused too. + { + uint8_t m[] = { 0xF0, 0x7D, 'M', 'W', 'L', LINK_VERSION + 1, 4, CMD_SCREEN, 0, 0, 0, 0, 0, 0xF7 }; + act(m, (int)sizeof m); + CHECK(last_reply[8] == ST_BAD && last_len == HEADER + 2); + } + + backpressure_checks(); + + if (!failed) + printf("ok\n"); + return failed; +} diff --git a/sdk/tests/test_dn2_link.py b/sdk/tests/test_dn2_link.py new file mode 100644 index 0000000000..e070f27367 --- /dev/null +++ b/sdk/tests/test_dn2_link.py @@ -0,0 +1,165 @@ +"""The Digitone II link's host (sdk/machines/digitone-ii/tools/dn2_link.py): its requests and the replies link.c +builds, without a unit.""" +import importlib.util +import pathlib +import unittest + +APP = pathlib.Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location("dn2_link", APP / "sdk/machines/digitone-ii/tools/dn2_link.py") +link = importlib.util.module_from_spec(spec) +spec.loader.exec_module(link) + + +def pack7(data): + out = bytearray() + for i in range(0, len(data), 7): + chunk = data[i:i + 7] + out.append(sum(0x40 >> k for k, b in enumerate(chunk) if b & 0x80)) + out += bytes(b & 0x7f for b in chunk) + return bytes(out) + + +class Dn2Link(unittest.TestCase): + def test_requests_are_the_rytm_links_frames(self): + self.assertEqual(link.request(5, "ident"), bytes([0xF0, 0x7D, 0x4D, 0x57, 0x4C, 1, 5, 0x01, 0xF7])) + shot = link.request(9, "screen", 384) + self.assertEqual(len(shot), 14) + self.assertEqual((shot[7], link.get32(shot, 8)), (0x20, 384)) + self.assertTrue(all(b < 0x80 for b in shot[1:-1])) + + def test_there_is_no_request_for_an_address(self): + self.assertEqual(set(link.CMD), {"ident", "screen"}) + + def test_replies_parse_as_link_c_builds_them(self): + data = bytes(range(0x70, 0x70 + 126)) + b"\xff\x80" + reply = screen_reply(9, 128, 3, data) + seq, cmd, status, payload = link.parse(reply) + self.assertEqual((seq, cmd, status), (9, 0x20, 0)) + self.assertEqual((link.get32(payload, 0), link.get32(payload, 5)), (128, 3)) + self.assertEqual(link.unpack7(payload[10:])[:len(data)], data) + self.assertIsNone(link.parse(link.request(9, "screen", 0))) # a request is not a reply + + +class Dn2Screen(unittest.TestCase): + def test_frame_rows_reads_the_frame_column_by_column_top_row_first(self): + fb = bytearray(1024) + fb[7] = 0x01 # x 0, y 0: the top-left pixel + fb[8 * 127] = 0x80 # x 127, y 63: the bottom-right pixel + rows = link.frame_rows(bytes(fb)) + self.assertEqual((len(rows), len(rows[0])), (64, 128)) + self.assertEqual([(x, y) for y in range(64) for x in range(128) if rows[y][x]], [(0, 0), (127, 63)]) + + def test_png_is_a_grayscale_image_of_the_frame(self): + import struct + import zlib + data = link.png(link.frame_rows(bytes(1024)), scale=2) + self.assertEqual(data[:8], b"\x89PNG\r\n\x1a\n") + self.assertEqual(struct.unpack(">II", data[16:24]), (256, 128)) + idat = data.index(b"IDAT") + size = struct.unpack(">I", data[idat - 4:idat])[0] + self.assertEqual(len(zlib.decompress(data[idat + 4:idat + 4 + size])), 128 * (1 + 256)) + + +def screen_reply(seq, off, number, data, status=0): + if status: + return link.HEADER + bytes([seq & 0x7f, 0x20 | 0x40, status, 0xF7]) + return link.HEADER + bytes([seq & 0x7f, 0x20 | 0x40, 0]) + link.u32(off) + link.u32(number) + pack7(data) + b"\xF7" + + +def frame_part(off): + return bytes((off + i) * 7 + 1 & 0xff for i in range(128)) + + +class FakeLine: + """A MIDI pair whose replies come from answer(request) after the request is sent; queued ones arrive first.""" + + def __init__(self, answer, queued=()): + self.answer, self.queue, self.sent = answer, list(queued), [] + + def drain(self): + pass + + def send(self, frame): + self.sent.append(frame) + self.queue += self.answer(frame) + + def poll(self): + return self.queue.pop(0) if self.queue else None + + +class Dn2LinkReplies(unittest.TestCase): + def unit(self, number=lambda off: 1, before=lambda f: []): + return FakeLine(lambda f: before(f) + [screen_reply(f[6], link.get32(f, 8), number(link.get32(f, 8)), + frame_part(link.get32(f, 8)))]) + + def test_the_screen_is_eight_parts_of_one_copy(self): + line = self.unit() + frame = link.screen("x", line) + self.assertEqual(frame, b"".join(frame_part(off) for off in range(0, 1024, 128))) + self.assertEqual([link.get32(f, 8) for f in line.sent], list(range(0, 1024, 128))) + + def test_each_request_takes_a_new_sequence_number(self): + line = self.unit() + link.screen("x", line) + self.assertEqual(len({f[6] for f in line.sent}), 8) + + def test_a_late_reply_to_the_previous_part_is_not_taken_for_the_current_one(self): + def before(f): + off = link.get32(f, 8) + return [screen_reply(f[6], off - 128, 1, bytes([0xAA] * 128))] if off else [] + self.assertEqual(link.screen("x", self.unit(before=before))[128:256], frame_part(128)) + + def test_a_late_reply_with_the_previous_sequence_number_is_skipped(self): + def before(f): + return [screen_reply(f[6] - 1, link.get32(f, 8), 1, bytes([1] * 128))] + self.assertEqual(link.screen("x", self.unit(before=before))[:128], frame_part(0)) + + def test_a_part_of_another_copy_is_not_taken(self): + # someone else asked for part 0 in between: the unit's copy is number 2 from then on + line = self.unit(number=lambda off: 1 if off < 512 else 2) + with self.assertRaises(link.LinkError): + link.exchange(line, "screen", 512, timeout=0.05, accept=link.screen_reply_fits(512, 1)) + with self.assertRaises(SystemExit): + link.screen("x", line) + + def test_a_short_reply_is_never_passed_on(self): + line = FakeLine(lambda f: [screen_reply(f[6], link.get32(f, 8), 1, bytes(100))]) + with self.assertRaises(link.LinkError): + link.exchange(line, "screen", 0, timeout=0.05, accept=link.screen_reply_fits(0)) + with self.assertRaises(SystemExit): + link.screen("x", FakeLine(lambda f: [screen_reply(f[6], link.get32(f, 8), 1, bytes(3))])) + + def test_a_refusal_is_still_reported(self): + line = FakeLine(lambda f: [screen_reply(f[6], 0, 0, b"", status=4)]) + with self.assertRaises(SystemExit) as e: + link.screen("x", line) + self.assertIn("out of range", str(e.exception.code)) + + def test_packed_length_is_link_cs(self): + for n in (1, 4, 7, 8, 127, 128): + self.assertEqual(len(pack7(bytes(n))), link.packed_len(n)) + + +class Dn2LinkOnTheHost(unittest.TestCase): + """base/link.c compiled for the host with stock's sysex_send and frame pointers stubbed (dn2_link_host.c): + ident and screen answer, and every other request, the old mem with it, is refused with nothing but its status.""" + + def test_the_device_answers_only_its_own_diagnostics(self): + import shutil + import subprocess + import tempfile + cc = shutil.which("cc") + if not cc: + self.skipTest("no host C compiler") + with tempfile.TemporaryDirectory() as tmp: + binary = pathlib.Path(tmp) / "dn2_link_host" + build = subprocess.run([cc, "-std=c11", "-O1", "-Wall", "-Wno-pointer-to-int-cast", "-Wno-int-to-pointer-cast", + "-Wno-unused-function", "-o", str(binary), str(APP / "sdk/tests/dn2_link_host.c")], + capture_output=True, text=True) + self.assertEqual(build.returncode, 0, build.stderr) + run = subprocess.run([str(binary)], capture_output=True, text=True) + self.assertEqual((run.returncode, run.stdout.strip()), (0, "ok"), run.stdout + run.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/devices/machines.generated.json b/src/devices/machines.generated.json index ca9e2015d0..36201e34b5 100644 --- a/src/devices/machines.generated.json +++ b/src/devices/machines.generated.json @@ -380,7 +380,7 @@ }, "stack": { "base": "started", - "link": "open", + "link": "started", "flash": "open", "loader": "open", "status": "open", diff --git a/src/engine/elektron/dn2-link.test.ts b/src/engine/elektron/dn2-link.test.ts index 7541058562..f02311764b 100644 --- a/src/engine/elektron/dn2-link.test.ts +++ b/src/engine/elektron/dn2-link.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import { sha } from '../../../vendor/elekloader/kit/src/bytes.ts' import { UploadSession } from '../elekloader/upload-session' import { UploadCommand, UploadPhase, UploadResult } from '../elekloader/upload-wire' -import { ask, frameRows, get32, ident, LINK_HEADER, linkRequest, LinkError, mem, pack7 as linkPack7, parseLinkReply, readLog, screen, u32, unpack7, uploadTransport, UPLOAD_BASE, UPLOAD_BASE_TEXT, type LinkLine } from './dn2-link' +import { ask, frameRows, get32, ident, LINK_COMMANDS, LINK_HEADER, linkRequest, LinkError, pack7 as linkPack7, parseLinkReply, screen, u32, unpack7, uploadTransport, UPLOAD_BASE, UPLOAD_BASE_TEXT, type LinkLine } from './dn2-link' // What link.c packs: groups of seven, each led by a byte holding their top bits. function pack7(data: Uint8Array): number[] { @@ -14,8 +14,10 @@ function pack7(data: Uint8Array): number[] { return out } -/** A unit running the development link: it answers ident, mem (DDR only) and diag as link.c does, from `memory`. */ -function unit(memory: Map, log?: { at: number; size: number }): LinkLine & { requests: number } { +/** A unit running the development link: it answers ident and screen as link.c does, from `frame` (screen copies it at + * part 0; `recopy` makes every later part claim another copy), and refuses anything else, the old mem (0x21) included. */ +function unit(frame = new Uint8Array(1024), recopy = false): LinkLine & { requests: number } { + let copy = 0, copied = new Uint8Array(1024) const queue: Uint8Array[] = [] const reply = (seq: number, cmd: number, status: number, payload: number[] = []) => queue.push(Uint8Array.from([...LINK_HEADER, seq, cmd | 0x40, status, ...payload, 0xf7])) @@ -25,80 +27,50 @@ function unit(memory: Map, log?: { at: number; size: number }): line.requests++ const seq = data[6], cmd = data[7] if (cmd === 0x01) reply(seq, cmd, 0, [1, 7, 0, 300, 1, 0, 3, 40, 0, 1, 0x1bf3c432, 0x47feffbc].flatMap(u32)) - else if (cmd === 0x22) reply(seq, cmd, 0, [log!.at, log!.size, 1500, 30].flatMap(u32)) - else if (cmd === 0x21) { - const address = get32(data, 8), n = get32(data, 13) - if (n < 1 || n > 128 || address < 0x40000000 || address + n > 0x48000000) return reply(seq, cmd, 4) - reply(seq, cmd, 0, [...u32(address), ...pack7(Uint8Array.from({ length: n }, (_, i) => memory.get(address + i) ?? 0))]) - } else reply(seq, cmd, 2) + else if (cmd === 0x20) { + const off = get32(data, 8) + if (off >= 1024 || off % 128 || (off && !copy)) return reply(seq, cmd, 4) + if (off === 0) { copy++; copied = frame.slice() } + reply(seq, cmd, 0, [...u32(off), ...u32(recopy && off ? copy + 1 : copy), ...pack7(copied.subarray(off, off + 128))]) + } + else reply(seq, cmd, 2) }, async next() { return queue.shift() ?? null }, } return line } -const put = (memory: Map, address: number, bytes: number[]) => bytes.forEach((b, i) => memory.set(address + i, b)) -const be = (value: number) => [value >>> 24, value >>> 16 & 0xff, value >>> 8 & 0xff, value & 0xff] describe('the Digitone II link from the site', () => { it('builds requests and reads replies in the Rytm link\'s format', () => { expect(Array.from(linkRequest(5, 'ident'))).toEqual([0xf0, 0x7d, 0x4d, 0x57, 0x4c, 1, 5, 0x01, 0xf7]) - const request = linkRequest(9, 'mem', 0x47f00000, 64) - expect([request.length, get32(request, 8), get32(request, 13)]).toEqual([19, 0x47f00000, 64]) + const request = linkRequest(9, 'screen', 384) + expect([request.length, request[7], get32(request, 8)]).toEqual([14, 0x20, 384]) expect(Array.from(request.subarray(1, -1)).every(b => b < 0x80)).toBe(true) expect(parseLinkReply(Uint8Array.of(0xf0, 1, 2, 0xf7))).toBeNull() + expect(Object.values(LINK_COMMANDS)).not.toContain(0x21) // no request names an address }) - it('reads the identity and memory, and names a refusal', async () => { - const memory = new Map() - put(memory, 0x47f00000, [0x2f, 0x0a, 0x45, 0xf9, 0x80, 0xff]) - const line = unit(memory) + it('reads the identity and names a refusal', async () => { + const line = unit() expect(await ident(line)).toMatchObject({ version: 1, received: 7, ticks: 300, armed: true, person: false, bootStatus: 1 }) - expect(Array.from(await mem(line, 0x47f00000, 6))).toEqual([0x2f, 0x0a, 0x45, 0xf9, 0x80, 0xff]) - await expect(mem(line, 0x0, 4)).rejects.toThrow('out of range') - await expect(ask(line, 'mem', [0x40000000])).rejects.toBeInstanceOf(LinkError) + await expect(ask(line, 'screen', [100])).rejects.toThrow('out of range') + await expect(ask(line, 'screen', [100])).rejects.toBeInstanceOf(LinkError) }) - it('reads the frame on the screen through its pointer', async () => { - const memory = new Map(), frame = 0x44623fc8 - put(memory, 0x402a10c8, [...be(0x44623bc8), ...be(frame)]) - put(memory, frame + 7, [0x01]) // x 0, y 0 - put(memory, frame + 8 * 127, [0x80]) // x 127, y 63 - const rows = await screen(unit(memory)) + it('reads the frame on the screen in eight parts of one copy, asking for no address', async () => { + const frame = new Uint8Array(1024) + frame[7] = 0x01 // x 0, y 0 + frame[8 * 127] = 0x80 // x 127, y 63 + const line = unit(frame), sent: number[][] = [], send = line.send + line.send = data => { sent.push([data[7], get32(data, 8)]); send(data) } + const rows = await screen(line) expect(rows.flatMap((row, y) => row.flatMap((px, x) => px ? [[x, y]] : []))).toEqual([[0, 0], [127, 63]]) + expect(sent).toEqual([0, 128, 256, 384, 512, 640, 768, 896].map(off => [0x20, off])) expect(frameRows(new Uint8Array(1024))[0]).toHaveLength(128) }) - it.each([ - [0x40000008, 4, 'reply does not match the requested address'], - [0x40000000, 3, 'expected 4 bytes, received 3'], - [0x40000000, 5, 'expected 4 bytes, received 5'], - ])('rejects a memory reply for address %i with %i bytes', async (address, length, error) => { - let reply: Uint8Array - const line: LinkLine = { - send(request) { - reply = Uint8Array.from([...LINK_HEADER, request[6], 0x61, 0, ...u32(address), ...pack7(new Uint8Array(length)), 0xf7]) - }, - async next() { return reply }, - } - await expect(mem(line, 0x40000000, 4)).rejects.toThrow(error) - }) - - it('reads the diagnostics log the unit keeps, in the Octatrack\'s layout, with the site\'s parser', async () => { - // As diag.c left it on a unit (19 November 2026): a START, then a FREEZE of 9,050 frames after FLTR (0x03). - const memory = new Map(), at = 0x47f0315c, size = 6148 - const incident = (n: number, seq: number, second: number, a: number, kind: number, keys: number[]) => { - const base = at + 40 + 92 + 32 * 96 + 92 * n - put(memory, base, [...be(seq), ...be(1), ...be(second), ...be(a), 0, kind]) - put(memory, base + 64, [...keys, ...Array(16 - keys.length).fill(0xff)]) - } - put(memory, at, [...be(0x4d574447), ...be(2), ...be(0x1234), ...be(1), ...be(2), ...be(0), ...be(2)]) - incident(0, 1, 0, 0, 1, []) - incident(1, 2, 14, 9050, 3, [3]) - const line = unit(memory, { at, size }), { bytes, log } = await readLog(line) - expect(bytes).toHaveLength(size) - expect(line.requests).toBe(1 + Math.ceil(size / 128)) - expect(log).toMatchObject({ version: 2, boot: 1, seq: 2, loads: [] }) - expect(log!.incidents.map(i => [i.kind, i.second, i.a, i.keys.filter(k => k !== 0xff)])).toEqual([['start', 0, 0, []], ['freeze', 14, 9050, [3]]]) + it('refuses a screen whose parts come from two copies', async () => { + await expect(screen(unit(new Uint8Array(1024), true))).rejects.toThrow('copied the screen again') }) }) diff --git a/src/engine/elektron/dn2-link.ts b/src/engine/elektron/dn2-link.ts index f4b70f2c5b..3ab5d04a99 100644 --- a/src/engine/elektron/dn2-link.ts +++ b/src/engine/elektron/dn2-link.ts @@ -1,28 +1,25 @@ // SPDX-License-Identifier: GPL-3.0-or-later // The Digitone II development link's client for the site (sdk/machines/digitone-ii/LINK.md, the host // sdk/machines/digitone-ii/tools/dn2_link.py): its requests and replies in the Analog Rytm MKII link's wire format, and -// the reads the page and the diagnostics need: the link's identity, memory, the screen and the diagnostics log, which -// is the Octatrack's layout and reads with parseDeviceLog. No keys, turns or RAM boot from here. The one command +// the reads the page needs: the link's identity and the screen. The unit chooses what it sends; no request names an +// address (the old mem, 0x21, is refused). No keys, turns or RAM boot from here. The one command // that changes the unit is `upload`, which carries the runtime loader's upload controller (uploadTransport): modules // load to RAM for a trial, and a power cycle ends them (sdk/machines/digitone-ii/LOADER.md). The wire itself, shared // with the Model:Cycles, is link-wire.ts; this file keeps the Digitone II's commands and status wording. // Transport-free (LinkLine): the page gives it Web MIDI, a test a simulated unit. import { sha } from '../../../vendor/elekloader/kit/src/bytes.ts' -import { DEVICE_LOG_IMAGE_BYTES, parseDeviceLog, type DeviceLog } from '../elekloader/device-log.ts' import type { UploadTransport } from '../elekloader/upload-session.ts' import { UPLOAD_RESPONSE } from '../elekloader/upload-wire.ts' import { askLink, get32, LinkError, linkFrame, pack7, u32, unpack7, type LinkLine } from './link-wire.ts' export { get32, LINK_HEADER, LinkError, pack7, parseLinkReply, u32, unpack7, type LinkLine } from './link-wire.ts' -export const LINK_COMMANDS = { ident: 0x01, mem: 0x21, diag: 0x22, upload: 0x30 } as const +export const LINK_COMMANDS = { ident: 0x01, screen: 0x20, upload: 0x30 } as const export type LinkCommand = keyof typeof LINK_COMMANDS export const LINK_STATUS: Readonly> = { 1: 'not armed (SETTINGS > REMOTE CTRL)', 2: 'bad request', 3: 'busy', 4: 'out of range', 5: 'a person is at the unit', } -/** The most a `mem` request reads. */ -export const MEM_MAX = 128 -/** Stock keeps two frame pointers side by side (OS 1.12): the frame on the screen is the second's. 128x64, 1 bit. */ -export const FRAME_POINTERS = 0x402a10c8, FRAME_BYTES = 1024 +/** The frame on the screen: 128x64, 1 bit, sent by the unit in eight parts of SCREEN_PART bytes. */ +export const FRAME_BYTES = 1024, SCREEN_PART = 128 export function linkRequest(seq: number, command: LinkCommand, ...values: number[]): Uint8Array { return linkFrame(seq, LINK_COMMANDS[command], values.flatMap(u32)) @@ -38,38 +35,27 @@ export async function ident(line: LinkLine): Promise { const p = await ask(line, 'ident'), v = Array.from({ length: Math.floor(p.length / 5) }, (_, i) => get32(p, 5 * i)) return { version: v[0], received: v[1], dropped: v[2], ticks: v[3], ...(v.length >= 9 ? { armed: v[4] === 1, person: v[5] === 1 } : {}), ...(v.length >= 11 ? { bootStatus: v[9] } : {}) } } -/** Up to MEM_MAX bytes of DDR or SRAM. */ -export async function mem(line: LinkLine, address: number, length: number): Promise { - if (length < 1 || length > MEM_MAX) throw new LinkError(`mem: 1 to ${MEM_MAX} bytes`) - const p = await ask(line, 'mem', [address, length]) - if (p.length < 5 || get32(p, 0) !== address) throw new LinkError('mem: reply does not match the requested address') - const bytes = unpack7(p.subarray(5)) - if (bytes.length !== length) throw new LinkError(`mem: expected ${length} bytes, received ${bytes.length}`) - return bytes +/** One part of the frame: `screen 0` makes the unit copy the frame on the screen, and every part carries the copy's + * number. A reply for another offset, another copy or of another length is refused, never passed on. */ +async function screenPart(line: LinkLine, offset: number, copy?: number): Promise<{ copy: number; bytes: Uint8Array }> { + const p = await ask(line, 'screen', [offset]) + if (p.length < 10 || get32(p, 0) !== offset) throw new LinkError('screen: reply does not match the requested part') + if (copy !== undefined && get32(p, 5) !== copy) throw new LinkError('screen: the unit copied the screen again during the read') + const bytes = unpack7(p.subarray(10)) + if (bytes.length !== SCREEN_PART) throw new LinkError(`screen: expected ${SCREEN_PART} bytes, received ${bytes.length}`) + return { copy: get32(p, 5), bytes } } -async function read(line: LinkLine, address: number, length: number): Promise { - const out = new Uint8Array(length) - for (let at = 0; at < length; at += MEM_MAX) out.set(await mem(line, address + at, Math.min(MEM_MAX, length - at)), at) - return out -} -/** The frame on the screen as 64 rows of 128 pixels, top row first (the Rytm's layout). A draw between its eight - * reads can tear it. */ +/** The frame on the screen as 64 rows of 128 pixels, top row first (the Rytm's layout): eight parts of one copy the unit + * took, so it never tears. The unit chooses the bytes; no address is asked for. */ export async function screen(line: LinkLine): Promise { - const pointers = await mem(line, FRAME_POINTERS, 8), front = new DataView(pointers.buffer, pointers.byteOffset).getUint32(4) - return frameRows(await read(line, front, FRAME_BYTES)) + const frame = new Uint8Array(FRAME_BYTES), first = await screenPart(line, 0) + frame.set(first.bytes) + for (let at = SCREEN_PART; at < FRAME_BYTES; at += SCREEN_PART) frame.set((await screenPart(line, at, first.copy)).bytes, at) + return frameRows(frame) } export function frameRows(frame: Uint8Array): number[][] { return Array.from({ length: 64 }, (_, y) => Array.from({ length: 128 }, (_, x) => frame[(7 - (y >> 3)) + 8 * x] >> (y & 7) & 1)) } -/** The diagnostics log (diag.c): its bytes, read through mem, and the log the site's parser reads from them. */ -export async function readLog(line: LinkLine): Promise<{ bytes: Uint8Array; log: DeviceLog | undefined }> { - const p = await ask(line, 'diag'), address = get32(p, 0), size = get32(p, 5) - if (size < 8 || size > DEVICE_LOG_IMAGE_BYTES) throw new LinkError(`diag: a ${size}-byte log`) - const bytes = await read(line, address, size), image = new Uint8Array(DEVICE_LOG_IMAGE_BYTES) - image.set(bytes) // the Digitone II keeps no crash or stall record: zeros, as an older base answers - return { bytes, log: parseDeviceLog(image) } -} - /** The development base's identity for the upload controller (link.c upload_start): the SHA-256 of this text. */ export const UPLOAD_BASE_TEXT = 'Modwerk Digitone II OS 1.12 development base, link upload v1' export const UPLOAD_BASE = sha(new TextEncoder().encode(UPLOAD_BASE_TEXT))