Skip to content

Commit

Permalink
Add delegate status listener for bluetooth
Browse files Browse the repository at this point in the history
  • Loading branch information
microbit-grace committed Aug 6, 2024
1 parent 09cbcad commit 70cfd35
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions lib/bluetooth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
ServiceConnectionEventMap,
TypedServiceEvent,
} from "./service-events.js";
import { MicrobitWebUSBConnection } from "./usb.js";

const requestDeviceTimeoutDuration: number = 30000;

Expand All @@ -49,6 +50,22 @@ export class MicrobitWebBluetoothConnection
private logging: Logging;
connection: BluetoothDeviceWrapper | undefined;

private serialSessionOpen: boolean = false;
private delegateStatusListener = (e: ConnectionStatusEvent) => {
const currentStatus = this.status;
if (e.status !== ConnectionStatus.CONNECTED) {
this.setStatus(e.status);
} else {
this.setStatus(ConnectionStatus.DISCONNECTED);
if (
currentStatus === ConnectionStatus.DISCONNECTED &&
this.serialSessionOpen
) {
this.connect();
}
}
};

private availabilityListener = (e: Event) => {
// TODO: is this called? is `value` correct?
const value = (e as any).value as boolean;
Expand All @@ -57,7 +74,10 @@ export class MicrobitWebBluetoothConnection
private availability: boolean | undefined;
private nameFilter: string | undefined;

constructor(options: MicrobitWebBluetoothConnectionOptions = {}) {
constructor(
private delegate: MicrobitWebUSBConnection,
options: MicrobitWebBluetoothConnectionOptions = {},
) {
super();
this.logging = options.logging || new NullLogging();
}
Expand All @@ -75,6 +95,8 @@ export class MicrobitWebBluetoothConnection
}

async initialize(): Promise<void> {
await this.delegate.initialize();
this.delegate.addEventListener("status", this.delegateStatusListener);
navigator.bluetooth?.addEventListener(
"availabilitychanged",
this.availabilityListener,
Expand Down Expand Up @@ -115,6 +137,7 @@ export class MicrobitWebBluetoothConnection
message: "error-disconnecting",
});
} finally {
this.serialSessionOpen = false;
this.connection = undefined;
this.setStatus(ConnectionStatus.DISCONNECTED);
this.logging.log("Disconnection complete");
Expand Down Expand Up @@ -159,8 +182,12 @@ export class MicrobitWebBluetoothConnection
{
onConnecting: () => this.setStatus(ConnectionStatus.CONNECTING),
onReconnecting: () => this.setStatus(ConnectionStatus.RECONNECTING),
onSuccess: () => this.setStatus(ConnectionStatus.CONNECTED),
onSuccess: () => {
this.serialSessionOpen = true;
this.setStatus(ConnectionStatus.CONNECTED);
},
onFail: () => {
this.serialSessionOpen = false;
this.setStatus(ConnectionStatus.DISCONNECTED);
this.connection = undefined;
},
Expand Down

0 comments on commit 70cfd35

Please sign in to comment.