Skip to content

Commit

Permalink
Limit progress callbacks (#30)
Browse files Browse the repository at this point in the history
Set it to a reasonable value by default that gives somewhat smooth
progress bars.
  • Loading branch information
microbit-matt-hillsdon authored Oct 17, 2024
1 parent 66b4d89 commit 4de7ea8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
25 changes: 24 additions & 1 deletion lib/usb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ export class MicrobitWebUSBConnection
options: {
partial: boolean;
progress: (percentage: number | undefined) => void;
miniumProgressIncrement: number;
},
): Promise<void> {
this.flashing = true;
Expand Down Expand Up @@ -232,6 +233,7 @@ export class MicrobitWebUSBConnection
options: {
partial: boolean;
progress: (percentage: number | undefined, partial: boolean) => void;
miniumProgressIncrement: number;
},
): Promise<void> {
this.log("Stopping serial before flash");
Expand All @@ -243,7 +245,10 @@ export class MicrobitWebUSBConnection
}

const partial = options.partial;
const progress = options.progress || (() => {});
const progress = rateLimitProgress(
options.miniumProgressIncrement ?? 0.0025,
options.progress || (() => {}),
);

const boardId = this.connection.boardSerialInfo.id;
const boardVersion = boardId.toBoardVersion();
Expand Down Expand Up @@ -516,3 +521,21 @@ const enrichedError = (err: any): DeviceError => {
}
}
};

const rateLimitProgress = (
miniumProgressIncrement: number,
callback: (value: number | undefined, partial: boolean) => void,
) => {
let lastCallValue = -1;
return (value: number | undefined, partial: boolean) => {
if (
value === undefined ||
value === 0 ||
value === 1 ||
value >= lastCallValue + miniumProgressIncrement
) {
lastCallValue = value ?? -1;
callback(value, partial);
}
};
};
2 changes: 2 additions & 0 deletions src/demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,12 +209,14 @@ const createFlashSection = (): Section => {
if (file) {
const text = await file.text();
if (connection.flash) {
console.time("flash");
await connection.flash(createUniversalHexFlashDataSource(text), {
partial: true,
progress: (percentage: number | undefined) => {
console.log(percentage);
},
});
console.timeEnd("flash");
}
}
},
Expand Down

0 comments on commit 4de7ea8

Please sign in to comment.