Skip to content

Add radio bridge support and button service #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jul 23, 2024
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
57 changes: 29 additions & 28 deletions lib/accelerometer-service.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,37 @@
import { AccelerometerData, AccelerometerDataEvent } from "./accelerometer.js";
import { GattOperation } from "./bluetooth-device-wrapper.js";
import { GattOperation, Service } from "./bluetooth-device-wrapper.js";
import { profile } from "./bluetooth-profile.js";
import { createGattOperationPromise } from "./bluetooth-utils.js";
import { BackgroundErrorEvent, DeviceError } from "./device.js";
import {
CharacteristicDataTarget,
TypedServiceEvent,
TypedServiceEventDispatcher,
} from "./service-events.js";

export class AccelerometerService {
export class AccelerometerService implements Service {
constructor(
private accelerometerDataCharacteristic: BluetoothRemoteGATTCharacteristic,
private accelerometerPeriodCharacteristic: BluetoothRemoteGATTCharacteristic,
private dispatchTypedEvent: TypedServiceEventDispatcher,
private isNotifying: boolean,
private queueGattOperation: (gattOperation: GattOperation) => void,
) {
this.addDataEventListener();
if (this.isNotifying) {
this.startNotifications();
}
this.accelerometerDataCharacteristic.addEventListener(
"characteristicvaluechanged",
(event: Event) => {
const target = event.target as CharacteristicDataTarget;
const data = this.dataViewToData(target.value);
this.dispatchTypedEvent(
"accelerometerdatachanged",
new AccelerometerDataEvent(data),
);
},
);
}

static async createService(
gattServer: BluetoothRemoteGATTServer,
dispatcher: TypedServiceEventDispatcher,
isNotifying: boolean,
queueGattOperation: (gattOperation: GattOperation) => void,
listenerInit: boolean,
): Promise<AccelerometerService | undefined> {
Expand Down Expand Up @@ -57,7 +63,6 @@ export class AccelerometerService {
accelerometerDataCharacteristic,
accelerometerPeriodCharacteristic,
dispatcher,
isNotifying,
queueGattOperation,
);
}
Expand Down Expand Up @@ -99,7 +104,7 @@ export class AccelerometerService {
// Values passed are rounded up to the allowed values on device.
// Documentation for allowed values looks wrong.
// https://lancaster-university.github.io/microbit-docs/resources/bluetooth/bluetooth_profile.html
const { callback } = createGattOperationPromise();
const { callback, gattOperationPromise } = createGattOperationPromise();
const dataView = new DataView(new ArrayBuffer(2));
dataView.setUint16(0, value, true);
this.queueGattOperation({
Expand All @@ -109,29 +114,25 @@ export class AccelerometerService {
dataView,
),
});
await gattOperationPromise;
}

private addDataEventListener(): void {
this.accelerometerDataCharacteristic.addEventListener(
"characteristicvaluechanged",
(event: Event) => {
const target = event.target as CharacteristicDataTarget;
const data = this.dataViewToData(target.value);
this.dispatchTypedEvent(
"accelerometerdatachanged",
new AccelerometerDataEvent(data),
);
},
);
async startNotifications(type: TypedServiceEvent): Promise<void> {
await this.characteristicForEvent(type)?.startNotifications();
}

startNotifications(): void {
this.accelerometerDataCharacteristic.startNotifications();
this.isNotifying = true;
async stopNotifications(type: TypedServiceEvent): Promise<void> {
await this.characteristicForEvent(type)?.stopNotifications();
}

stopNotifications(): void {
this.isNotifying = false;
this.accelerometerDataCharacteristic.stopNotifications();
private characteristicForEvent(type: TypedServiceEvent) {
switch (type) {
case "accelerometerdatachanged": {
return this.accelerometerDataCharacteristic;
}
default: {
return undefined;
}
}
}
}
128 changes: 89 additions & 39 deletions lib/bluetooth-device-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@

import { AccelerometerService } from "./accelerometer-service.js";
import { profile } from "./bluetooth-profile.js";
import { ButtonService } from "./button-service.js";
import { BoardVersion, DeviceError } from "./device.js";
import { Logging, NullLogging } from "./logging.js";
import {
ServiceConnectionEventMap,
TypedServiceEvent,
TypedServiceEventDispatcher,
} from "./service-events.js";

Expand Down Expand Up @@ -48,6 +50,50 @@ function findPlatform(): string | undefined {
const platform = findPlatform();
const isWindowsOS = platform && /^Win/.test(platform);

export interface Service {
startNotifications(type: TypedServiceEvent): Promise<void>;
stopNotifications(type: TypedServiceEvent): Promise<void>;
}

class ServiceInfo<T extends Service> {
private service: T | undefined;

constructor(
private serviceFactory: (
gattServer: BluetoothRemoteGATTServer,
dispatcher: TypedServiceEventDispatcher,
queueGattOperation: (gattOperation: GattOperation) => void,
listenerInit: boolean,
) => Promise<T | undefined>,
public events: TypedServiceEvent[],
) {}

get(): T | undefined {
return this.service;
}

async createIfNeeded(
gattServer: BluetoothRemoteGATTServer,
dispatcher: TypedServiceEventDispatcher,
queueGattOperation: (gattOperation: GattOperation) => void,
listenerInit: boolean,
): Promise<T | undefined> {
this.service =
this.service ??
(await this.serviceFactory(
gattServer,
dispatcher,
queueGattOperation,
listenerInit,
));
return this.service;
}

dispose() {
this.service = undefined;
}
}

export class BluetoothDeviceWrapper {
// Used to avoid automatic reconnection during user triggered connect/disconnect
// or reconnection itself.
Expand All @@ -67,15 +113,17 @@ export class BluetoothDeviceWrapper {
private connecting = false;
private isReconnect = false;
private reconnectReadyPromise: Promise<void> | undefined;
private accelerometerService: AccelerometerService | undefined;

private accelerometer = new ServiceInfo(AccelerometerService.createService, [
"accelerometerdatachanged",
]);
private buttons = new ServiceInfo(ButtonService.createService, [
"buttonachanged",
"buttonbchanged",
]);
private serviceInfo = [this.accelerometer, this.buttons];

boardVersion: BoardVersion | undefined;
serviceListenerState = {
accelerometerdatachanged: {
notifying: false,
service: this.getAccelerometerService,
},
};

private gattOperations: GattOperations = {
busy: false,
Expand All @@ -86,20 +134,13 @@ export class BluetoothDeviceWrapper {
public readonly device: BluetoothDevice,
private logging: Logging = new NullLogging(),
private dispatchTypedEvent: TypedServiceEventDispatcher,
private addedServiceListeners: Record<
keyof ServiceConnectionEventMap,
boolean
>,
// We recreate this for the same connection and need to re-setup notifications for the old events
private events: Record<keyof ServiceConnectionEventMap, boolean>,
) {
device.addEventListener(
"gattserverdisconnected",
this.handleDisconnectEvent,
);
for (const [key, value] of Object.entries(this.addedServiceListeners)) {
this.serviceListenerState[
key as keyof ServiceConnectionEventMap
].notifying = value;
}
}

async connect(): Promise<void> {
Expand Down Expand Up @@ -184,13 +225,9 @@ export class BluetoothDeviceWrapper {
this.connecting = false;
}

// Restart notifications for services and characteristics
// the user has listened to.
for (const serviceListener of Object.values(this.serviceListenerState)) {
if (serviceListener.notifying) {
serviceListener.service.call(this, { listenerInit: true });
}
}
Object.keys(this.events).forEach((e) =>
this.startNotifications(e as TypedServiceEvent),
);

this.logging.event({
type: this.isReconnect ? "Reconnect" : "Connect",
Expand Down Expand Up @@ -354,26 +391,39 @@ export class BluetoothDeviceWrapper {
this.gattOperations = { busy: false, queue: [] };
}

async getAccelerometerService(
options: {
listenerInit: boolean;
} = { listenerInit: false },
): Promise<AccelerometerService | undefined> {
if (!this.accelerometerService) {
const gattServer = this.assertGattServer();
this.accelerometerService = await AccelerometerService.createService(
gattServer,
this.dispatchTypedEvent,
this.serviceListenerState.accelerometerdatachanged.notifying,
this.queueGattOperation.bind(this),
options?.listenerInit,
);
private createIfNeeded<T extends Service>(
info: ServiceInfo<T>,
listenerInit: boolean,
): Promise<T | undefined> {
const gattServer = this.assertGattServer();
return info.createIfNeeded(
gattServer,
this.dispatchTypedEvent,
this.queueGattOperation.bind(this),
listenerInit,
);
}

async getAccelerometerService(): Promise<AccelerometerService | undefined> {
return this.createIfNeeded(this.accelerometer, false);
}

async startNotifications(type: TypedServiceEvent) {
const serviceInfo = this.serviceInfo.find((s) => s.events.includes(type));
if (serviceInfo) {
// TODO: type cheat! why?
const service = await this.createIfNeeded(serviceInfo as any, true);
service?.startNotifications(type);
}
return this.accelerometerService;
}

async stopNotifications(type: TypedServiceEvent) {
const serviceInfo = this.serviceInfo.find((s) => s.events.includes(type));
serviceInfo?.get()?.stopNotifications(type);
}

private disposeServices() {
this.accelerometerService = undefined;
this.serviceInfo.forEach((s) => s.dispose());
this.clearGattQueueOnDisconnect();
}
}
Expand Down
Loading