Fix BLE upload: write-with-response on CMD+DATA, on-demand advertising, wake-play-random, remove startup blink
This commit is contained in:
+1
-1
@@ -38,7 +38,7 @@ function fmtBytes(n) {
|
||||
|
||||
// ---- connection state ----
|
||||
dev.addEventListener('log', (e) => log(e.detail));
|
||||
dev.addEventListener('connected', (e) => { setConnected(true, e.detail.name); refresh(); fetchVolume(); });
|
||||
dev.addEventListener('connected', async (e) => { setConnected(true, e.detail.name); await refresh(); fetchVolume(); });
|
||||
dev.addEventListener('disconnected', () => {
|
||||
setConnected(false); deviceTracks = null; renderSlots();
|
||||
$('volume-val').textContent = '—';
|
||||
|
||||
+9
-9
@@ -186,7 +186,7 @@ export class BabyMobile extends EventTarget {
|
||||
|
||||
async _writeCmd(bytes) {
|
||||
this._requireConnected();
|
||||
await this.cmd.writeValueWithoutResponse(Uint8Array.from(bytes));
|
||||
await this.cmd.writeValue(Uint8Array.from(bytes));
|
||||
}
|
||||
|
||||
async play(track) {
|
||||
@@ -282,21 +282,21 @@ export class BabyMobile extends EventTarget {
|
||||
this._log(`Starting upload of ${total} bytes to slot ${track}…`);
|
||||
await this._writeCmd([CMD_UPLOAD_START, track & 0xff]);
|
||||
|
||||
// Send all data chunks sequentially. Chrome on Windows (WinRT BLE) only
|
||||
// allows one writeValueWithoutResponse in flight at a time; concurrent calls
|
||||
// fail with "GATT operation already in progress". Sequential writes are
|
||||
// reliable and throughput is governed by the BLE connection interval, not
|
||||
// by how many calls are in flight.
|
||||
// Send all data chunks using write-with-response. Each writeValue() call
|
||||
// blocks until the SoftDevice sends an ATT Write Response, which only happens
|
||||
// after it has delivered the packet to the firmware's write callback. This
|
||||
// provides natural per-packet flow control: CMD_UPLOAD_END cannot be sent until
|
||||
// every data packet has been confirmed received, eliminating all OS TX-queue
|
||||
// race conditions without any byte-counting hacks.
|
||||
for (let off = 0; off < total; off += DATA_CHUNK) {
|
||||
await this.data.writeValueWithoutResponse(
|
||||
await this.data.writeValue(
|
||||
wavBytes.subarray(off, Math.min(off + DATA_CHUNK, total)));
|
||||
// Cap the optimistic local count at 99%; the final 1% is filled only when
|
||||
// the device's finalize ack confirms the bytes actually landed in flash.
|
||||
report(Math.min(off + DATA_CHUNK, Math.floor(total * 0.99)));
|
||||
}
|
||||
|
||||
// Tell the firmware we're done. It will drain its ring buffer, write the
|
||||
// track table, then send ONE finalize notification with the total byte count.
|
||||
// All data confirmed received — finalize.
|
||||
await this._writeCmd([CMD_UPLOAD_END]);
|
||||
|
||||
// Wait for that single finalize notification. Allow up to 60 s: at 300 ms/sector
|
||||
|
||||
+5
-5
@@ -87,15 +87,15 @@ label { display: inline-flex; align-items: center; gap: 8px; font-size: .9rem; c
|
||||
.handle:focus { outline: none; }
|
||||
.handle:focus .line, .handle.dragging .line { background: var(--accent); box-shadow: 0 0 6px var(--accent); }
|
||||
.handle:focus .chev, .handle.dragging .chev { filter: drop-shadow(0 0 4px var(--accent)); }
|
||||
.trim-readout { display: flex; align-items: center; gap: 12px; font-size: .85rem; color: var(--muted); }
|
||||
.time-fields { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.trim-readout { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 12px; font-size: .85rem; color: var(--muted); }
|
||||
.time-fields { display: inline-flex; align-items: center; gap: 6px; flex-shrink: 0; }
|
||||
.time-fields .dash { color: var(--muted); }
|
||||
.time-in {
|
||||
width: 4.2rem; padding: 5px 7px; font-size: .85rem;
|
||||
width: 3.8rem; min-width: 0; padding: 5px 7px; font-size: .85rem;
|
||||
background: #1c123e; color: var(--text); border: 1px solid var(--line); border-radius: 7px;
|
||||
}
|
||||
.trim-readout .clip { color: var(--accent); font-weight: 600; }
|
||||
.trim-readout button { margin-left: auto; }
|
||||
.trim-readout .clip { margin-left: auto; color: var(--accent); font-weight: 600; }
|
||||
.trim-readout button { flex-shrink: 0; }
|
||||
.level { display: flex; align-items: center; gap: 10px; width: 100%; margin-top: 12px; font-size: .85rem; color: var(--muted); }
|
||||
.level input[type=range] { flex: 1; min-width: 0; }
|
||||
.level .unit { min-width: 3.2rem; text-align: right; color: var(--accent); font-weight: 600; }
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// sw.js — minimal offline cache so the PWA launches without a network.
|
||||
const CACHE = 'babymobile-v8';
|
||||
const CACHE = 'babymobile-v9';
|
||||
const ASSETS = [
|
||||
'./', './index.html', './styles.css',
|
||||
'./app.js', './ble.js', './wav.js',
|
||||
|
||||
@@ -49,6 +49,11 @@
|
||||
#include <Adafruit_TinyUSB.h>
|
||||
#include <bluefruit.h>
|
||||
|
||||
// ============================================================
|
||||
// When defined, a wake from deep sleep (button press) plays a random track
|
||||
// immediately instead of waiting for user input.
|
||||
//#define WAKE_PLAY_RANDOM
|
||||
|
||||
// ============================================================
|
||||
// POC MODE: stream audio from internal LittleFS instead of SPI flash.
|
||||
// Upload tracks via upload_track.py (serial) or BLE (CMD 0x02).
|
||||
@@ -247,6 +252,10 @@ unsigned long g_lastActivity = 0;
|
||||
// USB connected flag
|
||||
volatile bool g_usbConnected = false;
|
||||
|
||||
// Wake-from-sleep detection. Read before SoftDevice starts (setupBLE), stored here.
|
||||
static bool g_wakeFromSleep = false;
|
||||
static uint8_t g_wakeTrack = 0;
|
||||
|
||||
#ifdef POC_INTERNAL_FLASH
|
||||
static void pocFilename(uint8_t n, char *buf) { // buf must be >=16 bytes
|
||||
snprintf(buf, 16, "/track%d.wav", n);
|
||||
@@ -746,8 +755,10 @@ void audioCmd_write_cb(uint16_t conn_handle, BLECharacteristic* chr,
|
||||
loadTrackTable();
|
||||
Serial.println("BLE: Upload complete");
|
||||
#else
|
||||
// Signal loop() to finalize after ring buffer drains.
|
||||
// Don't call loadTrackTable() here — we're in a BLE callback.
|
||||
// Signal loop() to finalize once the ring buffer drains.
|
||||
// Because the DATA characteristic uses write-with-response, every data
|
||||
// packet has been ATT-acknowledged before the client sends this command,
|
||||
// so all bytes are already in the ring buffer by the time we get here.
|
||||
if (g_bleUploading) {
|
||||
g_bleFinalizing = true;
|
||||
Serial.println("BLE: Finalizing upload...");
|
||||
@@ -1003,17 +1014,20 @@ void setupBLE() {
|
||||
// Audio service
|
||||
audioSvc.begin();
|
||||
|
||||
// Command characteristic (write without response — avoids "GATT already in progress" errors)
|
||||
audioCmd.setProperties(CHR_PROPS_WRITE_WO_RESP);
|
||||
// Command characteristic: write-with-response so JS can await full OS-level
|
||||
// completion before issuing the next operation on any characteristic.
|
||||
audioCmd.setProperties(CHR_PROPS_WRITE);
|
||||
audioCmd.setPermission(SECMODE_OPEN, SECMODE_OPEN);
|
||||
audioCmd.setMaxLen(240);
|
||||
audioCmd.setWriteCallback(audioCmd_write_cb);
|
||||
audioCmd.begin();
|
||||
|
||||
// Data characteristic (write without response for speed)
|
||||
audioData.setProperties(CHR_PROPS_WRITE_WO_RESP);
|
||||
// Data characteristic (write with response — ATT flow control ensures the
|
||||
// SoftDevice has acknowledged every packet before the client sends the next,
|
||||
// so CMD_UPLOAD_END can never race ahead of the data stream)
|
||||
audioData.setProperties(CHR_PROPS_WRITE);
|
||||
audioData.setPermission(SECMODE_OPEN, SECMODE_OPEN);
|
||||
audioData.setMaxLen(240);
|
||||
audioData.setMaxLen(244); // must match DATA_CHUNK in ble.js (MTU 247 - 3 = 244)
|
||||
audioData.setWriteCallback(audioData_write_cb);
|
||||
audioData.begin();
|
||||
|
||||
@@ -1324,6 +1338,17 @@ void waitButtonRelease(uint8_t btn) {
|
||||
// SLEEP / WAKE
|
||||
// ============================================================
|
||||
|
||||
// One byte from the nRF52840 hardware true random number generator.
|
||||
static uint8_t hwRandom() {
|
||||
NRF_RNG->CONFIG = RNG_CONFIG_DERCEN_Enabled << RNG_CONFIG_DERCEN_Pos; // bias correction on
|
||||
NRF_RNG->EVENTS_VALRDY = 0;
|
||||
NRF_RNG->TASKS_START = 1;
|
||||
while (!NRF_RNG->EVENTS_VALRDY) {}
|
||||
uint8_t v = (uint8_t)NRF_RNG->VALUE;
|
||||
NRF_RNG->TASKS_STOP = 1;
|
||||
return v;
|
||||
}
|
||||
|
||||
void enterDeepSleep() {
|
||||
// Don't sleep if any button is currently LOW — would wake instantly.
|
||||
// Also catches floating pins that the internal pull-up isn't winning against.
|
||||
@@ -1372,22 +1397,6 @@ void setup() {
|
||||
digitalWrite(PIN_LED, HIGH);
|
||||
|
||||
Serial.begin(115200);
|
||||
Serial.println("...");
|
||||
|
||||
int c=0;
|
||||
while(c<10) {
|
||||
// pinMode(c, OUTPUT);
|
||||
delay(250);
|
||||
digitalWrite(PIN_LED, HIGH);
|
||||
// digitalWrite(c, HIGH);
|
||||
// Serial.println("0");
|
||||
delay(250);
|
||||
digitalWrite(PIN_LED, LOW);
|
||||
// digitalWrite(c, LOW);
|
||||
// Serial.println(c);
|
||||
c++;
|
||||
}
|
||||
|
||||
Serial.println("=== Baby Mobile v2 ===");
|
||||
Serial.println("nRF52840 + IS25LP128F + PAM8302A");
|
||||
|
||||
@@ -1444,11 +1453,31 @@ void setup() {
|
||||
usb_msc.begin();
|
||||
#endif
|
||||
|
||||
// Read RESETREAS and collect a random byte BEFORE starting the SoftDevice.
|
||||
// Once Bluefruit.begin() enables S140, the SoftDevice owns NRF_RNG and
|
||||
// NRF_POWER — direct register access after that point causes a hard fault.
|
||||
g_wakeFromSleep = (NRF_POWER->RESETREAS & POWER_RESETREAS_OFF_Msk) != 0;
|
||||
NRF_POWER->RESETREAS = 0xFFFFFFFFUL; // write-1-to-clear
|
||||
if (g_wakeFromSleep) Serial.println("Woke from deep sleep.");
|
||||
#ifdef WAKE_PLAY_RANDOM
|
||||
if (g_wakeFromSleep && g_numTracks > 0) {
|
||||
// hwRandom() is safe here — SoftDevice not yet started.
|
||||
g_wakeTrack = hwRandom() % g_numTracks;
|
||||
}
|
||||
#endif
|
||||
|
||||
// BLE
|
||||
setupBLE();
|
||||
|
||||
g_lastActivity = millis();
|
||||
|
||||
#ifdef WAKE_PLAY_RANDOM
|
||||
if (g_wakeFromSleep && g_numTracks > 0) {
|
||||
Serial.print("Auto-play random track "); Serial.println(g_wakeTrack);
|
||||
audioStart(g_wakeTrack);
|
||||
}
|
||||
#endif
|
||||
|
||||
digitalWrite(PIN_LED, HIGH);
|
||||
Serial.println("Ready! Plug in USB to upload audio, or press a button.");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user