From 1b0b5c6b1cbadeb5e9463d308db680d32c7ed4b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:46:23 -0300 Subject: [PATCH] SMK-37 port: the board layer (genkigenki/Felucca smk37, b67312c) on FMini-1 The SMK-37 target from github.com/genkigenki/Felucca branch smk37 (commit b67312c on Felucca 1.6.1, = hugelton/Felucca#237; the fm1-to-smk37 kit's Felucca layer), applied to FMini-1, whose firmware/hal and firmware/loader are Felucca 1.6.1's: - BOARD=smk37 / MODEL=pro|elite|mke (tools/build.py, build.sh), the SMK flash map with its protected ranges (fm1_flash_map.h), the update path and its size checks (ota.c, ldr_core.c), the SMK input HAL, LCD and pad LEDs, the owner tag of the store, installers and tests. - Conflicts resolved for FMini-1: packages fmini-1-fm1-.fwsc and fmini-1-smk37[-elite|-mke]-.fwsc; FL_JEDEC_OK keeps the UC25HQ80 (0xB36014) on the FM-1 and accepts it on the SMK too; the official V16 length stays FM-1 only; the sample slots stay gone (FMini-1 has no SAMPLE engine: the layer's eng_sample.c and editor sample hunks are not taken); main.c keeps FMini-1's UI_* hooks with the SMK calls around them. - The FM-1 build is byte-identical to 2.5.0 (app, package and loader hashes). The SMK build does not link yet: FMini-1's preset objects need places in the SMK store, and fmini_app.c's LED code is FM-1 sized. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QUF6pQ1NkTwmBC8SR8AK94 --- BUILDING.md | 11 +- SMK37.md | 82 +++++ build.sh | 5 +- firmware/hal/fm1_cc.h | 12 + firmware/hal/fm1_flash.h | 37 +- firmware/hal/fm1_flash_map.h | 115 ++++++ firmware/hal/fm1_input.h | 2 + firmware/hal/fm1_lcd_hw.h | 107 +++++- firmware/hal/smk_compat.h | 15 + firmware/hal/smk_input.h | 670 +++++++++++++++++++++++++++++++++++ firmware/loader/ldr_core.c | 15 + firmware/loader/loader.c | 15 +- firmware/src/console.c | 82 +++++ firmware/src/felucca.c | 19 + firmware/src/fm6_vbank.c | 4 + firmware/src/lcd.c | 50 ++- firmware/src/main.c | 101 +++++- firmware/src/ota.c | 25 +- firmware/src/ota_hw.c | 4 + firmware/src/panel.c | 29 +- firmware/src/project.c | 3 +- firmware/src/seq.c | 96 ++++- firmware/src/storage.c | 108 ++++++ firmware/src/storage_hw.c | 13 + firmware/src/ui_input.c | 142 +++++++- tests/install_test.py | 99 +++++- tests/ldr_test.c | 116 ++++-- tests/ota_test.c | 49 ++- tests/run_tests.sh | 24 ++ tests/smk_flash_test.c | 90 +++++ tests/smk_owner_test.c | 148 ++++++++ tests/smk_pkg_test.py | 55 +++ tools/build.py | 57 ++- tools/fm1_install.py | 98 ++++- tools/fm1pkg_make.py | 46 ++- web/emu/felucca_web.c | 3 +- web/fm1ota.js | 23 +- web/fm1pkg.js | 52 ++- web/make_site.py | 4 +- web/test_web.mjs | 28 +- 40 files changed, 2490 insertions(+), 164 deletions(-) create mode 100644 SMK37.md create mode 100644 firmware/hal/fm1_flash_map.h create mode 100644 firmware/hal/smk_compat.h create mode 100644 firmware/hal/smk_input.h create mode 100644 tests/smk_flash_test.c create mode 100644 tests/smk_owner_test.c create mode 100644 tests/smk_pkg_test.py diff --git a/BUILDING.md b/BUILDING.md index ba91fd4..b32c45c 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -74,7 +74,7 @@ Build options (environment, `0` or `1`; defaults in `firmware/src/felucca.c`, `c | `FELUCCA_UAC_48K` | 1 | `0`: the USB audio input at 44.1 kHz only, as up to 1.0.5.2 (`firmware/src/usb.c`) | | `FELUCCA_UAC_AS_FIRST` | 1 | the audio control header lists the audio streaming interface before the MIDI one, so the USB audio driver of older macOS (up to 15) finds it; `0`: 1.0 to 1.5's order, byte for byte (`firmware/src/usb.c`) | | `FELUCCA_CPU2` | 1 | the second core is built in (MENU > SYSTEM > 2ND CORE, OFF by default); `0`: none of it, 1.6's one-core code and RAM (`firmware/hal/fm1_cpu1.h`, `firmware/src/fx.c`) | -| `FELUCCA_UART` | 1 | TRS MIDI IN | +| `FELUCCA_UART` | 1 (SMK-37 Pro: 0) | TRS MIDI IN; must stay 0 on the SMK-37 Pro (PH8 is a key row there) | | `FELUCCA_SLICE` | 1 | the SLICE engine | | `FELUCCA_ICONS` | 1 | parameter icons on the knob cards | | `FELUCCA_FM4` | 0 | the retired DIGITAL engine (4-operator FM) instead of its FM6 conversion | @@ -82,6 +82,15 @@ Build options (environment, `0` or `1`; defaults in `firmware/src/felucca.c`, `c `FELUCCA_USB_LAYOUT` (`0` to `3`, default `0`) picks other USB descriptor layouts for testing; see `firmware/src/usb.c`. +Target board: `BOARD=smk37 ./build.sh` (or `./build.sh --board smk37`) builds FMini-1 for the +M-Vave SMK-37 (beta): `-DBOARD_SMK37=1` for the app and the update loader, identity `SMK-37 Pro_900` (release +`SMK-37 Pro_9XY`), the SMK flash layout (PRCT 0x9D000, the stock region table with USRTRIM / USRFLASH) and the +package `build/fmini-1-smk37-.fwsc`. `MODEL=elite` or `MODEL=mke` builds the same firmware under the SMK-37 +Elite's or the MKE-P37's model name (`build/fmini-1-smk37-elite-.fwsc`, `build/fmini-1-smk37-mke-.fwsc`), +so the stock updater still takes that unit's factory package. Controls: [SMK37.md](SMK37.md). The intermediate files +(`build/loader/ota.bin`, `build/felucca.dis`, `build/gen`) are shared: build the FM-1 again before `tests/run_tests.sh`. +The default stays the FM-1, byte for byte. + ## Browser emulator ``` diff --git a/SMK37.md b/SMK37.md new file mode 100644 index 0000000..d06878b --- /dev/null +++ b/SMK37.md @@ -0,0 +1,82 @@ +# Felucca on the SMK-37 (beta) + +Felucca also builds for the SMK-37, a 37-key controller with the same chip as the FM-1. The FM-1 build +is unchanged; everything for the SMK-37 is behind `BOARD_SMK37`. + +## Supported models + +- **SMK-37 Pro**: the default build (package identity `SMK-37 Pro_900`). +- **SMK-37 Elite**: `MODEL=elite` (identity `SMK-37 Elite_900`). +- **MKE-P37**: `MODEL=mke` (identity `MKE-P37_900`). + +All of them are the same hardware. Each build carries its model's name, so the stock updater still takes that +unit's stock package later: install the package for your model. The installers take a package only for exactly +the connected model (an Elite package is refused on a Pro, an FM-1 package on any SMK, an SMK package on an FM-1); +the unit's own stock package is the same model, so the way back to stock is always open. + +## Controls + +The FM-1's manual still applies; the SMK-37's controls map onto the FM-1's like this. + +| SMK-37 | Felucca | +| --- | --- | +| Keys F3..G5 (the middle 27) | the FM-1's 27 keys, with velocity | +| Keys C3..E3 and G#5..C6 (the outer 10) | more notes for the selected track (its key map, scale and octave), one note each, with velocity | +| 16 pads | the 16 white keys F3..G5, with velocity, low notes on the bottom row; where the keys are a grid (the DRUM grid, NAME, the layers) steps 1-8 are the top row and 9-16 the bottom row. Lit in the theme colour | +| K1 | MASTER (volume) | +| K2 / K3 / K4 | SELECT / ALGORITHM / PRESETS | +| K5..K8 | KNOB 1..4 | +| FX, SCALE, CHORD, NOTE REPEAT, PARA, GLOBE | FX, SCL, ENV, LFO, EDIT, GLO | +| PATCH / BT | HOME / SAVE | +| ARP / SEQ | ARP / SEQ | +| SEQ PLAY / SEQ REC | PLAY / REC | +| OCTAVE- / OCTAVE+ | OCT- / OCT+ | +| KNOB BANK | as HOME held: opens or closes the menu (lit while the menu is open) | +| < / > | the previous / next page of the current page group; in the menu, the previous / next row; on HOME, > is HOME tapped | +| FADER BANK | what the faders set for tracks 1..4: A LEVEL, B PAN, C REV send, D DLY send (lit off bank A) | +| Faders 1..4 | tracks 1..4 in the current bank; a fader takes over only once it moves | +| Pitch wheel | pitch bend of the selected track (its MIDI channel's bend range, 2 semitones unless set); also sent as MIDI | +| Mod wheel | the selected track's mod wheel (CC1, the MOD matrix's MODW source); also sent as MIDI | +| OCTAVE- + OCTAVE+ held at power-on | HARDWARE CALIBRATION: teach the buttons and knobs again | + +The SMK-37's TRS jack is a MIDI output and this build does not use it; there is no TRS MIDI IN. MIDI works over USB. + +## Build + +See [BUILDING.md](BUILDING.md) for the toolchain. + +```sh +BOARD=smk37 ./build.sh # build/felucca-smk37.fwsc (SMK-37 Pro) +BOARD=smk37 MODEL=elite ./build.sh # build/felucca-smk37-elite.fwsc +BOARD=smk37 MODEL=mke ./build.sh # build/felucca-smk37-mke.fwsc +./build.sh # the FM-1 build again before tests/run_tests.sh (the tests use its files) +``` + +## Install + +Connect the keyboard by USB and run, with the package for your model: + +```sh +python3 tools/fm1_install.py build/felucca-smk37.fwsc +``` + +`fm1_install.py` needs `mido` and `python-rtmidi` (`pip3 install mido python-rtmidi`). It checks that the package +is for the connected model. + +## Going back to the stock firmware + +Install the manufacturer's firmware package for your model with the manufacturer's updater. It works directly, because +the installed package keeps the keyboard's model name. `tools/fm1_install.py` can also install the stock SMK-37 Pro +V016 package. + +## Safety + +- Back up first: have the stock package for your model and the manufacturer's updater ready before you install. +- Keep the USB cable connected until the install has finished and the keyboard has restarted. +- The first start clears the stock firmware's settings, and any other firmware's data, in the shared data area. +- The stock firmware's key, knob and fader mapping (in the user sample area) is kept intact. Before the first + sample is written there, Felucca releases the stock firmware's marker for that area, so after going back to + stock the stock firmware rebuilds its factory mapping instead of reading erased data. +- The firmware never writes the keyboard's calibration, Bluetooth pairing or key areas; the flash map refuses + them at compile time and again in the flash driver. +- Installing other firmware is at your own risk. diff --git a/build.sh b/build.sh index 7a469cd..6a292d5 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,9 @@ # SPDX-License-Identifier: GPL-3.0-only # Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments # Build Felucca on macOS (see BUILDING.md). -# ./build.sh [--release X.Y] +# ./build.sh [--release X.Y] [--board fm1|smk37] +# BOARD target board: fm1 (default) or smk37 (SMK-37 -> build/felucca-smk37.fwsc) +# MODEL smk37: pro (default), elite or mke: the model name the keyboard reports # JIELI_TOOLCHAIN JieLi Linux toolchain (default: ~/.jieli/toolchain) # AC79_SDK JieLi AC79 SDK checkout (default: ~/fw-AC79_AIoT_SDK) set -e @@ -17,5 +19,6 @@ PY="${PYTHON:-python3}" if [ "$(uname -s)" != Linux ] || [ "$(uname -m)" != x86_64 ]; then docker info >/dev/null 2>&1 || { echo "build.sh: Docker is not running"; exit 1; } fi +export BOARD="${BOARD:-fm1}" # read by tools/build.py (--board overrides it) exec "$PY" tools/build.py "$@" diff --git a/firmware/hal/fm1_cc.h b/firmware/hal/fm1_cc.h index 948e81d..0852710 100644 --- a/firmware/hal/fm1_cc.h +++ b/firmware/hal/fm1_cc.h @@ -8,3 +8,15 @@ #pragma once #define FM1_INLINE static inline __attribute__((always_inline)) + +/* Target board: 0 = FM-1 (default), 1 = SMK-37 Pro (same AC791N, SPL and update loader; different + * panel wiring). build.py sets it from BOARD=smk37. */ +#ifndef BOARD_SMK37 +#define BOARD_SMK37 0 +#endif +/* SMK_MODEL: the model name the SMK build reports (its identity, its update loader's): the SMK-37 Pro, + * SMK-37 Elite and MKE-P37 are the same keyboard under three names, and the stock updater only takes a + * unit's own factory package. build.py sets it from MODEL=elite / mke. */ +#if BOARD_SMK37 && !defined(SMK_MODEL) +#define SMK_MODEL "SMK-37 Pro" +#endif diff --git a/firmware/hal/fm1_flash.h b/firmware/hal/fm1_flash.h index f4be4be..a3a7b93 100644 --- a/firmware/hal/fm1_flash.h +++ b/firmware/hal/fm1_flash.h @@ -35,28 +35,7 @@ static inline void *fl_far(void *p) { void *volatile q = p; return q; } #define T4_CNT REG32(0x10804u) /* TIMER4, 24 MHz free-running */ #define FL_XIP(off) FM1_XIP(off) /* fm1_xip.h */ -#define FL_DATA_LO 0x00097000u /* Felucca main store */ -#define FL_DATA_HI 0x000E0000u -#define FL_GLOB_LO 0x000FC000u /* Felucca superblock / globals */ -#define FL_GLOB_HI 0x000FF000u -#define FL_OTA_LO 0x000E0000u /* M-UPGRADE loader staging, ota.c */ -#define FL_OTA_HI 0x000E5000u -#define FL_AUTO_LO 0x000E5000u /* 1.2: the autosave (storage.c OBJ_AUTOSAVE), A/B, just above */ -#define FL_AUTO_HI 0x000E7000u /* the OTA staging */ -#define FL_VBANK_LO 0x000E7000u /* 1.4.1: the FM6 voice bank (fm6_vbank.c), the sector above */ -#define FL_VBANK_HI 0x000E8000u /* (below the stock OTA's VM backup, 0xE8000: never written) */ -/* [off, off + n) inside [lo, hi), without wrapping: off + n can overflow, and - * the 1 MiB part ignores the high address bits, so a wrapped range lands low. */ -#define FL_IN(off, n, lo, hi) ((uint32_t)(off) >= (lo) && (uint32_t)(off) <= (hi) && \ - (uint32_t)(n) <= (hi) - (uint32_t)(off)) -/* Felucca's own store (projects, user samples; settings; the autosave and the FM6 voice bank: one range) */ -#define FL_STORE_OK(off, n) (FL_IN(off, n, FL_DATA_LO, FL_DATA_HI) || FL_IN(off, n, FL_GLOB_LO, FL_GLOB_HI) || \ - FL_IN(off, n, FL_AUTO_LO, FL_VBANK_HI)) -/* Where the RAM driver may erase / program. The app build allows only its own - * data regions; the update loader (firmware/loader) defines its own window. */ -#ifndef FL_RANGE_OK -#define FL_RANGE_OK(off, n) (FL_STORE_OK(off, n) || FL_IN(off, n, FL_OTA_LO, FL_OTA_HI)) -#endif +#include "fm1_flash_map.h" /* FL_IN, FL_STORE_OK, FL_RANGE_OK, FL_GUARD, FL_JEDEC_OK; per board */ typedef struct { uint32_t sfc_con, spi_con; } fl_saved_t; @@ -148,11 +127,7 @@ RAMINL int fl_wait_ready(uint32_t max_us, uint32_t *took_us) /* ---- entry points: IRQs OFF, args/buffers in RAM ---- */ -/* the 1 MiB parts the FM-1 ships with: Puya P25Q80 (0x856014) and UC25HQ80 (0xB36014, AliExpress units). - * Same size, same plain SPI NOR commands. */ -#define FL_JEDEC_OK(id) ((id) == 0x856014u || (id) == 0xB36014u) - -static RAMFN uint32_t fl_jedec_ram(void) /* expect 0x856014 or 0xB36014 (FL_JEDEC_OK) */ +static RAMFN uint32_t fl_jedec_ram(void) /* expect 0x856014 or 0xB36014 (FL_JEDEC_OK, fm1_flash_map.h) */ { fl_saved_t s; uint32_t id; if (fl_enter(&s)) return 0; @@ -175,7 +150,7 @@ static RAMFN uint32_t fl_status_ram(void) /* SR1 | SR2 << 8 */ static RAMFN int fl_erase4k_ram(uint32_t off, uint32_t *took_us) { fl_saved_t s; int rc; - if (!FL_RANGE_OK(off, 0x1000u) || (off & 0xFFFu)) + if (!FL_GUARD(off, 0x1000u) || (off & 0xFFFu)) return -1; if (fl_enter(&s)) return -2; fl_wren(); @@ -192,7 +167,7 @@ static RAMFN int fl_erase4k_ram(uint32_t off, uint32_t *took_us) static RAMFN int fl_prog_ram(uint32_t off, const uint8_t *src, uint32_t n, uint32_t *took_us) { fl_saved_t s; int rc; uint32_t i; - if (!FL_RANGE_OK(off, n) || + if (!FL_GUARD(off, n) || n == 0 || n > 256u || ((off & 0xFFu) + n) > 256u) return -1; /* one page, no wrap */ if (fl_enter(&s)) return -2; fl_wren(); @@ -226,11 +201,11 @@ static RAMFN int fl_read_ram(uint32_t off, uint8_t *dst, uint32_t n) /* 0x0B f static void fl_plain_window_init(void) { SFCENC_CON &= (uint8_t)~2u; - SFCENC_UNENC_L = FL_XIP(0x93000u); /* 0x0208F000 */ + SFCENC_UNENC_L = FL_XIP(FL_PLAIN_LO); /* FM-1 0x0208F000 (0x93000); SMK 0x02099000 (0x9D000) */ SFCENC_UNENC_H = 0x07FFFFFFu; SFCENC_CON |= 2u; __asm__ volatile("cli" ::: "memory"); - fl_inval(0x93000u, 0x100000u - 0x93000u); /* drop any decrypted lines */ + fl_inval(FL_PLAIN_LO, 0x100000u - FL_PLAIN_LO); /* drop any decrypted lines */ __asm__ volatile("csync\n\tsti" ::: "memory"); } diff --git a/firmware/hal/fm1_flash_map.h b/firmware/hal/fm1_flash_map.h new file mode 100644 index 0000000..cf73725 --- /dev/null +++ b/firmware/hal/fm1_flash_map.h @@ -0,0 +1,115 @@ +/* SPDX-License-Identifier: GPL-3.0-only + * Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments */ +/* The flash map: which ranges the RAM flash driver (fm1_flash.h) may erase / program, per board + * (BOARD_SMK37, fm1_cc.h). Macros and compile-time checks only, so host tests can include it. */ +#pragma once +#include +#include "fm1_cc.h" + +/* [off, off + n) inside [lo, hi), without wrapping: off + n can overflow, and + * the 1 MiB part ignores the high address bits, so a wrapped range lands low. */ +#define FL_IN(off, n, lo, hi) ((uint32_t)(off) >= (lo) && (uint32_t)(off) <= (hi) && \ + (uint32_t)(n) <= (hi) - (uint32_t)(off)) +/* The flash chip Felucca's storage accepts (JEDEC id from 0x9F, project.c); extend it here for another part. */ +#if BOARD_SMK37 +/* SMK-37 Pro: 0xEB6014, 1 MiB, read from a unit over mask-ROM UBOOT (2026-10-09; jl-uboot-tool "Online device: + * ID: 0xeb6014"). The driver uses only generic SPI NOR commands (9F, 05/35, 06, 20, 02, 0B). */ +#define FL_JEDEC_OK(id) ((id) == 0xEB6014u || (id) == 0x856014u || (id) == 0xB36014u) +#else +/* FM-1: the Puya P25Q80 (0x856014); newer units (mostly AliExpress) carry a UC25HQ80 (0xB36014): same size, the same + * plain SPI NOR commands (FMini-1 2.5.0) */ +#define FL_JEDEC_OK(id) ((id) == 0x856014u || (id) == 0xB36014u) +#endif + +#if BOARD_SMK37 +/* ---- SMK-37 Pro flash map (hardware notes: https://github.com/genkigenki/fm1-to-smk37) ---- + * 0x00000-0x03FFF head (SPL, isd_config) NEVER + * 0x04000-0x9CFFF app area (stock PRCT end) update loader only (FL_APP) + * 0x9D000-0xBAFFF VM: Felucca store (projects, user presets, autosave, FM6 patches, settings, + * owner tag 0xAF000, FM6 voice bank 0xB0000; storage.c) FL_DATA + * 0xBB000-0xBFFFF VM: M-UPGRADE loader staging + update record (ota.c) FL_OTA + * 0xC0000-0xC0FFF BTIF (BT pairing) NEVER + * 0xC1000-0xC1FFF USRTRIM (key/pad/wheel calibration, "trimdat") NEVER + * 0xC2000-0xE9FFF USRFLASH: user sample slots USR1, USR2 (2 x 80 KiB) FL_SMP + * (the stock mapping until a sample is first loaded there) + * 0xEA000-0xEAFFF USRFLASH tail: the stock end marker "usrdata" at 0xEAFF8; erased once before the first + * write into FL_SMP (FL_STOCKTAG) + * 0xEB000-0xF3FFF free (unlisted), unused + * 0xF4000-0xFDFFF USR (stock resources; kept for a rollback) NEVER + * 0xFE000-0xFEFFF free, unused + * 0xFF000-0xFFFFF key_mac NEVER + * Everything below is an explicit allow-list; the asserts keep each allowed window out of the + * protected ranges at compile time. */ +#define FL_HEAD_HI 0x00004000u /* protected: [0, FL_HEAD_HI) */ +#define FL_CAL_LO 0x000C0000u /* protected: BTIF + USRTRIM */ +#define FL_CAL_HI 0x000C2000u +#define FL_USRRES_LO 0x000F4000u /* protected: stock USR resources */ +#define FL_USRRES_HI 0x000FE000u +#define FL_KEYMAC_LO 0x000FF000u /* protected: key_mac and above */ +#define FL_APP_LO 0x00004000u /* the update loader: app area */ +#define FL_APP_HI 0x0009D000u +#define FL_REC_LO 0x0009D000u /* the update loader: where it may drop records (VM only) */ +#define FL_REC_HI 0x000C0000u +#define FL_PLAIN_LO 0x0009D000u /* plain XIP window from the VM start */ +#define FL_DATA_LO 0x0009D000u /* Felucca store */ +#define FL_DATA_HI 0x000BB000u +#define FL_OTA_LO 0x000BB000u /* M-UPGRADE loader staging, ota.c */ +#define FL_OTA_HI 0x000C0000u +#define FL_SMP_LO 0x000C2000u /* user sample slots (eng_sample.c) */ +#define FL_SMP_HI 0x000EA000u +/* USRFLASH is the stock firmware's mapping (global settings 0xC2000, 8 presets from 0xC3000) with its end marker + * "usrdata\0" at 0xEAFF8: while the marker is there the stock firmware trusts the area and never rebuilds it. + * Before the first write into USRFLASH the marker sector is erased (storage.c st_stock_release), so a return to + * stock rebuilds the factory mapping. Exactly that one sector, nothing else above FL_SMP_HI. */ +#define FL_STOCKTAG_LO 0x000EA000u +#define FL_STOCKTAG_HI 0x000EB000u +#define FL_STOCKTAG_OFF 0x000EAFF8u +#define FL_STOCKTAG_OK(off, n) ((uint32_t)(off) == FL_STOCKTAG_LO && (uint32_t)(n) == FL_STOCKTAG_HI - FL_STOCKTAG_LO) +/* a window [lo, hi) is allowed: sector aligned, non-empty, and clear of every protected range */ +#define FL_WIN_SAFE(lo, hi) ((lo) % 0x1000u == 0u && (hi) % 0x1000u == 0u && (lo) < (hi) && \ + (lo) >= FL_HEAD_HI && (hi) <= FL_KEYMAC_LO && \ + ((hi) <= FL_CAL_LO || (lo) >= FL_CAL_HI) && \ + ((hi) <= FL_USRRES_LO || (lo) >= FL_USRRES_HI)) +_Static_assert(FL_WIN_SAFE(FL_DATA_LO, FL_DATA_HI), "SMK: FL_DATA overlaps a protected range"); +_Static_assert(FL_WIN_SAFE(FL_OTA_LO, FL_OTA_HI), "SMK: FL_OTA overlaps a protected range"); +_Static_assert(FL_WIN_SAFE(FL_SMP_LO, FL_SMP_HI), "SMK: FL_SMP overlaps a protected range"); +_Static_assert(FL_WIN_SAFE(FL_STOCKTAG_LO, FL_STOCKTAG_HI) && FL_STOCKTAG_LO == FL_SMP_HI && + FL_STOCKTAG_OFF + 8u == FL_STOCKTAG_HI, "SMK: the stock marker sector"); +_Static_assert(FL_WIN_SAFE(FL_APP_LO, FL_APP_HI), "SMK: FL_APP overlaps a protected range"); +_Static_assert(FL_WIN_SAFE(FL_REC_LO, FL_REC_HI), "SMK: FL_REC overlaps a protected range"); +_Static_assert(FL_REC_HI == FL_CAL_LO && FL_OTA_HI <= FL_REC_HI && FL_OTA_LO >= FL_REC_LO, + "SMK: the update record (OTA area) must lie in the loader's record window, below BTIF"); +_Static_assert(FL_DATA_HI <= FL_OTA_LO && FL_APP_HI <= FL_DATA_LO, "SMK: windows overlap"); +/* the update loader (loader.c): the app area, and records only in the VM below BTIF */ +#define FL_LDR_RANGE_OK(off, n) (FL_IN(off, n, FL_APP_LO, FL_APP_HI) || FL_IN(off, n, FL_REC_LO, FL_REC_HI)) +/* Felucca's own store: FL_DATA and the sample slots */ +#define FL_STORE_OK(off, n) (FL_IN(off, n, FL_DATA_LO, FL_DATA_HI) || FL_IN(off, n, FL_SMP_LO, FL_SMP_HI)) +#ifndef FL_RANGE_OK +#define FL_RANGE_OK(off, n) (FL_STORE_OK(off, n) || FL_IN(off, n, FL_OTA_LO, FL_OTA_HI) || FL_STOCKTAG_OK(off, n)) +#endif +/* second, independent net in the RAM driver: [off, off + n) touches a protected range (also when a + * caller supplies its own FL_RANGE_OK, as the update loader does) */ +#define FL_HITS(off, n, lo, hi) ((uint32_t)(off) < (hi) && ((uint32_t)(off) >= (lo) || (uint32_t)(n) > (lo) - (uint32_t)(off))) +#define FL_PROTECTED(off, n) (FL_HITS(off, n, 0u, FL_HEAD_HI) || FL_HITS(off, n, FL_CAL_LO, FL_CAL_HI) || FL_HITS(off, n, FL_USRRES_LO, FL_USRRES_HI) || (uint32_t)(off) >= FL_KEYMAC_LO || (uint32_t)(n) > FL_KEYMAC_LO - (uint32_t)(off)) +#define FL_GUARD(off, n) (FL_RANGE_OK(off, n) && !FL_PROTECTED(off, n)) +#else /* FM-1 */ +#define FL_PLAIN_LO 0x00093000u /* plain XIP window from the FM-1 VM start */ +#define FL_DATA_LO 0x00097000u /* Felucca main store */ +#define FL_DATA_HI 0x000E0000u +#define FL_GLOB_LO 0x000FC000u /* Felucca superblock / globals */ +#define FL_GLOB_HI 0x000FF000u +#define FL_OTA_LO 0x000E0000u /* M-UPGRADE loader staging, ota.c */ +#define FL_OTA_HI 0x000E5000u +#define FL_AUTO_LO 0x000E5000u /* 1.2: the autosave (storage.c OBJ_AUTOSAVE), A/B, just above */ +#define FL_AUTO_HI 0x000E7000u /* the OTA staging */ +#define FL_VBANK_LO 0x000E7000u /* 1.4.1: the FM6 voice bank (fm6_vbank.c), the sector above */ +#define FL_VBANK_HI 0x000E8000u /* (below the stock OTA's VM backup, 0xE8000: never written) */ +/* Felucca's own store (projects, user samples; settings; the autosave and the FM6 voice bank: one range) */ +#define FL_STORE_OK(off, n) (FL_IN(off, n, FL_DATA_LO, FL_DATA_HI) || FL_IN(off, n, FL_GLOB_LO, FL_GLOB_HI) || FL_IN(off, n, FL_AUTO_LO, FL_VBANK_HI)) +/* Where the RAM driver may erase / program. The app build allows only its own + * data regions; the update loader (firmware/loader) defines its own window. */ +#ifndef FL_RANGE_OK +#define FL_RANGE_OK(off, n) (FL_STORE_OK(off, n) || FL_IN(off, n, FL_OTA_LO, FL_OTA_HI)) +#endif +#define FL_GUARD(off, n) FL_RANGE_OK(off, n) +#endif /* BOARD_SMK37 */ diff --git a/firmware/hal/fm1_input.h b/firmware/hal/fm1_input.h index d0a5894..c34bd3c 100644 --- a/firmware/hal/fm1_input.h +++ b/firmware/hal/fm1_input.h @@ -144,6 +144,7 @@ #define FM1_NCOL 11u #define FM1_NKEY 41u /* ids: 0..13 buttons, 14..40 note keys */ #define FM1_NENC 7u +#define FM1_NBTN 14u /* buttons: ids 0..13 */ /* key id at (physical column, packed row bit), -1 = none */ @@ -160,6 +161,7 @@ static const uint8_t FM1_ENC[FM1_NENC][4] = { {0, 0, 1, 0}, {2, 0, 3, 0}, {8, 1, 9, 1}, {8, 0, 9, 0}, {6, 0, 7, 0}, {4, 0, 5, 0}, {0, 5, 1, 5}, }; enum { FM1_BTN_OCT_DOWN = 0, FM1_BTN_OCT_UP = 1 }; +#define FM1_OCT_BOTH (1u << FM1_BTN_OCT_DOWN | 1u << FM1_BTN_OCT_UP) static volatile struct { diff --git a/firmware/hal/fm1_lcd_hw.h b/firmware/hal/fm1_lcd_hw.h index 356a2c4..eb395d3 100644 --- a/firmware/hal/fm1_lcd_hw.h +++ b/firmware/hal/fm1_lcd_hw.h @@ -1,7 +1,14 @@ /* SPDX-License-Identifier: GPL-3.0-only * Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments */ -/* FM-1 LCD wiring: SPI1 on PC9 CLK, PC10 DO, PC7 CS, - * PC8 D/C; backlight PA2, active low. The panel protocol is src/lcd.c. +/* LCD wiring, SPI1. The panel protocol is src/lcd.c. + * + * FM-1: SPI1 group B (IOMAP_CON1 bit4 = 1): PC9 CLK, PC10 DO; PC7 CS, PC8 D/C; + * backlight PA2, active low. + * SMK-37 Pro: SPI1 group A (IOMAP_CON1 bit4 = 0): PB6 CLK, PB7 DO; PC8 CS, PB5 D/C; + * no backlight control (always on). Group B (PC10) carries the 16 RGB pad + * LEDs (WS2812 class) instead: fm1_padled_send() switches SPI1 over for one + * frame while the LCD CS is high, as the stock firmware does (stock v016; + * AC79 SDK spi.h for the pin groups). * * fm1_lcd_hw_init() pins, backlight on, SPI1 master at BAUD 4 * fm1_lcd_baud(b) SPI1 clock = lsb / (b + 1) @@ -9,12 +16,21 @@ * fm1_lcd_send_data(p, n) D/C high, CS low, DMA n bytes from RAM p * fm1_lcd_wait() SPI done (or timeout, counted), pending cleared * fm1_lcd_deselect() CS high - * fm1_lcd_backlight(on) PA2 low (on) / high (off); the TIMER5 scan writes port A too: IRQs off around it + * fm1_lcd_backlight(on) FM-1: PA2 low (on) / high (off); the TIMER5 scan writes port A too: IRQs off around it. + * SMK-37 Pro: nothing (always on; PA2 is a key-matrix row there) + * SMK-37 Pro only: + * fm1_padled_send(p, n) LCD deselected and idle: SPI1 to PC10 at BAUD 8, DMA n bytes + * (then fm1_lcd_wait, then fm1_padled_done) + * fm1_padled_done() SPI1 back to the LCD pins at the LCD baud */ #pragma once #include #include "fm1_cc.h" +#define FM1_LCD_PA_OUT (*(volatile uint32_t *)0x50000u) +#define FM1_LCD_PA_DIR (*(volatile uint32_t *)0x50008u) +#define FM1_LCD_PB_OUT (*(volatile uint32_t *)0x50040u) +#define FM1_LCD_PB_DIR (*(volatile uint32_t *)0x50048u) #define FM1_LCD_PC_OUT (*(volatile uint32_t *)0x50080u) #define FM1_LCD_PC_DIR (*(volatile uint32_t *)0x50088u) #define FM1_LCD_IOMAP_CON1 (*(volatile uint32_t *)0x51020u) @@ -23,28 +39,66 @@ #define FM1_LCD_SPI_BUF (*(volatile uint32_t *)0x11D08u) #define FM1_LCD_SPI_ADR (*(volatile uint32_t *)0x11D0Cu) #define FM1_LCD_SPI_CNT (*(volatile uint32_t *)0x11D10u) -#define FM1_LCD_PA_OUT (*(volatile uint32_t *)0x50000u) -#define FM1_LCD_PA_DIR (*(volatile uint32_t *)0x50008u) -#define FM1_LCD_BL (1u << 2) -#define FM1_LCD_CS (1u << 7) -#define FM1_LCD_DC (1u << 8) -#define FM1_LCD_CLK (1u << 9) -#define FM1_LCD_DO (1u << 10) +#define FM1_LCD_GROUP_B 0x10u /* IOMAP_CON1 bit4: SPI1 on PC8/PC9/PC10 */ + +#if BOARD_SMK37 +#define FM1_LCD_CS_OUT FM1_LCD_PC_OUT +#define FM1_LCD_CS (1u << 8) /* PC8 */ +#define FM1_LCD_DC_OUT FM1_LCD_PB_OUT +#define FM1_LCD_DC (1u << 5) /* PB5 */ +#define FM1_LCD_CLK (1u << 6) /* PB6 */ +#define FM1_LCD_DO (1u << 7) /* PB7 */ +#define FM1_PADLED_DO (1u << 10) /* PC10 */ +#define FM1_PADLED_BAUD 8u /* lsb / 9 = 6.67 MHz: one SPI byte per LED bit */ +#else +#define FM1_LCD_CS_OUT FM1_LCD_PC_OUT +#define FM1_LCD_CS (1u << 7) /* PC7 */ +#define FM1_LCD_DC_OUT FM1_LCD_PC_OUT +#define FM1_LCD_DC (1u << 8) /* PC8 */ +#define FM1_LCD_CLK (1u << 9) /* PC9 */ +#define FM1_LCD_DO (1u << 10) /* PC10 */ +#define FM1_LCD_BL (1u << 2) /* PA2, active low */ +#endif static uint32_t fm1_lcd_timeouts; +#if BOARD_SMK37 +static uint8_t fm1_lcd_cur_baud = 4u; /* (fm1_padled_done restores it) */ +#endif FM1_INLINE void fm1_lcd_hw_init(void) { +#if BOARD_SMK37 + FM1_LCD_IOMAP_CON1 &= ~FM1_LCD_GROUP_B; + FM1_LCD_CS_OUT |= FM1_LCD_CS; + FM1_LCD_PC_DIR &= ~FM1_LCD_CS; + FM1_LCD_PB_OUT &= ~(FM1_LCD_DC | FM1_LCD_CLK | FM1_LCD_DO); + FM1_LCD_PB_DIR &= ~(FM1_LCD_DC | FM1_LCD_CLK | FM1_LCD_DO); + FM1_LCD_PC_OUT &= ~FM1_PADLED_DO; /* the LED line idles low (latch) */ + FM1_LCD_PC_DIR &= ~FM1_PADLED_DO; +#else FM1_LCD_PA_OUT &= ~FM1_LCD_BL; FM1_LCD_PA_DIR &= ~FM1_LCD_BL; - FM1_LCD_IOMAP_CON1 |= 0x10u; - FM1_LCD_PC_OUT |= FM1_LCD_CS; + FM1_LCD_IOMAP_CON1 |= FM1_LCD_GROUP_B; + FM1_LCD_CS_OUT |= FM1_LCD_CS; FM1_LCD_PC_OUT &= ~(FM1_LCD_DC | FM1_LCD_CLK | FM1_LCD_DO); FM1_LCD_PC_DIR &= ~(FM1_LCD_CS | FM1_LCD_DC | FM1_LCD_CLK | FM1_LCD_DO); +#endif FM1_LCD_SPI_CON = 0x4021u; FM1_LCD_SPI_BAUD = 4u; +#if BOARD_SMK37 + fm1_lcd_cur_baud = 4u; +#endif } +#if BOARD_SMK37 +FM1_INLINE void fm1_lcd_backlight(uint32_t on) { (void)on; } /* always on; never touch PA2 (a matrix row) */ + +FM1_INLINE void fm1_lcd_baud(uint32_t b) +{ + FM1_LCD_SPI_BAUD = b; + fm1_lcd_cur_baud = (uint8_t)b; +} +#else FM1_INLINE void fm1_lcd_backlight(uint32_t on) { if (on) @@ -54,6 +108,7 @@ FM1_INLINE void fm1_lcd_backlight(uint32_t on) } FM1_INLINE void fm1_lcd_baud(uint32_t b) { FM1_LCD_SPI_BAUD = b; } +#endif static void fm1_lcd_wait(void) { @@ -65,21 +120,39 @@ static void fm1_lcd_wait(void) FM1_LCD_SPI_CON |= 0x4000u; } -FM1_INLINE void fm1_lcd_deselect(void) { FM1_LCD_PC_OUT |= FM1_LCD_CS; } +FM1_INLINE void fm1_lcd_deselect(void) { FM1_LCD_CS_OUT |= FM1_LCD_CS; } FM1_INLINE void fm1_lcd_send_cmd(uint8_t c) { - FM1_LCD_PC_OUT &= ~FM1_LCD_DC; - FM1_LCD_PC_OUT &= ~FM1_LCD_CS; + FM1_LCD_DC_OUT &= ~FM1_LCD_DC; + FM1_LCD_CS_OUT &= ~FM1_LCD_CS; FM1_LCD_SPI_CON |= 0x4000u; FM1_LCD_SPI_BUF = c; } FM1_INLINE void fm1_lcd_send_data(const void *p, uint32_t n) { - FM1_LCD_PC_OUT |= FM1_LCD_DC; - FM1_LCD_PC_OUT &= ~FM1_LCD_CS; + FM1_LCD_DC_OUT |= FM1_LCD_DC; + FM1_LCD_CS_OUT &= ~FM1_LCD_CS; FM1_LCD_SPI_CON |= 0x4000u; FM1_LCD_SPI_ADR = (uint32_t)(uintptr_t)p; FM1_LCD_SPI_CNT = n; } + +#if BOARD_SMK37 +FM1_INLINE void fm1_padled_send(const void *p, uint32_t n) +{ + FM1_LCD_CS_OUT |= FM1_LCD_CS; /* the panel ignores the bus */ + FM1_LCD_SPI_BAUD = FM1_PADLED_BAUD; + FM1_LCD_IOMAP_CON1 |= FM1_LCD_GROUP_B; + FM1_LCD_SPI_CON |= 0x4000u; + FM1_LCD_SPI_ADR = (uint32_t)(uintptr_t)p; + FM1_LCD_SPI_CNT = n; +} + +FM1_INLINE void fm1_padled_done(void) +{ + FM1_LCD_IOMAP_CON1 &= ~FM1_LCD_GROUP_B; + FM1_LCD_SPI_BAUD = fm1_lcd_cur_baud; +} +#endif diff --git a/firmware/hal/smk_compat.h b/firmware/hal/smk_compat.h new file mode 100644 index 0000000..321ef28 --- /dev/null +++ b/firmware/hal/smk_compat.h @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: GPL-3.0-only + * Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments + * SMK-37 Pro port: Copyright (C) 2026 M. Geisler (genkigenki/makkuro) */ +/* SMK-37 Pro: the parts of Felucca's FM-1 LED API (fm1_input.h, fm1_led_anim.h) the SMK has no hardware for: the + * glow level, the power-on sweep and the idle animation (the SMK's button LEDs are on / off; ui_input.c smk_leds + * draws the pads). No-ops, so the UI code stays as it is. Included after smk_input.h. */ +#pragma once +#include + +static void fm1_led_dim_level(uint32_t lo) { (void)lo; } +static void fm1_led_anim_start(uint32_t glow) { (void)glow; } +static int fm1_led_anim_on(void) { return 0; } +static void fm1_led_idle_start(uint32_t glow) { (void)glow; } +static int fm1_led_idle_on(void) { return 0; } +static void fm1_led_anim_stop(void) {} diff --git a/firmware/hal/smk_input.h b/firmware/hal/smk_input.h new file mode 100644 index 0000000..707b4fb --- /dev/null +++ b/firmware/hal/smk_input.h @@ -0,0 +1,670 @@ +/* SPDX-License-Identifier: GPL-3.0-only + * Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments + * SMK-37 Pro port: Copyright (C) 2026 M. Geisler (genkigenki/makkuro) */ +/* SMK-37 Pro input HAL: velocity keybed, buttons, encoders, button LEDs, pads, faders, wheels. + * The FM-1 counterpart is fm1_input.h + fm1_adc.h; this header keeps their API (fm1_in, fm1_input_init, + * fm1_input_tick, fm1_input_scan, fm1_enc_take, fm1_input_edges, fm1_input_note_edges, fm1_led_key) so + * the UI code compiles unchanged, and adds the SMK's extras (velocity, pads, faders, wheels). + * Hardware (stock v016; hardware notes: https://github.com/genkigenki/fm1-to-smk37): + * + * - 4 x 74HC595 (32 bits) shifted by SPI2 group C (PA3 CLK, PA4 DO; IOMAP_CON1 bit17), latched by + * PA1, PA0 low (/OE). Word bits 31..16: column select, active-low one-hot (col 0..7 = bits 31..24, + * col 8..15 = bits 23..16); bits 15..0: button LEDs (active low) and the analog mux address (bits 3..5). + * - 8 return lines with pull-ups, low = closed: PA2, PA5, PA6, PA7, PA9, PH6, PH8, PH9 = rows 0..7. + * Rows 0..4: keybed (2 contacts per key), rows 5..6: 18 buttons, row 7: 8 encoders. + * - Button LEDs: 19 positions in two groups, commons on the second USB PHY's pads used as GPIO + * (pin ids 150/151: SFR 0x16A0C bits 17/18, low = group on). + * - SARADC: ch1 = mux A (PA8, pads 0..7), ch8 = mux B (PC9, pads 8..15), ch2 = mux C (PA10: faders, + * wheels, pedal, battery), the 3 muxes share the address from the 595 word. + * + * Timing: fm1_input_tick() runs from the 10 kHz TIMER5 ISR. Each tick reads the rows of the column + * latched one tick ago, latches the word shifted during the last tick, starts the next SPI2 DMA (4 bytes, + * ~3 us) and runs one ADC conversion (read in the next tick). The order is the stock ISR's, so the matrix + * codes (col << 4 | row) of the spec apply unchanged. A frame = 16 ticks = 1.6 ms: keys, buttons, encoders + * and LEDs are processed once per frame. Analog: 8 mux addresses x 3 channels = 24 ticks per cycle. + * + * Key velocity: the stock two-contact algorithm (T = 10 + frames between contact 1 and contact 2, in the + * stock's 0.1 ms frames, from the 24 MHz time base here) and its 5-point curves (trimdata at flash 0xC1000, + * defaults {5,640,800,920,980}). Our scan samples a key once per 1.6 ms, so fast strikes quantise coarsely. */ +#pragma once +#include +#include "fm1_time.h" +#include "fm1_gpio.h" +#include "fm1_cc.h" + +#ifndef FM1_INPUT_IDLE +#define FM1_INPUT_IDLE() ((void)0) +#endif + +#define SMK_SPI2_CON (*(volatile uint32_t *)0x11E00u) +#define SMK_SPI2_BAUD (*(volatile uint32_t *)0x11E04u) +#define SMK_SPI2_ADR (*(volatile uint32_t *)0x11E0Cu) +#define SMK_SPI2_CNT (*(volatile uint32_t *)0x11E10u) +#define SMK_IOMAP_CON1 (*(volatile uint32_t *)0x51020u) +#define SMK_USBIO_CON (*(volatile uint32_t *)0x16A0Cu) /* second USB PHY pads as GPIO (LED commons) */ +#define SMK_ADC_CON (*(volatile uint32_t *)0x13100u) +#define SMK_ADC_RES (*(volatile uint32_t *)0x13104u) +#define SMK_WLA_CON0 (*(volatile uint32_t *)0x11900u) + +#define FM1_NCOL 16u +#define FM1_NBTN 18u +#define FM1_NKEY 37u /* the keybed */ +#define FM1_NENC 8u +#define SMK_NPAD 16u +#define SMK_NLED 19u +#define SMK_KEY_F3 5u /* keybed key 5 = F3: keys 5..31 are the FM-1's 27 note keys (bits 0..26) */ +#define SMK_DEB_RELEASE 4u /* frames open in a row: a button release (~6 ms) */ +#define SMK_DEB_PRESS 2u /* frames closed in a row: a button press (~3 ms) */ +#define SMK_KEY_REL 3u /* frames with contact 1 open: a key release (~5 ms) */ +#define SMK_ENC_DIV 4 /* decoder counts a step: a detent is a whole quadrature cycle (the stock's 2 + * gave two UI steps a click, as the FM-1 has one) */ +enum { FM1_BTN_OCT_DOWN = 4, FM1_BTN_OCT_UP = 5 }; +enum { SMK_BTN_KNOB_BANK = 0, SMK_BTN_FADER_BANK = 1, SMK_BTN_LEFT = 2, SMK_BTN_RIGHT = 3 }; /* (main.c: the power-on combo) */ +#define FM1_OCT_BOTH (1u << FM1_BTN_OCT_DOWN | 1u << FM1_BTN_OCT_UP) + +/* ---------------------------------------------------------------- tables --- */ +/* 595 word per column: active-low one-hot select (stock table) */ +#define SMK_COLW(c) (~((c) < 8u ? 0x01000000u << (c) : 0x00010000u << ((c) - 8u))) +/* keybed key k: (first contact, second contact) matrix codes, col << 4 | row (stock table) */ +static const uint8_t SMK_KEYC[FM1_NKEY][2] = { + {0x10, 0x52}, {0x20, 0x72}, {0x30, 0x92}, {0x40, 0xb2}, {0x50, 0xd2}, {0x60, 0xf2}, {0x70, 0xe2}, + {0x80, 0xc2}, {0x90, 0xa2}, {0xa0, 0x82}, {0xc0, 0x62}, {0xd0, 0x42}, {0xe0, 0x22}, {0xf0, 0x12}, + {0xb0, 0x32}, {0x11, 0x33}, {0x21, 0x43}, {0x31, 0x53}, {0x41, 0x63}, {0x51, 0x73}, {0x61, 0x83}, + {0x71, 0x93}, {0x81, 0xa3}, {0x91, 0xb3}, {0xa1, 0xc3}, {0xb1, 0xd3}, {0xc1, 0xe3}, {0xd1, 0x23}, + {0xe1, 0x13}, {0xf1, 0x14}, {0x64, 0x24}, {0x74, 0x34}, {0x84, 0x44}, {0x94, 0x54}, {0xa4, 0xd4}, + {0xb4, 0xf4}, {0xc4, 0xe4}, +}; +/* button id -> matrix code (stock table). Printed names (confirmed on a unit, 2026-10-09): + * 0 KNOB BANK, 1 FADER BANK, 2 <, 3 >, 4 OCTAVE-, 5 OCTAVE+, 6 ARP, 7 NOTE REPEAT, 8 SCALE, 9 CHORD, + * 10 GLOBE, 11 BT, 12 PATCH, 13 PARA, 14 FX, 15 SEQ, 16 SEQ PLAY, 17 SEQ REC */ +static const uint8_t SMK_BTNC[FM1_NBTN] = {0x26, 0x76, 0x96, 0x56, 0x66, 0x36, 0x75, 0x65, 0x25, + 0x45, 0x15, 0x86, 0x95, 0x55, 0x85, 0x35, 0x16, 0x46}; +/* encoder i: A and B matrix codes (stock table; K1..K8 order to confirm) */ +static const uint8_t SMK_ENCC[FM1_NENC][2] = {{0x97, 0xa7}, {0x37, 0x47}, {0x17, 0x27}, {0xb7, 0xc7}, + {0x57, 0x67}, {0x77, 0x87}, {0xd7, 0xe7}, {0xf7, 0x07}}; +/* LED i (= button i): group << 4 | bit in the 595 low half (stock table, its order differs at the end). + * SEQ PLAY has a two-colour LED: 16 = its green, 18 = its red (unused); SEQ REC's own red LED is 0x1b + * (confirmed on a unit: 0x1e lit PLAY red, 0x1b lit SEQ REC) */ +static const uint8_t SMK_LEDC[SMK_NLED] = {0x0c, 0x12, 0x00, 0x10, 0x0d, 0x1d, 0x02, 0x01, 0x09, 0x08, + 0x0b, 0x0a, 0x11, 0x19, 0x18, 0x1a, 0x1c, 0x1b, 0x1e}; +/* analog: mux address -> pad on mux A (ch1); mux B (ch8) = the same + 8 (stock table) */ +static const uint8_t SMK_PADMUX[8] = {1, 2, 3, 0, 4, 7, 5, 6}; +/* mux C (ch2): address 0..3 -> fader 1,2,3,0; 4, 5 wheels; 6 pedal; 7 battery */ +static const uint8_t SMK_FADMUX[4] = {1, 2, 3, 0}; +enum { SMK_ADC_PADA = 1, SMK_ADC_PADB = 8, SMK_ADC_MUXC = 2 }; +/* the pads are the 16 white keys of the FM-1's 27 (F3 G3 A3 B3 C4 D4 E4 F4 G4 A4 B4 C5 D5 E5 F5 G5): the step + * grid, the drum sounds and every layer's tiles land on them, low notes at the bottom: the bottom row + * (hardware pads 8..15, mux B; padtest on a unit, 2026-10-10) white keys 0..7, the top row (pads 0..7, mux A) 8..15 */ +static const uint8_t SMK_WHITE_NOTE[SMK_NPAD] = {0, 2, 4, 6, 7, 9, 11, 12, 14, 16, 18, 19, 21, 23, 24, 26}; +static volatile uint8_t smk_pad_grid; /* set by the UI: pads as a step grid, white key w on pad w (1-8 top row) */ +#define SMK_PAD_OF_WHITE(w) (smk_pad_grid ? (w) : (w) < 8u ? (w) + 8u : (w) - 8u) /* white key 0..15 -> hardware pad */ +/* the piano layout (the UI sets smk_pad_piano, e.g. for SCALE): top row C4 D4 E4 F4 G4 A4 B4 C5, bottom row the + * black keys between them (C#4 D#4 - F#4 G#4 A#4 - C#5); note-key index (0 = F3) by hardware pad, -1 = none */ +static const int8_t SMK_PIANO_NOTE[SMK_NPAD] = {7, 9, 11, 12, 14, 16, 18, 19, 8, 10, -1, 13, 15, 17, -1, 20}; +static volatile uint8_t smk_pad_piano; +static uint8_t smk_pad_note[SMK_NPAD]; /* the note key a pad pressed (+1; 0 = none): its release ends that one */ +#define SMK_WHITE_OF_PAD(p) (smk_pad_grid ? (p) : (p) < 8u ? (p) + 8u : (p) - 8u) + +#define SMK_TRIM_FLASH 0xC1000u /* USRTRIM: the factory calibration record ("trimdat"), never written here */ +/* 5-point velocity curves (trimdata, flash 0xC1000: +0x08 16 pads x 5 u16, +0xA8 37 keys x 5 u16) */ +static uint16_t smk_trim_pad[SMK_NPAD][5], smk_trim_key[FM1_NKEY][5]; + +/* ------------------------------------------------------------------ state --- */ +static volatile struct { + uint32_t notes; /* bit n = note key n (0 = F3 .. 26 = G5): keybed keys 5..31 | the pads */ + uint32_t knotes, pnotes; /* (the two sources of notes: keybed keys 5..31, pads as white keys) */ + uint32_t buttons; /* debounced: bit i = button i (0..17) */ + uint32_t pressed, released; /* button edges since the last fm1_input_edges() */ + uint32_t notes_pressed; /* note-key press edges since the last fm1_input_note_edges() */ + uint64_t keys; /* all 37 keybed keys: bit k = key k (0 = lowest C) */ + uint8_t key_vel[FM1_NKEY]; /* MIDI velocity 1..127 of each key's last press (a pad: its white key's) */ + uint8_t raw[FM1_NCOL]; /* last frame, rows packed, 1 = closed */ + uint8_t cnt[FM1_NBTN]; /* button debounce */ + uint8_t ks_last[FM1_NKEY], ks_stab[FM1_NKEY], ks_rel[FM1_NKEY]; + uint32_t ks_t1[FM1_NKEY]; /* fm1_ticks() when contact 1 closed */ + uint8_t enc_last[FM1_NENC], enc_hist[FM1_NENC]; + int16_t enc_cnt[FM1_NENC]; /* transitions, + = B leads */ + int16_t enc_steps[FM1_NENC]; + uint16_t pad_raw[SMK_NPAD], pad_base[SMK_NPAD], pad_peak[SMK_NPAD]; + uint8_t pad_st[SMK_NPAD]; /* 0 idle, 1..SMK_PAD_PEAKN collecting the peak, 0x80 on */ + uint8_t pad_low[SMK_NPAD]; + uint8_t pad_press[SMK_NPAD]; /* pressure 0..127 while on */ + uint16_t fad_acc[4]; /* faders: 0..1023 IIR */ + uint8_t fader[4]; /* 0..127 */ + uint16_t wheel[2], pedal, batt; /* raw 0..1023 (mux C addresses 4, 5, 6, 7) */ + uint16_t fad_raw[4]; /* (debug: the last raw fader readings) */ + uint16_t fad_hist[4][2]; /* the two readings before: a median of 3 drops a lone spike */ + uint32_t adc_ok, adc_miss; /* (debug: conversions read / not finished within a tick) */ + uint32_t frames; +} fm1_in; + +/* key events beyond the FM-1's 27 (keybed keys 0..4 and 32..36): key << 8 | velocity (0 = release) */ +#define SMK_EXTQ 32u +static volatile uint16_t smk_extq[SMK_EXTQ]; +static volatile uint8_t smk_extq_w, smk_extq_r; + +static uint8_t fm1_led[SMK_NLED]; /* 1 = lit (button LED i = button i) */ +static volatile uint32_t smk_ledw[2]; /* per LED group: 0xFFFF0000 | low half (LED lines active low) */ +static volatile uint32_t smk_muxw = 0xFFFFFFC7u; /* AND masks over the whole 32-bit word: only the low half */ +static uint8_t smk_col, smk_grp, smk_slot, smk_adc_slot = 0xFF; + +/* ------------------------------------------------------------------ pins --- */ +static void smk__pin_in_pu(uint32_t port, uint32_t m) +{ + FM1_PR(port, FM1_DIE) |= m; + FM1_PR(port, FM1_DIR) |= m; + FM1_PR(port, FM1_PD) &= ~m; + FM1_PR(port, FM1_PU) |= m; +} +static void smk__pin_out(uint32_t port, uint32_t m, int v) +{ + FM1_PR(port, FM1_DIE) |= m; + FM1_PR(port, FM1_PU) &= ~m; + FM1_PR(port, FM1_PD) &= ~m; + if (v) + FM1_PR(port, FM1_OUT) |= m; + else + FM1_PR(port, FM1_OUT) &= ~m; + FM1_PR(port, FM1_DIR) &= ~m; +} +static void smk__pin_analog(uint32_t port, uint32_t m) +{ + FM1_PR(port, FM1_DIE) &= ~m; + FM1_PR(port, FM1_DIR) |= m; + FM1_PR(port, FM1_PD) &= ~m; + FM1_PR(port, FM1_PU) &= ~m; +} +FM1_INLINE void smk__common(uint32_t grp_on) /* 0 / 1: that group's common low, the other high; 2: both off */ +{ + uint32_t v = SMK_USBIO_CON | 0x1000Fu; /* (as stock: GPIO mode bits on every write) */ + v |= (1u << 17) | (1u << 18); + if (grp_on < 2u) + v &= ~(1u << (17u + grp_on)); + SMK_USBIO_CON = v; +} + +FM1_INLINE uint32_t smk__rows(void) /* 1 = closed */ +{ + uint32_t a = FM1_PR(FM1_PA, FM1_IN), h = FM1_PR(FM1_PH, FM1_IN), r; + r = ((a >> 2) & 1u) | ((a >> 4) & 0x0Eu) | ((a >> 5) & 0x10u) | /* PA2; PA5..7; PA9 */ + ((h >> 1) & 0x20u) | ((h >> 2) & 0xC0u); /* PH6; PH8, PH9 */ + return ~r & 0xFFu; +} + +FM1_INLINE void smk__shift(uint32_t col) /* start the DMA of column col's word (needs a static buffer) */ +{ + static uint32_t w; + w = SMK_COLW(col) & smk_ledw[smk_grp] & smk_muxw; + SMK_SPI2_CON |= 0x4000u; + SMK_SPI2_ADR = (uint32_t)(uintptr_t)&w; + SMK_SPI2_CNT = 4u; +} + +FM1_INLINE void smk__latch(void) +{ + FM1_PR(FM1_PA, FM1_OUT) |= 1u << 1; + FM1_PR(FM1_PA, FM1_OUT) &= ~(1u << 1); +} + +/* analog slot s (0..23): mux address s / 3, channel {A, B, C}[s % 3] */ +FM1_INLINE uint32_t smk__slot_addr(uint32_t s) { return s / 3u; } + +/* -------------------------------------------------------------- velocity --- */ +static uint32_t smk_curve(const uint16_t *t, uint32_t x) /* stock curve: 5 points -> 1..1023 */ +{ + uint32_t i = 0, v; + while (i < 5u && x > t[i]) + i++; + if (i == 0) + return 1; + if (i == 5u) + return 1023; + v = (i - 1u) * 256u + ((x - t[i - 1u]) << 8) / (uint32_t)(t[i] - t[i - 1u]); + return v ? v : 1u; +} +FM1_INLINE uint8_t smk_vel7(uint32_t v10) { return (uint8_t)(v10 >> 3 ? v10 >> 3 : 1u); } + +static void smk_trim_defaults(void) +{ + static const uint16_t P[5] = {50, 550, 720, 850, 950}, K[5] = {5, 640, 800, 920, 980}; + uint32_t i, j; + for (i = 0; i < SMK_NPAD; i++) + for (j = 0; j < 5u; j++) + smk_trim_pad[i][j] = P[j]; + for (i = 0; i < FM1_NKEY; i++) + for (j = 0; j < 5u; j++) + smk_trim_key[i][j] = K[j]; +} + +/* the factory calibration record (0x22C bytes, "trimdat\0" at +0x224), e.g. read from flash 0xC1000; + * ignored unless the marker and strictly rising curves check out. Returns 1 if taken. */ +static int smk_trim_load(const uint8_t *rec) +{ + static const char M[8] = "trimdat"; + uint32_t i, j, ok = 1; + const uint8_t *p; + for (i = 0; i < 8u; i++) + ok &= rec[0x224u + i] == (uint8_t)M[i]; + for (i = 0; ok && i < SMK_NPAD + FM1_NKEY; i++) { + p = rec + 8u + i * 10u; + for (j = 1; j < 5u; j++) + ok &= (p[2u * j] | p[2u * j + 1u] << 8) > (p[2u * j - 2u] | p[2u * j - 1u] << 8); + } + if (!ok) + return 0; + for (i = 0; i < SMK_NPAD + FM1_NKEY; i++) + for (j = 0; j < 5u; j++) { + uint16_t v = (uint16_t)(rec[8u + i * 10u + 2u * j] | rec[9u + i * 10u + 2u * j] << 8); + if (i < SMK_NPAD) + smk_trim_pad[i][j] = v; + else + smk_trim_key[i - SMK_NPAD][j] = v; + } + return 1; +} + +/* ------------------------------------------------------------------ init --- */ +static void fm1_input_init(void) +{ + uint32_t i; + smk_trim_defaults(); + smk__pin_out(FM1_PA, (1u << 0) | (1u << 1), 0); /* PA0 /OE low, PA1 latch low */ + smk__pin_out(FM1_PA, (1u << 3) | (1u << 4), 0); /* SPI2 CLK, DO */ + smk__pin_in_pu(FM1_PA, (1u << 2) | (1u << 5) | (1u << 6) | (1u << 7) | (1u << 9)); + smk__pin_in_pu(FM1_PH, (1u << 6) | (1u << 8) | (1u << 9)); + smk__pin_analog(FM1_PA, (1u << 8) | (1u << 10)); /* ADC ch1, ch2 */ + smk__pin_analog(FM1_PC, 1u << 9); /* ADC ch8 (PC9 never an SPI1 clock) */ + smk_ledw[0] = smk_ledw[1] = 0xFFFFFFFFu; + smk_muxw = 0xFFFFFFC7u; /* mux address 0 (bits 3..5) */ + smk__common(2); + SMK_IOMAP_CON1 = (SMK_IOMAP_CON1 & ~0x30000u) | 0x20000u; /* SPI2 group C: PA3 / PA4 */ + SMK_SPI2_CON = 0x4020u; /* master, TX, no IRQ (stock: 0x6020) */ + SMK_SPI2_BAUD = 5u; + SMK_SPI2_CON |= 1u; + for (i = 0; i < FM1_NENC; i++) + fm1_in.enc_last[i] = 0xFF; + for (i = 0; i < SMK_NPAD; i++) + fm1_in.pad_base[i] = 100u; /* (stock init) */ + smk_col = 0; + smk__shift(0); /* the first word: latched on the first tick */ +} + +/* ------------------------------------------------------------------ frame --- */ +FM1_INLINE uint32_t smk__closed(uint32_t code) { return (fm1_in.raw[code >> 4] >> (code & 15u)) & 1u; } + +static void smk__extq(uint32_t k, uint32_t vel) +{ + uint8_t w = smk_extq_w; + if ((uint8_t)(w + 1u) % SMK_EXTQ == smk_extq_r) + return; + smk_extq[w] = (uint16_t)(k << 8 | vel); + smk_extq_w = (uint8_t)((w + 1u) % SMK_EXTQ); +} + +static void smk__key_event(uint32_t k, uint32_t vel) /* vel 0 = release */ +{ + if (vel) + fm1_in.key_vel[k] = (uint8_t)vel; + if (k >= SMK_KEY_F3 && k < SMK_KEY_F3 + 27u) { + uint32_t bit = 1u << (k - SMK_KEY_F3); + if (vel) { + fm1_in.knotes |= bit; + fm1_in.notes_pressed |= bit; + } else { + fm1_in.knotes &= ~bit; + } + fm1_in.notes = fm1_in.knotes | fm1_in.pnotes; + } else { + smk__extq(k, vel); + } + if (vel) + fm1_in.keys |= (uint64_t)1u << k; + else + fm1_in.keys &= ~((uint64_t)1u << k); +} + +static void smk__keys(uint32_t now) +{ + uint32_t k; + for (k = 0; k < FM1_NKEY; k++) { + uint32_t s = smk__closed(SMK_KEYC[k][0]) | smk__closed(SMK_KEYC[k][1]) << 1, st = fm1_in.ks_stab[k]; + if (s == 2u) /* contact 2 without 1: treat as 1 then 2 */ + s = 3u; + if (s == st) { + fm1_in.ks_rel[k] = 0; + continue; + } + if (s == 0u) { /* contact 1 open: a release after a few frames */ + if (++fm1_in.ks_rel[k] < SMK_KEY_REL) + continue; + fm1_in.ks_rel[k] = 0; + fm1_in.ks_stab[k] = 0; + if (st == 3u) + smk__key_event(k, 0); + continue; + } + fm1_in.ks_rel[k] = 0; + if (st == 0u) + fm1_in.ks_t1[k] = now; /* contact 1 made (or both in one frame) */ + if (s == 3u && st != 3u) { /* contact 2 made: the note, timed from contact 1 */ + uint32_t T = 10u + (now - fm1_in.ks_t1[k]) / (100u * FM1_TICKS_PER_US); /* stock 0.1 ms frames */ + uint32_t x = T <= 0x3FEu ? 0x3FFu - T : 1u; + smk__key_event(k, smk_vel7(smk_curve(smk_trim_key[k], x))); + } + if (s == 1u && st == 3u) /* 3 -> 1: still down */ + continue; + fm1_in.ks_stab[k] = (uint8_t)s; + } +} + +static void smk__buttons(void) +{ + uint32_t i; + for (i = 0; i < FM1_NBTN; i++) { + uint32_t closed = smk__closed(SMK_BTNC[i]), bit = 1u << i, on = (fm1_in.buttons & bit) != 0u; + volatile uint8_t *c = &fm1_in.cnt[i]; + if (closed == on) { + *c = 0; + continue; + } + if (++*c < (on ? SMK_DEB_RELEASE : SMK_DEB_PRESS)) + continue; + *c = 0; + fm1_in.buttons ^= bit; + if (!on) + fm1_in.pressed |= bit; + else + fm1_in.released |= bit; + } +} + +static void smk__encoders(void) /* stock decoder: 3-state window, 4 counts a cycle */ +{ + uint32_t e; + for (e = 0; e < FM1_NENC; e++) { + uint32_t cur = smk__closed(SMK_ENCC[e][0]) | smk__closed(SMK_ENCC[e][1]) << 1, h; + if (fm1_in.enc_last[e] == 0xFF) { /* first frame */ + fm1_in.enc_last[e] = (uint8_t)cur; + fm1_in.enc_hist[e] = (uint8_t)(cur * 0x15u); + continue; + } + if (cur != fm1_in.enc_last[e]) { /* must hold for two frames */ + fm1_in.enc_last[e] = (uint8_t)cur; + continue; + } + if (cur == (fm1_in.enc_hist[e] & 3u)) + continue; + h = ((uint32_t)fm1_in.enc_hist[e] << 2 | cur) & 0x3Fu; + fm1_in.enc_hist[e] = (uint8_t)h; + if (h == 0x07u || h == 0x1Eu || h == 0x21u || h == 0x38u) + fm1_in.enc_cnt[e]--; /* A leads */ + else if (h == 0x0Bu || h == 0x12u || h == 0x2Du || h == 0x34u) + fm1_in.enc_cnt[e]++; /* B leads */ + if (fm1_in.enc_cnt[e] >= SMK_ENC_DIV || fm1_in.enc_cnt[e] <= -SMK_ENC_DIV) { /* one step a detent */ + int32_t s = fm1_in.enc_cnt[e] / SMK_ENC_DIV; + fm1_in.enc_steps[e] = (int16_t)(fm1_in.enc_steps[e] + s); + fm1_in.enc_cnt[e] = (int16_t)(fm1_in.enc_cnt[e] - s * SMK_ENC_DIV); + } + } +} + +static void smk__leds(void) /* the next frame shows the other group */ +{ + uint32_t g, i, w[2] = {0xFFFFu, 0xFFFFu}; + for (i = 0; i < SMK_NLED; i++) + if (fm1_led[i]) + w[SMK_LEDC[i] >> 4] &= ~(1u << (SMK_LEDC[i] & 15u)); + smk_ledw[0] = 0xFFFF0000u | w[0] | 0x38u; /* (bits 3..5: the mux address, ANDed in) */ + smk_ledw[1] = 0xFFFF0000u | w[1] | 0x38u; + g = smk_grp ^ 1u; + smk_grp = (uint8_t)g; +} + +static void fm1__frame(void) +{ + uint32_t now = fm1_ticks(); + smk__keys(now); + smk__buttons(); + smk__encoders(); + smk__leds(); + fm1_in.frames++; +} + +/* ---------------------------------------------------------------- analog --- */ +#define SMK_PAD_ON 24u /* above the baseline: a hit starts */ +#define SMK_PAD_OFF 12u /* below base + this: released */ +#define SMK_PAD_PEAKN 3u /* samples (2.4 ms apart) for the peak */ + +static void smk__padq(uint32_t pad, uint32_t vel) /* a pad hit (vel) or release (0): its white key */ +{ + int32_t n0 = smk_pad_piano ? SMK_PIANO_NOTE[pad] : (int32_t)SMK_WHITE_NOTE[SMK_WHITE_OF_PAD(pad)]; + uint32_t n, bit; + if (vel) { + if (n0 < 0) + return; /* (a gap of the piano layout) */ + smk_pad_note[pad] = (uint8_t)(n0 + 1); + } else { + if (!smk_pad_note[pad]) + return; + n0 = smk_pad_note[pad] - 1; /* the key it pressed, whatever the layout is now */ + smk_pad_note[pad] = 0; + } + n = (uint32_t)n0; + bit = 1u << n; + if (vel) { + fm1_in.key_vel[SMK_KEY_F3 + n] = (uint8_t)vel; + fm1_in.pnotes |= bit; + fm1_in.notes_pressed |= bit; + } else { + fm1_in.pnotes &= ~bit; + } + fm1_in.notes = fm1_in.knotes | fm1_in.pnotes; +} + +static void smk__pad(uint32_t p, uint32_t raw) +{ + uint32_t base = fm1_in.pad_base[p], st = fm1_in.pad_st[p]; + fm1_in.pad_raw[p] = (uint16_t)raw; + if (st == 0u) { + if (raw > base + SMK_PAD_ON) { + fm1_in.pad_st[p] = 1; + fm1_in.pad_peak[p] = (uint16_t)raw; + } else if (base > raw) { + fm1_in.pad_base[p] = (uint16_t)(base - 1u); /* the baseline follows (stock) */ + } else if (base < smk_trim_pad[p][0]) { + fm1_in.pad_base[p] = (uint16_t)(base + 2u); + } + return; + } + if (st < 0x80u) { /* the peak of the first samples */ + if (raw > fm1_in.pad_peak[p]) + fm1_in.pad_peak[p] = (uint16_t)raw; + if (++st < SMK_PAD_PEAKN) { + fm1_in.pad_st[p] = (uint8_t)st; + return; + } + fm1_in.pad_st[p] = 0x80; + fm1_in.pad_low[p] = 0; + smk__padq(p, smk_vel7(smk_curve(smk_trim_pad[p], fm1_in.pad_peak[p]))); + return; + } + fm1_in.pad_press[p] = (uint8_t)(raw <= 0x200u ? raw >> 4 : (raw - 0x200u) / 4u + 32u > 127u ? 127u + : (raw - 0x200u) / 4u + 32u); + if (raw < base + SMK_PAD_OFF) { + if (++fm1_in.pad_low[p] >= 2u) { + fm1_in.pad_st[p] = 0; + fm1_in.pad_press[p] = 0; + smk__padq(p, 0); + } + } else { + fm1_in.pad_low[p] = 0; + } +} + +static void smk__analog(uint32_t slot, uint32_t raw) +{ + uint32_t a = smk__slot_addr(slot), ch = slot % 3u; + if (ch == 0u) { + smk__pad(SMK_PADMUX[a], raw); + } else if (ch == 1u) { + smk__pad(SMK_PADMUX[a] + 8u, raw); + } else if (a < 4u) { + uint32_t f = SMK_FADMUX[a], h0 = fm1_in.fad_hist[f][0], h1 = fm1_in.fad_hist[f][1], m, v; + int32_t acc = fm1_in.fad_acc[f]; + fm1_in.fad_raw[f] = (uint16_t)raw; + fm1_in.fad_hist[f][1] = (uint16_t)h0; + fm1_in.fad_hist[f][0] = (uint16_t)raw; + m = raw > h0 ? (h0 > h1 ? h0 : raw > h1 ? h1 : raw) : (raw > h1 ? raw : h0 > h1 ? h1 : h0); /* median */ + acc += ((int32_t)m * 16 - acc) / 4; /* x16 IIR (signed: it falls as well as rises) */ + fm1_in.fad_acc[f] = (uint16_t)acc; + v = (uint32_t)acc / 16u / 8u; + if (v > 127u) + v = 127u; + if (v > fm1_in.fader[f] + 1u || v + 1u < fm1_in.fader[f] || (v != fm1_in.fader[f] && (v == 0u || v == 127u))) + fm1_in.fader[f] = (uint8_t)v; /* +-1 dead band, the ends reachable */ + } else if (a < 6u) { + fm1_in.wheel[a - 4u] = (uint16_t)(fm1_in.wheel[a - 4u] + ((int32_t)raw - fm1_in.wheel[a - 4u]) / 4); + } else if (a == 6u) { + fm1_in.pedal = (uint16_t)raw; + } else { + fm1_in.batt = (uint16_t)raw; + } +} + +FM1_INLINE void smk__adc_start(uint32_t ch) +{ + SMK_ADC_CON = 0; + if (SMK_WLA_CON0 & (1u << 14)) + SMK_WLA_CON0 &= ~(1u << 14); + /* the stock SMK timing (0x407D without IE): start delay 4 x 8 ADC clocks, divider 0b101; done in ~40 us, + * well inside a tick. (The FM-1's 0xF04E, delay 15 x 8 at /96, takes ~200 us: it never finished in time.) */ + SMK_ADC_CON = 0x400Du | ((ch & 0xFu) << 8); + SMK_ADC_CON |= 0x10u; + SMK_ADC_CON |= 0x40u; +} + +/* ------------------------------------------------------------------- tick --- */ +/* one column per call, from the 10 kHz timer ISR (the stock ISR's order, see top) */ +static void fm1_input_tick(void) +{ + static const uint8_t CH[3] = {SMK_ADC_PADA, SMK_ADC_PADB, SMK_ADC_MUXC}; + uint32_t col = smk_col, next; + if (smk_adc_slot != 0xFF) { /* the conversion of the last tick */ + if (SMK_ADC_CON & 0x80u) { + fm1_in.adc_ok++; + smk__analog(smk_adc_slot, SMK_ADC_RES & 0x3FFu); + } else { + fm1_in.adc_miss++; + } + SMK_ADC_CON = 0x40u; + SMK_ADC_CON = 0; + smk_adc_slot = 0xFF; + } + fm1_in.raw[col] = (uint8_t)smk__rows(); + if (col == 0u) /* a new frame: its LED group */ + smk__common(smk_grp); + smk__latch(); /* the word shifted last tick */ + next = (col + 1u) & 15u; + smk_col = (uint8_t)next; + /* the mux address for the slot after this one goes out with the next word */ + { + uint32_t s = smk_slot, ns = s + 1u == 24u ? 0u : s + 1u; + smk__adc_start(CH[s % 3u]); /* this slot: its address was latched now */ + smk_adc_slot = (uint8_t)s; + smk_slot = (uint8_t)ns; + smk_muxw = 0xFFFFFFC7u | smk__slot_addr(ns) << 3; + } + if (next == 0u) + fm1__frame(); /* (before the shift: column 0 carries the new LED group) */ + smk__shift(next); +} + +/* one full frame, polled (recovery screen, power-on); calls FM1_INPUT_IDLE() while it waits */ +static void fm1_input_scan(void) +{ + uint32_t i; + for (i = 0; i < FM1_NCOL; i++) { + uint32_t t0 = fm1_ticks(); + fm1_input_tick(); + while ((uint32_t)(fm1_ticks() - t0) < 100u * FM1_TICKS_PER_US) + FM1_INPUT_IDLE(); + } +} + +/* ------------------------------------------------------- main-loop API --- */ +static inline uint32_t fm1__lock(void) +{ + __asm__ volatile("cli" ::: "memory"); + return 0; +} +static inline void fm1__unlock(uint32_t v) +{ + (void)v; + __asm__ volatile("csync\n\tsti" ::: "memory"); +} + +static int32_t fm1_enc_take(uint32_t e) +{ + uint32_t k = fm1__lock(); + int32_t s = fm1_in.enc_steps[e]; + fm1_in.enc_steps[e] = 0; + fm1__unlock(k); + return s; +} + +static uint32_t fm1_input_edges(uint32_t *released) +{ + uint32_t k = fm1__lock(); + uint32_t p = fm1_in.pressed; + if (released) + *released = fm1_in.released; + fm1_in.pressed = fm1_in.released = 0; + fm1__unlock(k); + return p; +} + +static uint32_t fm1_input_note_edges(void) +{ + uint32_t k = fm1__lock(); + uint32_t p = fm1_in.notes_pressed; + fm1_in.notes_pressed = 0; + fm1__unlock(k); + return p; +} + +/* the next outer-key event (keybed key << 8 | velocity, 0 = release), -1 if none */ +static int32_t smk_extkey_take(void) +{ + int32_t v = -1; + if (smk_extq_r != smk_extq_w) { + v = smk_extq[smk_extq_r]; + smk_extq_r = (uint8_t)((smk_extq_r + 1u) % SMK_EXTQ); + } + return v; +} + +/* LED of button id (0..17); note keys have no LED on the SMK (the pads show the step grid) */ +static void fm1_led_key(uint32_t id, int on) +{ + if (id < SMK_NLED) + fm1_led[id] = (uint8_t)(on != 0); +} + +/* fm1_adc.h stand-ins for main.c: the battery comes from mux C; the FM-1's MASTER pot is knob K1 here, as a + * virtual pot (0..1023, 24 a detent; starts at 724: master_q12 2048, the level the firmware starts with) */ +enum { FM1_ADC_BATT = 3, FM1_ADC_MASTER = 4 }; +#define SMK_ENC_MASTER 0u /* K1, where the FM-1 has its MASTER pot (top left) */ +static int32_t smk_master = 724; +static void fm1_adc_init(void) {} +static int32_t fm1_enc_take(uint32_t e); +static int32_t fm1_adc_read(uint32_t ch) +{ + if (ch == FM1_ADC_BATT) + return fm1_in.batt ? (int32_t)fm1_in.batt : -1; + if (ch == FM1_ADC_MASTER) { + smk_master += fm1_enc_take(SMK_ENC_MASTER) * 24; + smk_master = smk_master < 0 ? 0 : smk_master > 1023 ? 1023 : smk_master; + return smk_master; + } + return -1; +} diff --git a/firmware/loader/ldr_core.c b/firmware/loader/ldr_core.c index 3b73c16..297e19c 100644 --- a/firmware/loader/ldr_core.c +++ b/firmware/loader/ldr_core.c @@ -31,11 +31,26 @@ * ldr_progress(done, total) * plus the ota.c hooks (frames, time, idle). */ #define LDR_APP_LO 0x4000u +#if BOARD_SMK37 +/* SMK-37 Pro: app area up to the stock PRCT end; records only in the VM, so ldr_records_drop can never + * erase BTIF / USRTRIM (0xC0000..0xC1FFF, the key calibration) or anything above */ +#define LDR_APP_HI 0x9D000u +#define LDR_REC_LO 0x9D000u +#define LDR_REC_HI 0xC0000u +/* records are dropped in the whole VM, where the stock app may have staged its own (its staging address is only + * known at run time): the store there holds only Felucca's objects (commit records at +0, user samples are in + * USRFLASH 0xC2000.., outside this window), so no skipped range */ +#define LDR_DATA_LO 0u +#define LDR_DATA_HI 0u +_Static_assert(LDR_APP_HI <= LDR_REC_LO && LDR_REC_HI <= 0xC0000u && LDR_APP_LO >= 0x4000u, + "SMK loader windows must stay below BTIF / USRTRIM and above the head"); +#else #define LDR_APP_HI 0x93000u #define LDR_REC_LO 0x93000u /* update records live above the app ... */ #define LDR_REC_HI 0xFC000u /* ... and below Felucca's globals (Felucca's records: 0xE4F00, */ #define LDR_DATA_LO 0x97000u /* the stock firmware's: 0xE8F00), never in Felucca's store, whose */ #define LDR_DATA_HI 0xE0000u /* bytes (user samples) the host writes */ +#endif #define LDR_NSEC ((LDR_APP_HI - LDR_APP_LO) >> 12) static int ldr_fread(uint32_t off, void *p, uint32_t n); diff --git a/firmware/loader/loader.c b/firmware/loader/loader.c index b74dfa1..8c62010 100644 --- a/firmware/loader/loader.c +++ b/firmware/loader/loader.c @@ -3,7 +3,8 @@ /* Felucca update loader (device side). Runs from RAM, started by the SPL from * an update record, with interrupts off: USB is polled from the main loop. * It is a USB-MIDI device "Felucca Update" (1209:0002) that answers the - * M-UPGRADE update protocol as "ota-FM-1_900" (hosts look for "ota-"), and + * M-UPGRADE update protocol as "ota-FM-1_900" (SMK: "ota-SMK-37 Pro_900", or the + * SMK_MODEL build's name; hosts look for "ota-"), and * writes the app area only (ldr_core.c). The UBOOT soft key works here too. * Single compilation unit. */ #include @@ -12,13 +13,25 @@ #define FELUCCA_OTA 1 #define FELUCCA_OTA_DRYRUN 0 #define FELUCCA_USB_PID 0x0002 +#include "fm1_cc.h" /* BOARD_SMK37 */ +#if BOARD_SMK37 +#define FELUCCA_ID "ota-" SMK_MODEL "_900" +#else #define FELUCCA_ID "ota-FM-1_900" +#endif #define RING_PUBLISH() __asm__ volatile("" ::: "memory") #include "fm1_time.h" #include "fm1_sys.h" /* the loader may write the app area and erase update records; never the head, nor Felucca's store * [0x97000, 0xE0000) (user data, never a record: ldr_core.c) */ +#if BOARD_SMK37 +/* SMK: app area 0x4000..0x9CFFF, records in the VM 0x9D000..0xBFFFF only: never BTIF / USRTRIM + * 0xC0000..0xC1FFF, USR 0xF4000.., key_mac 0xFF000 (FL_LDR_RANGE_OK, asserted in fm1_flash_map.h; the + * RAM driver also refuses every protected range on its own, FL_GUARD) */ +#define FL_RANGE_OK(off, n) FL_LDR_RANGE_OK(off, n) +#else #define FL_RANGE_OK(off, n) (FL_IN(off, n, 0x4000u, 0x97000u) || FL_IN(off, n, 0xE0000u, 0xFC000u)) +#endif #include "fm1_flash.h" #include "../src/libc.c" #include "../src/usb.c" diff --git a/firmware/src/console.c b/firmware/src/console.c index 0a3f9bf..f73c591 100644 --- a/firmware/src/console.c +++ b/firmware/src/console.c @@ -140,8 +140,13 @@ static void con_flr(const char *p) /* flash read over SPI (no X static uint8_t b[256]; int ok, ok2; uint32_t a = con_num(&p, &ok), n = con_num(&p, &ok2), i; +#if BOARD_SMK37 + if (!ok || a < 0x9D000u || a >= 0x100000u) { + con_puts("usage: flr OFFSET [LEN<=256] (0x9D000..0xFFFFF)\r\n"); +#else if (!ok || a < 0x93000u || a >= 0x100000u) { con_puts("usage: flr OFFSET [LEN<=256] (0x93000..0xFFFFF)\r\n"); +#endif return; } if (!ok2 || !n) @@ -264,6 +269,10 @@ static void con_dbg(void) * bits of the 595 shift it spans), encoder transitions */ static void con_inp(void) { +#if BOARD_SMK37 + con_kv("timer_irqs", (int32_t)felucca_dbg.timer_irqs); /* (SMK-37 Pro: no scan statistics; `smk`) */ + con_kv("nested", (int32_t)felucca_dbg.nested); +#else static uint32_t t_last; uint32_t now = fm1_ticks(), win = now - t_last, i, k; uint32_t win_us = win / FM1_TICKS_PER_US; @@ -320,6 +329,7 @@ static void con_inp(void) memset((void *)&fm1_in_stat.gap_max, 0, sizeof fm1_in_stat - sizeof fm1_in_stat.last); fm1__unlock(k2); } +#endif } static void con_crash(void) @@ -350,6 +360,70 @@ static void con_params(void) } } +#if BOARD_SMK37 +static void con_smk(void) /* the SMK-37 Pro inputs (smk_input.h) */ +{ + uint32_t i; + con_kv("adc_ok", (int32_t)fm1_in.adc_ok); + con_kv("adc_miss", (int32_t)fm1_in.adc_miss); + con_kv("frames", (int32_t)fm1_in.frames); + con_puts("pad raw "); + for (i = 0; i < SMK_NPAD; i++) { con_dec(fm1_in.pad_raw[i]); con_putc(' '); } + con_puts("\r\npad base "); + for (i = 0; i < SMK_NPAD; i++) { con_dec(fm1_in.pad_base[i]); con_putc(' '); } + con_puts("\r\npad st "); + for (i = 0; i < SMK_NPAD; i++) { con_dec(fm1_in.pad_st[i]); con_putc(' '); } + con_puts("\r\nfader raw "); + for (i = 0; i < 4u; i++) { con_dec(fm1_in.fad_raw[i]); con_putc(' '); } + con_puts("\r\nfader "); + for (i = 0; i < 4u; i++) { con_dec(fm1_in.fader[i]); con_putc(' '); } + con_puts("\r\n"); + con_kv("wheel0", fm1_in.wheel[0]); + con_kv("wheel1", fm1_in.wheel[1]); + con_kv("bend", smk_bend14); + con_kv("modw", smk_modw); + con_kv("pedal", fm1_in.pedal); + con_kv("batt", fm1_in.batt); + con_kx("buttons", fm1_in.buttons); + con_kx("notes", fm1_in.notes); + for (i = 0; i < FM1_NENC; i++) { + con_puts("enc"); + con_dec((int32_t)i); + con_putc('='); + con_dec(fm1_in.enc_steps[i]); + con_putc(i + 1u == FM1_NENC ? '\r' : ' '); + } + con_puts("\r\n"); +} + +/* what the firmware sends the pads: GRB words by hardware pad (0..7 top row, 8..15 bottom row) */ +static void con_leds(void) +{ + uint32_t i; + for (i = 0; i < SMK_NPAD; i++) { + con_puts("pad"); + con_dec((int32_t)i); + con_puts(" grb "); + con_hex(padled_rgb[i], 6); + con_puts(i % 4u == 3u ? "\r\n" : " "); + } +} + +/* the pad LEDs' colour order: hardware pad 8 (bottom left) red, 9 green, 10 blue, 11 white, for 20 s */ +static void con_padtest(void) +{ + uint32_t i; + for (i = 0; i < SMK_NPAD; i++) + padled_set(i, 0, 0, 0); + padled_set(8, 40, 0, 0); + padled_set(9, 0, 40, 0); + padled_set(10, 0, 0, 40); + padled_set(11, 40, 40, 40); + padled_hold_until = fm1_ms + 20000u; + con_puts("top row from the left: red green blue white\r\n"); +} +#endif + static void con_exec(const char *p) { if (con_word(&p, "help") || con_word(&p, "?")) @@ -364,6 +438,14 @@ static void con_exec(const char *p) con_inp(); else if (con_word(&p, "params")) con_params(); +#if BOARD_SMK37 + else if (con_word(&p, "smk")) + con_smk(); + else if (con_word(&p, "padtest")) + con_padtest(); + else if (con_word(&p, "leds")) + con_leds(); +#endif else if (con_word(&p, "memr")) con_memr(p); #if FELUCCA_FLASH diff --git a/firmware/src/felucca.c b/firmware/src/felucca.c index 3c7514a..fd2cbbc 100644 --- a/firmware/src/felucca.c +++ b/firmware/src/felucca.c @@ -32,11 +32,23 @@ #define FELUCCA_UAC_OUT (FELUCCA_UAC && !FELUCCA_CDC) /* USB audio out (the playback interface; no data yet) */ #endif #ifndef FELUCCA_UART +#if BOARD_SMK37 +#define FELUCCA_UART 0 /* SMK-37 Pro: TRS MIDI OUT (UART1 TX, PC7), no MIDI IN; PH8 is a key-matrix + * row there and must never become UART RX. TODO: a TX driver */ +#else #define FELUCCA_UART 1 /* TRS MIDI IN on UART1 / PH8 */ #endif +#endif +#if BOARD_SMK37 && FELUCCA_UART +#error "BOARD_SMK37: midi_uart.c is the FM-1 MIDI IN driver (RX on PH8, a key-matrix row on the SMK)" +#endif #ifndef FELUCCA_ID +#if BOARD_SMK37 +#define FELUCCA_ID "SMK-37 Pro_900" /* package identity (build.py: the .fwsc marker string) */ +#else #define FELUCCA_ID "FM-1_900" /* package identity (build.py: the .fwsc marker string) */ #endif +#endif #ifndef FELUCCA_CPU2 #define FELUCCA_CPU2 1 /* 1 (1.6.1): the second core is built in and renders some parts when MENU > SYSTEM > * 2ND CORE is ON (BETA; OFF by default: one core, as 1.6; hal/fm1_cpu1.h, fx.c @@ -64,10 +76,17 @@ #define C1_RUN(fn, arg) fm1_cpu1_run(fn, arg) #define C1_WAIT() fm1_cpu1_wait() #endif +#if BOARD_SMK37 +#include "smk_input.h" /* SMK-37 Pro: keys, buttons, encoders, LEDs, pads, faders, wheels, battery */ +#include "smk_compat.h" /* (the FM-1 LED glow and animations: none on the SMK) */ +#else #include "fm1_input.h" +#endif #include "fm1_timer.h" #include "fm1_audio.h" +#if !BOARD_SMK37 #include "fm1_adc.h" +#endif #include "fm1_lcd_hw.h" #include "felucca_tables.h" /* generated by build.py (tools/gen_tables.py) */ diff --git a/firmware/src/fm6_vbank.c b/firmware/src/fm6_vbank.c index 49ffd5c..6646fe5 100644 --- a/firmware/src/fm6_vbank.c +++ b/firmware/src/fm6_vbank.c @@ -21,7 +21,11 @@ * fvb_boot finishes the copy at the next power-on, before any autosave can take that sector): never half of one. A * wrong CRC commits nothing. An autosave between two requests (it waits 10 s after the last, project.c) takes the * sector: WRITE and END find its commit record there and answer 5 (start again). Included by upreset.c. */ +#if BOARD_SMK37 +#define FVB_HOME ST_SMK_VBANK /* SMK-37 Pro: 0xB0000 in FL_DATA (storage.c) */ +#else #define FVB_HOME 0xE7000u +#endif #define FVB_INFO 224u /* the bank's header; the voices from FVB_VOICES */ #define FVB_VOICES 256u #define FVB_MAGIC 0x56364D46u /* "FM6V" */ diff --git a/firmware/src/lcd.c b/firmware/src/lcd.c index 46beb7b..86beb28 100644 --- a/firmware/src/lcd.c +++ b/firmware/src/lcd.c @@ -97,7 +97,11 @@ static void lcd_blit(uint32_t x, uint32_t y, uint32_t w, uint32_t h, const uint1 /* ST7789V init: reset, then 16-bit colour, scan direction and IPS inversion; * voltage and gamma stay at the defaults. Format: cmd, n, n data bytes; - * cmd 0x00 = wait (data byte: ~ms). */ + * cmd 0x00 = wait (data byte: ~ms). + * The SMK-37 Pro's panel (also an ST7789V 240x240 IPS, the window at RAM 0,0 with MADCTL 0x00) takes the same + * sequence: after SWRESET the datasheet's reset values stand for PORCTRL (B2h 0C 0C 00 33 33), GCTRL (B7h 35), + * VCOMS (BBh 20), LCMCTRL (C0h 2C), VDVVRHEN (C2h 01 FF), VRHS (C3h 0B), VDVS (C4h 20), FRCTRL2 (C6h 0F, 60 Hz), + * PWCTRL1 (D0h A4 A1) and the gamma curves (E0h / E1h); CASET / RASET are lcd_window's, DISPON lcd_init's. */ static const uint8_t LCD_SEQ[] = { 0x01, 0, /* SWRESET */ 0x00, 1, 150, @@ -156,3 +160,47 @@ static void lcd_wake_now(void) lcd_cmd(0x29); fm1_lcd_backlight(1); } + +#if BOARD_SMK37 +/* The 16 RGB pads (SMK-37 Pro): WS2812-class LEDs on SPI1 group B (PC10), one SPI byte per + * LED bit (0xF0 = 1, 0xC0 = 0, MSB first, GRB), 250 zero bytes of reset first (~300 us; the + * stock firmware's 36 bytes = 43 us are too short for newer WS2812 parts: a glitch on PC10 at the + * pin switch then counts as a first bit and shifts the chain by one, so a lit pad turns its chain + * neighbour green). The frame goes out between LCD transfers (LCD CS high), blocking for ~0.8 ms; + * padled_flush() only sends when a colour changed. */ +#define PADLED_N 16u +#define PADLED_LATCH 250u +static uint8_t padled_buf[PADLED_LATCH + PADLED_N * 24u]; +static uint32_t padled_rgb[PADLED_N]; +static uint8_t padled_dirty = 1; +static uint32_t padled_hold_until; /* (console padtest: the UI leaves the pads alone until then) */ +/* hardware pad (0..7 top row, 8..15 bottom row, left to right; smk_input.h SMK_PAD_OF_WHITE) -> position in + * the chain (stock table) */ +static const uint8_t PADLED_SLOT[PADLED_N] = {0, 15, 14, 13, 12, 11, 10, 9, 1, 2, 3, 4, 5, 6, 7, 8}; + +static void padled_set(uint32_t pad, uint8_t r, uint8_t g, uint8_t b) +{ + uint32_t c = (uint32_t)g << 16 | (uint32_t)r << 8 | b; + if (pad < PADLED_N && padled_rgb[pad] != c) { + padled_rgb[pad] = c; + padled_dirty = 1; + } +} + +static void padled_flush(void) +{ + uint32_t p, i; + if (!padled_dirty) + return; + padled_dirty = 0; + for (p = 0; p < PADLED_N; p++) { + uint8_t *o = padled_buf + PADLED_LATCH + PADLED_SLOT[p] * 24u; + for (i = 0; i < 24u; i++) + o[i] = (padled_rgb[p] >> (23u - i)) & 1u ? 0xF0u : 0xC0u; + } + lcd_sync(); + fm1_padled_send(padled_buf, sizeof padled_buf); + fm1_lcd_wait(); + fm1_padled_done(); +} +#endif diff --git a/firmware/src/main.c b/firmware/src/main.c index 1b832fc..3836c95 100644 --- a/firmware/src/main.c +++ b/firmware/src/main.c @@ -77,6 +77,89 @@ static void hexs(char *b, uint32_t v) b[8] = 0; } +#if BOARD_SMK37 +/* pads as a step grid (1-8 top row): the DRUM grid, NAME, the layers' tiles (not SCL: notes) */ +static void smk_grid(void) +{ + uint32_t l = ui.layer ? ui.layer : ui.ly; + smk_pad_grid = (uint8_t)(grid_on() || (name_on() && !ui.menu) || (l && l != LAYER_SCL)); +} + +/* the SMK-37 Pro's 4 faders, tracks 1..4, by FADER BANK (ui_input.c smk_fbank), as the MIXER page: A LEVEL, + * B PAN (the middle centre), C REV send, D DLY send. A fader takes over only once it moves (also after a bank + * change), so nothing jumps. */ +static void smk_faders(void) +{ + static uint8_t last[4] = {0xFF, 0xFF, 0xFF, 0xFF}; + uint32_t i; + if (smk_fbank_new) { /* a new bank: wait for each fader to move */ + smk_fbank_new = 0; + for (i = 0; i < 4u; i++) + last[i] = 0xFF; + } + for (i = 0; i < 4u && i < NTRK; i++) { + uint32_t v = fm1_in.fader[i]; + int16_t *pv; + if (last[i] == 0xFF || fm1_in.frames < 200u) { /* (the first readings settle) */ + last[i] = (uint8_t)v; + continue; + } + if (v == last[i]) + continue; + last[i] = (uint8_t)v; + pv = smk_fbank == 1 ? &trk[i].p[P_PAN] : smk_fbank == 2 ? &trk[i].p[P_REV] : + smk_fbank == 3 ? &trk[i].p[P_DLY] : &trk[i].p[P_LEVEL]; + *pv = (int16_t)(smk_fbank == 1 ? (int32_t)v - 64 : (int32_t)v); /* (PAN -64..63) */ + ui.force = 1; + } +} + +/* the wheels (stock: mux C address 4 = pitch, 5 = mod), self-calibrating: the pitch wheel's rest is its centre + * (taken at power-on, followed slowly while it rests), each wheel's range grows to what it has reached (the + * travel is short: raw ~445..640 pitch, ~474..629 mod on a unit). Pitch: a 14-bit bend -8192..8191 with a dead + * band around the centre; mod: 0..127, up (lower raw) = more. The audio ISR plays them as the selected track's + * MIDI pitch bend and CC1 (seq.c smk_wheels_block) */ +static void smk_wheels(void) +{ + enum { DEAD = 12, SPAN0 = 80, MOD_LO = 485, MOD_HI = 615 }; + static int32_t pc, plo, phi, mlo, mhi, rest; + int32_t p = fm1_in.wheel[0], m = fm1_in.wheel[1], d, b, mw; + if (fm1_in.frames < 300u) /* (the readings settle) */ + return; + if (!pc) { + pc = p; + plo = p - SPAN0; + phi = p + SPAN0; + mlo = m < MOD_LO ? m : MOD_LO; + mhi = m > MOD_HI ? m : MOD_HI; + } + if (p < plo) + plo = p; + if (p > phi) + phi = p; + if (m < mlo) + mlo = m; + if (m > mhi) + mhi = m; + d = p - pc; + if (d > -DEAD && d < DEAD) { + b = 0; + if (++rest > 200) { /* resting: the centre follows a slow drift */ + pc += d > 0 ? 1 : d < 0 ? -1 : 0; + rest = 0; + } + } else { + rest = 0; + b = d > 0 ? (d - DEAD) * 8191 / (phi - pc - DEAD > 1 ? phi - pc - DEAD : 1) + : (d + DEAD) * 8192 / (pc - plo - DEAD > 1 ? pc - plo - DEAD : 1); + b = clamp(b, -8192, 8191); + } + mw = mhi - m <= DEAD ? 0 : (mhi - m - DEAD) * 127 / (mhi - mlo - DEAD > 1 ? mhi - mlo - DEAD : 1); + smk_bend14 = (int16_t)b; + smk_modw = (uint8_t)clamp(mw, 0, 127); +} +#endif + static void fm1_fault(const fm1_crash_t *c) { char b[12]; @@ -198,6 +281,10 @@ static void fm1_main(void) felucca_dbg.prev_rst = fm1_boot.p3_rst; fm1_input_init(); fm1_adc_init(); +#if BOARD_SMK37 && FELUCCA_FLASH + if (flash_ok) /* the factory key / pad velocity curves (USRTRIM, read only) */ + smk_trim_load(fm1_xip_ptr(SMK_TRIM_FLASH)); +#endif panel_init(); felucca_init(); master_boot(); @@ -223,7 +310,7 @@ static void fm1_main(void) fm1_guard_lock_top(); fm1_irq_enable_all(); fm1_delay_ms(30); - if ((fm1_in.buttons & 3u) == 3u) { + if ((fm1_in.buttons & FM1_OCT_BOTH) == FM1_OCT_BOTH) { panel_setup(); /* OCT- + OCT+ held at power-on */ settings_save(); } @@ -332,11 +419,23 @@ static void fm1_main(void) settings_poll(); /* queued settings save: only while stopped */ autosave_poll(); /* (1.2) the music, stopped and idle: project.c */ felucca_dbg.stage = 2; +#if BOARD_SMK37 + smk_grid(); +#endif UI_LEDS(); +#if BOARD_SMK37 + smk_faders(); + smk_wheels(); + padled_flush(); /* the pads' colours, between LCD transfers */ +#endif UI_DRAW(); felucca_dbg.stage = 9; while (fm1_ms - m < 15u) { /* ~60 UI frames/s at most */ UI_INPUT(); +#if BOARD_SMK37 + smk_wheels(); /* (bends follow the wheel, not the screen) */ + smk_grid(); +#endif #if FELUCCA_OTA ed_service(); /* editor replies without waiting for the next frame */ #endif diff --git a/firmware/src/ota.c b/firmware/src/ota.c index b6aee22..700797f 100644 --- a/firmware/src/ota.c +++ b/firmware/src/ota.c @@ -6,8 +6,8 @@ * cmd 0x11 handshake -> we answer our package identity (FELUCCA_ID) * F0 22 24 35 7F F7 upgrade -> ota_session(): pull parts of the package * with cmd 0x30 read requests, check them, stage the package's update - * loader at 0xE0000 (outside Felucca's store), ask 0xE0000000 ("success"), - * then write the UPDATA_PARM record (flash 0xE4F00 + RAM 0x01C7FD88) and + * loader at 0xE0000 (outside Felucca's store; SMK: 0xBB000), ask 0xE0000000 ("success"), + * then write the UPDATA_PARM record (flash 0xE4F00, SMK 0xBFF00, + RAM 0x01C7FD88) and * reset. The SPL runs the loader, which installs the package. * Nothing is committed before the host's "success"; a failure after the * staging began erases the staging area, and Felucca carries on. A package @@ -25,12 +25,29 @@ * ota_show(step, code) progress / result for the screen * ota_commit(parm) write RAM record + reset (never returns on hardware) */ +#if BOARD_SMK37 +/* SMK-37 Pro: the last 5 sectors of the stock VM (0xBB000..0xBFFFF, FL_OTA in fm1_flash.h), below BTIF / + * USRTRIM 0xC0000..0xC1FFF; the update loader may drop records only below 0xC0000 (ldr_core.c) */ +#define OTA_AREA 0x000BB000u /* staged loader, 5 x 4 KiB */ +#define OTA_AREA_LEN 0x5000u +#define OTA_RES (OTA_AREA + OTA_AREA_LEN - 0x100u) /* 0xBFF00 = 4K boundary - 256: SPL scan */ +#define OTA_FL_LEN 0x9D000u /* flash.bin = [0, the PRCT end): the head and the SMK's app area + * (ldr_core.c LDR_APP_HI) */ +#ifndef SMK_MODEL +#define SMK_MODEL "SMK-37 Pro" /* (fm1_cc.h) */ +#endif +#define OTA_PARM_ID "ota-" SMK_MODEL "_016" /* the stock app's parm identity (Pro 18 B, Elite 20 B) */ +#define OTA_FL_LEN_V16 OTA_FL_LEN /* SMK: the stock package's flash.bin is the same size (one size) */ +_Static_assert(OTA_AREA + OTA_AREA_LEN <= 0xC0000u && OTA_AREA >= 0x9D000u, "SMK: OTA area outside the VM"); +#else #define OTA_AREA 0x000E0000u /* staged loader, 5 x 4 KiB */ #define OTA_AREA_LEN 0x5000u #define OTA_RES (OTA_AREA + OTA_AREA_LEN - 0x100u) /* 0xE4F00 = 4K boundary - 256: SPL scan */ #define OTA_FL_LEN 0x93000u /* flash.bin = [0, the PRCT end): the head and this board's app area, * the size the update loader writes (ldr_core.c LDR_APP_HI) */ #define OTA_FL_LEN_V16 0xA9000u /* the official V16 package's flash.bin (its app area is larger; the official loader only) */ +#define OTA_PARM_ID "ota-FM-1_015" +#endif #define OTA_LDR_HCRC 0xEBAAu /* official update loader (usb_hid_ota.bin) */ #define OTA_LDR_DCRC 0x5881u #define OTA_LDR_LEN 0x4DE1u @@ -364,8 +381,8 @@ static int ota_session(void) ota_wr16(parm + 2, 0x5A0Du); ota_wr16(parm + 4, 0x5A01u); ota_wr16(parm + 6, 0x5441u); - for (i = 0; i < 12u; i++) - parm[8 + i] = (uint8_t)"ota-FM-1_015"[i]; /* the loader's own USB identity */ + for (i = 0; i < sizeof OTA_PARM_ID - 1u; i++) /* FM-1 12 B, SMK 18 B; zero up to +0x27 */ + parm[8 + i] = (uint8_t)OTA_PARM_ID[i]; /* the loader's own USB identity */ ota_wr32(parm + 72, OTA_AREA); ota_wr16(parm, ota_crc16(parm + 2, 78, 0)); #if FELUCCA_OTA_DRYRUN diff --git a/firmware/src/ota_hw.c b/firmware/src/ota_hw.c index 6e5c609..b3254d5 100644 --- a/firmware/src/ota_hw.c +++ b/firmware/src/ota_hw.c @@ -23,7 +23,11 @@ static int ota_prog(uint32_t off, const void *p, uint32_t n) static int ota_fread(uint32_t off, void *p, uint32_t n) { return st_read(off, p, n); } static void ota_show(uint32_t step, int32_t code) { +#if BOARD_SMK37 /* step 5 stays on screen while the loader writes the flash: say so */ + static const char *const STEP[] = {"", "PACKAGE", "CHECK HEAD", "LOADER", "CONFIRM", "UPDATING..."}; +#else static const char *const STEP[] = {"", "PACKAGE", "CHECK HEAD", "LOADER", "CONFIRM", "RESTART"}; +#endif char b[24]; lcd_fill(0, 0, 240, 240, T_BG); draw_text_box(0, 92, 240, &AF_M, "UPDATE", T_TEXT, 1); diff --git a/firmware/src/panel.c b/firmware/src/panel.c index 991e5af..854683d 100644 --- a/firmware/src/panel.c +++ b/firmware/src/panel.c @@ -13,7 +13,17 @@ static const char *const B_NAME[NB] = {"FX", "SCL", "ENV", "LFO", "EDIT", "GLO", "ARP", "SEQ", "PLAY", "REC", "OCT-", "OCT+"}; static const char *const E_NAME[NE] = {"SELECT", "ALGORITHM", "PRESETS", "KNOB 1", "KNOB 2", "KNOB 3", "KNOB 4"}; +#ifndef FM1_NBTN /* (host tests without a HAL: the FM-1's buttons and encoders) */ +#define FM1_NBTN 14u +#endif +#ifndef FM1_NENC +#define FM1_NENC 7u +#endif +#if BOARD_SMK37 +#define PANEL_MAGIC 0x504E5334u /* "PNS4" (SMK-37 Pro): bump when PANEL_DEFAULT changes */ +#else #define PANEL_MAGIC 0x50414E35u /* "PAN5": bump when PANEL_DEFAULT changes */ +#endif typedef struct { uint32_t magic; @@ -23,22 +33,37 @@ typedef struct { } panel_t; panel_t panel __attribute__((section(".noinit"))); +#if BOARD_SMK37 +/* SMK-37 Pro (smk_input.h button ids, confirmed on a unit; the printed SMK label -> the FM-1 function): + * FX = FX, SCALE = SEL, CHORD = ENV, NOTE REPEAT = LFO, PARA = EDIT, GLOBE = GLO, PATCH = HOME, BT = SAVE, + * ARP, SEQ as printed, SEQ PLAY = PLAY, SEQ REC = REC, OCTAVE- / + as printed. KNOB BANK (the menu), FADER BANK, + * < and > (pages) keep SMK functions (ui_input.c). Knobs as the FM-1's top row: K1 = MASTER (smk_input.h: the FM-1's MASTER pot, as a virtual one), + * K2 = SELECT, K3 = ALGORITHM (track), K4 = PRESETS; K5..K8 = KNOB 1..4 (the screen's four dials). + * HARDWARE CALIBRATION (OCT- + OCT+ at power-on) re-teaches all of it. */ +static const panel_t PANEL_DEFAULT = { + PANEL_MAGIC, + {14, 8, 9, 7, 13, 10, 12, 11, 6, 15, 16, 17, 4, 5}, + {1, 2, 3, 4, 5, 6, 7}, + {1, 1, 1, 1, 1, 1, 1}, +}; +#else static const panel_t PANEL_DEFAULT = { PANEL_MAGIC, {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 1}, /* PLAY = 12, REC = 13 (measured on hardware) */ {0, 1, 6, 2, 3, 4, 5}, /* SELECT = enc 0, ALGORITHM = enc 1, PRESETS = enc 6 (printed labels) */ {1, 1, 1, 1, 1, 1, 1}, }; +#endif static void panel_init(void) /* also after a flash load: ids are used as array indexes and shifts */ { uint32_t i, buttons = 0, encoders = 0, ok = panel.magic == PANEL_MAGIC; for (i = 0; ok && i < NB; i++) { - ok = panel.btn[i] < NB && !(buttons & (1u << panel.btn[i])); + ok = panel.btn[i] < FM1_NBTN && !(buttons & (1u << panel.btn[i])); if (ok) buttons |= 1u << panel.btn[i]; } for (i = 0; ok && i < NE; i++) { - ok = panel.enc[i] < NE && !(encoders & (1u << panel.enc[i])) && + ok = panel.enc[i] < FM1_NENC && !(encoders & (1u << panel.enc[i])) && (panel.dir[i] == 1 || panel.dir[i] == -1); if (ok) encoders |= 1u << panel.enc[i]; } diff --git a/firmware/src/project.c b/firmware/src/project.c index 9834e6b..54354b7 100644 --- a/firmware/src/project.c +++ b/firmware/src/project.c @@ -1183,7 +1183,8 @@ static void persist_boot(void) /* before settings_init / pane irq_restore(f); if (!flash_ok) return; - fl_plain_window_init(); /* flash above 0x93000 reads as plaintext through XIP */ + fl_plain_window_init(); /* flash above 0x93000 (SMK 0x9D000) reads as plaintext through XIP */ + st_owner_check(); /* SMK: never parse another ported firmware's store (storage.c) */ { int n = st_load(OBJ_SETTINGS, &p, sizeof p); if (settings_import(&p, n)) diff --git a/firmware/src/seq.c b/firmware/src/seq.c index c25e899..3182ea8 100644 --- a/firmware/src/seq.c +++ b/firmware/src/seq.c @@ -711,11 +711,22 @@ static __attribute__((noinline)) void perf_key_remap(void) } } +#if BOARD_SMK37 +/* SMK-37 Pro: velocity keys and pads. Key k's velocity (a pad: its white key's, smk_input.h) */ +static uint32_t key_vel(uint32_t k) +{ + uint32_t v = fm1_in.key_vel[SMK_KEY_F3 + k]; + return v ? v : kb_vel; +} +#else +#define key_vel(k) ((uint32_t)kb_vel) /* the FM-1's keys: SELECT VEL */ +#endif + /* key k plays kb_note[k] on track t: its chord (chord.c; the note alone with CHRD OFF). A note another key * holds already sounds: it is not started again (nor sent to MIDI OUT); the key keeps its notes */ static void key_on(uint32_t k, track_t *t) { - uint32_t n = chord_build(t, kb_note[k], kb_chord[k]), i, mc = trk_midi_ch(trk_index(t)), vel = kb_vel; + uint32_t n = chord_build(t, kb_note[k], kb_chord[k]), i, mc = trk_midi_ch(trk_index(t)), vel = key_vel(k); kb_chn[k] = 0; in_key = (uint8_t)(k + 1u); /* (the arp keeps the key: arp_add) */ for (i = 0; i < n; i++) { @@ -762,10 +773,52 @@ static __attribute__((noinline)) void kb_lat(uint32_t k) } #endif +#if BOARD_SMK37 +/* SMK-37 Pro: the keybed's 10 keys beyond the FM-1's 27 (C3..E3 below F3, G#5..C6 above G5) continue the keys: the + * selected track's key map (kb_map: QNT, ROOT, SCALE, TRN, the octave; DRUM's GM drum map, SLICE's slices) past + * either end, one note each at the key's velocity (no chord). They play only while the keys play: no layer held or + * locked, no DRUM grid, NAME or SONG keys, not under the splash or waking the screen */ +static uint8_t ext_note[FM1_NKEY], ext_trk[FM1_NKEY]; /* note + 1 sounding, 0 = none */ +static volatile int16_t smk_bend14; /* the pitch wheel, -8192..8191 (main.c smk_wheels) */ +static volatile uint8_t smk_modw; /* the mod wheel, 0..127 */ +static void ext_keys_block(void) +{ + int32_t e; + while ((e = smk_extkey_take()) >= 0) { + uint32_t k = (uint32_t)e >> 8, v = (uint32_t)e & 0x7Fu, sel = song.sel % NTRK, n, mc; + if (k >= FM1_NKEY) + continue; + if (!v) { + if (ext_note[k]) { + n = ext_note[k] - 1u; + mc = trk_midi_ch(ext_trk[k] % NTRK); + input_off(&trk[ext_trk[k] % NTRK], n); + midi_out_event(0x08u | (0x80u | mc) << 8 | n << 16); + ext_note[k] = 0; + } + continue; + } + if (ext_note[k] || kb_boot_hold || kb_asleep || song.grid || (fm1_in.buttons & kb_mask) || kb_lock) + continue; + n = kb_map(&trk[sel], (uint32_t)((int32_t)k - (int32_t)SMK_KEY_F3)); + if (n == KB_SILENT) + continue; + ext_note[k] = (uint8_t)(n + 1u); + ext_trk[k] = (uint8_t)sel; + mc = trk_midi_ch(sel); + input_on(&trk[sel], n, v); + midi_out_event(0x09u | (0x90u | mc) << 8 | n << 16 | v << 24); + } +} +#endif + static void keyboard_block(void) { uint32_t cur = fm1_in.notes, ch, k; uint32_t lay, fx, mute; +#if BOARD_SMK37 + ext_keys_block(); +#endif ch = cur ^ kb_prev; /* keys also sound while entering steps */ if (perf_remap) perf_key_remap(); @@ -1320,6 +1373,44 @@ static int32_t click_beat_now(void) } /* everything that happens between two rendered blocks */ +#if BOARD_SMK37 +/* SMK-37 Pro: the wheels (main.c smk_wheels) as the selected track's own MIDI controllers, as if played on its + * channel: the pitch wheel its pitch bend (the channel's bend range, RPN 0: 2 semitones unless set; a DRUM track + * ignores it, as it ignores MIDI bend), the mod wheel its CC1, the mod matrix's MODW source (mod.c). Both go to MIDI + * OUT too. Another track selected: the one before is left unbent, its MODW at 0. Audio ISR, before the MIDI IN of + * the block (an incoming bend or CC1 for the same track wins until the wheel moves again) */ +static void smk_wheels_block(void) +{ + static uint8_t prev = 0xFF, lm = 0xFF; + static int32_t lb = 0x7FFFFFFF; + uint32_t sel = song.sel % NTRK, mc = trk_midi_ch(sel), m = smk_modw; + int32_t b = smk_bend14; + if (sel != prev) { + if (prev < NTRK) { + midi_bend_target[prev] = 0; + trk[prev].mw = 0; + } + prev = (uint8_t)sel; + lb = 0x7FFFFFFF; + lm = 0xFF; + } + if (b != lb) { + const midi_channel_t *c = midi_channel(mc); + int32_t range = ((int32_t)c->semis * 100 + c->cents) * 256 / 100; + uint32_t u = (uint32_t)(b + 8192); + lb = b; + if (!drum_track(&trk[sel])) + midi_bend_target[sel] = b * range / (b < 0 ? 8192 : 8191); + midi_out_event(0x0Eu | (0xE0u | mc) << 8 | (u & 0x7Fu) << 16 | ((u >> 7) & 0x7Fu) << 24); + } + if (m != lm) { + lm = (uint8_t)m; + trk[sel].mw = (uint8_t)m; + midi_out_event(0x0Bu | (0xB0u | mc) << 8 | 1u << 16 | m << 24); + } +} +#endif + static void events_block(uint32_t n) { uint32_t i, pr, seq_n = n; @@ -1395,6 +1486,9 @@ static void events_block(uint32_t n) t->armp = t->p[P_AMODE]; t->aholdp = t->p[P_AHOLD]; } +#if BOARD_SMK37 + smk_wheels_block(); +#endif keyboard_block(); while (mi_r != mi_w) { /* USB-MIDI (and TRS) in */ uint32_t at = mi_r % MQ, pkt = midi_in_q[at], status = (pkt >> 8) & 0xFFu; diff --git a/firmware/src/storage.c b/firmware/src/storage.c index f67891b..a48ec24 100644 --- a/firmware/src/storage.c +++ b/firmware/src/storage.c @@ -64,6 +64,113 @@ static uint32_t st_crc32_add(uint32_t c, const void *p, uint32_t n) /* zlib CR } static uint32_t st_crc32(const void *p, uint32_t n) { return ~st_crc32_add(0xFFFFFFFFu, p, n); } +#if BOARD_SMK37 +/* SMK-37 Pro: every object in FL_DATA 0x9D000..0xBAFFF (the stock VM), + * A/B neighbours: projects 0x9D000..0xA4FFF, user preset banks 0xA5000..0xA8FFF, autosave 0xA9000 / + * 0xAA000, the user presets' FM6 patches (OBJ_UPFM6, the pair of the retired OBJ_FM6BANK) 0xAB000 / 0xAC000, + * settings 0xAD000 / 0xAE000; the store owner tag 0xAF000 (st_owner_check), the FM6 voice bank 0xB0000 + * (fm6_vbank.c FVB_HOME); 0xB1000..0xBAFFF spare. Never near BTIF / USRTRIM (0xC0000..0xC1FFF) or key_mac + * (0xFF000). */ +#define ST_SMK_BASE 0x9D000u +#define ST_SMK_PAIRS 9u +#define ST_SMK_SECTORS (2u * ST_SMK_PAIRS) +#define ST_SMK_VBANK 0xB0000u /* the FM6 voice bank (fm6_vbank.c), one sector */ +_Static_assert(OBJ_COUNT == 10u && OBJ_UPFM6 == OBJ_FM6BANK + 1u, "SMK store: a new object needs a place"); +_Static_assert(ST_SMK_BASE + ST_SMK_SECTORS * ST_SECTOR == 0xAF000u, "SMK store: the objects end at the owner tag"); +_Static_assert(ST_SMK_VBANK >= 0xAF000u + ST_SECTOR && ST_SMK_VBANK + ST_SECTOR <= 0xBB000u, "SMK store: past FL_DATA"); +static uint32_t st_sector(uint32_t obj, uint32_t copy) /* flash offset of copy A (0) / B (1) */ +{ + static const uint8_t ORDER[OBJ_COUNT] = { + [OBJ_PROJECT0] = 0, [OBJ_PROJECT0 + 1] = 1, [OBJ_PROJECT0 + 2] = 2, [OBJ_PROJECT0 + 3] = 3, + [OBJ_UPRESET0] = 4, [OBJ_UPRESET0 + 1] = 5, [OBJ_AUTOSAVE] = 6, [OBJ_FM6BANK] = 7, [OBJ_UPFM6] = 7, + [OBJ_SETTINGS] = 8}; + return ST_SMK_BASE + (ORDER[obj % OBJ_COUNT] * 2u + (copy & 1u)) * ST_SECTOR; +} + +/* The owner of the store. The store area is the stock firmware's VM, so after an install it may hold the stock + * firmware's (or any other firmware's) data, which Felucca must never parse as its own. The sector after the objects + * (0xAF000) holds the tag "SMK37DATAFELUCCA". Tagged: load as ever. Anything else (another tag, or none): clear the + * objects (0x9D000..0xAEFFF) and the FM6 voice bank (0xB0000), then write the tag. FELUCCA_DATA_UNTAGGED_OK 1 would + * keep a store with an erased tag (0: the SMK build never wrote untagged data). User samples (FL_SMP) validate + * themselves. Calibration, BT pairing and key_mac are outside FL_DATA: never touched. Called first in persist_boot + * (project.c), before any store read. */ +#ifndef FELUCCA_DATA_UNTAGGED_OK +#define FELUCCA_DATA_UNTAGGED_OK 0 +#endif +#define ST_OWNER_OFF 0xAF000u +_Static_assert(ST_OWNER_OFF == ST_SMK_BASE + ST_SMK_SECTORS * ST_SECTOR && ST_OWNER_OFF != ST_SMK_VBANK, + "SMK store owner: the sector after the objects"); +/* The stock firmware's mapping in USRFLASH (global settings at 0xC2000, magic A3 3A; 8 presets from 0xC3000 every + * 0x5000, 0x29E3 bytes each, the rest erased; the end marker "usrdata\0" at 0xEAFF8, FL_STOCKTAG): the stock firmware + * trusts the area while the marker is there and never rebuilds it, so after a return to stock the user samples + * would be its key, knob and fader mapping (every key one note). So: an intact stock mapping is kept (it reads as + * empty slots), and the marker is released (its sector erased: the stock firmware rebuilds its factory mapping at + * its next start) before the first erase in USRFLASH (storage_hw.c st_erase, editor.c) and at boot when it stands + * over anything else (st_owner_check: ours, an older build's, another firmware's). */ +static int st_stock_tagged(void) +{ + static const uint8_t TAG[8] = {'u', 's', 'r', 'd', 'a', 't', 'a', 0}; + uint8_t t[8]; + uint32_t i; + if (st_read(FL_STOCKTAG_OFF, t, 8)) + return 0; + for (i = 0; i < 8u; i++) + if (t[i] != TAG[i]) + return 0; + return 1; +} +static int st_stock_intact(void) /* the marker over the stock layout */ +{ + uint8_t b[8]; + uint32_t n, k, i, ff; + if (!st_stock_tagged() || st_read(FL_SMP_LO, b, 2) || b[0] != 0xA3u || b[1] != 0x3Au) + return 0; + for (n = 0; n < 8u; n++) /* each preset: its head written, its last two sectors erased */ + for (k = 0; k < 3u; k++) { + if (st_read(FL_SMP_LO + 0x1000u + n * 0x5000u + (k ? 0x2000u + k * 0x1000u : 0u), b, 8)) + return 0; + for (ff = 1, i = 0; i < 8u; i++) + ff &= b[i] == 0xFFu; + if (ff != (k != 0u)) + return 0; + } + return 1; +} +static void st_stock_release(void) /* erase the marker's sector, once: later calls find no marker */ +{ + if (st_stock_tagged()) + st_erase(FL_STOCKTAG_LO); +} +static inline int st_in_usrflash(uint32_t off) { return off >= FL_SMP_LO && off < FL_SMP_HI; } +static uint8_t st_owner_cleared; /* (the UI may say so) */ +static void st_owner_check(void) +{ + static const char FAM[] = "FELUCCA"; /* the tag: "SMK37DATA" + this, zero-padded to 16 B */ + uint8_t tag[16], want[16]; + uint32_t i, erased = 1, ours = 1, s; + for (i = 0; i < 16u; i++) + want[i] = i < 9u ? (uint8_t)"SMK37DATA"[i] : i - 9u < sizeof FAM - 1u ? (uint8_t)FAM[i - 9u] : 0u; + if (!st_stock_intact()) + st_stock_release(); /* the marker over anything but the stock mapping: let it rebuild */ + if (st_read(ST_OWNER_OFF, tag, 16)) + return; + for (i = 0; i < 16u; i++) { + erased &= tag[i] == 0xFFu; + ours &= tag[i] == want[i]; + } + if (ours) + return; + if (!erased || !FELUCCA_DATA_UNTAGGED_OK) { /* not ours (or untagged data): clear it */ + for (s = 0; s < ST_SMK_SECTORS; s++) + st_erase(ST_SMK_BASE + s * ST_SECTOR); + st_erase(ST_SMK_VBANK); + st_owner_cleared = 1; + } + st_erase(ST_OWNER_OFF); + st_prog(ST_OWNER_OFF, want, 16); +} +#else +static void st_owner_check(void) {} static uint32_t st_sector(uint32_t obj, uint32_t copy) /* flash offset of copy A (0) / B (1) */ { if (obj == OBJ_SETTINGS) @@ -78,6 +185,7 @@ static uint32_t st_sector(uint32_t obj, uint32_t copy) /* flash offset of copy return 0xDC000u + (obj - OBJ_UPRESET0) * 2u * ST_SECTOR + copy * ST_SECTOR; return 0x97000u + (obj - OBJ_PROJECT0) * 2u * ST_SECTOR + copy * ST_SECTOR; } +#endif static uint8_t st_buf[ST_PAYLOAD_MAX] __attribute__((aligned(4), section(".pool"))); /* (main loop only) */ diff --git a/firmware/src/storage_hw.c b/firmware/src/storage_hw.c index 88c19f5..76d2a5a 100644 --- a/firmware/src/storage_hw.c +++ b/firmware/src/storage_hw.c @@ -25,15 +25,28 @@ static void audio_silence(void) /* IRQs off: the DMA would loop for (i = 0; i < sizeof abuf / sizeof abuf[0]; i++) abuf[i] = 0; } +#if BOARD_SMK37 +static void st_stock_release(void); /* storage.c: the stock mapping's end marker */ +static int st_in_usrflash(uint32_t off); +#endif static int st_erase(uint32_t off) { uint32_t took, f; int rc; +#if BOARD_SMK37 + if (!FL_STORE_OK(off, 0x1000u) && !FL_STOCKTAG_OK(off, 0x1000u)) + return -8; + if (st_in_usrflash(off)) + st_stock_release(); /* before the first erase in USRFLASH: see storage.c */ +#else if (!FL_STORE_OK(off, 0x1000u)) return -8; +#endif f = irq_save(); audio_silence(); +#if !BOARD_SMK37 /* (the SMK-37's LEDs are latched, no scan) */ fm1__led_lines(0); /* (#236) the erase stops the LED scan for ~17 ms (the IRQs are off and its code */ +#endif rc = FL_FAR(fl_erase4k_ram)(off, &took); /* is in the flash): one column would stay lit at full duty and the rest dark, a */ irq_restore(f); /* flash of the whole panel. Dark rows: the panel just drops out; the tick lights */ return rc; /* the rows again at its next pass */ diff --git a/firmware/src/ui_input.c b/firmware/src/ui_input.c index 3c68e88..553c3d3 100644 --- a/firmware/src/ui_input.c +++ b/firmware/src/ui_input.c @@ -5,6 +5,26 @@ /* ----------------------------------------------------------- LEDs --- */ /* The LED picture is built off-line and copied one byte per column: clearing * and relighting would let the 10 kHz scan catch the dark gap and flicker. */ +#if BOARD_SMK37 +/* SMK-37 Pro: one flag per id. Ids 0..18 are the button LEDs (smk_input.h); the note keys (no LEDs of their own) + * take LED_KEY0 + k: ui_leds shows the white keys F3..G5 on the 16 RGB pads (smk_input.h SMK_WHITE_NOTE) */ +#define LED_BUF 64u +#define LED_KEY0 32u +static uint8_t smk_fbank, smk_fbank_new; /* FADER BANK: 0 LEVEL, 1 PAN, 2 REV, 3 DLY (main.c smk_faders) */ +static void led_pos_init(void) {} +static void led_put(uint8_t *nl, uint32_t id, int on) +{ + if (id < LED_BUF && on) + nl[id] = 1; +} +static void led_clear(uint8_t *nl, uint32_t id) +{ + if (id < LED_BUF) + nl[id] = 0; +} +#else +#define LED_BUF FM1_NCOL +#define LED_KEY0 14u /* the note keys' ids: 14..40 */ static uint8_t led_pos[41]; /* (col << 3) | row bit, 0xFF = none */ static void led_pos_init(void) @@ -34,6 +54,7 @@ static void led_clear(uint8_t *nl, uint32_t id) if (q != 0xFF) nl[q >> 3] &= (uint8_t)~(1u << (q & 7u)); } +#endif static const uint8_t FAM_BTN[FAM_COUNT] = {B_HOME, B_ENV, B_LFO, B_FX, B_SCL, B_EDIT, B_GLO, B_SAVE, B_ARP, B_SEQ, B_HOME}; /* MIXER: HOME's (1.2); REC is transport */ @@ -382,10 +403,46 @@ static uint32_t key_leds(uint32_t *br) /* (*br: a layer's keys t * rest: the root's keys lit, the scale's at the mid level, the others glowing; the keys held and playing as ever * (lit, INV dark). Each picture is built off-line and copied one byte per column, the * glow first: an LED going from lit to dim never has a dark frame */ +#if BOARD_SMK37 +/* SMK-37 Pro: an SMK button keeps its own function unless HARDWARE CALIBRATION gave it an FM-1 label */ +static int smk_btn_free(uint32_t id) +{ + uint32_t b; + for (b = 0; b < NB; b++) + if (panel.btn[b] == id) + return 0; + return 1; +} + +/* SMK-37 Pro: the picture of ui_leds on the panel. The 19 button LEDs are on / off: lit (nl) and breathing (nb) show + * lit, the glow layers have no LED level here. The 16 RGB pads are the white keys F3..G5 (smk_input.h SMK_WHITE_NOTE) + * in the theme's colour: lit full, breathing dark .. full and back (~1.1 s, as fm1_input.h), the mid level (nm: the + * grid's beats, the scale's root) a quarter, the glow of a key that does something (og: the DRUM grid's lanes, sg: + * SCALE LEDS) a sixteenth; the other keys' idle glow is off: off is off on the pads */ +static void smk_leds(const uint8_t *nl, const uint8_t *nb, const uint8_t *nm, const uint8_t *og, const uint8_t *sg) +{ + uint32_t c, th = T_THEME, br = (fm1_ms >> 2) & 0xFFu; + uint32_t r = (th >> 11) << 3 | (th >> 13), g = ((th >> 5) & 0x3Fu) << 2 | ((th >> 9) & 3u), b = (th & 0x1Fu) << 3 | ((th >> 2) & 7u); + br = br < 128u ? br * 2u : (255u - br) * 2u; /* the breath: 0..254 over ~1 s */ + for (c = 0; c < SMK_NLED; c++) + fm1_led[c] = (uint8_t)(nl[c] | nb[c]); + fm1_led[SMK_BTN_FADER_BANK] = smk_fbank != 0u; /* FADER BANK lit off bank A */ + if (smk_btn_free(SMK_BTN_KNOB_BANK)) + fm1_led[SMK_BTN_KNOB_BANK] = ui.menu != 0; /* KNOB BANK lit while the menu is up */ + if ((int32_t)(fm1_ms - padled_hold_until) < 0) /* (console padtest has them) */ + return; + for (c = 0; c < SMK_NPAD; c++) { /* white key c on its pad (the top row first) */ + uint32_t id = LED_KEY0 + SMK_WHITE_NOTE[c]; + uint32_t lv = nl[id] ? 256u : nb[id] ? br + 2u : nm[id] ? 64u : og[id] | sg[id] ? 16u : 0u; + padled_set(SMK_PAD_OF_WHITE(c), (uint8_t)(r * lv >> 8), (uint8_t)(g * lv >> 8), (uint8_t)(b * lv >> 8)); + } +} +#endif + static void ui_leds(void) { - uint8_t nl[FM1_NCOL] = {0}, nd[FM1_NCOL] = {0}, own[FM1_NCOL] = {0}, og[FM1_NCOL] = {0}, nb[FM1_NCOL] = {0}; - uint8_t nm[FM1_NCOL] = {0}, sg[FM1_NCOL] = {0}, sm[FM1_NCOL] = {0}, iv[FM1_NCOL] = {0}; + uint8_t nl[LED_BUF] = {0}, nd[LED_BUF] = {0}, own[LED_BUF] = {0}, og[LED_BUF] = {0}, nb[LED_BUF] = {0}; + uint8_t nm[LED_BUF] = {0}, sg[LED_BUF] = {0}, sm[LED_BUF] = {0}, iv[LED_BUF] = {0}; uint32_t k, c, g, br, beat, sc, sr = 0; uint32_t fam = cur_fam(), mode = settings_leds, inv = leds_inv(); /* (1.5.6: INV LO 1, INV HI 2) */ int keys_map = keys_own(); @@ -416,20 +473,20 @@ static void ui_leds(void) sc = keys_map ? 0u : scale_leds(&sr); /* SCALE LEDS: the scale's keys glow, the root's brighter */ for (k = 0; k < 27u; k++) { uint32_t in = (sc >> k) & 1u, rt = (sr >> k) & 1u, idle = !((c >> k) & 1u); - led_put(nm, 14u + k, (int)((beat >> k) & 1u)); - led_put(keys_map ? own : nl, 14u + k, (int)((c >> k) & 1u)); - led_put(keys_map ? og : nd, 14u + k, keys_map ? (int)((g >> k) & 1u) : !sc || (mode == LEDS_INV && rt)); - led_put(nb, 14u + k, (int)((br >> k) & 1u)); + led_put(nm, LED_KEY0 + k, (int)((beat >> k) & 1u)); + led_put(keys_map ? own : nl, LED_KEY0 + k, (int)((c >> k) & 1u)); + led_put(keys_map ? og : nd, LED_KEY0 + k, keys_map ? (int)((g >> k) & 1u) : !sc || (mode == LEDS_INV && rt)); + led_put(nb, LED_KEY0 + k, (int)((br >> k) & 1u)); if (!sc) continue; - led_put(sg, 14u + k, mode == LEDS_INV ? !in && idle : (int)in); /* (INV: the active ones dark) */ - led_put(sm, 14u + k, mode == LEDS_INV ? in && !rt && idle : (int)rt); + led_put(sg, LED_KEY0 + k, mode == LEDS_INV ? !in && idle : (int)in); /* (INV: the active ones dark) */ + led_put(sm, LED_KEY0 + k, mode == LEDS_INV ? in && !rt && idle : (int)rt); } for (k = 0; k < NB; k++) led_put(nd, panel.btn[k], 1); if (song.playing || seq_counting()) /* playing: PLAY's green, its own LED dark in every mode */ led_clear(nd, panel.btn[B_PLAY]); - for (c = 0; c < FM1_NCOL; c++) { + for (c = 0; c < LED_BUF; c++) { if (mode == LEDS_INV) { /* INV: the active ones dark, the rest lit (1.5.6, #212: */ iv[c] = (uint8_t)(nd[c] & ~nl[c]); /* INV LO / HI: at the steady mid level, below) */ nl[c] = inv ? 0u : iv[c]; @@ -445,6 +502,11 @@ static void ui_leds(void) nl[c] &= (uint8_t)~nb[c]; /* breathing: neither lit (INV's idle) nor the glow */ nd[c] &= (uint8_t)~nb[c]; } +#if BOARD_SMK37 + if (song.playing || (seq_counting() && cin_pos < click_beat_len() / 4u)) /* (no green LED: PLAY itself) */ + led_put(nl, panel.btn[B_PLAY], 1); + smk_leds(nl, nb, nm, og, sg); +#else if (song.playing || (seq_counting() && cin_pos < click_beat_len() / 4u)) /* counting in: green on each beat */ nl[LED_PLAY_GREEN >> 3] |= (uint8_t)(1u << (LED_PLAY_GREEN & 7u)); fm1_led_dim_level(mode == LEDS_DIM_LO || inv == 1u); /* (INV LO: the darker mid level, ~8 %; HI ~12.5 %) */ @@ -455,6 +517,7 @@ static void ui_leds(void) } for (c = 0; c < FM1_NCOL; c++) fm1_led[c] = nl[c]; +#endif } /* ---------------------------------------------------------- input --- */ @@ -1426,6 +1489,33 @@ static void ui_notices(void) } } +#if BOARD_SMK37 +/* SMK-37 Pro < / >: the previous / next page of the page's family (its button tapped again, both ways); on HOME, > + * is HOME tapped (MIXER, CLOCK) */ +static void smk_page_step(int32_t d) +{ + uint32_t n, i = ui.page, fam; + if (ui.home) { + if (d > 0) + home_tap(); + return; + } + if (page_over) + return; + fam = cur_page()->fam; + for (n = 0; n < NPAGES; n++) { + i = (i + (d > 0 ? 1u : NPAGES - 1u)) % NPAGES; + if (PAGES[i].fam == fam && page_visible(i)) + break; + } + if (i == ui.page) + return; + ui.page = (uint8_t)i; + ui.fam_last[fam] = ui.page; + page_entered(); +} +#endif + static void ui_input(void) { uint32_t pressed = fm1_input_edges(0), notes = fm1_input_note_edges(), now = fm1_ticks(), id, b, k; @@ -1436,6 +1526,18 @@ static void ui_input(void) static uint32_t lock_ms; /* BPM LOCK: the last locked SELECT turn (fm1_ms | 1; 0 none) */ midi_take(); /* (MIDI IN notes: lights, SCREEN WAKE, AUTO SELECT's) */ midi_pc_poll(); /* MIDI Program Change (before fm6_poll: a bank voice) */ +#if BOARD_SMK37 + /* KNOB BANK: what holding HOME does (the menu, or leave it); < / >: a page back / forward (in the menu: a row) */ + uint32_t smk_kb = ((pressed >> SMK_BTN_KNOB_BANK) & 1u) && smk_btn_free(SMK_BTN_KNOB_BANK); + int32_t smk_lr = ((pressed >> SMK_BTN_RIGHT) & 1u) && smk_btn_free(SMK_BTN_RIGHT) ? 1 : + ((pressed >> SMK_BTN_LEFT) & 1u) && smk_btn_free(SMK_BTN_LEFT) ? -1 : 0; + if (pressed & 1u << SMK_BTN_FADER_BANK) { /* SMK-37 Pro FADER BANK: what the four faders set */ + static const char *const FB[4] = {"A LEVEL", "B PAN", "C REV", "D DLY"}; + smk_fbank = (uint8_t)((smk_fbank + 1u) % 4u); + smk_fbank_new = 1; + ui_say("FADER BANK ", FB[smk_fbank]); + } +#endif fm6_poll(); /* FM6: PTCH turned -> its patch */ fmini_poll(); /* FMINI: SLOT turned -> its patch */ #if !FELUCCA_FM4 @@ -1527,6 +1629,10 @@ static void ui_input(void) ui.hot_t = 40; } song.grid = (uint8_t)keys_mode(); /* (the menu, a dialog: the keys play again; NAME: silent) */ +#if BOARD_SMK37 + if (smk_kb && !lay && home == BT_NONE && !ui.home_t0) + home = BT_HOLD; /* SMK-37 Pro KNOB BANK: as HOME held */ +#endif if (home == BT_TAP && ui.menu) { /* HOME (pressed, or held) closes the menu, from ABOUT too; */ menu_close(); /* the release of the hold that opened it is no tap */ home = BT_NONE; /* (menu_close went HOME already) */ @@ -1547,10 +1653,18 @@ static void ui_input(void) if (ui.save_t0) ui.save_t0 |= 2u; ui.pg_down = 0; +#if BOARD_SMK37 + if (smk_lr && ui.menu == 1) + menu_move(smk_lr); /* SMK-37 Pro < / >: the previous / next row */ +#endif if (!ui.home_t0) menu_input(oct); return; } +#if BOARD_SMK37 + if (smk_lr && !lay && !ui.confirm && !name_on()) + smk_page_step(smk_lr); +#endif if (name_on() && !ui.confirm) { /* NAME: the keys type, KNOB 1 / 2, OCT+ / OCT- (ui_name.c); */ if (ui.save_t0) /* SAVE does nothing */ ui.save_t0 |= 2u; @@ -1628,7 +1742,7 @@ static void ui_input(void) if (home == BT_TAP) /* HOME acts on release: a hold opens the menu */ home_tap(); cursor_fix(); /* LEN may have changed (knob, editor, load) */ - for (id = 0; id < 14u; id++) { + for (id = 0; id < FM1_NBTN; id++) { if (!((pressed >> id) & 1u)) continue; b = panel_btn_of(id); @@ -1823,7 +1937,7 @@ static void panel_setup(void) if (SETUP_GIVE_UP(t0)) goto timeout; } - for (id = 0; id < 14u; id++) + for (id = 0; id < FM1_NBTN; id++) if (((p & ~used) >> id) & 1u) break; panel.btn[i] = (uint8_t)id; @@ -1834,17 +1948,17 @@ static void panel_setup(void) uint32_t e; int32_t st = 0; setup_show("TURN RIGHT", E_NAME[i]); - for (e = 0; e < 7u; e++) + for (e = 0; e < FM1_NENC; e++) fm1_enc_take(e); t0 = fm1_ms; for (;;) { fm1_wdt_feed(); if (SETUP_GIVE_UP(t0)) goto timeout; - for (e = 0; e < 7u; e++) + for (e = 0; e < FM1_NENC; e++) if (!((used >> e) & 1u) && (st = fm1_enc_take(e)) != 0) break; - if (e < 7u) + if (e < FM1_NENC) break; } panel.enc[i] = (uint8_t)e; diff --git a/tests/install_test.py b/tests/install_test.py index 4bcfa25..e51ccd4 100755 --- a/tests/install_test.py +++ b/tests/install_test.py @@ -6,7 +6,8 @@ The fake device is the one in web/test_web.mjs: identity on the handshake, then "device asks, host answers" reads of the logical image. Run from the repo root: python3 tests/install_test.py Also checks logical_image/product_of against web/fm1pkg.js (needs node and -build/fmini-1-fm1-.fwsc, skipped otherwise).""" +build/fmini-1-fm1-.fwsc, skipped otherwise), and (BOARD_SMK37) the SMK-37 Pro identities and port names and the +20 / 36 block deinterleave (the stock SMK-37 Pro V016 from a directory named by SMK_STOCK_DIR, skipped when unset).""" import io import queue import shutil @@ -67,8 +68,9 @@ class FakeFM1: """a MIDI backend with one FM-1 on it""" def __init__(self, image, identity="FM-1_015", name="FM-1", unplug_after=None, after_write="FM-1_900", - stall_after=None, bad_addr=None): + stall_after=None, bad_addr=None, loader=("ota-FM-1_900", "Felucca Update")): self.image, self.unplug_after, self.after_write = image, unplug_after, after_write + self.loader = loader self.stall_after, self.bad_addr = stall_after, bad_addr self.served = self.bad = self.upgrades = 0 self.sent, self.links, self.gen, self.lock = [], [], 0, threading.Lock() @@ -123,7 +125,7 @@ class FakeFM1: if self.stall_after and self.served >= self.stall_after: return if addr == I.FINISH_CHECK: - threading.Timer(0.05, self.boot, ("ota-FM-1_900", "Felucca Update")).start() + threading.Timer(0.05, self.boot, self.loader).start() elif addr == I.FINISH_WRITE: threading.Timer(0.05, self.boot, (self.after_write, "Felucca")).start() else: @@ -148,6 +150,32 @@ def package(product="FM-1_900", marker=True, size=0x2000): return bytes(raw) +def package_crc(product="FM-1_900", size=0x3000, blocks=20, seed=7): + """a package with a valid header and file list (one file, flash.bin: 0x400 to the end), as fm1pkg_make writes, + in `blocks` interleave blocks (the stock SMK-37 Pro V016: 36)""" + img = bytearray((i * seed) & 0xFF for i in range(size)) + img[0x1800:0x1800 + 16] = I.LOADER_MARK + data = bytes(img[0x400:]) + e = bytearray(0x50) + e[0:16] = bytes(4) + I._crc16(data).to_bytes(2, "little") + bytes(2) + \ + (0x400).to_bytes(4, "little") + len(data).to_bytes(4, "little") + e[0x40:0x49] = b"flash.bin" + lst = I._dec(bytes(e)) + hdr = bytearray(0x40) + hdr[4:8] = size.to_bytes(4, "little") + hdr[8:10] = (1).to_bytes(2, "little") + hdr[2:4] = I._crc16(lst).to_bytes(2, "little") + hdr[0:2] = I._crc16(bytes(hdr[2:0x40])).to_bytes(2, "little") + img[0:0x40] = I._dec(bytes(hdr)) + img[0x40:0x90] = lst + raw = bytearray() + for i in range(blocks): + m = (ord(product[i]) + i + 1) & 0xFF if i < len(product) else 0x7D + raw += img[i * I.KEEP:(i + 1) * I.KEEP] + bytes([m]) + raw += img[blocks * I.KEEP:] + return bytes(raw) + + TMP = Path(tempfile.mkdtemp(prefix="felucca-install-")) @@ -243,6 +271,9 @@ def errors(): dev = FakeFM1(image, identity="XY-9_001", name="usb-midi") rc, out, err = cli([p, "--yes"], dev) ok(rc == 6 and dev.upgrades == 0, "another model -> exit 6, nothing sent") + dev = FakeFM1(image, identity="ota-SMK-37 Pro_900", name="Felucca Update") + rc, out, err = cli([p, "--yes"], dev) + ok(rc == 6 and dev.upgrades == 0, "FM-1 package on an SMK in update mode -> exit 6 (wrong model), nothing sent") class Stuck(FakeFM1): # the loader never shows up def boot(self, identity, name): @@ -298,9 +329,71 @@ def official(): ok(rc == 2 and "official V15" in err and dev.sent == [], "a modified V15 is still refused (no MIDI)") +def smk(): + """SMK-37 Pro: identities, port names, the 36-block stock package, the SMK install path""" + ok(I.PORT_RE.search("SMK-37 Pro Midi") and I.PORT_RE.search("FM-1") and not I.PORT_RE.search("IAC Driver Bus 1"), + "port names: SMK-37 Pro ports probed, FM-1 too, other gear not") + ident = I.parse_identity(b"\xF0" + I.pack7(bytes([0, 0x59, 0x11, 0, 0, 0]) + b"SMK-37 Pro_016" + bytes(14)) + b"\xF7") + ok(ident and ident.model == "SMK-37 Pro" and ident.version == 16 and I.model_of("ota-SMK-37 Pro_900") == "SMK-37 Pro", + "identity SMK-37 Pro_016 parses (model SMK-37 Pro, the space kept)") + raw36 = package_crc("SMK-37 Pro_900", blocks=36) + image36 = I.deinterleave(raw36) + ok(I.block_count(raw36) == 36 and len(image36) == len(raw36) - 36 and I.files_ok(image36) + and I.product_of(raw36) == "SMK-37 Pro_900", "36 blocks (synthetic): detected, logical image valid") + ok(not I.files_ok(I.logical_image(raw36)), "... a fixed 20-block deinterleave of it fails the CRCs") + for seed in range(1, 256): # a 20-block package with 0x7D at the 21st marker by chance + raw = package_crc("FM-1_900", seed=seed) + if raw[20 * I.BLK + I.KEEP] == 0x7D: + break + image = I.deinterleave(raw) + ok(I.block_count(raw) > 20 and image == I.logical_image(raw) and I.files_ok(image), + f"20 blocks with a 0x7D data byte at the 21st marker (seed {seed}): falls back to 20") + raw = package("FM-1_900") + ok(I.deinterleave(raw) == I.logical_image(raw), "a plain 20-block package: deinterleave == logical_image") + + p = pkgfile("smk.fwsc", package("SMK-37 Pro_900")) + image = I.logical_image(package("SMK-37 Pro_900")) + dev = FakeFM1(image, identity="SMK-37 Pro_016", name="SMK-37 Pro Midi", after_write="SMK-37 Pro_900", + loader=("ota-SMK-37 Pro_900", "Felucca Update")) + rc, out, err = cli([p, "--yes"], dev) + ok(rc == 0 and dev.bad == 0 and dev.upgrades == 2 and "SMK-37 Pro_900" in out, + "install on an SMK-37 Pro: running -> loader -> SMK-37 Pro_900") + dev = FakeFM1(image, identity="ota-SMK-37 Pro_900", name="Felucca Update", after_write="SMK-37 Pro_900") + rc, out, err = cli([p, "--yes"], dev) + ok(rc == 0 and dev.upgrades == 1, "SMK-37 Pro in Felucca's update mode -> finishes the write") + dev = FakeFM1(image, identity="SMK-37 Pro_016", name="SMK-37 Pro Midi") + rc, out, err = cli([pkgfile("fm1.fwsc", package("FM-1_900")), "--yes"], dev) + ok(rc == 6 and dev.upgrades == 0, "FM-1 package on an SMK-37 Pro -> exit 6 (wrong model), nothing sent") + dev = FakeFM1(image, identity="FM-1_015", name="FM-1") + rc, out, err = cli([p, "--yes"], dev) + ok(rc == 6 and dev.upgrades == 0, "SMK-37 Pro package on an FM-1 -> exit 6, nothing sent") + + import os # the stock package (outside this repo; read only) + v016 = Path(os.environ.get("SMK_STOCK_DIR") or ROOT / "no-stock-packages") / "SMK-37_Pro_016.fwsc" + if not v016.exists(): + print("stock SMK-37 Pro V016: skipped (SMK_STOCK_DIR not set)") + return + raw = v016.read_bytes() + image = I.deinterleave(raw) + ok(I.block_count(raw) == 36 and I.product_of(raw) == "SMK-37 Pro_016" and I.files_ok(image), + "stock SMK-37_Pro_016.fwsc: 36 blocks, identity SMK-37 Pro_016, CRCs ok") + product, image2 = I.load_package(str(v016), False) + ok(product == "SMK-37 Pro_016" and image2 == image, "... accepted for the return to stock (pinned SHA-256)") + + wire() installs() errors() +smk() +# a package installs only on exactly its own model: each SMK model's build on that model, never FM-1 <-> SMK +ok(I.same_model("SMK-37 Pro_016", "SMK-37 Pro_900") and I.same_model("ota-SMK-37 Elite_900", "SMK-37 Elite_900") + and I.same_model("MKE-P37_016", "MKE-P37_900") and I.same_model("FM-1_015", "FM-1_900") + and not I.same_model("SMK-37 Elite_016", "SMK-37 Pro_900") and not I.same_model("ota-MKE-P37_900", "SMK-37 Elite_900") + and not I.same_model("SMK-37 Pro_016", "MKE-P37_900") and not I.same_model("FM-1_015", "SMK-37 Pro_900") + and not I.same_model("ota-SMK-37 Pro_900", "FM-1_900") and not I.same_model("XY-9_001", "SMK-37 Pro_900"), + "models: a package only for exactly its own model (Pro, Elite, MKE-P37, FM-1)") +ok(all(I.PORT_RE.search(n) for n in ("SMK-37 Elite", "MKE-P37", "STARRYKEY-37 PLAY", "Felucca", "Felucca Update")), + "port names: every SMK model and Felucca probed") against_js() official() shutil.rmtree(TMP, ignore_errors=True) diff --git a/tests/ldr_test.c b/tests/ldr_test.c index ac0f78b..7bd693d 100644 --- a/tests/ldr_test.c +++ b/tests/ldr_test.c @@ -3,14 +3,43 @@ /* Host test of the Felucca update loader (firmware/loader/ldr_core.c): a fake * host serves a package over the SysEx protocol, the "device" flash starts as * another package's flash.bin (as if that firmware were installed). - * ldr_test OLD.fwsc NEW.fwsc */ + * ldr_test OLD.fwsc NEW.fwsc + * With -DBOARD_SMK37=1 (packages from fm1pkg_make.py --board smk37): the SMK-37 Pro windows (app area + * up to 0x9D000, records 0x9D000..0xBFFFF) and the protected ranges BTIF / USRTRIM 0xC0000..0xC1FFF, + * USR 0xF4000..0xFDFFF and key_mac 0xFF000 never touched, even with a valid-looking record in them. */ #include #include #include #include #define __attribute__(x) /* (the sources' .pool sections: no Mach-O section names) */ +#if BOARD_SMK37 +#define FELUCCA_ID "ota-SMK-37 Pro_900" +#define T_APP_HI 0x9D000u /* end of the app area the loader writes */ +#define T_REC 0xBFF00u /* the SMK build's update record (ota.c OTA_RES) */ +#define T_REC2 0xAEF00u /* a record elsewhere in the VM (the stock app's staging is not fixed) */ +#define T_ERASE_LO 0x9D000u /* records: the VM only */ +#define T_ERASE_HI 0xC0000u /* nothing erased at or above (BTIF, USRTRIM, ...) */ +#define T_DATA_LO 0u /* no store range skipped (user samples are in USRFLASH) */ +#define T_DATA_HI 0u +#define T_USER 0xC2000u /* user sample data (USR1), outside the record window */ +#define T_FL_OTHER 0x93000u /* another board's (the FM-1's) flash.bin size */ +#define T_FL_OTHER_NAME "0x93000" +#define T_FL_NAME "0x9D000" +#else #define FELUCCA_ID "ota-FM-1_900" +#define T_APP_HI 0x93000u +#define T_REC 0xE4F00u +#define T_REC2 0xE8F00u /* the stock firmware's */ +#define T_ERASE_LO 0x4000u +#define T_ERASE_HI 0xFC000u +#define T_DATA_LO 0x97000u +#define T_DATA_HI 0xE0000u +#define T_USER 0xA0000u +#define T_FL_OTHER 0x9D000u /* an SMK-37 Pro package's flash.bin size */ +#define T_FL_OTHER_NAME "0x9D000" +#define T_FL_NAME "0x93000" +#endif #define FELUCCA_OTA_DRYRUN 0 static uint8_t nor[0x100000], *logical; @@ -84,7 +113,8 @@ static void ota_commit(const uint8_t *parm) { (void)parm; } static int ldr_fread(uint32_t off, void *p, uint32_t n) { memcpy(p, nor + off, n); return 0; } static int ldr_erase(uint32_t off) { - if (off < 0x4000u || off >= 0xFC000u || (off & 0xFFFu) || (off >= 0x97000u && off < 0xE0000u)) bad_range++; + if (off < 0x4000u || off >= T_ERASE_HI || (off & 0xFFFu) || (off >= T_DATA_LO && off < T_DATA_HI) || + (off >= T_APP_HI && off < T_ERASE_LO)) bad_range++; if (off < 0x4000u) { printf("ERASE IN THE HEAD %#x\n", off); exit(1); } erases++; memset(nor + off, 0xFF, 0x1000); @@ -94,7 +124,7 @@ static int ldr_prog(uint32_t off, const void *p, uint32_t n) { const uint8_t *s = p; uint32_t i; - if (off < 0x4000u || off + n > 0x93000u || ((off & 0xFFu) + n) > 256u) bad_range++; + if (off < 0x4000u || off + n > T_APP_HI || ((off & 0xFFu) + n) > 256u) bad_range++; for (i = 0; i < n; i++) nor[off + i] &= s[i]; return 0; } @@ -158,6 +188,43 @@ static void set_fl_size(uint8_t *lg, uint32_t size) static int check(const char *what, int ok) { printf("%-56s %s\n", what, ok ? "ok" : "FAIL"); return ok ? 0 : 1; } +static void put_record_at(uint32_t at) /* a valid update record (the SPL runs the loader) */ +{ + uint8_t r[112] = {0}; + r[2] = 0x0D; r[3] = 0x5A; r[4] = 0x01; r[5] = 0x5A; r[6] = 0x41; r[7] = 0x54; + ota_wr16(r, ota_crc16(r + 2, 78, 0)); + memcpy(nor + at, r, sizeof r); +} + +#if BOARD_SMK37 +/* the SMK's protected ranges: a pattern, and a valid-looking record in BTIF, USRTRIM and USR */ +static const uint32_t PROT[][2] = {{0xC0000u, 0xC2000u}, {0xF4000u, 0xFE000u}, {0xFF000u, 0x100000u}}; +static uint8_t prot_img[sizeof nor]; +static void protect_fill(void) +{ + uint32_t i, k; + for (k = 0; k < sizeof PROT / sizeof PROT[0]; k++) + for (i = PROT[k][0]; i < PROT[k][1]; i++) + nor[i] = (uint8_t)(i * 13u + 5u); + memcpy(nor + 0xC1224u, "trimdat", 8); + put_record_at(0xC1F00u); /* USRTRIM sector: must never be erased */ + put_record_at(0xC0F00u); /* BTIF */ + put_record_at(0xF4F00u); /* USR */ + memcpy(prot_img, nor, sizeof nor); +} +static int protect_ok(void) +{ + uint32_t k; + for (k = 0; k < sizeof PROT / sizeof PROT[0]; k++) + if (memcmp(nor + PROT[k][0], prot_img + PROT[k][0], PROT[k][1] - PROT[k][0])) + return 0; + return 1; +} +#else +static void protect_fill(void) {} +static int protect_ok(void) { return 1; } +#endif + int main(int argc, char **argv) { size_t olen; @@ -170,33 +237,29 @@ int main(int argc, char **argv) logical = load_logical(argv[2], &logical_len); ofo = flash_off(old); nfo = flash_off(logical); - /* device: OLD installed, plus a valid update record at 0xE4F00 (Felucca's step 1) and 0xE8F00 (the stock - * firmware's, a first install from it); user sample data in Felucca's store that looks like a record */ + /* device: OLD installed, plus a valid update record at T_REC (Felucca's step 1; FM-1 0xE4F00) and T_REC2 (FM-1: + * the stock firmware's 0xE8F00, a first install from it); user sample data that looks like a record */ memset(nor, 0xFF, sizeof nor); - memcpy(nor, old + ofo, 0x93000); + memcpy(nor, old + ofo, T_APP_HI); + protect_fill(); memcpy(head, nor, sizeof head); - { - uint8_t r[112] = {0}; - r[2] = 0x0D; r[3] = 0x5A; r[4] = 0x01; r[5] = 0x5A; r[6] = 0x41; r[7] = 0x54; - ota_wr16(r, ota_crc16(r + 2, 78, 0)); - memcpy(nor + 0xE4F00, r, sizeof r); - memcpy(nor + 0xE8F00, r, sizeof r); - for (i = 0; i < 0x1000u; i++) nor[0xA0000 + i] = (uint8_t)(i * 7u); - memcpy(nor + 0xA0F00, r, sizeof r); - memcpy(user, nor + 0xA0000, sizeof user); - } + put_record_at(T_REC); + put_record_at(T_REC2); + for (i = 0; i < 0x1000u; i++) nor[T_USER + i] = (uint8_t)(i * 7u); + put_record_at(T_USER + 0xF00u); + memcpy(user, nor + T_USER, sizeof user); /* 1.6.1: flash.bin must be exactly this board's [0, app area end): a package with another board's size (an * SMK-37's app area ends at 0x9D000, the FM-1's at 0x93000; one byte short too) is refused before any erase */ { - static const uint32_t SZ[2] = {0x9D000u, LDR_APP_HI - 1u}; + static const uint32_t SZ[2] = {T_FL_OTHER, LDR_APP_HI - 1u}; uint32_t k; for (k = 0; k < 2u; k++) { set_fl_size(logical, SZ[k]); erases = 0; rc = ldr_session(); bad += check(k ? "flash.bin a byte short of the app area: refused, nothing erased" : - "another board's size (0x9D000): refused (-14), nothing erased", - rc == -14 && erases == 0 && !memcmp(nor + 0x4000, old + ofo + 0x4000, 0x93000 - 0x4000)); + "another board's size (" T_FL_OTHER_NAME "): refused (-14), nothing erased", + rc == -14 && erases == 0 && !memcmp(nor + 0x4000, old + ofo + 0x4000, T_APP_HI - 0x4000)); } set_fl_size(logical, LDR_APP_HI); /* back: this board's size, the install below takes it */ requests = 0; @@ -208,7 +271,7 @@ int main(int argc, char **argv) erases = 0; rc = ldr_session(); bad += check("damaged package (flash.bin CRC) refused, nothing erased", rc == -12 && erases == 0 && - !memcmp(nor + 0x4000, old + ofo + 0x4000, 0x93000 - 0x4000) && nor[0xE4F06] == 0x41); + !memcmp(nor + 0x4000, old + ofo + 0x4000, T_APP_HI - 0x4000) && nor[T_REC + 6u] == 0x41); logical[at] ^= 0x01; requests = 0; } @@ -216,15 +279,15 @@ int main(int argc, char **argv) flip_addr = nfo + 0x20000u; flip_on = 2; flip_seen = 0; rc = ldr_session(); printf(" rc %d, %u requests, %u sector erases\n", rc, requests, erases); - bad += check("install completes (flash.bin exactly the app area, 0x93000)", rc == 0); + bad += check("install completes (flash.bin exactly the app area, " T_FL_NAME ")", rc == 0); bad += check("a sector changed in transfer after the check is read again", flip_seen == 3); flip_addr = 0xFFFFFFFFu; - bad += check("app area == the new package's flash.bin", !memcmp(nor + 0x4000, logical + nfo + 0x4000, 0x93000 - 0x4000)); + bad += check("app area == the new package's flash.bin", !memcmp(nor + 0x4000, logical + nfo + 0x4000, T_APP_HI - 0x4000)); bad += check("flash head [0, 0x4000) untouched", !memcmp(nor, head, sizeof head)); bad += check("finish asked (0xF0000000)", f0_asked >= 1); - bad += check("update records cleared (RAM + flash 0xE4F00, the stock firmware's 0xE8F00)", - record_cleared && nor[0xE4F06] == 0xFF && nor[0xE8F06] == 0xFF); - bad += check("user data in Felucca's store that looks like a record is kept", !memcmp(nor + 0xA0000, user, sizeof user)); + bad += check("update records cleared (RAM + flash: ours, the other one)", + record_cleared && nor[T_REC + 6u] == 0xFF && nor[T_REC2 + 6u] == 0xFF); + bad += check("user sample data that looks like a record is kept", !memcmp(nor + T_USER, user, sizeof user)); bad += check("no write outside the allowed windows", bad_range == 0); /* same package again: nothing to erase */ erases = 0; requests = 0; @@ -234,12 +297,13 @@ int main(int argc, char **argv) { uint8_t save = logical[nfo + 0x4000 + 5]; logical[nfo + 0x4000 + 5] ^= 0x5A; /* app area head no longer decrypts */ - memcpy(nor, old + ofo, 0x93000); + memcpy(nor, old + ofo, T_APP_HI); erases = 0; rc = ldr_session(); bad += check("foreign key / damaged app head refused, nothing erased", rc == -6 && erases == 0); logical[nfo + 0x4000 + 5] = save; } + bad += check("protected ranges untouched (SMK: BTIF, USRTRIM, USR, key_mac)", protect_ok()); printf("%s\n", bad ? "LOADER TEST FAILED" : "loader test passed"); return bad != 0; } diff --git a/tests/ota_test.c b/tests/ota_test.c index 1786dac..a37a9ce 100644 --- a/tests/ota_test.c +++ b/tests/ota_test.c @@ -11,7 +11,29 @@ #include #define __attribute__(x) /* (the sources' .pool sections: no Mach-O section names) */ +#if BOARD_SMK37 /* -DBOARD_SMK37=1: the SMK-37 Pro build of ota.c */ +#if T_MODEL == 1 /* -DT_MODEL=1 / 2: the MODEL=elite / mke build */ +#define SMK_MODEL "SMK-37 Elite" +#elif T_MODEL == 2 +#define SMK_MODEL "MKE-P37" +#else +#define SMK_MODEL "SMK-37 Pro" +#endif +#define FELUCCA_ID SMK_MODEL "_900" +#define T_AREA 0xBB000u +#define T_FL_LEN "0x9D000" /* flash.bin: this board's [0, app area end) */ +#define T_FL_OTHER 0x93000u /* the other board's (the FM-1's) */ +#define T_FL_OTHER_NAME "0x93000" +#define T_PARM_ID "ota-" SMK_MODEL "_016" +#else #define FELUCCA_ID "FM-1_900" +#define T_AREA 0xE0000u +#define T_PARM_ID "ota-FM-1_015" +#define T_FL_LEN "0x93000" +#define T_FL_OTHER 0x9D000u /* an SMK-37 Pro package's */ +#define T_FL_OTHER_NAME "0x9D000" +#endif +#define T_AREA_HI (T_AREA + 0x5000u) #define FELUCCA_OTA_DRYRUN 0 static uint8_t nor[0x100000]; @@ -97,7 +119,7 @@ static uint32_t ota_now_ms(void) { return now_ms; } static void ota_idle(void) { now_ms += 1; } static int ota_erase(uint32_t off) { - if (off < 0xE0000u || off >= 0xE5000u || (off & 0xFFFu)) { bad_erase++; return -8; } + if (off < T_AREA || off >= T_AREA_HI || (off & 0xFFFu)) { bad_erase++; return -8; } erases++; memset(nor + off, 0xFF, 4096); return 0; @@ -106,7 +128,7 @@ static int ota_prog(uint32_t off, const void *src, uint32_t n) { const uint8_t *s = src; uint32_t i; - if (off < 0xE0000u || off + n > 0xE5000u) { bad_erase++; return -8; } + if (off < T_AREA || off + n > T_AREA_HI) { bad_erase++; return -8; } for (i = 0; i < n; i++) nor[off + i] &= s[i]; return 0; } @@ -162,7 +184,7 @@ static int check(const char *what, int ok) static int area_erased(void) { uint32_t i; - for (i = 0xE0000; i < 0xE5000; i++) if (nor[i] != 0xFF) return 0; + for (i = T_AREA; i < T_AREA_HI; i++) if (nor[i] != 0xFF) return 0; return 1; } @@ -207,19 +229,24 @@ int main(int argc, char **argv) reset_dev(); rc = ota_session(); printf(" %u requests\n", requests); - bad += check("session commits (flash.bin exactly 0x93000)", rc == 0 && committed); + bad += check("session commits (flash.bin exactly " T_FL_LEN ")", rc == 0 && committed); /* own loader: 19 requests; the official loader (V15, V16) is larger: 44 (it writes the head, which is no longer read) */ bad += check("headers + loader + confirm, no head reads", requests >= 10 && requests <= 60); { - uint8_t *h = nor + 0xE0000, *p = committed_parm; - bad += check("staged body == the package's loader", !memcmp(nor + 0xE0020, logical + ota_body_off(), 64)); + uint8_t *h = nor + T_AREA, *p = committed_parm; + uint32_t k, zero = 1; + for (k = 8u + sizeof T_PARM_ID - 1u; k < 0x28u; k++) + zero &= p[k] == 0; + bad += check("staged body == the package's loader", !memcmp(nor + T_AREA + 0x20u, logical + ota_body_off(), 64)); bad += check("LOADER.BIN head CRC", (h[0] | h[1] << 8) == ota_crc16(h + 2, 30, 0) && !memcmp(h + 16, "LOADER.BIN", 10)); - bad += check("record at 0xE4F00 == RAM record", !memcmp(nor + 0xE4F00, p, 112)); + bad += check("record at the area end - 256 == RAM record", !memcmp(nor + T_AREA_HI - 0x100u, p, 112)); + bad += check("parm identity " T_PARM_ID ", zero to +0x27", + !memcmp(p + 8, T_PARM_ID, sizeof T_PARM_ID - 1u) && zero); bad += check("record CRC / type / magic / ota_addr", (p[0] | p[1] << 8) == ota_crc16(p + 2, 78, 0) && (p[2] | p[3] << 8) == 0x5A0D && - (p[6] | p[7] << 8) == 0x5441 && ota_rd32(p + 72) == 0xE0000); - bad += check("nothing written outside 0xE0000..0xE4FFF", bad_erase == 0); + (p[6] | p[7] << 8) == 0x5441 && ota_rd32(p + 72) == T_AREA); + bad += check("nothing written outside the staging area", bad_erase == 0); } /* boot cleanup erases it */ bad += check("boot cleanup erases the area", ota_boot_cleanup() == 1 && area_erased()); @@ -230,9 +257,9 @@ int main(int argc, char **argv) uint8_t keep[0x40 + 11 * 0x50]; memcpy(keep, logical, sizeof keep); reset_dev(); - set_fl_size(logical, 0x9D000u); + set_fl_size(logical, T_FL_OTHER); rc = ota_session(); - bad += check("another board's size (0x9D000): -15, no commit, no erase", rc == -15 && !committed && erases == 0 && + bad += check("another board's size (" T_FL_OTHER_NAME "): -15, no commit, no erase", rc == -15 && !committed && erases == 0 && area_erased()); memcpy(logical, keep, sizeof keep); } diff --git a/tests/run_tests.sh b/tests/run_tests.sh index 611cc71..92ac56f 100755 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -263,6 +263,30 @@ python3 tools/fm1pkg_make.py "$OUT/old_app.bin" build/loader/ota.bin "$OUT/old.f $CC -o "$OUT/ldr_test" tests/ldr_test.c run "update loader: other app -> this build" "$OUT/ldr_test" "$OUT/old.fwsc" "$PKG" +# SMK-37 Pro (BOARD_SMK37): the flash map, the OTA staging and the loader windows on SMK-layout packages +# (made here from the FM-1 binaries: only the layout and the protocol are under test) +$CC -DBOARD_SMK37=1 -Ifirmware/hal -o "$OUT/smk_flash_test" tests/smk_flash_test.c +run "SMK-37 Pro flash map: allow-lists never reach the head, BTIF/USRTRIM, USR, key_mac; store layout" "$OUT/smk_flash_test" +$CC -DBOARD_SMK37=1 -Ifirmware/hal -o "$OUT/smk_owner_test" tests/smk_owner_test.c +run "SMK-37 Pro store owner tag: another firmware's store cleared, ours kept, nothing else written" "$OUT/smk_owner_test" +python3 tools/fm1pkg_make.py --board smk37 build/felucca.bin build/loader/ota.bin "$OUT/smk_new.fwsc" >/dev/null +python3 tools/fm1pkg_make.py --board smk37 "$OUT/old_app.bin" build/loader/ota.bin "$OUT/smk_old.fwsc" >/dev/null +run "SMK-37 Pro package layout (fm1pkg_make --board smk37): PRCT 0x9D000, stock region table" python3 tests/smk_pkg_test.py "$OUT/smk_new.fwsc" +$CC -DBOARD_SMK37=1 -DOWN_PKG=1 -o "$OUT/ota_test_smk" tests/ota_test.c +run "M-UPGRADE entry, SMK-37 Pro build (staging 0xBB000, parm ota-SMK-37 Pro_016)" "$OUT/ota_test_smk" "$OUT/smk_new.fwsc" +for m in 1 2; do # the MODEL=elite / mke builds of ota.c + $CC -DBOARD_SMK37=1 -DT_MODEL=$m -o "$OUT/ota_test_smk_m$m" tests/ota_test.c + run "M-UPGRADE entry, SMK model $m build (MODEL=elite / mke: its own parm identity)" "$OUT/ota_test_smk_m$m" "$OUT/smk_new.fwsc" +done +for m in pro elite mke; do # the packages build.sh made (BOARD=smk37 MODEL=...), when present + f=build/felucca-smk37.fwsc; id="SMK-37 Pro_900" + [ $m = elite ] && f=build/felucca-smk37-elite.fwsc && id="SMK-37 Elite_900" + [ $m = mke ] && f=build/felucca-smk37-mke.fwsc && id="MKE-P37_900" + [ -f $f ] && run "SMK package $f: identity $id, stock region table" python3 tests/smk_pkg_test.py $f "$id" +done +$CC -DBOARD_SMK37=1 -o "$OUT/ldr_test_smk" tests/ldr_test.c +run "update loader, SMK-37 Pro: app area 0x4000-0x9CFFF, protected ranges untouched" "$OUT/ldr_test_smk" "$OUT/smk_old.fwsc" "$OUT/smk_new.fwsc" + if [ -f build/gen/felucca_tables.h ]; then $CC -O2 -w -Ibuild/gen -Ifirmware/src -o "$OUT/hostsim" tests/hostsim.c -lm $CC -O2 -w -Ibuild/gen -Ifirmware/src -o "$OUT/scale_test" tests/scale_test.c -lm diff --git a/tests/smk_flash_test.c b/tests/smk_flash_test.c new file mode 100644 index 0000000..7a8c938 --- /dev/null +++ b/tests/smk_flash_test.c @@ -0,0 +1,90 @@ +/* SPDX-License-Identifier: GPL-3.0-only + * Felucca on the SMK-37 Pro (BOARD_SMK37) */ +/* SMK-37 Pro flash map (build with -DBOARD_SMK37=1): + * every 4 KiB sector of the 1 MiB part through the app's allow-list (FL_RANGE_OK / FL_GUARD, fm1_flash.h), + * the update loader's (loader.c) and ldr_core.c's record window: none of them may ever reach + * the head 0x0-0x3FFF, BTIF / USRTRIM 0xC0000-0xC1FFF, USR 0xF4000-0xFDFFF or key_mac 0xFF000-; + * the store's objects (storage.c), the FM6 voice bank (fm6_vbank.c) and the OTA staging (ota.c) lie + * inside the allowed windows; ranges that wrap or straddle a boundary are refused. */ +#include +#include +#include +#include "fm1_cc.h" +#if !BOARD_SMK37 +#error "build with -DBOARD_SMK37=1" +#endif + +#include "fm1_flash_map.h" + +static int st_read(uint32_t off, void *dst, uint32_t n) { (void)off; (void)dst; (void)n; return -1; } +static int st_erase(uint32_t off) { (void)off; return -1; } +static int st_prog(uint32_t off, const void *src, uint32_t n) { (void)off; (void)src; (void)n; return -1; } +#include "../firmware/src/storage.c" +#define LDR_RANGE_OK(off, n) FL_LDR_RANGE_OK(off, n) /* what loader.c uses on the SMK */ + +static int bad; +static void check(const char *what, int ok) { printf("smk flash: %-78s %s\n", what, ok ? "ok" : "FAIL"); bad += !ok; } + +static int protected_sector(uint32_t s) +{ + return s < 0x4000u || (s >= 0xC0000u && s < 0xC2000u) || (s >= 0xF4000u && s < 0xFE000u) || s >= 0xFF000u; +} + +int main(void) +{ + uint32_t s, o, c, leak_app = 0, leak_ldr = 0, leak_guard = 0, allowed = 0, in_store = 1; + for (s = 0; s < 0x100000u; s += 0x1000u) { + if (!protected_sector(s)) + continue; + leak_app += FL_RANGE_OK(s, 0x1000u) || FL_STORE_OK(s, 0x1000u) || FL_RANGE_OK(s, 256u) || FL_RANGE_OK(s + 0xF00u, 256u); + leak_ldr += LDR_RANGE_OK(s, 0x1000u) || LDR_RANGE_OK(s + 0xF00u, 256u); + leak_guard += !FL_PROTECTED(s, 0x1000u) || !FL_PROTECTED(s + 0xF00u, 256u); + } + for (s = 0; s < 0x100000u; s += 0x1000u) + allowed += FL_GUARD(s, 0x1000u); + check("no protected sector passes the app's allow-list (erase, page)", leak_app == 0); + check("no protected sector passes the loader's allow-list", leak_ldr == 0); + check("the RAM driver's own net (FL_PROTECTED) covers every protected sector", leak_guard == 0); + check("straddling ranges refused: 0xBF000+0x2000, 0xE9000+0x2000, 0x3000+0x2000", + !FL_GUARD(0xBF000u, 0x2000u) && !FL_GUARD(0xE9000u, 0x2000u) && !LDR_RANGE_OK(0xBF000u, 0x2000u) && + !LDR_RANGE_OK(0x3000u, 0x2000u) && FL_PROTECTED(0xBF000u, 0x2000u) && FL_PROTECTED(0x3F00u, 0x200u)); + check("wrapping ranges refused (off + n past 4 GiB)", + !FL_GUARD(0xBB000u, 0xFFFFF000u) && !LDR_RANGE_OK(0x9D000u, 0xFFFFFF00u) && FL_PROTECTED(0xBB000u, 0xFFFFF000u)); + check("app windows: FL_DATA 0x9D000-0xBAFFF, FL_OTA 0xBB000-0xBFFFF, FL_SMP 0xC2000-0xE9FFF", + FL_GUARD(0x9D000u, 0x1000u) && FL_GUARD(0xBA000u, 0x1000u) && FL_GUARD(0xBF000u, 0x1000u) && + FL_GUARD(0xC2000u, 0x1000u) && FL_GUARD(0xE9000u, 0x1000u) && FL_GUARD(0xEA000u, 0x1000u) && + !FL_GUARD(0xEB000u, 0x1000u) && !FL_GUARD(0x9C000u, 0x1000u) && + allowed == (0xC0000u - 0x9D000u + 0xEA000u - 0xC2000u) / 0x1000u + 1u); + check("the stock marker sector 0xEA000: the whole sector only (its erase), never a page or a range into it", + FL_STOCKTAG_OK(0xEA000u, 0x1000u) && !FL_GUARD(0xEA000u, 256u) && !FL_GUARD(0xEAF00u, 256u) && + !FL_GUARD(0xE9000u, 0x2000u) && !FL_GUARD(0xEA000u, 0x2000u) && FL_STOCKTAG_OFF == 0xEAFF8u); + check("loader: app area 0x4000-0x9CFFF, records 0x9D000-0xBFFFF only", + LDR_RANGE_OK(0x4000u, 0x1000u) && LDR_RANGE_OK(0x9C000u, 0x1000u) && LDR_RANGE_OK(0xBF000u, 0x1000u) && + !LDR_RANGE_OK(0xC0000u, 0x1000u) && FL_REC_HI == 0xC0000u); + for (o = 0; o < OBJ_COUNT; o++) + for (c = 0; c < 2u; c++) + in_store &= FL_STORE_OK(st_sector(o, c), 0x1000u) && st_sector(o, c) < FL_DATA_HI; + { /* every object's two copies distinct */ + uint32_t o2, c2, distinct = 1; + for (o = 0; o < OBJ_COUNT; o++) + for (c = 0; c < 2u; c++) + for (o2 = 0; o2 < OBJ_COUNT; o2++) + for (c2 = 0; c2 < 2u; c2++) + if ((o != o2 || c != c2) && st_sector(o, c) == st_sector(o2, c2) && + !(c == c2 && (o == OBJ_FM6BANK || o == OBJ_UPFM6) && (o2 == OBJ_FM6BANK || o2 == OBJ_UPFM6))) + distinct = 0; /* (the retired FM6 bank and OBJ_UPFM6 share a pair, as on the FM-1) */ + check("storage.c: every object (A/B) in FL_DATA, no two share a sector", in_store && distinct); + for (o = 0, distinct = 1; o < OBJ_COUNT; o++) + for (c = 0; c < 2u; c++) + distinct &= st_sector(o, c) != ST_SMK_VBANK && st_sector(o, c) < 0xAF000u; + check("FM6 voice bank 0xB0000: in FL_DATA, its own sector; objects below the owner tag 0xAF000", + distinct && FL_STORE_OK(ST_SMK_VBANK, 0x1000u) && ST_SMK_VBANK == 0xB0000u); + } + check("storage.c: settings 0xAD000/0xAE000, projects from 0x9D000", + st_sector(OBJ_SETTINGS, 0) == 0xAD000u && st_sector(OBJ_SETTINGS, 1) == 0xAE000u && st_sector(OBJ_PROJECT0, 0) == 0x9D000u); + check("FL_PLAIN_LO = the VM start 0x9D000", FL_PLAIN_LO == 0x9D000u); + check("FL_JEDEC_OK: the SMK part 0xEB6014 and 0x856014 only", FL_JEDEC_OK(0xEB6014u) && FL_JEDEC_OK(0x856014u) && + !FL_JEDEC_OK(0u) && !FL_JEDEC_OK(0xFFFFFFu) && !FL_JEDEC_OK(0xEB6015u)); + printf("%s\n", bad ? "SMK FLASH TEST FAILED" : "smk flash test passed"); + return bad != 0; +} diff --git a/tests/smk_owner_test.c b/tests/smk_owner_test.c new file mode 100644 index 0000000..28daf3a --- /dev/null +++ b/tests/smk_owner_test.c @@ -0,0 +1,148 @@ +/* SPDX-License-Identifier: GPL-3.0-only + * Felucca on the SMK-37 Pro (BOARD_SMK37) */ +/* SMK-37 Pro store owner tag (storage.c st_owner_check, build with -DBOARD_SMK37=1): a simulated flash with + * another firmware's store, an untagged one and Felucca's own; only FL_DATA objects, the voice bank and the tag + * sector are ever erased, and ours is kept. */ +#include +#include +#include +#include "fm1_cc.h" +#if !BOARD_SMK37 +#error "build with -DBOARD_SMK37=1" +#endif +#include "fm1_flash_map.h" + +static uint8_t nor[0x100000]; +static int bad_write; +static int tag_erases; +static int st_read(uint32_t off, void *dst, uint32_t n) { memcpy(dst, nor + off, n); return 0; } +static int st_erase(uint32_t off) +{ + if ((off & 0xFFFu) || !(FL_IN(off, 0x1000u, 0x9D000u, 0xAF000u) || off == 0xAF000u || off == 0xB0000u || off == 0xEA000u)) + bad_write++; + if (off == 0xEA000u) + tag_erases++; + memset(nor + off, 0xFF, 0x1000); + return 0; +} +static int st_prog(uint32_t off, const void *src, uint32_t n) +{ + const uint8_t *s = src; + uint32_t i; + if (off != 0xAF000u) + bad_write++; + for (i = 0; i < n; i++) + nor[off + i] &= s[i]; + return 0; +} +#include "../firmware/src/storage.c" + +static int bad; +static void check(const char *what, int ok) { printf("smk owner: %-74s %s\n", what, ok ? "ok" : "FAIL"); bad += !ok; } + +static void fill(void) +{ + memset(nor, 0xFF, sizeof nor); + memset(nor + 0x9D000, 0x11, 0x12000); /* objects */ + memset(nor + 0xB0000, 0x22, 0x1000); /* voice bank */ + memset(nor + 0xC1000, 0x33, 0x1000); /* USRTRIM: never touched */ + memset(nor + 0xC2000, 0x44, 0x1000); /* a user sample */ +} +static int store_erased(void) +{ + uint32_t i; + for (i = 0x9D000; i < 0xAF000; i++) if (nor[i] != 0xFF) return 0; + for (i = 0xB0000; i < 0xB1000; i++) if (nor[i] != 0xFF) return 0; + return 1; +} +static int others_kept(void) { return nor[0xC1000] == 0x33 && nor[0xC1FFF] == 0x33 && nor[0xC2000] == 0x44; } + +static void stock(void) /* the stock mapping as V016 writes it */ +{ + uint32_t n; + memset(nor + 0xC2000, 0xFF, 0x29000); + memset(nor + 0xC2000, 0x07, 0x86); + nor[0xC2000] = 0xA3; nor[0xC2001] = 0x3A; + for (n = 0; n < 8u; n++) { + memset(nor + 0xC3000 + n * 0x5000, 0x01, 0x29E3); + nor[0xC3000 + n * 0x5000 + 4] = 0x7F; + } + memcpy(nor + 0xEAFF8, "usrdata", 8); +} +static int is_stock(void) +{ + static uint8_t keep[0x29000]; + int same; + memcpy(keep, nor + 0xC2000, sizeof keep); + stock(); + same = !memcmp(keep, nor + 0xC2000, sizeof keep); + memcpy(nor + 0xC2000, keep, sizeof keep); + return same; +} +static int erased(uint32_t lo, uint32_t hi) +{ + for (; lo < hi; lo++) + if (nor[lo] != 0xFF) + return 0; + return 1; +} + +int main(void) +{ + fill(); + memcpy(nor + 0xAF000, "SMK37DATAOTHER\0", 16); + st_owner_check(); + check("another firmware's store (another tag): cleared, tagged FELUCCA", store_erased() && st_owner_cleared && + !memcmp(nor + 0xAF000, "SMK37DATAFELUCCA", 16)); + check("... calibration (USRTRIM) and samples untouched", others_kept()); + fill(); + memcpy(nor + 0xAF000, "SMK37DATAFELUCCA", 16); + st_owner_cleared = 0; + st_owner_check(); + check("our own store: kept as it is", nor[0x9D000] == 0x11 && nor[0xB0000] == 0x22 && !st_owner_cleared); + fill(); + st_owner_check(); + check("an untagged store (FELUCCA_DATA_UNTAGGED_OK 0): cleared, tagged", store_erased() && + !memcmp(nor + 0xAF000, "SMK37DATAFELUCCA", 16) && others_kept()); + /* the stock firmware's mapping in USRFLASH: kept while intact, its marker released over anything else */ + fill(); + stock(); + memcpy(nor + 0xAF000, "SMK37DATAOTHER\0", 16); + tag_erases = 0; + st_owner_check(); + check("owner change over the intact stock mapping: USRFLASH and its marker kept", is_stock() && tag_erases == 0 && + st_stock_intact()); + st_owner_check(); + check("... and at the next boot (ours now)", is_stock() && tag_erases == 0); + st_stock_release(); /* the first erase in USRFLASH (storage_hw.c, editor.c) */ + check("first write into USRFLASH: the marker sector erased, once", erased(0xEA000, 0xEB000) && tag_erases == 1 && + !st_stock_tagged() && nor[0xC2000] == 0xA3); + st_stock_release(); + check("... and only once", tag_erases == 1); + { + static const uint32_t HIT[] = {0xC2000u, 0xC6000u, 0xD6000u, 0xDB000u, 0xE5000u, 0xEA000u}; + uint32_t h, ok = 1; + for (h = 0; h < sizeof HIT / sizeof HIT[0]; h++) { + stock(); + nor[HIT[h]] = 0x46; /* (a sample's header or data over the stock layout) */ + ok &= !st_stock_intact(); + } + stock(); + memset(nor + 0xC8000, 0xFF, 0x1000); /* (an erased preset head) */ + ok &= !st_stock_intact(); + check("the stock layout checked: its settings' magic, each preset's head and erased tail", ok); + } + stock(); + memcpy(nor + 0xD6000, "FSMP", 4); /* USR2 loaded by an older build over the stock presets */ + tag_erases = 0; + st_owner_check(); + check("the marker over our samples (an older build): released at boot, the samples kept", tag_erases == 1 && + !st_stock_tagged() && !memcmp(nor + 0xD6000, "FSMP", 4)); + fill(); + tag_erases = 0; + st_owner_check(); + check("no marker: the marker sector never erased", tag_erases == 0); + check("nothing written outside FL_DATA's objects, the voice bank and the tag", bad_write == 0); + printf("%s\n", bad ? "SMK OWNER TEST FAILED" : "smk owner test passed"); + return bad != 0; +} diff --git a/tests/smk_pkg_test.py b/tests/smk_pkg_test.py new file mode 100644 index 0000000..e677a51 --- /dev/null +++ b/tests/smk_pkg_test.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +# Felucca on the SMK-37 Pro (BOARD_SMK37) +"""An SMK-37 Pro package from fm1pkg_make.py --board smk37: flash.bin is the stock PRCT size (0x9D000) and +its app area carries the stock v016 region table exactly, so the SDK +and a later stock rollback see the same VM / BTIF / USRTRIM / USRFLASH / USR regions. + smk_pkg_test.py PACKAGE.fwsc [PRODUCT]""" +import struct +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import fm1_install as I # noqa: E402 +import fm1pkg_make as M # noqa: E402 + +failed = 0 + + +def ok(cond, what): + global failed + print(f"smk pkg: {what:<70} {'ok' if cond else 'FAIL'}") + failed += not cond + + +raw = Path(sys.argv[1]).read_bytes() +want_product = sys.argv[2] if len(sys.argv) > 2 else "SMK-37 Pro_900" +image, n = I.deinterleave(raw), I.block_count(raw) +ok(n == 20 and I.product_of(raw) == want_product and I.files_ok(image), + f"identity {I.product_of(raw)}, 20 blocks, CRCs ok") +hdr = I._dec(image[:0x40]) +e0 = I._dec(image[0x40:0x90]) +off, size = struct.unpack_from("[-elite|-mke]-.fwsc +# smk37: the keyboard's model name (MODEL env or --model); one hardware, three names. pro adds no flag +MODELS = {"pro": "SMK-37 Pro", "elite": "SMK-37 Elite", "mke": "MKE-P37"} VERSION = None # FELUCCA_VERSION for release builds (default: firmware/src/felucca.c) STEM = "fmini-1-fm1" # output stem: fmini-1-fm1- (set by main) # FELUCCA_CPU2 (firmware/src/felucca.c), unset or 1, the default (1.6.1): the second core is built in, its entry and @@ -152,7 +165,7 @@ def ldr_wrap(image): def build_loader(): LDR.mkdir(parents=True, exist_ok=True) src = FW / "loader" - flags = [*CFLAGS, "-Ifirmware/hal", "-Ifirmware/src"] + flags = [*CFLAGS, *BOARD_DEFS[BOARD], "-Ifirmware/hal", "-Ifirmware/src"] tc_all(("cc", "-c", src / "crt0_ldr.S", "-o", LDR / "crt0_ldr.o"), ("cc", *flags, "-c", src / "loader.c", "-o", LDR / "loader.o")) elf = LDR / "loader.elf" @@ -191,7 +204,7 @@ def ld_regions(): def build_app(): - flags = [*CFLAGS, "-Ifirmware/hal", "-Ifirmware/src", "-Ibuild/gen"] + flags = [*CFLAGS, *BOARD_DEFS[BOARD], "-Ifirmware/hal", "-Ifirmware/src", "-Ibuild/gen"] for flag in ("FELUCCA_FLASH", "FELUCCA_OTA", "FELUCCA_OTA_DRYRUN", "FELUCCA_OTA_RAMONLY", "FELUCCA_CDC", "FELUCCA_UART", "FELUCCA_UAC", "FELUCCA_UAC_TONE", "FELUCCA_UAC_48K", "FELUCCA_ICONS", "FELUCCA_FM4", "FELUCCA_CDC_DEFAULT", "FELUCCA_UAC_AS_FIRST", "FELUCCA_CPU2", "FELUCCA_FMINI_ONLY"): @@ -222,7 +235,14 @@ def build_app(): tc("cc", *[f for f in flags if not f.startswith(("-I", "-D", "-W"))], "-c", OUT / "felucca_size.ll", "-o", OUT / "felucca.o") elf = OUT / "felucca.elf" - tc("pi32v2/bin/ld", "-T", FW / "app.ld", OUT / "crt0.o", OUT / "fm1_vec.o", OUT / "fm1_isr.o", + ld = FW / "app.ld" + if APP_SLOT != 0x8DFBC: # another board's app slot (SMK-37 Pro): the same script, its XIP length + txt = ld.read_text() + if txt.count("LENGTH = 0x8DFBC") != 1: + raise SystemExit("app.ld: the XIP LENGTH line was not found") + ld = OUT / "app.ld" + ld.write_text(txt.replace("LENGTH = 0x8DFBC", f"LENGTH = {APP_SLOT:#X}".replace("0X", "0x"))) + tc("pi32v2/bin/ld", "-T", ld, OUT / "crt0.o", OUT / "fm1_vec.o", OUT / "fm1_isr.o", *([OUT / "fm1_cpu1.o"] if CPU2 else []), OUT / "felucca.o", "-o", elf) for sect in ("text.bin", "data.bin", "ramtext.bin", "c1text.bin"): (OUT / sect).unlink(missing_ok=True) @@ -372,21 +392,40 @@ def mmio_check(): def main(): - global PRODUCT, VERSION + global PRODUCT, VERSION, BOARD, APP_SLOT ap = argparse.ArgumentParser() ap.add_argument("--release", metavar="X.Y", help="release build: identity FM-1_9XY, version string vX.Y") + ap.add_argument("--board", choices=sorted(BOARD_PREFIX), default=None, + help="target board: fm1 (default) or smk37 (default: $BOARD, else fm1)") + ap.add_argument("--model", choices=sorted(MODELS), default=None, + help="smk37: the model name, pro (default), elite or mke (default: $MODEL, else pro)") ap.add_argument("--sdk", type=Path, help="JieLi AC79 SDK checkout (default: $AC79_SDK)") a = ap.parse_args() global STEM + BOARD = (a.board or os.environ.get("BOARD") or "fm1").lower().replace("-", "") + if BOARD not in BOARD_PREFIX: + raise SystemExit(f"BOARD={BOARD}: use fm1 or smk37") + model = (a.model or (os.environ.get("MODEL") if BOARD == "smk37" else None) or "pro").lower() + if model not in MODELS or (model != "pro" and BOARD != "smk37"): + raise SystemExit(f"MODEL={model}: pro, elite or mke, with BOARD=smk37") + fm1pkg_make.set_board(BOARD) + APP_SLOT = fm1pkg_make.APP_SLOT + stem = BOARD_STEM[BOARD] + PRODUCT = fm1pkg_make.BOARDS[BOARD][2] + if model != "pro": # another model name: identity, loader and update record (fm1_cc.h SMK_MODEL) + BOARD_DEFS[BOARD] = [*BOARD_DEFS[BOARD], f'-DSMK_MODEL="{MODELS[model]}"'] + PRODUCT = PRODUCT.replace(MODELS["pro"], MODELS[model]) + BOARD_PREFIX[BOARD] = BOARD_PREFIX[BOARD].replace(MODELS["pro"], MODELS[model]) + stem += "-" + model m0 = re.search(r'#define FMINI_VERSION "v(\d+\.\d+\.\d+)"', (FW / "src" / "core.h").read_text()) - STEM = "fmini-1-fm1-" + (m0[1] if m0 else "dev") # the FMini-1-fm1 package: fmini-1-fm1-.fwsc + STEM = f"{stem}-" + (m0[1] if m0 else "dev") # fmini-1-fm1-, fmini-1-smk37[-elite|-mke]- if a.release: # one digit each: the identity has room for two (X.Y.Z and X.Y.Z.W keep X.Y's) m = re.fullmatch(r"(\d)\.(\d)(?:\.\d){0,2}(-[A-Za-z0-9]+)?", a.release) if not m: raise SystemExit(f"--release {a.release}: use X.Y, X.Y.Z, X.Y.Z.W or X.Y-suffix, one digit each") - PRODUCT = "FM-1_9" + m[1] + m[2] + PRODUCT = BOARD_PREFIX[BOARD] + m[1] + m[2] VERSION = "v" + a.release.lower() # e.g. v1.0, v1.1-rc1 - STEM = f"fmini-1-fm1-{a.release}" + STEM = f"{stem}-{a.release}" name = STEM + ".fwsc" if not (FW / "engines" / "src" / "felucca_engine.h").exists(): raise SystemExit("firmware/engines is empty: the Felucca-Engines submodule " @@ -416,7 +455,7 @@ def main(): (OUT / name).write_bytes(pkg) print(f"app {OUT / (STEM + '.bin')} {len(img)} B") print(f"loader {LDR / 'ota.bin'} {len(ota)} B") - print(f"package {OUT / name} {len(pkg)} B, identity {PRODUCT}") + print(f"package {OUT / name} {len(pkg)} B, identity {PRODUCT}, board {BOARD}") if a.release: # what a release carries: the package, the app and every licence they need rel = OUT / f"release-{a.release}" shutil.rmtree(rel, ignore_errors=True) diff --git a/tools/fm1_install.py b/tools/fm1_install.py index 08e54c6..490507e 100755 --- a/tools/fm1_install.py +++ b/tools/fm1_install.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-only # Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments -"""Install a Felucca package (.fwsc) on an FM-1 over USB-MIDI. +"""Install a Felucca package (.fwsc) on an FM-1 (or an SMK-37) over USB-MIDI. The same update as the web installer (web/fm1ota.js): step 1, the running firmware reads parts of the package and starts the update loader; @@ -11,6 +11,7 @@ the FM-1 restarts and the installed identity is checked. fm1_install.py PACKAGE.fwsc [--port NAME] [--yes] [--force] fm1_install.py FM-1.fwsc (the official V15 file: back to the stock firmware) + fm1_install.py SMK-37_Pro_016.fwsc (the official SMK-37 Pro V016 file: back to the stock firmware) fm1_install.py --info [--port NAME] If the FM-1 is still in update mode (an earlier install was cut off), the @@ -19,6 +20,9 @@ install finishes the write. Needs mido with python-rtmidi. Exit codes: 0 done, 1 cancelled or other error, 2 bad arguments or package, 3 FM-1 not found, 4 connection lost or the device stopped, 5 timeout (no loader / no restart), 6 wrong model, or another identity after the install. + +Packages: 20 interleave blocks (FM-1, Felucca, the SMK build) or more (the stock SMK-37 Pro v016 has 36: the extra +markers are 0x7D); the count is detected and checked with the files' CRCs. """ import argparse import hashlib @@ -31,12 +35,15 @@ HS_QUERY = bytes([0xF0, 0x00, 0x32, 0x45, 0x00, 0x00, 0x00, 0x40, 0x7F, 0xF7]) UPGRADE = bytes([0xF0, 0x22, 0x24, 0x35, 0x7F, 0xF7]) FINISH_CHECK, FINISH_WRITE = 0xE0000000, 0xF0000000 MAXDATA = 512 -BLOCKS, BLK, KEEP = 20, 0x30, 0x2F +BLOCKS, BLK, KEEP = 20, 0x30, 0x2F # BLOCKS: the identity blocks (more may follow, see block_count) +MAX_BLOCKS = 64 LOADER_MARK = b"FELUCCA-LOADER-1" # the unmodified official FM-1 V15 (FM-1.fwsc from M-VAVE): returning to it is allowed without --force, # as the web installer's "Return to official V15" (web/fm1pkg.js validateStockPackage) STOCK_V15_SHA256 = "db1642b2b6fa5c2cccb11ffd13878068bb28601678d3644049f99dc40e7edb8a" -PORT_RE = re.compile(r"fm-1|fmini|felucca|ota|composite|sinco|usb-midi", re.I) # never probe other gear +# the unmodified official SMK-37 Pro V016 (SMK-37_Pro_016.fwsc, 36 interleave blocks): the return of an SMK-37 Pro +STOCK_SMK016_SHA256 = "2d98ce72530e71d617384963423820536f094501299e2cfec0a8d3c3fb6bcfb0" +PORT_RE = re.compile(r"fm-1|fmini|smk|elite|mke-p37|starry|felucca|ota|composite|sinco|usb-midi", re.I) # never probe other gear # seconds; the tests shorten them DELAY = {"open": 0.3, "start": 2.0, "reply": 0.01, "loader": 3.0, "reboot": 3.0, "retry": 1.0, @@ -127,24 +134,89 @@ def parse_identity(pkt): # --------------------------------------------------------------- package --- def product_of(raw): - """the package identity ("FM-1_906"): one marker byte after each of the first 20 blocks""" + """the package identity ("FM-1_906", "SMK-37 Pro_016"): one marker byte after each of the first 20 blocks""" if len(raw) < BLOCKS * BLK: raise InstallError("badpkg", "not an FM-1 package (too short)") return "".join(chr((m - i - 1) & 0xFF) for i in range(BLOCKS) if (m := raw[i * BLK + KEEP]) != 0x7D) -def logical_image(raw): - """the image the device reads during an update: the package without the 20 marker bytes""" +def block_count(raw): + """interleave blocks: 20, then more while the marker is the unused 0x7D (SMK-37 Pro v016: 36). + A 20-block package can have 0x7D there by chance: deinterleave checks the CRCs and falls back.""" + n = BLOCKS + while n < MAX_BLOCKS and (n + 1) * BLK <= len(raw) and raw[n * BLK + KEEP] == 0x7D: + n += 1 + return n + + +def logical_image(raw, blocks=BLOCKS): + """the image the device reads during an update: the package without the marker bytes""" out = bytearray() - for i in range(BLOCKS): + for i in range(blocks): out += raw[i * BLK:i * BLK + KEEP] - return bytes(out + raw[BLOCKS * BLK:]) + return bytes(out + raw[blocks * BLK:]) + + +def _crc16(data, crc=0): + """CRC-16/XMODEM, as the package and the device use""" + for b in data: + crc ^= b << 8 + for _ in range(8): + crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF + return crc + + +def _dec(b): + """JieLi ENC stream cipher (its own inverse)""" + out, key = bytearray(b), 0xFFFF + for i in range(len(out)): + out[i] ^= key & 0xFF + key = ((key << 1) ^ (0x1021 if key & 0x8000 else 0)) & 0xFFFF + return bytes(out) + + +def files_ok(image): + """the logical image's header and file list are intact and flash.bin (0) / ota.bin (100) match their CRCs. + The stock packer's other entries store a CRC of something else: checked for their bounds only.""" + if len(image) < 0x40: + return False + hdr = _dec(image[0:0x40]) + if _crc16(hdr[2:0x40]) != int.from_bytes(hdr[0:2], "little"): + return False + count = int.from_bytes(hdr[8:10], "little") + if not 1 <= count <= 8 or len(image) < 0x40 + 0x50 * count: + return False + for i in range(count): + e = _dec(image[0x40 + i * 0x50:0x90 + i * 0x50]) + typ = int.from_bytes(e[0:2], "little") + off, size = int.from_bytes(e[8:12], "little"), int.from_bytes(e[12:16], "little") + if off + size > len(image): + return False + if typ in (0, 100) and _crc16(image[off:off + size]) != int.from_bytes(e[4:6], "little"): + return False + return True + + +def deinterleave(raw): + """the logical image: 20 blocks, or the detected count when the files' CRCs agree""" + n = block_count(raw) + if n != BLOCKS: + image = logical_image(raw, n) + if files_ok(image) or not files_ok(logical_image(raw, BLOCKS)): + return image + return logical_image(raw, BLOCKS) def model_of(text): return text.split("_")[0].removeprefix("ota-") +def same_model(a, b): + """identities a and b name exactly the same model ("ota-" aside): a package installs only on its own model + (the SMK-37 Pro, SMK-37 Elite and MKE-P37 builds each on their own model, never an FM-1 and an SMK)""" + return model_of(a) == model_of(b) + + # ------------------------------------------------------------------ MIDI --- class MidoLink: @@ -361,7 +433,7 @@ class Updater: def install(self, dev, image, product, step=lambda *a: None): """running firmware -> loader -> new firmware; dev from find(). A device already in update mode only needs the write.""" - if model_of(dev.id.text) != model_of(product): + if not same_model(dev.id.text, product): dev.link.close() raise InstallError("model", f"the device is {dev.id.text}, the package is for {product}") ota = dev if dev.id.loader else self.check(dev, image, step) @@ -379,12 +451,12 @@ def load_package(path, force): product = product_of(raw) if not re.fullmatch(r"[^_]+_\d+", product): raise InstallError("badpkg", f"{path}: not an FM-1 package (identity {product!r})") - official = hashlib.sha256(raw).hexdigest() == STOCK_V15_SHA256 + official = hashlib.sha256(raw).hexdigest() in (STOCK_V15_SHA256, STOCK_SMK016_SHA256) if LOADER_MARK not in raw and not official and not force: raise InstallError("badpkg", f"{path}: no Felucca update loader in this package; only Felucca's own " - "packages and the unmodified official V15 (FM-1.fwsc) are installed " - "(--force overrides)") - return product, logical_image(raw) + "packages and the unmodified official V15 (FM-1.fwsc) or SMK-37 Pro V016 " + "(SMK-37_Pro_016.fwsc) are installed (--force overrides)") + return product, deinterleave(raw) def not_found(up): diff --git a/tools/fm1pkg_make.py b/tools/fm1pkg_make.py index ac7a7d1..34b2c2a 100755 --- a/tools/fm1pkg_make.py +++ b/tools/fm1pkg_make.py @@ -20,7 +20,10 @@ The three SDK files (uboot.boot, cfg_tool.bin, eq_cfg_hw.bin) are Apache-2.0, no ship LICENSES/Apache-2.0.txt with every package (LICENSING.md; make_site.py and build.py --release do). - fm1pkg_make.py APP.bin OTA.bin OUT.fwsc [--product FM-1_9XY] [--key 0x980F] + fm1pkg_make.py APP.bin OTA.bin OUT.fwsc [--board fm1|smk37] [--product FM-1_9XY] [--key 0x980F] + +--board smk37 (SMK-37 Pro, same AC791N, SPL and loader) selects the SMK flash layout: PRCT +0x9D000 and the stock v016 region table (VM, BTIF, USRTRIM, USRFLASH, USR). """ import argparse import os @@ -29,6 +32,36 @@ from pathlib import Path APP_SLOT = 0x8DFBC FLASH_SIZE = 0x93000 +BOARD = "fm1" +# the region descriptors after app.bin / cfg_tool.bin: (offset, size, flags, resvd, index, name16 or name). +# The offsets are ABSOLUTE flash offsets. The 16 name bytes after the names are SDK packer fields. +REGIONS = { + "fm1": [(0x93000, 352256, 0x12, 0x80, 0, bytes.fromhex("564d00ffffffffffffffffff00800000")), # VM + (0, None, 0x92, 0x82, 0, bytes.fromhex("5052435400ffffffffffffff434f4445")), # PRCT = FLASH_SIZE + (0xE9000, 0x1000, 0x92, 0x80, 0, bytes.fromhex("4254494600ffffffffffffff4155544f")), # BTIF + (0xEA000, 0x12000, 0x92, 0x81, 1, "USR")], + # SMK-37 Pro v016, as the stock package's region table + "smk37": [(0x9D000, 0x23000, 0x12, 0x81, 0, bytes.fromhex("564d00ffffffffffffffffff00800000")), # VM + (0, None, 0x92, 0x82, 0, bytes.fromhex("5052435400ffffffffffffff434f4445")), # PRCT = FLASH_SIZE + (0xC0000, 0x1000, 0x92, 0x82, 0, bytes.fromhex("4254494600ffffffffffffff4155544f")), # BTIF + (0xC1000, 0x1000, 0x92, 0x81, 0, bytes.fromhex("5553525452494d00ffffffffffffffff")), # USRTRIM + (0xC2000, 0x29000, 0x92, 0x81, 0, bytes.fromhex("555352464c41534800ffffffffffffff")), # USRFLASH + (0xF4000, 0xA000, 0x92, 0x81, 1, "USR")], +} +# per board: (FLASH_SIZE = PRCT = the end of what the update loader writes, APP_SLOT, default product) +BOARDS = {"fm1": (0x93000, 0x8DFBC, "FM-1_900"), + "smk37": (0x9D000, 0x97400, "SMK-37 Pro_900")} # SMK: the stock app is 0x974B8; build.py sets app.ld XIP + + +def set_board(board): + """select the flash layout of a board ("fm1" default, "smk37")""" + global BOARD, FLASH_SIZE, APP_SLOT + if board not in BOARDS: + raise SystemExit(f"fm1pkg_make: unknown board {board!r} (fm1, smk37)") + BOARD = board + FLASH_SIZE, APP_SLOT, _ = BOARDS[board] + + KEY = 0x980F # flash header: JieLi SDK defaults (burner_size 544, VID "0.01", flash_size 0xFF000, # fs_ver 0x10, PID "AC791N_STORY"), plain, without its CRC @@ -136,10 +169,8 @@ def flash_image(app, key): ents = [entry(crc16(app), 0x120, APP_SLOT, 0x82, 0xFF, 0, "app.bin"), entry(crc16(cfg_tool), 0x120 + APP_SLOT, len(cfg_tool), 0x82, 0xFF, 0, "cfg_tool.bin"), # region descriptors; the bytes after the names are SDK packer fields (VM size, "CODE", "AUTO") - entry(0xFFFF, 0x93000, 352256, 0x12, 0x80, 0, bytes.fromhex("564d00ffffffffffffffffff00800000")), - entry(0xFFFF, 0, FLASH_SIZE, 0x92, 0x82, 0, bytes.fromhex("5052435400ffffffffffffff434f4445")), - entry(0xFFFF, 0xE9000, 0x1000, 0x92, 0x80, 0, bytes.fromhex("4254494600ffffffffffffff4155544f")), - entry(0xFFFF, 0xEA000, 0x12000, 0x92, 0x81, 1, "USR")] + *(entry(0xFFFF, o, FLASH_SIZE if sz is None else sz, fl, rs, ix, nm) + for o, sz, fl, rs, ix, nm in REGIONS[BOARD])] area[32:32 + len(b"".join(ents))] = b"".join(ents) area[0:32] = entry(crc16(area[32:blk]), 0x02000120, blk, 0x83, 0xFF, 0, "app_area_head") # nested cfg directory right after the block: SDK default EQ table @@ -197,12 +228,15 @@ def main(): ap.add_argument("app", type=Path) ap.add_argument("ota", type=Path) ap.add_argument("out", type=Path) - ap.add_argument("--product", default="FM-1_900") + ap.add_argument("--board", choices=sorted(BOARDS), default="fm1") + ap.add_argument("--product", help="package identity (default: FM-1_900; smk37: SMK-37 Pro_900)") ap.add_argument("--key", type=lambda s: int(s, 0), default=KEY) ap.add_argument("--sdk", type=Path, help="JieLi AC79 SDK checkout (default: $AC79_SDK)") a = ap.parse_args() global SDK SDK = a.sdk + set_board(a.board) + a.product = a.product or BOARDS[a.board][2] pkg = ufw(flash_image(a.app.read_bytes(), a.key), a.ota.read_bytes(), a.product) a.out.write_bytes(pkg) print(f"package {a.out}: {len(pkg)} B, identity {a.product}, chip key {a.key:#06x}") diff --git a/web/emu/felucca_web.c b/web/emu/felucca_web.c index 670dc4e..899c652 100644 --- a/web/emu/felucca_web.c +++ b/web/emu/felucca_web.c @@ -202,7 +202,8 @@ static int st_prog(uint32_t off, const void *src, uint32_t n) /* NOR: a wr static uint32_t irq_save(void) { return 0; } static void irq_restore(uint32_t f) { (void)f; } static uint32_t fl_jedec_ram(void) { return 0x856014u; } /* the FM-1's part (project.c) */ -#define FL_JEDEC_OK(id) ((id) == 0x856014u || (id) == 0xB36014u) /* as firmware/hal/fm1_flash.h (not included here) */ +#define FL_JEDEC_OK(id) ((id) == 0x856014u || (id) == 0xB36014u) /* as hal/fm1_flash_map.h (FM-1) */ +#define FM1_OCT_BOTH 3u /* OCT- + OCT+, as hal/fm1_input.h (FM-1) */ static void fl_plain_window_init(void) {} #define FL_FAR(fn) (fn) #include "../../firmware/src/storage.c" diff --git a/web/fm1ota.js b/web/fm1ota.js index def172e..3c9cb34 100644 --- a/web/fm1ota.js +++ b/web/fm1ota.js @@ -31,6 +31,9 @@ const sleep = (ms) => new Promise((r) => { w.postMessage({ id, ms }); }); const IS_OTA = (id) => /^ota-/i.test(id.model); +// two models ("ota-" aside) are exactly the same: a package installs only on its own model (the SMK-37 Pro, +// SMK-37 Elite and MKE-P37 builds each on their own model, never an FM-1 and an SMK) +export const sameModel = (a, b) => a.replace(/^ota-/i, "") === b.replace(/^ota-/i, ""); // errors carry a code the pages translate: notfound, model, stopped, noloader, lost, noreturn, // mismatch (detail: the identity the device reports), badreq @@ -138,7 +141,7 @@ export class Updater { for (const input of this.access.inputs.values()) { if (input.state === "disconnected") continue; // never probe other gear: by name, unless the player picked a port (a firmware that names its USB device differently) - if (this.portName ? input.name !== this.portName : !/fm-1|fmini|felucca|ota|composite|sinco|usb-midi/i.test(input.name || "")) continue; + if (this.portName ? input.name !== this.portName : !/fm-1|fmini|smk|elite|mke-p37|starry|felucca|ota|composite|sinco|usb-midi/i.test(input.name || "")) continue; const output = outs.find((o) => o.name === input.name && o.state !== "disconnected"); if (!output) continue; try { await input.open(); await output.open(); } catch (_) { continue; } @@ -196,7 +199,7 @@ export class Updater { this.portName = null; // (the picked port was for the running firmware: the loader is ours, FMini-1 Update) if (!dev) throw fail("notfound", "FM-1 not found (USB cable, and no other app using it?)"); const [model] = product.split("_"); - if (dev.id.model !== model) { dev.link.close(); throw fail("model", `the device is ${dev.id.text}, the package is for ${product}`); } + if (!sameModel(dev.id.model, model)) { dev.link.close(); throw fail("model", `the device is ${dev.id.text}, the package is for ${product}`); } step("start", dev.id.text); dev.link.send(UPGRADE); await sleep(2000); @@ -228,18 +231,24 @@ export class Updater { return s2; } - // resume: the device is already in update mode (loader) -> true when the write finished - async resume(image, onStep, product = null) { - const model = product && product.split("_")[0]; - const ota = await this.find((id) => model ? id.model === "ota-" + model : IS_OTA(id)); + // resume: the device is already in update mode (loader) -> true when the write finished. product: the + // package's identity; the loader's model must be exactly the package's (sameModel, as install()): an SMK's + // loader never gets an FM-1 image nor another model's, and without the identity nothing is written + async resume(image, onStep, product = "") { + const model = (product || "").split("_")[0]; + const ota = await this.find(IS_OTA); if (!ota) return false; + if (!product || !sameModel(ota.id.model, model)) { + ota.link.close(); + throw fail("model", `the device is in the update mode of ${ota.id.text}, the package is for ${product || "an unknown model"}`, ota.id.text); + } const step = onStep || (() => {}); const result = await this.write(ota, image, step); if (!result.finished) return false; if (product) { step("reboot"); await sleep(3000); - const back = await this.waitFor((id) => id.model === model, 40000); + const back = await this.waitFor((id) => !IS_OTA(id) && sameModel(id.model, model), 40000); if (!back) throw fail("noreturn", "The FM-1 did not return after resuming the write."); back.link.close(); if (back.id.text !== product) throw fail("mismatch", "The FM-1 reports a different firmware after resuming.", back.id.text); diff --git a/web/fm1pkg.js b/web/fm1pkg.js index 82d35ce..2a7fd8d 100644 --- a/web/fm1pkg.js +++ b/web/fm1pkg.js @@ -1,10 +1,10 @@ // SPDX-License-Identifier: GPL-3.0-only // Copyright (C) 2026 Leo Kuroshita (@kurogedelic), Hügelton Instruments // -// FM-1 .fwsc packages in the browser: the package identity and the image the +// FM-1 (and SMK-37 Pro) .fwsc packages in the browser: the package identity and the image the // device reads during an update. -const BLOCKS = 20, BLK = 0x30, KEEP = 0x2F; +const BLOCKS = 20, BLK = 0x30, KEEP = 0x2F, MAX_BLOCKS = 64; export const STOCK_V15_SHA256 = "db1642b2b6fa5c2cccb11ffd13878068bb28601678d3644049f99dc40e7edb8a"; export const STOCK_APP_SIZE = 0x8DFBC; export const STOCK_V15_SIZE = 699956; @@ -208,7 +208,7 @@ export class Package { } } -// the package identity ("FM-1_904"): one marker byte after each of the first 20 blocks +// the package identity ("FM-1_904", "SMK-37 Pro_016"): one marker byte after each of the first 20 blocks export function productOf(fwsc) { if (fwsc.length < BLOCKS * BLK) throw new Error("not an FM-1 package (too short)"); let s = ""; @@ -219,14 +219,50 @@ export function productOf(fwsc) { return s; } -// the image the device addresses during an update: the .fwsc without the 20 marker bytes -export function logicalImage(fwsc) { - const out = new Uint8Array(fwsc.length - BLOCKS); - for (let i = 0; i < BLOCKS; i++) out.set(fwsc.subarray(i * BLK, i * BLK + KEEP), i * KEEP); - out.set(fwsc.subarray(BLOCKS * BLK), BLOCKS * KEEP); +// interleave blocks: 20, then more while the marker is the unused 0x7D (the stock SMK-37 Pro v016 has 36) +export function blockCount(fwsc) { + let n = BLOCKS; + while (n < MAX_BLOCKS && (n + 1) * BLK <= fwsc.length && fwsc[n * BLK + KEEP] === 0x7D) n++; + return n; +} + +function deinterleave(fwsc, blocks) { + const out = new Uint8Array(fwsc.length - blocks); + for (let i = 0; i < blocks; i++) out.set(fwsc.subarray(i * BLK, i * BLK + KEEP), i * KEEP); + out.set(fwsc.subarray(blocks * BLK), blocks * KEEP); return out; } +// the logical image's flash.bin (type 0) and ota.bin (type 100) match their CRCs (as fm1_install.py files_ok) +function filesOk(img) { + if (img.length < 0x40) return false; + const rd = (a, o, n) => a.slice(o, o + n).reduce((v, x, i) => v + x * 2 ** (8 * i), 0); + const h = Uint8Array.from(img.subarray(0, 0x40)); + enc(h, 0, 0x40); + if (crc16(h.subarray(2, 0x40)) !== rd(h, 0, 2)) return false; + const count = rd(h, 8, 2); + if (count < 1 || count > 8 || img.length < 0x40 + 0x50 * count) return false; + for (let i = 0; i < count; i++) { + const e = Uint8Array.from(img.subarray(0x40 + i * 0x50, 0x90 + i * 0x50)); + enc(e, 0, 0x50); + const typ = rd(e, 0, 2), off = rd(e, 8, 4), size = rd(e, 12, 4); + if (off + size > img.length) return false; + if ((typ === 0 || typ === 100) && crc16(img.subarray(off, off + size)) !== rd(e, 4, 2)) return false; + } + return true; +} + +// the image the device addresses during an update: the .fwsc without the marker bytes (20 blocks, or the +// detected count when the files' CRCs agree: a 20-block package can have 0x7D after block 20 by chance) +export function logicalImage(fwsc) { + const n = blockCount(fwsc); + if (n !== BLOCKS) { + const img = deinterleave(fwsc, n); + if (filesOk(img) || !filesOk(deinterleave(fwsc, BLOCKS))) return img; + } + return deinterleave(fwsc, BLOCKS); +} + export async function sha256hex(bytes) { const d = await crypto.subtle.digest("SHA-256", bytes); return [...new Uint8Array(d)].map((x) => x.toString(16).padStart(2, "0")).join(""); diff --git a/web/make_site.py b/web/make_site.py index 7533154..ad8cb02 100644 --- a/web/make_site.py +++ b/web/make_site.py @@ -40,8 +40,8 @@ def main(pkg, version, out): pkg, out = Path(pkg), Path(out) raw = pkg.read_bytes() product = product_of(raw) - if not re.fullmatch(r"FM-1_9\d\d", product): - raise SystemExit(f"{pkg}: identity {product!r} is not a Felucca package (FM-1_9xx)") + if not re.fullmatch(r"(FM-1|SMK-37 Pro)_9\d\d", product): + raise SystemExit(f"{pkg}: identity {product!r} is not a Felucca package (FM-1_9xx, SMK-37 Pro_9xx)") if b"FELUCCA-LOADER-1" not in raw: # Felucca loader marker: never publish a package with vendor files raise SystemExit(f"{pkg}: no Felucca loader in it; the site ships only fm1pkg_make.py packages " "(a package patched from an official one carries vendor files)") diff --git a/web/test_web.mjs b/web/test_web.mjs index 80b2cd3..5ebfffd 100644 --- a/web/test_web.mjs +++ b/web/test_web.mjs @@ -1651,9 +1651,10 @@ const UPGRADE = [0xF0, 0x22, 0x24, 0x35, 0x7F, 0xF7]; /* an FM-1 on WebMIDI: identity, then "device asks, host answers" reads of the image */ class FakeFM1 { - constructor(image, { unplugAfter = Infinity, run = "Felucca", ota = "Felucca Update" } = {}) { + constructor(image, { unplugAfter = Infinity, run = "Felucca", ota = "Felucca Update", back = null } = {}) { this.image = image; this.unplugAfter = unplugAfter; this.served = 0; this.bad = 0; this.runName = run; this.otaName = ota; // the USB names: "Felucca" / "Felucca Update" (until v1.4.27), "FMini-1" / "FMini-1 Update" (v1.4.28+) + this.back = back || ["FM-1_900", run]; // what it boots as after the write (an SMK test: its identity) this.access = { inputs: new Map(), outputs: new Map() }; this.boot("FM-1_015", "FM-1"); } @@ -1690,7 +1691,7 @@ class FakeFM1 { this.served++; if (this.served >= this.unplugAfter) { this.input.state = this.output.state = "disconnected"; return; } if (addr === 0xE0000000) setTimeout(() => this.boot("ota-FM-1_900", this.otaName), 300); - else if (addr === 0xF0000000) setTimeout(() => this.boot("FM-1_900", this.runName), 300); + else if (addr === 0xF0000000) setTimeout(() => this.boot(...this.back), 300); else this.next(); } } @@ -1740,8 +1741,29 @@ async function updater() { const dev2 = new FakeFM1(image, { unplugAfter: 3 }); dev2.boot("ota-FM-1_900", "Felucca Update"); const t0 = Date.now(); - const done = await new Updater(dev2.access).resume(image); + const done = await new Updater(dev2.access).resume(image, null, "FM-1_900"); ok(done === false && Date.now() - t0 < 6000, "fm1ota.js: unplugged during the write -> stops at once"); + /* resume() checks the loader's model against the package, as install() checks the running firmware */ + const smkOta = new FakeFM1(image); + smkOta.boot("ota-SMK-37 Pro_900", "Felucca Update"); + const m1 = await new Updater(smkOta.access).resume(image, null, "FM-1_900").then(() => null, (x) => x); + ok(m1 && m1.code === "model" && smkOta.served === 0, "fm1ota.js: an SMK-37 Pro in update mode is never given an FM-1 package ('model')"); + const fm1Ota = new FakeFM1(image); + fm1Ota.boot("ota-FM-1_900", "Felucca Update"); + const m3 = await new Updater(fm1Ota.access).resume(image, null, "SMK-37 Pro_900").then(() => null, (x) => x); + ok(m3 && m3.code === "model" && fm1Ota.served === 0, "fm1ota.js: an FM-1 in update mode is never given an SMK package ('model')"); + const noPkg = new FakeFM1(image); + noPkg.boot("ota-FM-1_900", "Felucca Update"); + const m2 = await new Updater(noPkg.access).resume(image).then(() => null, (x) => x); + ok(m2 && m2.code === "model" && noPkg.served === 0, "fm1ota.js: resume without the package's identity writes nothing"); + const elite = new FakeFM1(image); + elite.boot("ota-SMK-37 Elite_900", "Felucca Update"); + const m4 = await new Updater(elite.access).resume(image, null, "SMK-37 Pro_900").then(() => null, (x) => x); + ok(m4 && m4.code === "model" && elite.served === 0, "fm1ota.js: an SMK-37 Elite in update mode is never given an SMK-37 Pro package ('model')"); + const smkPro = new FakeFM1(image, { back: ["SMK-37 Pro_900", "Felucca"] }); + smkPro.boot("ota-SMK-37 Pro_900", "Felucca Update"); + const r3 = await new Updater(smkPro.access).resume(image, null, "SMK-37 Pro_900"); + ok(r3 === true && smkPro.served > 0 && smkPro.bad === 0, "fm1ota.js: resume: an SMK-37 Pro in update mode takes an SMK-37 Pro package"); const dev3 = new FakeFM1(image, { unplugAfter: 2 }); const e = await new Updater(dev3.access).install(image, "FM-1_900").then(() => null, (x) => x);