From 1dff94d9cfac1e1f6f6ec22bec6b23cd80d3a557 Mon Sep 17 00:00:00 2001 From: David Konsumer Date: Sat, 31 Oct 2026 18:24:35 -0700 Subject: [PATCH] Connect out over Bluetooth --- README.md | 17 +- platform/ble/ble_hw_wl82_central.c | 3 +- platform/bt.c | 276 +++++++++++++++++++++++++++-- platform/clock.c | 10 +- platform/fm1.c | 53 ++++++ platform/fm1.h | 12 +- platform/hal/fm1_ble_rf.h | 8 +- platform/mvave/port.c | 15 ++ platform/src/ota.c | 4 + tools/flash.py | 181 +++++++++++++++++-- 10 files changed, 532 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index b842401..a113f1b 100644 --- a/README.md +++ b/README.md @@ -88,12 +88,18 @@ clock and start / stop through the clock helper (`clock_follow(MIDI_BLE)`), and `bt_status()` says whether it's advertising, connected or ready for MIDI. Notes held when the link drops get their note-offs. +It can also connect out, to a Bluetooth MIDI controller or another FM-1: `ble_scan()` looks for 15 s, `ble_device(i)` +names the BLE MIDI devices found (with a rough signal), `ble_device_addr(i)` gives one's address (keep it to find the +device again later with `ble_find()`), `ble_connect(i)` connects, `ble_disconnect()` leaves it (a computer connected +to the FM-1 stays). A link not made in a few seconds is worth leaving and trying again. One link at a time, no +pairing. A clock from Bluetooth is placed by its senders' time stamps, so it comes out as evenly as it was sent. + On Felucca's platform it's Henri David's Bluetooth stack from [Optimist](https://github.com/w0ts/optimist) with the radio drivers of [felucca-bsp](https://github.com/hugelton/felucca-bsp) (`platform/ble`, `platform/hal/fm1_ble*.h`, `platform/bt.c`): written from the Bluetooth specifications and measurements of the FM-1's radio, no JieLi library. -It calibrates the radio when it starts, so nothing stored on the FM-1 is needed. It's a peripheral only: no pairing -(macOS and iOS connect without it), no connecting out to a controller (`ble_central` answers "not ready") and no -audio. Tested on an FM-1 with a Mac, both ways. +It starts the radio with the FM-1's own calibration, as the stock firmware left it in flash (the defaults when it's +gone), and measures the radio's VCO bands at every start (with another unit's, reception went bad seconds after the +start). No pairing (macOS and iOS connect without it) and no audio. Tested on FM-1s with a Mac and with each other. To connect from a Mac: Audio MIDI Setup, Window > Show MIDI Studio, the Bluetooth button, then Connect. @@ -158,7 +164,10 @@ The FM-1 runs a JieLi AC791N. The emulator is forgiving, the chip is not; the bu `./fm1 flash` runs on your computer, not in Docker (Docker on a Mac can't reach USB), and needs only `python3` (CoreMIDI on macOS, ALSA on Linux; not on Windows yet: use the page). `./fm1 flash` installs `build/web/firmware.fwsc`, `./fm1 flash FILE.fwsc` any package, `./fm1 flash --id` says what the FM-1 runs (`FM-1_000`: the USB rescue). Quit -other apps that use the FM-1's MIDI port first. If an install is cut off, run it again: it finishes it. +other apps that use the FM-1's MIDI port first. If an install is cut off, run it again: it finishes it. With more than +one FM-1 on USB, `./fm1 flash --list` numbers them and `--port N` first picks one (`./fm1 flash --port 2`). +`./fm1 flash --crash` shows the last crash the FM-1 recorded (the USB rescue answers it too); with Bluetooth, +`--bt` shows the link and what the last scan found, and `--radio` which radio calibration it started with. Windows: `fm1.cmd dev` (Docker Desktop). Without the script: `docker run --rm -it --platform linux/amd64 -p 8000:8000 -v "$PWD:/work" konsumer/foma-toolchain python3 tools/build.py --dev 8000`. diff --git a/platform/ble/ble_hw_wl82_central.c b/platform/ble/ble_hw_wl82_central.c index d3d23f0..b02da49 100644 --- a/platform/ble/ble_hw_wl82_central.c +++ b/platform/ble/ble_hw_wl82_central.c @@ -37,7 +37,8 @@ BLE_API void ble_hw_scan_start(const struct ble_hw_scan *s) CB->wincntl2 = HW_SCAN_WIN2; fm1_ble_col_wr(HW_LINK, 1, iv & 0xFFFFu); fm1_ble_col_wr(HW_LINK, 15, iv >> 16); /* bit15 = 0 for scanning (its meaning: C8) */ - CB->filtercntl &= (uint16_t)~8u; /* 5: filter policy 0 (no whitelist) */ + CB->filtercntl &= (uint16_t)~(8u | 0x10u | 1u); /* 5: filter policy 0 (no whitelist; initiating's target + * entry and its CONNECT_IND-only bit off too) */ drv.scan_active = s->active ? 1u : 0u; CB->format = (uint16_t)(drv.scan_active ? 0u : 0x100u); /* 6: bit8 0 = SCAN_REQ allowed */ fm1_ble_col_wr(HW_LINK, 6, 0x2100u | 37u); /* 7: channel 37 first */ diff --git a/platform/bt.c b/platform/bt.c index 142ad4b..35af26a 100644 --- a/platform/bt.c +++ b/platform/bt.c @@ -7,18 +7,30 @@ * (IRQ 45 and 29, priority 2: below the audio and TIMER5) and talks to the rest through single-producer rings: * in: the BLE interrupts write, the TIMER5 tick moves it to the MIDI ring (and the clock) as cable 2; * out: midi_send writes (interrupts off), the BLE interrupts send it. - * The FM-1 is a BLE MIDI peripheral: a computer or phone connects to it. No pairing (macOS and iOS connect anyway), - * no central role, no audio. */ + * The FM-1 is a BLE MIDI peripheral (a computer or phone connects to it), and it can connect to one itself: ble_scan, + * ble_device, ble_connect (the central role, at the stack's minimal level: no pairing, so a controller or another + * FM-1, not a device that insists on pairing). One link at a time. No pairing as a peripheral either (macOS and + * iOS connect anyway), no audio. */ #ifndef BLE_DEVICE_NAME #define BLE_DEVICE_NAME APP_NAME /* advertised as "NAME XXXX", XXXX from this FM-1's address */ #endif #define FELUCCA_BLE_DIAG 0 -#define BLE_CENTRAL 0 +#ifndef BLE_CENTRAL +#define BLE_CENTRAL 3 /* the central role without pairing (ble_cfg.h) */ +#endif #include "ble/ble_stack.c" +#include "ble/ble_vm.c" /* the stock firmware's stored radio records (read only) */ -/* the SDK board's constant records (crystal load, PA bias; the Wi-Fi rates' gains left as they are): as fm1-base's - * bt_own.c. The radio's own record (187) is measured at every start (fm1_rf_cal.h) */ -static const struct ble_rf_trims BT_TRIMS = {{0x0B, 0x0B}, {1, 7, 4, 7, 11, 1, 7}, {0}, {0}}; +/* the radio's four records (106, 107, 108, 187): this FM-1's own from the stock firmware's VM when it's still there + * (ble_vm.c: the factory's, read only), else the SDK board's constant ones with the captured start-up's 187 fields + * (as fm1-base's bt_own.c, without its measuring). Our own calibration (hal/fm1_rf_cal.h) is not run: the radio's + * writes after it, in group 10 of the start-up, left the chip hanging or faulting in most builds (fomajam with or + * without the central role, the code in flash or in RAM, 2026-10-31), and ran only in some, by their layout */ +static struct ble_rf_trims bt_trims = {{0x0B, 0x0B}, {1, 7, 4, 7, 11, 1, 7}, {0}, {0}}; +static volatile struct { /* which records the last start used, kept over a reset (fm1.c platform_frame 0x14) */ + uint32_t magic, src, area, nrec; + uint8_t x187[68], pad[44]; +} bt_rf_kept __attribute__((section(".noinit.ble"))); static void bt_audio_hold(int hold); /* fm1.c: the audio stopped (1) or going again (0) */ @@ -34,7 +46,18 @@ static struct { static volatile uint32_t bo_w, bo_r; static uint8_t bt_addr[6]; static volatile uint8_t bt_up, bt_on, bt_live; /* the radio started; switched on; a central listens for MIDI */ -static uint8_t bt_held[16][16]; /* notes a central holds on: ended when the link goes */ +static uint8_t bt_held[16][16]; +/* notes a central holds on: ended when the link goes */ +#if BLE_CENTRAL +static struct ble_scan_tab bt_scan; /* the BLE MIDI devices around (ble_scan) */ +static uint32_t bt_scan_end, bt_aged; +static uint32_t bt_adv_at; /* when our scan's end or a cancel started advertising again (fm1_ms) */ +/* advertising stopped right after it started leaves the engine deaf in the next mode (nothing heard while scanning or + * initiating, 2026-10-31): a scan or a connect waits until advertising has run BT_SETTLE_MS */ +#define BT_SETTLE_MS 250u +static int bt_settled(void) { return fm1_ms - bt_adv_at >= BT_SETTLE_MS; } +static uint8_t bt_role; /* ble_central */ +#endif /* ---- the stack's side: the BLE interrupts */ BLE_API int ble_app_midi_peek(uint32_t *pkt, uint32_t *t_ms) { @@ -50,11 +73,29 @@ BLE_API void ble_app_midi_pop(void) { bo_r++; } } +/* when a message was meant, from its BLE-MIDI time stamp (the sender's ms, 13 bits): our ms minus its stamp is the + * two clocks' offset plus the trip; its smallest (the quickest trip) is kept, creeping up 1 ms every 2 s to follow the + * clocks' drift. A message's time is its arrival less what it was late past that, plus BT_CLOCK_DELAY_MS, so a clock + * comes out as evenly as it was sent (clock.c holds a tick that isn't due yet) */ +#define BT_CLOCK_DELAY_MS 6u +static uint32_t bt_when(uint16_t ts) { + static uint32_t off, off_at; + static uint8_t have; + uint32_t now = fm1_ticks(), ms = fm1_ms, d = (ms - ts) & 8191u, late = (d - off) & 8191u; + if (!have || late > 4096u) { /* the quickest trip yet (or the first) */ + off = d, have = 1, late = 0, off_at = ms; + } else if (ms - off_at > 2000u) { + off = (off + 1u) & 8191u, off_at = ms, late = late ? late - 1u : 0u; + } + late = late > 50u ? 50u : late; /* (a stamp far off: as it came) */ + return now - late * 1000u * FM1_TICKS_PER_US + BT_CLOCK_DELAY_MS * 1000u * FM1_TICKS_PER_US; +} + BLE_API void ble_app_midi_in(uint32_t pkt, uint16_t ts, uint16_t last_ts) { - (void)ts, (void)last_ts; + (void)last_ts; if (bi_w - bi_r < BQ) { bt_in[bi_w % BQ].pkt = pkt & ~0xF0u; - bt_in[bi_w % BQ].t = fm1_ticks(); + bt_in[bi_w % BQ].t = bt_when(ts); RING_PUBLISH(); bi_w++; } @@ -151,6 +192,11 @@ static void bt_addr_make(void) { bt_addr[5] = (uint8_t)((g >> 24) | 0xC0u); /* static random: the top two bits set */ } +static int bt_vm_read(void *ctx, uint32_t off, uint8_t *dst, uint32_t n) { /* ble_vm_scan's flash reads */ + (void)ctx; + return st_read(off, dst, n); +} + /* the first bt_enable: the two BLE vectors (masked), the radio and its calibration, then advertising. Nothing of * this runs at boot: a firmware that never turns Bluetooth on never touches the radio (attaching the vectors at * boot crashed the FM-1) */ @@ -163,10 +209,26 @@ static void bt_start(void) { fm1_guard_lock_top(); irq_restore(f); ble_init(bt_addr, 1); - fm1_rf_cal_on = 1; - fm1_wdt_arm(0x0F); /* (the radio's start-up and calibration take a while) */ + { + struct ble_vm_info vi; + struct ble_rf_trims vm; + uint32_t i, src = flash_ok && ble_vm_scan(bt_vm_read, 0, &vi, &vm, 0, 0) ? 1u : 0u; + if (src) { + bt_trims = vm; + } + bt_rf_kept.magic = 0x52464B54u; /* "TKFR" */ + bt_rf_kept.src = src; + bt_rf_kept.area = src ? vi.area : 0u; + bt_rf_kept.nrec = src ? vi.nrec : 0u; + for (i = 0; i < 68u; i++) { + bt_rf_kept.x187[i] = bt_trims.x187[i]; + } + } + fm1_rf_cal_on = 2; /* this unit's own VCO bands (the replay's are another FM-1's: reception went bad seconds + * after the start), the stored 187 for the rest (our trim hung the start-up: hal/fm1_ble_rf.h) */ + fm1_wdt_arm(0x0F); /* (the radio's start-up takes a while) */ bt_audio_hold(1); /* the audio interrupt paused: a long audio() in the start-up's timed sequences hangs it */ - ble_hw_wl82_start(&BT_TRIMS); + ble_hw_wl82_start(&bt_trims); bt_audio_hold(0); fm1_wdt_arm(0x0D); /* (as fm1_cstart arms it) */ bt_up = 1; @@ -187,19 +249,203 @@ int bt_enable(int features) { return 0; } +#if BLE_CENTRAL void bt_status(bt_status_t *s) { + uint8_t idx[BLE_SCAN_N], cs = bt_up ? ble_central_state() : BLE_CS_IDLE; *s = (bt_status_t){0}; s->ready = bt_up; - s->ble_state = !bt_up || !bt_on ? BLE_OFF : bt_live ? BLE_READY + s->ble_role = bt_role; + s->ble_count = (uint8_t)(bt_up ? ble_scan_list(&bt_scan, idx) : 0u); + s->ble_error = bt_up ? ble_central_fail() : 0; + s->ble_state = !bt_up || !bt_on ? BLE_OFF + : bt_live ? BLE_READY + : cs == BLE_CS_CONNECTING ? BLE_CONNECTING + : cs == BLE_CS_SETUP ? BLE_DISCOVERING + : ble_connected() ? BLE_CONNECTED + : bt_scan_end && ble_ll_scanning() ? BLE_SCANNING + : BLE_ADVERTISING; +} + +/* the main loop (platform_poll): the scan's reports into the list, and its end */ +static void bt_loop(void) { + uint8_t pdu[40]; + uint16_t rssi; + uint8_t n; + if (!bt_up) { + return; + } + while ((n = ble_ll_scan_take(pdu, &rssi)) != 0) { + ble_scan_add(&bt_scan, pdu, n, rssi, fm1_ms); + } + if (fm1_ms - bt_aged > 1000u) { + bt_aged = fm1_ms; + ble_scan_age(&bt_scan, fm1_ms); + } + if (bt_scan_end && (int32_t)(fm1_ms - bt_scan_end) >= 0) { + bt_scan_end = 0; + fm1_ble_irqs_hold(1); + ble_ll_scan(0); + fm1_ble_irqs_hold(0); + bt_adv_at = fm1_ms; + } +} + +/* ---- the central role: the FM-1 connects to a BLE MIDI device (a controller, another FM-1) */ +int ble_central(int on) { + bt_role = (uint8_t)(on != 0); + if (!on) { + ble_disconnect(); + } + return 0; +} +int ble_scan(void) { + if (!bt_up || !bt_on) { + return -3; + } + if (!bt_settled()) { + return -2; /* (busy: ask again) */ + } + ble_scan_clear(&bt_scan); + bt_scan_end = (fm1_ms + 15000u) | 1u; + fm1_ble_irqs_hold(1); + ble_ll_scan(1); + fm1_ble_irqs_hold(0); + return 0; +} +int ble_device(int i, char name[25], int *rssi) { + uint8_t idx[BLE_SCAN_N]; + uint32_t n = bt_up ? ble_scan_list(&bt_scan, idx) : 0u, k; + if (i < 0 || (uint32_t)i >= n) { + return -1; + } + const struct ble_found *e = &bt_scan.e[idx[i]]; + for (k = 0; k < 24u && e->name[k]; k++) { + name[k] = e->name[k]; + } + name[k] = 0; + if (rssi) { /* (no gain table: the list's three bars as a rough dBm) */ + *rssi = -100 + 20 * (int)ble_scan_bars(&bt_scan, idx[i]); + } + return 0; +} +int ble_device_addr(int i, uint8_t addr[6], int *random) { + uint8_t idx[BLE_SCAN_N]; + uint32_t n = bt_up ? ble_scan_list(&bt_scan, idx) : 0u; + if (i < 0 || (uint32_t)i >= n) { + return -1; + } + ble_cpy(addr, bt_scan.e[idx[i]].addr, 6); + if (random) { + *random = bt_scan.e[idx[i]].addr_rand; + } + return 0; +} +int ble_find(const uint8_t addr[6], int random, const char *name) { + uint8_t idx[BLE_SCAN_N]; + uint32_t n = bt_up ? ble_scan_list(&bt_scan, idx) : 0u, i, k; + for (i = 0; i < n; i++) { /* its address */ + const struct ble_found *e = &bt_scan.e[idx[i]]; + if (e->addr_rand == (uint8_t)(random != 0) && ble_eq(e->addr, addr, 6)) { + return (int)i; + } + } + for (i = 0; name && name[0] && i < n; i++) { /* else its name (an address that changes) */ + const struct ble_found *e = &bt_scan.e[idx[i]]; + for (k = 0; name[k] && e->name[k] == name[k]; k++) { + } + if (!name[k] && !e->name[k]) { + return (int)i; + } + } + return -1; +} +int ble_connect(int i) { + uint8_t idx[BLE_SCAN_N]; + uint32_t n = bt_up && bt_on ? ble_scan_list(&bt_scan, idx) : 0u; + struct ble_peer p; + int ok; + if (i < 0 || (uint32_t)i >= n) { + return -1; + } + if (!bt_settled()) { + return -2; + } + ble_zero((uint8_t *)&p, sizeof p); + ble_cpy(p.addr, bt_scan.e[idx[i]].addr, 6); + p.addr_rand = bt_scan.e[idx[i]].addr_rand; + bt_scan_end = 0; + fm1_ble_irqs_hold(1); + ok = ble_central_connect(&p); /* (from the scan: it stops it. A scan stopped first starts advertising again, and + * initiating right after that left the engine deaf: nothing heard, no link) */ + ble_ll_scan(0); /* (initiating: only the wish to scan goes, so the scan doesn't come back after) */ + fm1_ble_irqs_hold(0); + return ok ? 0 : -2; +} +int ble_disconnect(void) { + if (!bt_up) { + return -3; + } + fm1_ble_irqs_hold(1); + ble_central_cancel(); /* (a computer connected to us stays) */ + fm1_ble_irqs_hold(0); + bt_adv_at = fm1_ms; + return 0; +} +int ble_forget(void) { return 0; } /* (no pairings are kept) */ + +#else +/* (BLE_CENTRAL 0: a peripheral only) */ +void bt_status(bt_status_t *s) { + *s = (bt_status_t){0}; + s->ready = bt_up; + s->ble_state = !bt_up || !bt_on ? BLE_OFF : bt_live ? BLE_READY : ble_connected() ? BLE_CONNECTED : BLE_ADVERTISING; } - -/* not on this platform: the central role (connecting to a controller) and audio from Bluetooth */ +static void bt_loop(void) {} int ble_central(int on) { return on ? -3 : 0; } int ble_scan(void) { return -3; } int ble_device(int i, char name[25], int *rssi) { return (void)i, (void)name, (void)rssi, -1; } +int ble_device_addr(int i, uint8_t addr[6], int *random) { return (void)i, (void)addr, (void)random, -1; } +int ble_find(const uint8_t addr[6], int random, const char *name) { return (void)addr, (void)random, (void)name, -1; } int ble_connect(int i) { return (void)i, -3; } int ble_disconnect(void) { return -3; } int ble_forget(void) { return -3; } +#endif + +#if BLE_CENTRAL +/* for ./fm1 flash --bt (fm1.c platform_frame): 0x15 the state, 0x16 scan entry i. 32 bytes each */ +static void bt_report(uint32_t cmd, uint32_t i, uint8_t o[32]) { + uint8_t idx[BLE_SCAN_N]; + uint32_t n = bt_up ? ble_scan_list(&bt_scan, idx) : 0u, k; + bt_status_t b; + for (k = 0; k < 32u; k++) { + o[k] = 0; + } + if (cmd == 0x15u) { + bt_status(&b); + o[0] = bt_up, o[1] = bt_on, o[2] = bt_live, o[3] = bt_role, o[4] = b.ble_state; + o[5] = bt_up ? ble_central_state() : 0u, o[6] = bt_up ? ble_central_fail() : 0u, o[7] = bt_up ? ble_central_code() : 0u; + o[8] = (uint8_t)(bt_up && ble_connected()), o[9] = (uint8_t)n, o[10] = (uint8_t)(bt_up && ble_ll_scanning()), o[11] = drv.state; + ble_cpy(o + 12, bcen.peer.addr, 6); + o[18] = bcen.peer.addr_rand, o[19] = drv.master; + for (k = 0; k < 4u; k++) { + o[20 + k] = (uint8_t)(ble_hw_stat.connects >> 8 * k), o[24 + k] = (uint8_t)(ble_hw_stat.rx >> 8 * k); + o[28 + k] = (uint8_t)(bt_scan.reports >> 8 * k); + } + } else if (cmd == 0x19u) { /* our own address */ + ble_cpy(o, bt_addr, 6); + } else if (i < n) { + const struct ble_found *e = &bt_scan.e[idx[i]]; + o[0] = 1, o[1] = e->midi, o[2] = e->addr_rand, o[3] = e->hits; + ble_cpy(o + 4, e->addr, 6); + o[10] = (uint8_t)e->rssi, o[11] = (uint8_t)(e->rssi >> 8); + for (k = 0; k < 20u && e->name[k]; k++) { + o[12 + k] = (uint8_t)e->name[k]; + } + } +} +#endif + +/* not on this platform: audio from Bluetooth */ const int32_t *bt_audio_in(void) { return 0; } diff --git a/platform/clock.c b/platform/clock.c index 3e9f51c..6a6fe1a 100644 --- a/platform/clock.c +++ b/platform/clock.c @@ -50,11 +50,14 @@ static void ck_add(uint32_t at, int what) { } } -static void ck_tick(uint32_t at) { /* a followed tick: its length, smoothed (a pause is not one) */ +static void ck_tick(uint32_t at) { /* a followed tick: its length, smoothed over about a beat (a pause is not one) */ uint32_t f = ck_frames + at, d = f - ck_last; ck_last = f; if (ck_on && d < 44100u && (!ck_q4 || d << 4 < ck_q4 * 3u)) { - ck_q4 = ck_q4 ? (uint32_t)((int32_t)ck_q4 + ((int32_t)(d << 4) - (int32_t)ck_q4) / 4) : d << 4; + ck_q4 = ck_q4 ? (uint32_t)((int32_t)ck_q4 + ((int32_t)(d << 4) - (int32_t)ck_q4) / 24) : d << 4; /* (a quarter + * each tick: a + * tempo that + * wobbled) */ } ck_on = 1; ck_add(at, CLOCK_TICK); @@ -75,6 +78,9 @@ static void clock_block(uint32_t n, uint32_t t) { RING_PUBLISH(); uint32_t st = ck_q[r % CK_Q].st, src = ck_q[r % CK_Q].src; int32_t dt = (int32_t)(ck_q[r % CK_Q].t - ck_t); + if ((int32_t)(ck_q[r % CK_Q].t - t) > 0) { + break; /* (not due yet: Bluetooth's are timed a little ahead, bt.c) */ + } uint32_t at = dt <= 0 ? 0 : (uint32_t)(((uint64_t)(uint32_t)dt * CLOCK_MUL) >> 32); r++; if (!(src & from)) { diff --git a/platform/fm1.c b/platform/fm1.c index 301230b..4a112cd 100644 --- a/platform/fm1.c +++ b/platform/fm1.c @@ -87,6 +87,8 @@ static int st_read(uint32_t off, void *dst, uint32_t n) { static uint8_t recovery_active; #define OTA_IDENTITY (recovery_active ? "FM-1_000" : FELUCCA_ID) +static void platform_frame(uint32_t cmd, const uint8_t *b, uint32_t n); +#define OTA_MORE platform_frame #include "ota.c" static void recovery_poll(void); static uint32_t ota_now_ms(void) { return fm1_ms; } @@ -135,6 +137,57 @@ static void ota_commit(const uint8_t *parm) { #include "bt.c" #endif +/* the host's other messages (./fm1 flash --crash, --radio, --bt). Each answer is 32 bytes. + * 0x12, the last crash (fm1_irq.h, from before this boot: read it from the USB rescue too), 8 little-endian words: + * magic ("CRSH" when there's a record), count, vec, pc, rets, emu, dbg (the exception's cause), the reset reason | the + * BLE start-up step << 8. 0x13, the BLE breadcrumb (fm1_ble_rf.h, 0s without Bluetooth): now, irqs, op, gop, addr, + * stop, the crash's uptime_ms, etm[0]. With Bluetooth: 0x14 [k], the radio records the last start used (bt.c + * bt_rf_kept) from k * 32; 0x15, the link (bt.c bt_report); 0x16 [i], device i of the scan; 0x19, our address */ +static void platform_frame(uint32_t cmd, const uint8_t *b, uint32_t n) { + if ((cmd == 0x12u || cmd == 0x13u) && !n) { + uint32_t w[8] = {0}, step = 0; + uint8_t o[32]; +#if FOMA_BLUETOOTH + uint8_t ble = fm1_ble_bc.now >> 24 == 0xB1u; + step = ble ? fm1_ble_bc.now >> 16 & 0xFFu : 0u; + if (cmd == 0x13u && ble) { + w[0] = fm1_ble_bc.now, w[1] = fm1_ble_bc.irqs, w[2] = fm1_ble_bc.op, w[3] = fm1_ble_bc.gop; + w[4] = fm1_ble_bc.addr, w[5] = fm1_ble_bc.stop; + } +#endif + if (cmd == 0x12u) { + w[0] = fm1_crash.magic, w[1] = fm1_crash.count, w[2] = fm1_crash.vec, w[3] = fm1_crash.pc; + w[4] = fm1_crash.rets, w[5] = fm1_crash.emu, w[6] = fm1_crash.dbg, w[7] = fm1_boot.p3_rst | step << 8; + } else { + w[6] = fm1_crash.uptime_ms, w[7] = fm1_crash.etm[0]; + } + for (uint32_t i = 0; i < 32u; i++) { + o[i] = (uint8_t)(w[i / 4u] >> (8u * (i & 3u))); + } + ota_send_msg(cmd, o, sizeof o); + return; + } +#if FOMA_BLUETOOTH +#if BLE_CENTRAL + if (((cmd == 0x15u || cmd == 0x19u) && !n) || (cmd == 0x16u && n == 1u)) { + uint8_t o[32]; + bt_report(cmd, n ? b[0] : 0u, o); + ota_send_msg(cmd, o, sizeof o); + return; + } +#endif + if (cmd == 0x14u && n == 1u && b[0] < 4u) { /* the radio records the last start used (bt.c bt_rf_kept): 32 bytes at b[0] * 32 */ + uint8_t o[32]; + for (uint32_t i = 0; i < 32u; i++) { + o[i] = ((const volatile uint8_t *)&bt_rf_kept)[b[0] * 32u + i]; + } + ota_send_msg(cmd, o, sizeof o); + return; + } +#endif + (void)b, (void)n; +} + /* ---- the screen, the sound helpers (shared with the emulator) */ #include "common.c" diff --git a/platform/fm1.h b/platform/fm1.h index 8d735fb..5d214d8 100644 --- a/platform/fm1.h +++ b/platform/fm1.h @@ -169,11 +169,15 @@ typedef struct { } bt_status_t; int bt_enable(int features); /* BT_AUDIO | BT_MIDI, 0 off */ void bt_status(bt_status_t *s); -int ble_central(int on); /* 0: others connect to the FM-1; 1: it connects to a controller */ -int ble_scan(void); /* central: 15 s of looking for BLE MIDI devices */ -int ble_device(int i, char name[25], int *rssi); /* 0: device i of the scan */ +int ble_central(int on); /* 0: others connect to the FM-1; 1: it connects to a controller */ +int ble_scan(void); /* central: 15 s of looking for BLE MIDI devices */ +int ble_device(int i, char name[25], int *rssi); /* 0: device i of the scan */ +int ble_device_addr(int i, uint8_t addr[6], int *random); /* 0: device i's address, least significant octet first + * ("mvave": -1, not known) */ +int ble_find(const uint8_t addr[6], int random, const char *name); /* the scan's index of that device (by address, else + * by name when name is not empty), -1: not seen */ int ble_connect(int i); -int ble_disconnect(void); +int ble_disconnect(void); /* leave the device we connected to (a computer connected to us stays) */ int ble_forget(void); /* forget the BLE pairings */ const int32_t *bt_audio_in(void); /* in audio(): this block from Bluetooth (as audio_in), or 0 */ #endif diff --git a/platform/hal/fm1_ble_rf.h b/platform/hal/fm1_ble_rf.h index b1b27f0..0175eec 100644 --- a/platform/hal/fm1_ble_rf.h +++ b/platform/hal/fm1_ble_rf.h @@ -204,7 +204,9 @@ static void fm1_rfspi(uint32_t addr, uint32_t cmd, uint32_t data) /* HW ยง5.2: * table's banks (word 1, entries 0-127) and RX DC (word 0, 128-223) from what it measured. The x187 given to * fm1_ble_rf_run is ignored then. docs/bt/RF-CALIBRATION.md. */ #include "fm1_rf_cal.h" -static uint8_t fm1_rf_cal_on; /* set by the firmware: measure (1), or the stored 187 (0) */ +static uint8_t fm1_rf_cal_on; /* set by the firmware: measure (1), or the stored 187 (0), + * or measure only the VCO bands (2: the scan, its band and + * the RF-die words; the stored 187 for the rest) */ static struct fm1_rf_cal fm1_rfc; /* what was measured (the log reads it) */ static uint8_t fm1_rfc_x187[68]; /* the record built from it */ static uint8_t fm1_rfc_scanned, fm1_rfc_trimmed; @@ -409,7 +411,7 @@ static void fm1_ble_rf_exec(uint32_t pc, uint32_t end, const uint8_t *const rec[ fm1_ble_bc.addr = a; if (a == FM1_WL_A00) v = (v & ~(1u << 14)) | (FM1_RF_REG(a) & 1u << 14); - if (fm1_rf_cal_on && fm1_rfc_is187(trim, nt)) { + if (fm1_rf_cal_on == 1u && fm1_rfc_is187(trim, nt)) { fm1_rfc_before_187(); for (i = 0; i < nt; i++) if ((ble_rf_fields[4u * trim[i]] & 3u) != 3u) @@ -425,7 +427,7 @@ static void fm1_ble_rf_exec(uint32_t pc, uint32_t end, const uint8_t *const rec[ pc += 5; } else if ((op & 0xFCu) == 0x80u) { /* a window write */ v = rmw ? last : p[pc + 2]; - if (fm1_rf_cal_on && fm1_rfc_is187(trim, nt)) { + if (fm1_rf_cal_on == 1u && fm1_rfc_is187(trim, nt)) { fm1_rfc_before_187(); for (i = 0; i < nt; i++) if ((ble_rf_fields[4u * trim[i]] & 3u) != 3u) diff --git a/platform/mvave/port.c b/platform/mvave/port.c index 7bdd4d3..847b9a7 100644 --- a/platform/mvave/port.c +++ b/platform/mvave/port.c @@ -250,6 +250,21 @@ int ble_device(int i, char name[25], int *rssi) { *rssi = r; return 0; } +int ble_device_addr(int i, uint8_t addr[6], int *random) { return (void)i, (void)addr, (void)random, -1; } +int ble_find(const uint8_t addr[6], int random, const char *name) { /* (by name only: the addresses aren't known here) */ + char nm[25]; + (void)addr, (void)random; + for (int i = 0; name && name[0] && ble_device(i, nm, 0) == 0; i++) { + int k = 0; + while (name[k] && nm[k] == name[k]) { + k++; + } + if (!name[k] && !nm[k]) { + return i; + } + } + return -1; +} int ble_connect(int i) { return i < 0 ? -1 : mv_ble_connect((unsigned)i); } int ble_disconnect(void) { return mv_ble_disconnect(); } int ble_forget(void) { return mv_ble_forget(); } diff --git a/platform/src/ota.c b/platform/src/ota.c index 9dbfb30..f97b9d8 100644 --- a/platform/src/ota.c +++ b/platform/src/ota.c @@ -167,6 +167,10 @@ static void ota_service(void) uint32_t d = ota_take(); if (d == 7u && ota_dec[2] == 0x11) ota_reply_identity(); +#ifdef OTA_MORE + else if (d) + OTA_MORE(ota_dec[2], ota_dec + 6, d - 7u); /* the platform's other messages (fm1.c platform_frame) */ +#endif } /* one read request (3 tries x 5 s); data -> dst */ diff --git a/tools/flash.py b/tools/flash.py index 27f4cfa..c65e91f 100644 --- a/tools/flash.py +++ b/tools/flash.py @@ -5,7 +5,11 @@ tools/flash.py build/web/firmware.fwsc tools/flash.py bt build/web/firmware-bt.fwsc (any package the build made: bt, smk37, ...) tools/flash.py FILE.fwsc that package + tools/flash.py --list every FM-1 on USB, numbered (with more than one: --port N before the rest picks one) tools/flash.py --id only say what the FM-1 runs (FM-1_000: the USB rescue; ota-...: an install isn't finished) + tools/flash.py --crash the last crash the FM-1 recorded (from the firmware or the USB rescue) + tools/flash.py --bt the Bluetooth link: its state, what the last scan found (Bluetooth builds) + tools/flash.py --radio which radio records the last Bluetooth start used (this FM-1's stock ones?) It runs on the computer, not in Docker (Docker on a Mac can't reach USB MIDI), with nothing to install: CoreMIDI on macOS, ALSA's raw MIDI on Linux. Quit anything else that uses the FM-1's MIDI port first. @@ -132,6 +136,35 @@ def parse_request(p): return u[6], int.from_bytes(u[7:11], "little"), u[11] | u[12] << 8 | u[13] << 16 +def frame(cmd, body=b""): # a message to the device, as ota.c takes it + m = bytes([0x00, 0x59, cmd, len(body) & 0xFF, len(body) >> 8 & 0xFF, 0]) + body + return b"\xf0" + pack7(m + bytes([~sum(body) & 0xFF])) + b"\xf7" + + +BLE_STEPS = "none set_on stack_init rf_init bb_init started enable link_stop link_open adv_prog adv_started irqs_on running set_off".split() + + +def words(p, cmd): # an 8-word answer (fm1.c platform_frame) + d = unpack7(p[1:-1]) + if len(d) < 39 or d[0] != 0 or d[1] != 0x59 or d[2] != cmd: + return None + return [int.from_bytes(d[6 + 4 * i : 10 + 4 * i], "little") for i in range(8)] + + +def show_crash(w, b): + if w[0] != 0x43525348: + out = "no crash recorded" + else: + out = f"crashes {w[1]} vec 0x{w[2]:02x} pc 0x{w[3]:08x} rets 0x{w[4]:08x} emu 0x{w[5]:08x} dbg 0x{w[6]:08x}" + if b: + out += f" at {b[6]} ms etm 0x{b[7]:08x}" + rst, step = w[7] & 0xFF, w[7] >> 8 & 0xFF + out += f"\nlast reset 0x{rst:02x}{' (watchdog)' if rst & 4 else ''}" + if b and b[0] >> 24 == 0xB1: + out += f"\nbluetooth start-up: step {BLE_STEPS[step] if step < len(BLE_STEPS) else step}, group {b[0] & 0xFF}, op {b[2]} (+{b[3]}), last access 0x{b[4]:08x}, irqs {b[1]}, stop 0x{b[5]:08x}" + return out + + def parse_identity(p): d = unpack7(p[1:-1]) if len(d) != 34 or d[0] != 0 or d[1] != 0x59 or d[2] != 0x11: @@ -247,16 +280,18 @@ def pump(self, s): # (endpoints come and go only while the run loop runs) def ports(self): # [(name, (source, destination))] cm = self.cm - dests = {} + dests = {} # name -> destinations, in order (two FM-1s have the same name: the n-th source goes with the n-th) for i in range(cm.MIDIGetNumberOfDestinations()): d = cm.MIDIGetDestination(i) - dests.setdefault(self.name(d), d) - out = [] + dests.setdefault(self.name(d), []).append(d) + out, used = [], {} for i in range(cm.MIDIGetNumberOfSources()): s = cm.MIDIGetSource(i) nm = self.name(s) - if nm in dests: - out.append((nm, (s, dests[nm]))) + k = used.get(nm, 0) + if k < len(dests.get(nm, [])): + used[nm] = k + 1 + out.append((nm, (s, dests[nm][k]))) return out def open(self, ep): @@ -350,7 +385,8 @@ def send(self, data): # ---- the install (fm1ota.js Updater) class Updater: - def __init__(self, names): + def __init__(self, names, port=0): + self.port = port # 0: the first FM-1 that answers, else the port-th (--port) self.midi = CoreMidi() if sys.platform == "darwin" else Alsa() self.names = [n.lower() for n in names if n] @@ -374,8 +410,9 @@ def handshake(self, link, tries): return ident return None - def find(self, want=None): # (link, (identity, model), port name) of the first FM-1 that answers + def find(self, want=None, every=False): # (link, (identity, model), port name) of the first FM-1 that answers self.midi.pump(0.05) + found, k = [], 0 for nm, ep in self.midi.ports(): if not PORTS.search(nm) and not any(n in nm.lower() for n in self.names): continue @@ -385,9 +422,13 @@ def find(self, want=None): # (link, (identity, model), port name) of the first continue ident = self.handshake(link, 2) if ident and (not want or want(ident[1])): - return link, ident, nm + k += 1 + if every: + found.append((k, ident[0], nm)) + elif self.port in (0, k): + return link, ident, nm self.midi.close() - return None + return found if every else None def wait_for(self, want, s): end = time.monotonic() + s @@ -451,8 +492,99 @@ def project_name(): def main(): - args = sys.argv[1:] - up = Updater([project_name()]) + args, port = sys.argv[1:], 0 + if args[:1] == ["--port"] and len(args) > 1 and args[1].isdigit(): + port, args = int(args[1]), args[2:] + up = Updater([project_name()], port) + if args == ["--list"]: + for k, ident, nm in up.find(every=True): + print(f"{k}: {ident} (on {nm})") + return + if args == ["--crash"]: + dev = up.find() + if not dev: + raise SystemExit("flash: no FM-1 found (USB cable, and no other app using it?)") + link, ans = dev[0], {} + for cmd in (0x12, 0x13): + link.drain() + link.send(frame(cmd)) + end = time.monotonic() + 2 + while cmd not in ans and time.monotonic() < end: + p = link.read(end - time.monotonic()) + w = p and words(p, cmd) + if w: + ans[cmd] = w + up.midi.close() + got = 0x12 in ans and show_crash(ans[0x12], ans.get(0x13)) + print(f"{dev[1][0]}: {got or 'no answer (a firmware from before --crash)'}") + return + if args == ["--bt"]: + dev = up.find() + if not dev: + raise SystemExit("flash: no FM-1 found (USB cable, and no other app using it?)") + link = dev[0] + + def ask(cmd, body=b""): + link.drain() + link.send(frame(cmd, body)) + end = time.monotonic() + 2 + while time.monotonic() < end: + p = link.read(end - time.monotonic()) + d = p and unpack7(p[1:-1]) + if d and len(d) >= 39 and d[2] == cmd: + return d[6:38] + return None + + st = ask(0x15) + if not st: + up.midi.close() + raise SystemExit(f"{dev[1][0]}: no answer (not a Bluetooth build with --bt)") + states = "OFF IDLE ADVERTISING SCANNING CONNECTING DISCOVERING CONNECTED READY DISCONNECTING".split() + u32 = lambda b, o: int.from_bytes(b[o : o + 4], "little") + me = ask(0x19) + if me: + print( + f"{dev[1][0]} on {dev[2]}, Bluetooth address {':'.join(f'{x:02X}' for x in reversed(me[:6]))} (advertised as {project_name()} {me[1]:02X}{me[0]:02X})" + ) + print( + f"{dev[1][0]}: radio {'up' if st[0] else 'off'}, on {st[1]}, MIDI flowing {st[2]}, connecting out {st[3]}, state {states[st[4]] if st[4] < len(states) else st[4]}" + ) + print(f" central step {st[5]}, last fail {st[6]} (code {st[7]}), link {st[8]} (driver state {st[11]}, master {st[19]}), scanning {st[10]}") + print( + f" target {':'.join(f'{x:02X}' for x in reversed(st[12:18]))} ({'random' if st[18] else 'public'}), links made {u32(st, 20)}, packets in {u32(st, 24)}, scan reports {u32(st, 28)}" + ) + for i in range(st[9]): + e = ask(0x16, bytes([i])) + if e and e[0]: + print( + f" found {e[12:32].rstrip(bytes(1)).decode('latin-1')!r:24} {':'.join(f'{x:02X}' for x in reversed(e[4:10]))} midi {e[1]} hits {e[3]} rssi word {e[10] | e[11] << 8}" + ) + up.midi.close() + return + if args == ["--radio"]: + dev = up.find() + if not dev: + raise SystemExit("flash: no FM-1 found (USB cable, and no other app using it?)") + link, data = dev[0], b"" + for k in range(4): + link.drain() + link.send(frame(0x14, bytes([k]))) + end, got = time.monotonic() + 2, None + while not got and time.monotonic() < end: + p = link.read(end - time.monotonic()) + d = p and unpack7(p[1:-1]) + got = d and len(d) >= 39 and d[2] == 0x14 and d[6:38] + if not got: + break + data += got + up.midi.close() + if len(data) < 84 or int.from_bytes(data[:4], "little") != 0x52464B54: + print(f"{dev[1][0]}: the radio hasn't started since a reset (or a firmware from before --radio)") + return + src, area, nrec = (int.from_bytes(data[4 * i : 4 * i + 4], "little") for i in (1, 2, 3)) + print(f"{dev[1][0]}: radio records " + (f"from the stock VM at 0x{area:06x} ({nrec} records)" if src else "the defaults (no stock VM)")) + print("x187", data[16:84].hex(" ")) + return if args == ["--id"]: dev = up.find() if not dev: @@ -464,6 +596,10 @@ def main(): path = arg if arg.endswith(".fwsc") or os.sep in arg else f"build/web/firmware{'-' + arg if arg else ''}.fwsc" if not os.path.isfile(path): raise SystemExit(f"flash: no {path} (./fm1 build first)") + every = up.find(every=True) # (counted before any link is held: find() leaves the last one it tried open) + others = sum(1 for _, i, _n in every if not is_ota(i.split("_")[0])) # (the FM-1s not in update mode) + if not port and len(every) > 1 and not any(is_ota(i.split("_")[0]) for _, i, _n in every): + raise SystemExit("flash: more than one FM-1 on USB: pick one with --port N (./fm1 flash --list numbers them)") fwsc = open(path, "rb").read() product, image = product_of(fwsc), logical_image(fwsc) print(f"package {path}: {product}") @@ -482,6 +618,7 @@ def main(): if not same_model(ident[1], product.split("_")[0]): raise SystemExit(f"flash: the device is {ident[0]}, the package is for {product}") print(f"{ident[0]} on {nm}: starting") + others -= 1 # (this one comes back as the new firmware) link.send(UPGRADE) up.sleep(2) served, done, lost = up.serve(link, image, 0xE0000000, 8, lambda n, a: bar("verify", n, 0)) @@ -490,6 +627,7 @@ def main(): if not done: raise SystemExit(f"flash: the device {'was disconnected' if lost else 'stopped'} after {served} requests: nothing was written") print("loader waiting") + up.port = 0 # (--port picks the FM-1 to start from: one loader comes up, and the rest go by their identity) up.sleep(3) ota = up.wait_for(is_ota, 30) if not ota: @@ -500,15 +638,22 @@ def main(): raise SystemExit(f"flash: the loader {'was disconnected' if lost else 'stopped'} after {served} requests. Replug and run it again to resume") print("reboot waiting") up.sleep(3) - back = up.wait_for(lambda m: not is_ota(m), 90) # (two failed boots, then the USB rescue, take a while) - if not back: + up.port = 0 # (other FM-1s may be on USB: wait for one more than are there now, the one rebooting) + ids = lambda: [i for _, i, _n in up.find(every=True)] + end, now = time.monotonic() + 90, [] # (two failed boots, then the USB rescue, take a while) + while time.monotonic() < end: + now = ids() + if len(now) > others and not any(is_ota(i.split("_")[0]) for i in now): + break + up.sleep(1) + else: raise SystemExit("flash: the device did not come back: power-cycle it") up.midi.close() - if back[1][0] != product: - raise SystemExit( - f"flash: installed, but the device reports {back[1][0]}" + (" (the USB rescue: the firmware didn't start)" if back[1][0].endswith("_000") else "") - ) - print(f"done {back[1][0]}") + rescue = [i for i in now if i.endswith("_000")] + if rescue or product not in now: + got = rescue[0] if rescue else now[-1] + raise SystemExit(f"flash: installed, but the device reports {got}" + (" (the USB rescue: the firmware didn't start)" if rescue else "")) + print(f"done {product}") if __name__ == "__main__":