Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 146 additions & 20 deletions js/common/ble-file-transfer.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import {FileTransferClient as BLEFileTransferClient} from '@adafruit/ble-file-transfer-js';
//import {FileTransferClient as BLEFileTransferClient} from '../../../ble-file-transfer-js/adafruit-ble-file-transfer.js';

const RESPONSE_TIMEOUT_MS = 10000;

class BLEFileTransferTimeoutError extends Error {
constructor() {
super("The Bluetooth device did not respond. Reconnect and try again.");
this.name = "BLEFileTransferTimeoutError";
}
}

// Wrapper that holds mutating-op promises open across the firmware
// autoreload + silent reconnect, so callers see a live GATT on return.
// See circuitpython/web-editor#377.
Expand All @@ -9,6 +18,105 @@ class FileTransferClient extends BLEFileTransferClient {
super(bleDevice, bufferSize);
this._workflow = workflow;
this.fileChangeAttempts = 0;
this._fileRequestInProgress = false;
this._pendingFileResponse = null;
this._responseTimeoutError = null;
}

async checkConnection() {
// A timed-out client must not accept packets from a new GATT session.
// A manual reconnect creates a fresh FileTransferClient.
if (this._responseTimeoutError) {
throw this._responseTimeoutError;
}
return await super.checkConnection();
}

_pendingResponse() {
const result = super._pendingResponse();
const response = {timer: null, writes: 0};
this._pendingFileResponse = response;
const finish = settle => value => {
clearTimeout(response.timer);
this._pendingFileResponse = null;
settle(value);
};
this._resolve = finish(this._resolve);
this._reject = finish(this._reject);
return result;
}

async _writeRequest(...parts) {
const response = this._pendingFileResponse;
if (response) {
clearTimeout(response.timer);
response.writes++;
// Each file operation uses 0xN1 for its response, including
// replies to READ_PACING (0x12) and WRITE_DATA (0x22).
response.expectedCommand = (new DataView(parts[0]).getUint8(0) & 0xf0) | 1;
}
try {
return await super._writeRequest(...parts);
} finally {
if (response) {
response.writes--;
this._waitForResponse(response);
}
}
}

async onTransferNotify(event) {
if (event.target !== this._transfer || !event.target.value?.byteLength) {
return;
}
const response = this._pendingFileResponse;
if (response && this._offset === 0 && event.target.value.getUint8(0) !== response.expectedCommand) {
return;
}
this._waitForResponse(response);
await super.onTransferNotify(event);
}

_waitForResponse(response) {
// Large writes can spend a long time sending a chunk. Count only the
// idle time waiting for a reply, and restart on each notification.
if (!response || response !== this._pendingFileResponse || response.writes) {
return;
}
clearTimeout(response.timer);
response.timer = setTimeout(() => {
this._handleResponseTimeout(response).catch(error =>
console.error("Could not close timed-out Bluetooth file transfer:", error));
}, RESPONSE_TIMEOUT_MS);
}

async _handleResponseTimeout(response) {
if (response !== this._pendingFileResponse) {
return;
}
this._responseTimeoutError = new BLEFileTransferTimeoutError();
const reject = this._reject;
this._resolve = null;
this._reject = null;
// The protocol has no request IDs. Reset both ends of the connection
// so a late reply cannot be mistaken for the result of the next request.
const reset = this.onDisconnected();
reject(this._responseTimeoutError);
if (this._workflow) {
await this._workflow.disconnectAfterFileTransferTimeout(this);
} else {
this._device.gatt?.disconnect();
}
await reset;
}

async onDisconnected() {
this._transfer?.removeEventListener("characteristicvaluechanged", this._onTransferNotify);
this._incomingFile = null;
this._incomingOffset = 0;
this._outgoingContents = null;
this._outgoingOffset = 0;
return await super.onDisconnected();
}

_signalMutatingOp() {
Expand All @@ -25,32 +133,50 @@ class FileTransferClient extends BLEFileTransferClient {
}
}

async writeFile(path, offset, contents, modificationTime, raw) {
this._signalMutatingOp();
const result = await super.writeFile(path, offset, contents, modificationTime, raw);
await this._awaitReconnectIfNeeded();
async _fileRequest(operation, mutating = false) {
// Reserve the shared response and payload state before the first
// await. A second operation can otherwise change the first's buffers.
if (this._fileRequestInProgress) {
throw new Error("A Bluetooth file request is already in progress.");
}
this._fileRequestInProgress = true;
let result;
try {
if (mutating) {
this._signalMutatingOp();
}
result = await operation();
} finally {
this._fileRequestInProgress = false;
}
if (mutating) {
await this._awaitReconnectIfNeeded();
}
return result;
}

async move(oldPath, newPath) {
this._signalMutatingOp();
const result = await super.move(oldPath, newPath);
await this._awaitReconnectIfNeeded();
return result;
readFile(filename, raw) {
return this._fileRequest(() => super.readFile(filename, raw));
}

async delete(path) {
this._signalMutatingOp();
const result = await super.delete(path);
await this._awaitReconnectIfNeeded();
return result;
listDir(path) {
return this._fileRequest(() => super.listDir(path));
}

async makeDir(path, modificationTime) {
this._signalMutatingOp();
const result = await super.makeDir(path, modificationTime);
await this._awaitReconnectIfNeeded();
return result;
writeFile(path, offset, contents, modificationTime, raw) {
return this._fileRequest(() => super.writeFile(path, offset, contents, modificationTime, raw), true);
}

move(oldPath, newPath) {
return this._fileRequest(() => super.move(oldPath, newPath), true);
}

delete(path) {
return this._fileRequest(() => super.delete(path), true);
}

makeDir(path, modificationTime) {
return this._fileRequest(() => super.makeDir(path, modificationTime), true);
}

async readOnly() {
Expand Down Expand Up @@ -103,4 +229,4 @@ class FileTransferClient extends BLEFileTransferClient {
}
}

export {FileTransferClient};
export {BLEFileTransferTimeoutError, FileTransferClient};
35 changes: 23 additions & 12 deletions js/common/dialogs.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {sleep, isIp, switchDevice} from './utilities.js';
import {BLEFileTransferTimeoutError} from './ble-file-transfer.js';
import {renderFirmwareSuggestions} from './firmware-check.js';
import * as focusTrap from 'focus-trap';

Expand Down Expand Up @@ -353,8 +354,10 @@ function showDeviceInfoError(modal, error) {
console.error("Unable to read device info:", error);
const msgElement = modal.querySelector("#message");
if (msgElement) {
msgElement.textContent =
"Could not read device information. The connection to the device was lost.";
const detail = error instanceof BLEFileTransferTimeoutError
? error.message
: "The connection to the device was lost.";
msgElement.textContent = `Could not read device information. ${detail}`;
}
}

Expand Down Expand Up @@ -436,23 +439,31 @@ class DiscoveryModal extends GenericModal {
}

class DeviceInfoModal extends GenericModal {
async _getDeviceInfo() {
async _getDeviceInfo() {
const modal = this._currentModal;
const fileHelper = this._fileHelper;
modal.querySelector("#message").textContent = "";
let deviceInfo;
try {
deviceInfo = await this._showBusy(this._fileHelper.versionInfo());
deviceInfo = await this._showBusy(fileHelper.versionInfo());
} catch (error) {
showDeviceInfoError(this._currentModal, error);
if (this._currentModal === modal && this._fileHelper === fileHelper) {
showDeviceInfoError(modal, error);
}
return;
}
this._currentModal.querySelector("#version").textContent = deviceInfo.version;
const boardLink = this._currentModal.querySelector("#board");
if (this._currentModal !== modal || this._fileHelper !== fileHelper) {
return;
}
modal.querySelector("#version").textContent = deviceInfo.version;
const boardLink = modal.querySelector("#board");
boardLink.href = `https://circuitpython.org/board/${deviceInfo.board_id}/`;
boardLink.textContent = deviceInfo.board_name;
this._currentModal.querySelector("#builddate").textContent = deviceInfo.build_date;
this._currentModal.querySelector("#mcuname").textContent = deviceInfo.mcu_name;
this._currentModal.querySelector("#boardid").textContent = deviceInfo.board_id;
this._currentModal.querySelector("#uid").textContent = deviceInfo.uid;
const updateContainer = this._currentModal.querySelector("#firmware-update");
modal.querySelector("#builddate").textContent = deviceInfo.build_date;
modal.querySelector("#mcuname").textContent = deviceInfo.mcu_name;
modal.querySelector("#boardid").textContent = deviceInfo.board_id;
modal.querySelector("#uid").textContent = deviceInfo.uid;
const updateContainer = modal.querySelector("#firmware-update");
if (updateContainer) {
renderFirmwareSuggestions(updateContainer, deviceInfo);
}
Expand Down
6 changes: 6 additions & 0 deletions js/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { classHighlighter } from "@lezer/highlight";
import initRuffFormatter, { PositionEncoding, Workspace } from "@astral-sh/ruff-wasm-web";
import { circuitpythonHighlight } from "./common/circuitpython_highlight.js";
import { getFileIcon } from "./common/file_dialog.js";
import { BLEFileTransferTimeoutError } from "./common/ble-file-transfer.js";

import { Terminal } from '@xterm/xterm';
import { WebLinksAddon } from '@xterm/addon-web-links';
Expand Down Expand Up @@ -1233,6 +1234,11 @@ async function saveFileContents(path, savingWorkflow, selection) {
if (!saveContextIsCurrent()) {
return false;
}
if (e instanceof BLEFileTransferTimeoutError) {
setSaved(false);
await showMessage(e.message);
return false;
}
offset = 0;
// If the device cleanly told us the filesystem is held by
// someone else (most commonly USB-MSC: the host has
Expand Down
13 changes: 13 additions & 0 deletions js/workflows/ble.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,19 @@ class BLEWorkflow extends Workflow {
await super.onDisconnected(e, reconnect);
}

async disconnectAfterFileTransferTimeout(client) {
if (this.fileHelper?.getFileClient() !== client) {
return;
}
const device = this.bleDevice;
this._lastMutatingOpAt = 0;
// Remove the workflow's GATT listener before disconnecting so this
// intentional reset cannot start an autoreload reconnect.
const cleanup = this.onDisconnected(null, false);
device.gatt.disconnect();
await cleanup;
}

async showConnect(documentState) {
let p = this.connectDialog.open();
let modal = this.connectDialog.getModal();
Expand Down