diff --git a/changelog/2026-11-19-digitone-ii-link-keys.md b/changelog/2026-11-19-digitone-ii-link-keys.md new file mode 100644 index 0000000000..92eedbab09 --- /dev/null +++ b/changelog/2026-11-19-digitone-ii-link-keys.md @@ -0,0 +1 @@ +Digitone II: the development link can now play panel keys and encoder turns from the computer over USB while SETTINGS > REMOTE CTRL is on, and stops for a few seconds when someone at the unit presses a key. Release bases do not have it. 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-keys-on-a-unit.md b/docs/verification/2026-11-19-digitone-ii-link-keys-on-a-unit.md new file mode 100644 index 0000000000..e39ea1949c --- /dev/null +++ b/docs/verification/2026-11-19-digitone-ii-link-keys-on-a-unit.md @@ -0,0 +1,13 @@ +# Digitone II: the development link plays panel keys and encoders, 19 November 2026 + +Stage two of the Digitone II development link (`sdk/machines/digitone-ii/LINK.md`) on OS 1.12. Contributor's Digitone II (@prodbysmolec), on the unit of the [stage one record](2026-11-19-digitone-ii-link-on-a-unit.md), flashed over USB with the OS upgrade protocol of `os-upgrade.ts` (the developer pressed YES on the unit). + +- **Found on the unit first, with stage one's `mem`:** the UI queue's getter (0x4013747a) holds 0x4059e214; the queue keeps 1,024 message pointers at 0x405c6a34. With the developer pressing and turning, the panel's messages read as the Analog Rytm MKII's: kind 0 a key (its id, flags 0x01 press and 0x10 release, a time), kind 1 an encoder (its number, the delta in the top byte). Keys, each pressed alone in a named order: TRIG (page) 0x01, SYN 0x02, FLTR 0x03, AMP 0x04, FX 0x05, MOD 0x06, PERFORM 0x07, SAVE PROJ 0x08, TAP TEMPO 0x09, YES 0x0a, UP 0x0b, NO 0x0c, LEFT 0x0d, DOWN 0x0e, RIGHT 0x0f, TRK 0x10, FUNC 0x11, KB SETUP 0x12, REC 0x13, PLAY 0x14, STOP 0x15, PAGE 0x16, PTN 0x17, SONG 0x18, TRIG 1 0x19 to TRIG 16 0x28, ARP 0x33, TRANSPOSE + 0x34, NOTE EDIT 0x35, TRANSPOSE - 0x36, UNISON 0x32. The ids between, 0x29 to 0x31, fit the encoders' pushes (stock reads is_key_held(encoder + 40) on a turn); they were not pressed alone. Encoders: A to H 1 to 8, LEVEL 9, each read alone. is_key_held is 0x4011fac4 with its tables at 0x401f3d10 (111 ids) and 0x445a2e30. +- **Build:** `npm run machine:base -- digitone-ii --dev`, development package `300c83be199c70fca8f31b6203953fdd1a2b92938415020d0fa855c4d18fe4b1` (.run 6,629, .bss 4,364 bytes; 16 sites; no jump to an odd address), 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): `.syx` `4fd37eac11d36a393163975e9cd98ec2baa1fa841c68e63670839202a0f48249`. It flashed and booted; `ident` read armed at boot. +- **Encoders:** `turn A 3` showed ATK's value change; turns of one detent each moved Attack Time about a fifth of a step (530 to 117), turns of up to 8 a message moved it faster, as the panel's fast turns do: up to Attack Time=127, then down to 0, each read on the screen through `screen`. +- **Keys:** `press PLAY`, four seconds, `press STOP`: the pattern ran and stopped (the developer). +- **The link's own events:** after 650 posted keys and turns, `ident` counted no person and refused none. +- **Arm:** SETTINGS ended with REMOTE CTRL: ON. The developer pressed YES on it: REMOTE CTRL: OFF, and `press STOP` came back not armed. YES again turned it on. +- **A person at the unit:** the developer pressed a key while armed; the link's next key came back "a person is at the unit" (status 5), and one 3.5 s later went through. +- **A held key:** while the link held FUNC, the SYN page's ATK read DEL (FUNC's second parameter) and the panel's own bitmap at 0x445a2e30 read all zero, so stock saw the hold through is_key_held's site; after `let FUNC` it read ATK again. +- **Not tested:** a held key with a second key from the host (FUNC + TRIG), a module's replayed key, keys and turns while the queue is full (the link answers busy), long sessions. 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..3fcee53025 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 link in the Rytm link's format whose requests return only what the unit chooses ([LINK.md](LINK.md)): `ident`, the link's counters, `screen`, the frame on the screen, and while SETTINGS > REMOTE CTRL is on, panel keys and encoder turns. This link ran on a unit, its cases at UPGRADE OS NOW? with a person at the unit included ([5 December 2026](../../../docs/verification/2026-12-05-digitone-ii-dev-stack-on-a-unit.md)); the 19 November runs ([stage one](../../../docs/verification/2026-11-19-digitone-ii-link-on-a-unit.md), [keys](../../../docs/verification/2026-11-19-digitone-ii-link-keys-on-a-unit.md)) were on earlier builds that still read memory through `mem`. Not yet: the remote YES and RAM boot | 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..30aa8b9878 --- /dev/null +++ b/sdk/machines/digitone-ii/LINK.md @@ -0,0 +1,63 @@ +# Digitone II development link + +Piece 4 of the [goal](GOAL.md): diagnostics over USB MIDI SysEx and, while armed, panel keys and encoders, 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 +python3 sdk/machines/digitone-ii/tools/dn2_link.py press PLAY # keys: FUNC PLAY STOP TRIG1-16, or an id +python3 sdk/machines/digitone-ii/tools/dn2_link.py turn A 8 # encoders A-H, LEVEL +``` + +| Request | cmd | What comes back | +| --- | --- | --- | +| `ident` | 0x01 | the link's own counters: link version, link messages received, dropped (ring full or too long), ticks, armed, a person at the unit, presses and turns by a person, events posted, requests refused | +| `disarm` | 0x02 | turns the arm off and lets go of every key the link holds; a release the UI queue cannot take yet follows from the UI tick | +| `key ID FLAGS` | 0x10 | armed: a panel key message, flags 0x01 press, 0x10 release; a held key reads as held to stock's is_key_held | +| `enc N DELTA` | 0x11 | armed: an encoder turn, 1-8 A-H, 9 LEVEL | +| `release` | 0x12 | armed: lets go of every key the link holds | +| `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, posts keys and turns while armed, and reaches 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, 1 not armed, 2 bad request, 3 busy, 4 out of range, 5 a person at the unit, 6 an OS upload waits at UPGRADE OS NOW? (key and enc refused, and stock's is_key_held stops seeing the link's holds, until the next boot: a flash needs a person's YES). A press, release or turn the link posted, still in stock's queue when the prompt opens or posted by `release` after it, is taken at `ev_key`/`ev_enc` before stock sees it and counted as refused: stock answers the prompt on YES's release as on its press (on a unit, 26 November 2026, a link holding YES and then `release` started the flash). The link's events stay held back at the prompt however late stock dispatches them. After the link has given up an event (stock had not taken it within about a second), a person's press of the same key can be held back once: their first YES may do nothing, so they press it again. Otherwise a person's YES and NO reach stock. 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 every request and refusal (`test_dn2_link.py` +runs it). This version ran on a unit over USB: `ident`, a whole frame through `screen`, the refusals, `mem` included, +keys and turns, and the prompt cases with a person at the unit +([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. +- **Keys and encoders.** Posted on the UI task's queue (getter 0x4013747a, queue_put 0x40001896) as the panel's + messages are, so the UI loop plays them through the core's ev_key/ev_enc sites and stock, and modules see them too. + A key the link holds also reads as held to stock's is_key_held (0x4011fac4, which base.json points at + mw_link_held). Key ids and encoders were read from the panel's own messages on a unit + ([record](../../../docs/verification/2026-11-19-digitone-ii-link-keys-on-a-unit.md)). +- **Arm.** SETTINGS > REMOTE CTRL, ON at every boot of a development base. Keys and turns need it; reads do not. A + press or turn from a person at the panel refuses the host for about two seconds (60 UI ticks) and lets go of what + it held; the YES that turns the row on does not count. OFF stops the host until the next boot. +- **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 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..8addb2ac6e 100644 --- a/sdk/machines/digitone-ii/elekloader/base.json +++ b/sdk/machines/digitone-ii/elekloader/base.json @@ -170,5 +170,63 @@ "requires", "conflicts" ] + }, + "dev": { + "about": "The development link (base/link.c, link.s): diagnostics over USB MIDI SysEx in the Analog Rytm MKII link's wire format (ident, the link's counters; screen, the frame on the screen in eight parts of 128 bytes copied when the first is asked for; no request names an address), and while SETTINGS > REMOTE CTRL is on (at every boot) panel keys and encoder turns, posted on the UI queue as the panel's. 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. is_key_held (0x4011fac4) also sees the keys the link holds. Development bases only.", + "sources": [ + "../base/link.c", + "../base/link.s" + ], + "sites": [ + { + "addr": "0x4012197a", + "len": 6, + "stockSha256": "d8acd0e6e84b3d17d530cf3e5621bc1d0a1e5062f8c0a62a79113c0d9548fc33", + "op": "jsr", + "target": "mw_link_router" + }, + { + "addr": "0x4011fac4", + "len": 6, + "stockSha256": "9eab14ed9d527816054c9f68837b2e021fba5470d105516b94b63ffb8ed1f45d", + "op": "jmp", + "target": "mw_link_held" + } + ], + "cflags": [ + "-DSYSEX_SEND_AT=0x401236d2", + "-DUSB_SYSEX_STATE_AT=0x445090ac", + "-DFRAME_POINTERS_AT=0x402a10c8", + "-DUI_QUEUE_AT=0x4013747a", + "-DQUEUE_POST_AT=0x40001896", + "-DKEY_INDEX_AT=0x401f3d10", + "-DKEY_BITS_AT=0x445a2e30", + "-DUPLOAD_AT=0x4038bec0" + ], + "defsym": { + "SYSEX_TABLE": "0x40207f9e" + }, + "subscribe": [ + { + "event": "ev_tick", + "fn": "mw_link_tick", + "order": 240 + }, + { + "event": "ev_key", + "fn": "mw_link_key", + "order": 1 + }, + { + "event": "ev_enc", + "fn": "mw_link_enc", + "order": 1 + }, + { + "event": "ev_settings", + "fn": "mw_link_settings", + "order": 50 + } + ] } } 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..a23bbd6ddb --- /dev/null +++ b/sdk/machines/digitone-ii/elekloader/base/link.c @@ -0,0 +1,488 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// The Digitone II's development link: diagnostics and, while armed, panel keys and encoders 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, armed, person at the unit, +// presses and turns from a person, events posted, requests refused +// disarm 0x02 -> turns the arm off and lets go of every key the link holds (a release the queue cannot take yet +// follows from the UI tick) +// key 0x10 ID FLAGS -> a panel key message (flags bit 0 down, 0x10 a release), armed only; refused while an +// OS upload waits at UPGRADE OS NOW? (a flash needs a person's YES) +// enc 0x11 N DELTA -> an encoder turn (1-8 A-H, 9 LEVEL), armed only, refused as key +// release 0x12 -> lets go of every key the link holds, armed only +// 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 posts keys and turns, and reaches nothing else of the unit. +// Keys and turns go on the UI task's queue (0x4013747a, queue_put 0x40001896) as the panel's messages do, so the UI +// loop plays them through the core's ev_key/ev_enc sites and stock: modules see them too. A key the link holds reads +// as held to stock's is_key_held (0x4011fac4, which base.json points at mw_link_held). Arm: SETTINGS > REMOTE CTRL, ON +// at every boot of a development base; a press or turn from a person at the panel refuses the host for about three +// seconds and lets go of what it held, and OFF stops it until the next boot. +// 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 UI_QUEUE ((void *(*)(void))UI_QUEUE_AT) +#define QUEUE_POST ((void (*)(void *, const void *))QUEUE_POST_AT) +#define KEY_INDEX ((const int32_t *)KEY_INDEX_AT) // is_key_held's tables: id -> bit, -1 for none +#define KEY_BITS ((const volatile uint8_t *)KEY_BITS_AT) +// Stock's OS upload buffer (OS 1.12, 0x40122574 returns it): header byte 0 is 3 once an upload is complete, which is +// when stock asks UPGRADE OS NOW?. Boot clears it (0x402fb000-0x466b8c50). +#define UPLOAD_STATE (*(const volatile uint8_t *)UPLOAD_AT) +#define KEY_IDS 111 // KEY_INDEX's entries +#define MSG_KEY 0 +#define MSG_ENC 1 +#define KEY_DOWN 1 +#define KEY_RELEASE 0x10 // flags of a release, as the panel posts it +#define ENC_FIRST 1 // A..H are 1..8, LEVEL 9 (seen on a unit) +#define ENC_LAST 9 + +#define USB 2 +#define AUTO_USB 4 +#define ST_OK 0 +#define ST_NOT_ARMED 1 +#define ST_BAD 2 +#define ST_BUSY 3 +#define ST_RANGE 4 +#define ST_HUMAN 5 +#define ST_FLASH 6 // an OS upload waits at UPGRADE OS NOW?: only a person confirms it +#define CMD_IDENT 0x01 +#define CMD_DISARM 0x02 +#define CMD_KEY 0x10 +#define CMD_ENC 0x11 +#define CMD_RELEASE_ALL 0x12 +#define CMD_SCREEN 0x20 +#define SLOTS 40 // posted messages, reused in turn (more than PENDING) +#define PENDING 32 // posted events not yet seen at ev_key/ev_enc +#define HUMAN_TICKS 60 // about 3 s +#define PEND_TICKS 20 // about 1 s: a posted event never seen at ev_key/ev_enc is given up +#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 (key and enc, the longest, are 19) +#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 * 9 + (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); +} + +// ---- arm, the person at the unit, the posted events --------------------------- +static int armed = 1, human_ticks = -1, release_due; +static uint32_t human_count, posted_count, refused_count; +static uint8_t held_bits[KEY_IDS / 8 + 1]; +#define HELD(k) (held_bits[(k) >> 3] >> ((k) & 7) & 1) +#define HOLD(k, on) (held_bits[(k) >> 3] = (uint8_t)((held_bits[(k) >> 3] & ~(1 << ((k) & 7))) | (!!(on) << ((k) & 7)))) + +struct pend { uint8_t kind, id; int8_t value; }; +static struct pend pend[PENDING]; +static uint32_t pend_head, pend_tail, pend_seen; +static int pend_age; +// Events the link gave up waiting for (pend's aging, a new arm) may still be in stock's queue. Outside UPGRADE OS NOW? +// a late one is a stray press at worst; at the prompt it would be an answer, so there one that matches is held back +// however late it comes. A person's identical press is then held back once instead: the side that never flashes. +static struct pend lost[PENDING]; +static uint32_t lost_head; +static int32_t slots[SLOTS][4]; +static uint32_t slot_next; + +static int panel_down(int key) // the panel's own bitmap, as stock reads it +{ + int32_t index; + if ((unsigned)key >= KEY_IDS) + return 0; + index = KEY_INDEX[key]; + return index >= 0 && (KEY_BITS[index >> 3] >> (index & 7) & 1); +} + +// An OS upload is staged: a flash is one YES away, so the link neither presses nor holds a key until the next boot. +static int flash_waits(void) +{ + return UPLOAD_STATE == 3; +} + +int mw_link_held(int key) // stock's is_key_held, and the link's holds +{ + if ((unsigned)key < KEY_IDS && HELD(key) && !flash_waits()) + return 1; + return panel_down(key); +} + +static int post(int kind, int id, int value) +{ + int32_t *m; + if (pend_head - pend_tail >= PENDING) + return 0; // the loop is behind: the host retries + m = slots[slot_next++ % SLOTS]; + m[0] = kind << 24; + m[1] = id; + m[2] = kind == MSG_KEY ? value : (int32_t)((uint32_t)(uint8_t)value << 24); + m[3] = 0; // the event's time + pend[pend_head % PENDING] = (struct pend){ (uint8_t)kind, (uint8_t)id, (int8_t)(kind == MSG_KEY ? value & 1 : value) }; + pend_head++; + QUEUE_POST(UI_QUEUE(), m); + posted_count++; + return 1; +} + +static int release_all(void) // -> 1 when any key was held; one the queue cannot take now stays due +{ + int k, any = 0; + release_due = 0; + for (k = 0; k < KEY_IDS; k++) + if (HELD(k)) { + any = 1; + if (post(MSG_KEY, k, KEY_RELEASE)) + HOLD(k, 0); + else + release_due = 1; + } + return any; +} + +// New presses stop at once; a release the queue cannot take now stays held and due, and the UI tick posts it when +// there is room, so stock never keeps a key down that the link pressed. +static void disarm(void) +{ + if (armed) + release_all(); + armed = 0; +} + +// A press or turn the link posted that stock would get while UPGRADE OS NOW? waits: taken before stock, counted as +// refused. The check where the host asks (ST_FLASH) cannot see one already in stock's queue when the upload completes. +static void held_back(void) +{ + refused_count++; +} + +static int ours(int kind, int id, int value) // the next event the link posted? pops it if so +{ + struct pend *p; + if (pend_head == pend_tail) + return 0; + p = &pend[pend_tail % PENDING]; + if (p->kind != kind || p->id != (uint8_t)id || (kind == MSG_KEY && (value & 1) != p->value)) + return 0; + pend_tail++; + return 1; +} + +static void give_up(void) // what pend still waits for goes to lost +{ + while (pend_tail != pend_head) + lost[lost_head++ % PENDING] = pend[pend_tail++ % PENDING]; + pend_seen = pend_tail; +} + +static int was_lost(int kind, int id, int value) // an event the link gave up? forgets it if so +{ + uint32_t i = lost_head > PENDING ? lost_head - PENDING : 0; + for (; i != lost_head; i++) { + struct pend *p = &lost[i % PENDING]; + if (p->kind == kind && p->id == (uint8_t)id && (kind != MSG_KEY || (value & 1) == p->value)) { + p->kind = 0xFF; + return 1; + } + } + return 0; +} + +static int human(void) // a person pressed or turned something; -> 1 takes that first press +{ + int any; + human_count++; + if (!armed) + return 0; + human_ticks = 0; + any = release_all(); + return flash_waits() ? 0 : any; // at UPGRADE OS NOW? a person's press always reaches stock: their YES or NO +} + +// ev_key, ev_enc: (brain, event); the key or encoder at event + 12, a key's flags at + 16. A release alone is not a +// person; a press the link did not post is, unless it is the key just dispatched in this tick again and the panel's +// bitmap does not hold it (a module replaying a tap through core_key). +static int32_t last_key = -1; +static uint32_t last_tick; +int mw_link_key(void *brain, char *event) +{ + int32_t key = *(int32_t *)(event + 12), flags = *(int32_t *)(event + 16); + int replay = key == last_key && ticks == last_tick, person; + (void)brain; + int mine = (uint32_t)key < KEY_IDS && ours(MSG_KEY, key, flags); + person = (uint32_t)key < KEY_IDS && !mine && (flags & KEY_DOWN) && (!replay || panel_down(key)); + last_key = key; + last_tick = ticks; + if (mine) { // nothing the link queued reaches UPGRADE OS NOW?, a press or a release: stock + if (!flash_waits()) // takes the release of a YES it saw go down as the answer (on a unit, 26 Nov) + return 0; + held_back(); + return 1; + } + if (flash_waits() && (uint32_t)key < KEY_IDS && was_lost(MSG_KEY, key, flags)) { + held_back(); // the link's, given up but still dispatched: never the prompt's answer + return 1; + } + return person ? human() : 0; +} + +int mw_link_enc(void *brain, char *event) +{ + int32_t enc = *(int32_t *)(event + 12); + (void)brain; + if (enc < ENC_FIRST || enc > ENC_LAST) + return 0; + if (ours(MSG_ENC, enc, 0)) { // nor a turn the link queued + if (!flash_waits()) + return 0; + held_back(); + return 1; + } + if (flash_waits() && was_lost(MSG_ENC, enc, 0)) { + held_back(); + return 1; + } + return human(); +} + +// 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, status = ST_OK; + 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); + p = put32(p, (uint32_t)armed); + p = put32(p, human_ticks >= 0 && human_ticks < HUMAN_TICKS); + p = put32(p, human_count); + p = put32(p, posted_count); + p = put32(p, refused_count); + send(p); + return; + case CMD_DISARM: + disarm(); + send(begin(seq, cmd, ST_OK)); + return; + case CMD_KEY: + case CMD_ENC: + case CMD_RELEASE_ALL: + if (!armed) + status = ST_NOT_ARMED; + else if (human_ticks >= 0 && human_ticks < HUMAN_TICKS) + status = ST_HUMAN; + else if (cmd == CMD_RELEASE_ALL) + release_all(); + else if (flash_waits()) + status = ST_FLASH; + else if (n < 10) + status = ST_BAD; + else { + uint32_t id = get32(m + HEADER), v = get32(m + HEADER + 5); + if (cmd == CMD_KEY ? id >= KEY_IDS || KEY_INDEX[id] < 0 : id < ENC_FIRST || id > ENC_LAST) + status = ST_BAD; // only the panel's own keys and encoders + else if (cmd == CMD_KEY) { + if (!post(MSG_KEY, (int)id, (int)v)) + status = ST_BUSY; + else + HOLD(id, v & KEY_DOWN); + } else if (!post(MSG_ENC, (int)id, (int)(int8_t)v)) + status = ST_BUSY; + } + if (status != ST_OK) + refused_count++; + send(begin(seq, cmd, status)); + 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++; + if (human_ticks >= 0 && human_ticks < HUMAN_TICKS) + human_ticks++; + if (release_due) + release_all(); + // A posted event the loop never passed to ev_key/ev_enc would hold the head of pend for good, and every later + // event of the link would count as a person's: give it up after about a second, into lost. Never while + // UPGRADE OS NOW? waits: there the link's events stay in pend until stock dispatches them. + if (pend_head == pend_tail || pend_tail != pend_seen) { + pend_seen = pend_tail; + pend_age = 0; + } else if (!flash_waits() && ++pend_age > PEND_TICKS) { + give_up(); + pend_age = 0; + } + 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; + } +} + +// ---- SETTINGS > REMOTE CTRL ---------------------------------------------------- +extern void mw_link_row_label(void); +extern void core_additem(void *menu, const void *row); +extern void fw_invalidate(void *view); // the core's (fw.s): a view's redraw, a menu's at menu + 0x38 +// An integer, so the pointer comes back in d0 whatever the compiler's pointer convention. +uint32_t mw_link_row_text(void) { return (uint32_t)(armed ? "REMOTE CTRL: ON" : "REMOTE CTRL: OFF"); } + +static void COLD set_armed(void **menu, int on) +{ + if (on && !armed) { + armed = 1; + human_ticks = -1; + give_up(); // nothing the link posted before is still due + } else if (!on) + disarm(); + fw_invalidate((char *)*menu + 0x38); +} + +static void row_select(void **menu, void *item) { (void)item; set_armed(menu, !armed); } +static void row_draw(void **menu, void *item, void *bitmap, int x, int y) { (void)menu; (void)item; (void)bitmap; (void)x; (void)y; } +static void row_change(void **menu, void *item, int dir) { (void)item; if (dir) set_armed(menu, dir > 0); } + +static const void *const row[4] = { + (const void *)mw_link_row_label, (const void *)row_select, (const void *)row_draw, (const void *)row_change, +}; + +void COLD mw_link_settings(void *menu) +{ + core_additem(menu, row); +} 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..262b2f596f --- /dev/null +++ b/sdk/machines/digitone-ii/elekloader/base/link.s @@ -0,0 +1,43 @@ +| 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 + +| ---- SETTINGS > REMOTE CTRL's label: a std::function returning a std::string -------- +| The string to build is at a0; d0 returns a0. + .globl mw_link_row_label +mw_link_row_label: + link %a6, #-4 + lea -8(%sp), %sp | ColdFire's movem takes (An) only + movem.l %d2/%a2, (%sp) + move.l %a0, %d2 + jsr mw_link_row_text | d0 = the text, as an integer + movea.l %d0, %a2 + pea -1(%a6) | the allocator, unused + move.l %a2, -(%sp) + move.l %d2, -(%sp) + jsr FW_STR_NEW | stock (string, text, allocator), from the recipe + lea 12(%sp), %sp + move.l %d2, %d0 + movea.l %d2, %a0 + movem.l (%sp), %d2/%a2 + unlk %a6 + 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..a4b3596110 --- /dev/null +++ b/sdk/machines/digitone-ii/tools/dn2_link.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""The Digitone II development link's host (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) + dn2_link.py press KEY [KEY...] # press and let go, one after the other (dn2_link.py keys lists them, or an id) + dn2_link.py hold KEY / let KEY # press, or let go of, one key (FUNC + TRIG: hold FUNC, press TRIG1, let FUNC) + dn2_link.py turn ENC DELTA # an encoder (A-H, LEVEL) by DELTA detents, up to 8 a message + dn2_link.py release / disarm # let go of every key the link holds / and turn the arm off +Keys and turns need SETTINGS > REMOTE CTRL on (it is at every boot); a person at the panel stops them for about 2 s. + +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, 'disarm': 0x02, 'key': 0x10, 'enc': 0x11, 'release': 0x12, 'screen': 0x20} +STATUS = {0: 'ok', 1: 'not armed (SETTINGS > REMOTE CTRL)', 2: 'bad request', 3: 'busy', 4: 'out of range', + 5: 'a person is at the unit', 6: 'an OS upload waits at UPGRADE OS NOW?: confirm it at the unit'} +# Panel key ids and encoders as stock's messages carry them (OS 1.12, seen on a unit). +KEYS = {'TRIGPAGE': 0x01, 'SYN': 0x02, 'FLTR': 0x03, 'AMP': 0x04, 'FX': 0x05, 'MOD': 0x06, 'PERFORM': 0x07, + 'SAVEPROJ': 0x08, 'TAPTEMPO': 0x09, 'UNISON': 0x32, 'YES': 0x0a, 'UP': 0x0b, 'NO': 0x0c, 'LEFT': 0x0d, 'DOWN': 0x0e, 'RIGHT': 0x0f, 'TRK': 0x10, 'FUNC': 0x11, + 'KBSETUP': 0x12, 'REC': 0x13, 'PLAY': 0x14, 'STOP': 0x15, 'PAGE': 0x16, 'PTN': 0x17, 'SONG': 0x18, + 'ARP': 0x33, 'TRANSPOSE+': 0x34, 'NOTEEDIT': 0x35, 'TRANSPOSE-': 0x36, + **{'TRIG%d' % (i + 1): 0x19 + i for i in range(16)}} +# Not pressed alone on a unit: an encoder's push, which stock reads as is_key_held(encoder + 40) when a turn arrives. +KEYS.update({'PUSH' + name: number + 40 for name, number in {**{chr(ord('A') + i): i + 1 for i in range(8)}, 'LEVEL': 9}.items()}) +ENCODERS = {**{chr(ord('A') + i): i + 1 for i in range(8)}, 'LEVEL': 9} +DOWN, RELEASE = 0x01, 0x10 + + +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. No request names an address. +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 ok(name, *values, port): + _, _, status, p = ask(name, *values, port=port) + if status: + sys.exit('%s: %s' % (name, STATUS.get(status, str(status)))) + return p + + +def key_id(name): + return KEYS[name.upper()] if name.upper() in KEYS else int(name, 0) + + +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') + for name in ('press', 'hold', 'let'): + sub.add_parser(name).add_argument('keys', nargs='+') + turn = sub.add_parser('turn') + turn.add_argument('enc') + turn.add_argument('delta', type=int) + sub.add_parser('release') + sub.add_parser('disarm') + sub.add_parser('keys') + 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 + if a.cmd == 'keys': + print(' '.join(sorted(KEYS, key=KEYS.get)) + '; encoders ' + ' '.join(ENCODERS)) + return + if a.cmd in ('press', 'hold', 'let'): + for name in a.keys: + if a.cmd != 'let': + ok('key', key_id(name), DOWN, port=a.port) + if a.cmd != 'hold': + time.sleep(0.08) + ok('key', key_id(name), RELEASE, port=a.port) + time.sleep(0.15) + return + if a.cmd == 'turn': + enc = ENCODERS[a.enc.upper()] if a.enc.upper() in ENCODERS else int(a.enc, 0) + left = a.delta # in turns of up to 8, as the panel sends a fast turn (it went to 11) + while left: + step = max(-8, min(8, left)) + ok('enc', enc, step & 0xffffffff, port=a.port) + left -= step + time.sleep(0.06) + return + if a.cmd in ('release', 'disarm'): + ok(a.cmd, port=a.port) + return + if a.cmd == 'ident': + _, _, status, p = ask('ident', port=a.port) + if status: + sys.exit('refused: ' + STATUS.get(status, str(status))) + v = [get32(p, 5 * i) for i in range(len(p) // 5)] + line = 'link %d, received %d, dropped %d, ticks %d' % tuple(v[:4]) + if len(v) >= 9: + line += ', armed %d, person %d, presses by a person %d, posted %d, refused %d' % tuple(v[4:9]) + print(line) + + +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..edca42af26 --- /dev/null +++ b/sdk/tests/dn2_link_host.c @@ -0,0 +1,373 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// The Digitone II link (base/link.c) on the host, with stock's sysex_send, queue, key tables, upload buffer 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 int queue_obj; +static void *stub_ui_queue(void) { return &queue_obj; } +struct posted { int32_t kind, id, value; }; +static struct posted posted[256]; +static int posted_count_host; +static void stub_queue_post(void *q, const void *msg) +{ + const int32_t *m = msg; + (void)q; + posted[posted_count_host++ % 256] = (struct posted){ m[0] >> 24, m[1], m[2] }; +} +static int32_t key_index[111]; +static uint8_t key_bits[16]; +static uint8_t usb_state, upload[64]; + +#define SYSEX_SEND_AT ((uintptr_t)stub_sysex_send) +#define USB_SYSEX_STATE_AT ((uintptr_t)&usb_state) +#define UI_QUEUE_AT ((uintptr_t)stub_ui_queue) +#define QUEUE_POST_AT ((uintptr_t)stub_queue_post) +#define KEY_INDEX_AT ((uintptr_t)key_index) +#define KEY_BITS_AT ((uintptr_t)key_bits) +#define UPLOAD_AT ((uintptr_t)upload) +// "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 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" + +void mw_link_row_label(void) {} +void core_additem(void *menu, const void *r) { (void)menu; (void)r; } +void fw_invalidate(void *view) { (void)view; } + +static int failed; +#define CHECK(c) do { if (!(c)) { printf("failed at line %d: %s\n", __LINE__, #c); failed = 1; } } while (0) + +#define PANEL_YES 10 // the YES key (the SDK guide's key codes) +static int presses_of(int key) +{ + int i, n = 0; + for (i = 0; i < posted_count_host; i++) + n += posted[i].kind == MSG_KEY && posted[i].id == key && posted[i].value == KEY_DOWN; + return n; +} + +static int releases_of(int key) +{ + int i, n = 0; + for (i = 0; i < posted_count_host; i++) + n += posted[i].kind == MSG_KEY && posted[i].id == key && posted[i].value == KEY_RELEASE; + return n; +} + +static int request(int cmd, uint32_t id, uint32_t v) // the link's reply status +{ + uint8_t m[32] = { 0xF0, 0x7D, 'M', 'W', 'L', LINK_VERSION, 1, (uint8_t)cmd }; + uint8_t *p = m + HEADER; + int i; + for (i = 0; i < 5; i++) + *p++ = (uint8_t)((id >> (7 * i)) & 0x7f); + for (i = 0; i < 5; i++) + *p++ = (uint8_t)((v >> (7 * i)) & 0x7f); + *p++ = 0xF7; + act(m, (int)(p - m)); + return last_reply[8]; +} + +// ---- what a client can read: the link's counters and the screen, nothing at an address it names ---- +static int ask1(int cmd, int words, uint32_t a) // a request with no value or one; -> its status +{ + uint8_t m[32] = { 0xF0, 0x7D, 'M', 'W', 'L', LINK_VERSION, 3, (uint8_t)cmd }; + uint8_t *p = m + HEADER; + if (words > 0) + p = put32(p, a); + *p++ = 0xF7; + act(m, (int)(p - m)); + return last_reply[8]; +} + +static void unpack_reply(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)); +} + +static int part_fits(uint32_t off, uint32_t *number, uint8_t *out) // OFF, the copy's number, 128 packed bytes, F7 +{ + int expected = HEADER + 1 + 5 + 5 + SCREEN_PART + (SCREEN_PART + 6) / 7 + 1; + if (last_len != expected || last_reply[last_len - 1] != 0xF7 || get32(last_reply + 9) != off) + return 0; + *number = get32(last_reply + 14); + unpack_reply(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(ask1(CMD_IDENT, 0, 0) == ST_OK); // and the link answers as before +} + +static void screen_checks(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); + 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); + + CHECK(ask1(CMD_SCREEN, 1, 128) == ST_RANGE && last_len == HEADER + 2); // no copy yet + CHECK(ask1(CMD_SCREEN, 1, 0) == ST_OK && part_fits(0, &number, got) && number == 1); + for (i = 0; i < FRAME_BYTES; i++) + frame_pointers[1][i] ^= 0xFF; // stock draws between the parts + for (off = SCREEN_PART; off < FRAME_BYTES; off += SCREEN_PART) + CHECK(ask1(CMD_SCREEN, 1, off) == ST_OK && part_fits(off, &n2, got + off) && n2 == number); + for (i = 0; i < FRAME_BYTES; i++) + CHECK(got[i] == (uint8_t)(i * 7 + 1)); // one frame, not torn + CHECK(ask1(CMD_SCREEN, 1, 0) == ST_OK && part_fits(0, &n2, part) && n2 == 2 && part[0] == (uint8_t)(1 ^ 0xFF)); + { + 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(ask1(CMD_SCREEN, 1, bad[i]) == ST_RANGE && last_len == HEADER + 2); + } + CHECK(ask1(CMD_SCREEN, 0, 0) == ST_BAD); + frame_pointers[1] = outside; // a pointer not wholly in DDR is never read + CHECK(ask1(CMD_SCREEN, 1, 0) == ST_RANGE); + frame_pointers[1] = ddr + sizeof ddr - FRAME_BYTES + 1; + CHECK(ask1(CMD_SCREEN, 1, 0) == ST_RANGE); + frame_pointers[1] = 0; + CHECK(ask1(CMD_SCREEN, 1, 0) == ST_RANGE); + CHECK(ask1(CMD_SCREEN, 1, SCREEN_PART) == ST_OK && part_fits(SCREEN_PART, &n2, part) && n2 == 2); + + // The old mem, and every command the link does not have: refused with nothing but the status. + { + 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, addrs[i], 16) == ST_BAD && last_len == HEADER + 2); + for (i = 0; i < 0x40; i++) + if (i != CMD_IDENT && i != CMD_SCREEN && i != CMD_DISARM && i != CMD_KEY && i != CMD_ENC && i != CMD_RELEASE_ALL) + CHECK(request(i, 0x40000000, 128) == ST_BAD && last_len == HEADER + 2); + } + { + 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); + } +} + +static int ui_sees_key(int key, int flags) // stock's loop passes a posted key to ev_key; 1: taken, stock never sees it +{ + char event[20] = { 0 }; + memcpy(event + 12, &key, 4); + memcpy(event + 16, &flags, 4); + return mw_link_key(0, event); +} + +static int ui_sees_enc(int enc) +{ + char event[20] = { 0 }; + memcpy(event + 12, &enc, 4); + return mw_link_enc(0, event); +} + +int main(void) +{ + int i; + for (i = 0; i < 111; i++) + key_index[i] = i < 100 ? i : -1; + + screen_checks(); + + // Disarm with a held key and a full queue: the release waits, then arrives once when there is room. + CHECK(request(CMD_KEY, 5, KEY_DOWN) == ST_OK); + ui_sees_key(5, KEY_DOWN); + while (post(MSG_ENC, 1, 1)) + ; // the UI loop is behind: the queue is full + disarm(); + CHECK(releases_of(5) == 0); + CHECK(mw_link_held(5)); // stock still sees the key the link pressed + CHECK(request(CMD_KEY, 6, KEY_DOWN) == ST_NOT_ARMED); // and no new press is taken + mw_link_tick(); + CHECK(releases_of(5) == 0); // still no room + for (i = 0; i < PENDING; i++) + ui_sees_enc(1); // the loop catches up + mw_link_tick(); + CHECK(releases_of(5) == 1); + CHECK(!mw_link_held(5)); + mw_link_tick(); + mw_link_tick(); + CHECK(releases_of(5) == 1); // once + + // Disarm with room: the release goes at once, as before. + set_armed((void **)&(void *){ upload }, 1); + CHECK(request(CMD_KEY, 7, KEY_DOWN) == ST_OK); + ui_sees_key(7, KEY_DOWN); + disarm(); + CHECK(releases_of(7) == 1 && !mw_link_held(7)); + + // An OS upload waits at UPGRADE OS NOW?: no remote key, encoder or hold until a person confirms. + set_armed((void **)&(void *){ upload }, 1); + CHECK(request(CMD_KEY, 9, KEY_DOWN) == ST_OK); // held before the upload completes + ui_sees_key(9, KEY_DOWN); + upload[0] = 3; + CHECK(!mw_link_held(9)); // stock's is_key_held no longer sees it + CHECK(request(CMD_KEY, KEY_INDEX[10] >= 0 ? 10 : 9, KEY_DOWN) == ST_FLASH); + CHECK(request(CMD_ENC, 1, 1) == ST_FLASH); + CHECK(request(CMD_RELEASE_ALL, 0, 0) == ST_OK); // letting go stays allowed + CHECK(releases_of(9) == 1); + CHECK(ui_sees_key(9, KEY_RELEASE) == 1); // taken: stock would answer the prompt with it + upload[0] = 0; + CHECK(request(CMD_KEY, 10, KEY_DOWN) == ST_OK); + CHECK(ui_sees_key(10, KEY_DOWN) == 0); + CHECK(request(CMD_KEY, 10, KEY_RELEASE) == ST_OK); + CHECK(ui_sees_key(10, KEY_RELEASE) == 0); + + // The upload completes while a press and a turn the link posted are still in stock's queue: they were accepted + // before the prompt, so the request's check cannot stop them. At dispatch the link takes them before stock sees + // them, a release the link posted too (stock takes a YES key-up as the answer), and a person's YES and NO always + // reach stock. + for (i = 0; i <= HUMAN_TICKS; i++) + mw_link_tick(); // past the person's interval + { + uint32_t refused = refused_count; + int yes = presses_of(PANEL_YES), key = KEY_INDEX[12] >= 0 ? 12 : 10; + CHECK(request(CMD_KEY, PANEL_YES, KEY_DOWN) == ST_OK); // queued, not yet dispatched + CHECK(request(CMD_ENC, 2, 1) == ST_OK); + CHECK(presses_of(PANEL_YES) == yes + 1); + upload[0] = 3; // UPGRADE OS NOW? opens + CHECK(ui_sees_key(PANEL_YES, KEY_DOWN) == 1); // taken: stock never sees the link's YES + CHECK(ui_sees_enc(2) == 1); + CHECK(refused_count == refused + 2); + CHECK(pend_head == pend_tail); // both popped: the next event is not mistaken for the link's + CHECK(request(CMD_RELEASE_ALL, 0, 0) == ST_OK); + CHECK(ui_sees_key(PANEL_YES, KEY_RELEASE) == 1); // the link's release is taken too + CHECK(refused_count == refused + 3); + CHECK(!mw_link_held(PANEL_YES)); + CHECK(ui_sees_key(PANEL_YES, KEY_DOWN) == 0); // a person's YES: stock gets it + CHECK(ui_sees_key(PANEL_YES, KEY_RELEASE) == 0); + CHECK(request(CMD_KEY, key, KEY_DOWN) != ST_OK); // the link presses nothing at the prompt + CHECK(ui_sees_key(key, KEY_DOWN) == 0); // a person's NO (any key): stock gets it + upload[0] = 0; + } + + // Late: stock dispatches the link's YES long after it was posted. Whether the prompt opened before the lag (pend + // keeps it while UPGRADE OS NOW? waits) or during it (pend gave it up into lost), it never reaches the prompt, + // and a person's YES still does. Timing is not what decides. + { + uint32_t refused; + int lag; + for (lag = 0; lag < 2; lag++) { + for (i = 0; i <= HUMAN_TICKS; i++) + mw_link_tick(); // past the person's interval + refused = refused_count; + CHECK(request(CMD_KEY, PANEL_YES, KEY_DOWN) == ST_OK); // queued, not yet dispatched + if (lag) + for (i = 0; i < 10 * PEND_TICKS; i++) + mw_link_tick(); // given up before the prompt opens + upload[0] = 3; // UPGRADE OS NOW? opens + for (i = 0; i < 10 * PEND_TICKS; i++) + mw_link_tick(); // and stock still lags + CHECK(request(CMD_RELEASE_ALL, 0, 0) == ST_OK); + CHECK(ui_sees_key(PANEL_YES, KEY_DOWN) == 1); // the link's YES: held back + CHECK(ui_sees_key(PANEL_YES, KEY_RELEASE) == 1); // and its release + CHECK(refused_count == refused + 2); + CHECK(ui_sees_key(PANEL_YES, KEY_DOWN) == 0); // a person's YES: stock gets it + CHECK(ui_sees_key(PANEL_YES, KEY_RELEASE) == 0); + upload[0] = 0; + } + // A turn the link gave up, dispatched at the prompt: held back too. + for (i = 0; i <= HUMAN_TICKS; i++) + mw_link_tick(); + refused = refused_count; + CHECK(request(CMD_ENC, 3, 1) == ST_OK); + for (i = 0; i < 10 * PEND_TICKS; i++) + mw_link_tick(); + upload[0] = 3; + CHECK(ui_sees_enc(3) == 1 && refused_count == refused + 1); + CHECK(ui_sees_enc(3) == 0); // a person's turn reaches stock + upload[0] = 0; + } + + // A person's press while the link holds a key: taken (it lets the link's keys go) outside the prompt, passed + // through at the prompt, where it is the person's answer. + for (i = 0; i <= HUMAN_TICKS; i++) + mw_link_tick(); + CHECK(request(CMD_KEY, 9, KEY_DOWN) == ST_OK); + CHECK(ui_sees_key(9, KEY_DOWN) == 0); + upload[0] = 3; + CHECK(ui_sees_key(PANEL_YES, KEY_DOWN) == 0); + CHECK(!mw_link_held(9)); + upload[0] = 0; + + 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..9f836e6715 --- /dev/null +++ b/sdk/tests/test_dn2_link.py @@ -0,0 +1,178 @@ +"""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", "disarm", "key", "enc", "release"}) + + 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)) + + +class Dn2Keys(unittest.TestCase): + def test_key_and_encoder_names_are_the_panels_ids(self): + self.assertEqual([link.key_id(n) for n in ("FUNC", "play", "TRIG1", "TRIG16", "0x30")], [0x11, 0x14, 0x19, 0x28, 0x30]) + self.assertEqual([link.ENCODERS[n] for n in ("A", "H", "LEVEL")], [1, 8, 9]) + self.assertEqual(len(set(link.KEYS.values())), len(link.KEYS)) + + def test_a_negative_turn_reaches_the_link_as_its_low_byte(self): + enc = link.request(3, "enc", 1, -8 & 0xffffffff) + self.assertEqual(link.get32(enc, 13) & 0xff, 0xF8) + self.assertTrue(all(b < 0x80 for b in enc[1:-1])) + + +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, queue, key tables, upload buffer and frame pointers + stubbed (dn2_link_host.c): ident and screen answer, the old mem and every unknown request are refused with nothing + but their status; disarm keeps releases, and a flash needs a person.""" + + 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))