Skip to content

LED service support #27

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 2 commits into from
Aug 29, 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
9 changes: 8 additions & 1 deletion lib/bluetooth-device-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ 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 { LedService } from "./led-service.js";
import { Logging, NullLogging } from "./logging.js";
import { PromiseQueue } from "./promise-queue.js";
import {
Expand Down Expand Up @@ -114,7 +115,9 @@ export class BluetoothDeviceWrapper {
"buttonachanged",
"buttonbchanged",
]);
private serviceInfo = [this.accelerometer, this.buttons];
private led = new ServiceInfo(LedService.createService, []);

private serviceInfo = [this.accelerometer, this.buttons, this.led];

boardVersion: BoardVersion | undefined;

Expand Down Expand Up @@ -376,6 +379,10 @@ export class BluetoothDeviceWrapper {
return this.createIfNeeded(this.accelerometer, false);
}

async getLedService(): Promise<LedService | undefined> {
return this.createIfNeeded(this.led, false);
}

async startNotifications(type: TypedServiceEvent) {
const serviceInfo = this.serviceInfo.find((s) => s.events.includes(type));
if (serviceInfo) {
Expand Down
26 changes: 26 additions & 0 deletions lib/bluetooth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
DeviceConnectionEventMap,
} from "./device.js";
import { TypedEventTarget } from "./events.js";
import { LedMatrix } from "./led.js";
import { Logging, NullLogging } from "./logging.js";
import {
ServiceConnectionEventMap,
Expand Down Expand Up @@ -244,4 +245,29 @@ export class MicrobitWebBluetoothConnection
await this.connection?.getAccelerometerService();
return accelerometerService?.setPeriod(value);
}

async setLedText(text: string): Promise<void> {
const ledService = await this.connection?.getLedService();
return ledService?.setText(text);
}

async getLedScrollingDelay(): Promise<number | undefined> {
const ledService = await this.connection?.getLedService();
return ledService?.getScrollingDelay();
}

async setLedScrollingDelay(delayInMillis: number): Promise<void> {
const ledService = await this.connection?.getLedService();
await ledService?.setScrollingDelay(delayInMillis);
}

async getLedMatrix(): Promise<LedMatrix | undefined> {
const ledService = await this.connection?.getLedService();
return ledService?.getLedMatrix();
}

async setLedMatrix(matrix: LedMatrix): Promise<void> {
const ledService = await this.connection?.getLedService();
ledService?.setLedMatrix(matrix);
}
}
137 changes: 137 additions & 0 deletions lib/led-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { Service } from "./bluetooth-device-wrapper.js";
import { profile } from "./bluetooth-profile.js";
import { BackgroundErrorEvent, DeviceError } from "./device.js";
import { LedMatrix } from "./led.js";
import {
TypedServiceEvent,
TypedServiceEventDispatcher,
} from "./service-events.js";

const createLedMatrix = (): LedMatrix => {
return [
[false, false, false, false, false],
[false, false, false, false, false],
[false, false, false, false, false],
[false, false, false, false, false],
[false, false, false, false, false],
];
};

export class LedService implements Service {
constructor(
private matrixStateCharacteristic: BluetoothRemoteGATTCharacteristic,
private scrollingDelayCharacteristic: BluetoothRemoteGATTCharacteristic,
private textCharactertistic: BluetoothRemoteGATTCharacteristic,
private queueGattOperation: <R>(action: () => Promise<R>) => Promise<R>,
) {}

static async createService(
gattServer: BluetoothRemoteGATTServer,
dispatcher: TypedServiceEventDispatcher,
queueGattOperation: <R>(action: () => Promise<R>) => Promise<R>,
listenerInit: boolean,
): Promise<LedService | undefined> {
let ledService: BluetoothRemoteGATTService;
try {
ledService = await gattServer.getPrimaryService(profile.led.id);
} catch (err) {
if (listenerInit) {
dispatcher("backgrounderror", new BackgroundErrorEvent(err as string));
return;
} else {
throw new DeviceError({
code: "service-missing",
message: err as string,
});
}
}
const matrixStateCharacteristic = await ledService.getCharacteristic(
profile.led.characteristics.matrixState.id,
);
const scrollingDelayCharacteristic = await ledService.getCharacteristic(
profile.led.characteristics.scrollingDelay.id,
);
const textCharacteristic = await ledService.getCharacteristic(
profile.led.characteristics.text.id,
);
return new LedService(
matrixStateCharacteristic,
scrollingDelayCharacteristic,
textCharacteristic,
queueGattOperation,
);
}

async getLedMatrix(): Promise<LedMatrix> {
const dataView = await this.queueGattOperation(() =>
this.matrixStateCharacteristic.readValue(),
);
return this.dataViewToLedMatrix(dataView);
}

async setLedMatrix(value: LedMatrix): Promise<void> {
const dataView = this.ledMatrixToDataView(value);
return this.queueGattOperation(() =>
this.matrixStateCharacteristic.writeValue(dataView),
);
}

private dataViewToLedMatrix(dataView: DataView): LedMatrix {
if (dataView.byteLength !== 5) {
throw new Error("Unexpected LED matrix byte length");
}
const matrix = createLedMatrix();
for (let row = 0; row < 5; ++row) {
const rowByte = dataView.getUint8(row);
for (let column = 0; column < 5; ++column) {
const columnMask = 0x1 << (4 - column);
matrix[row][column] = (rowByte & columnMask) != 0;
}
}
return matrix;
}

private ledMatrixToDataView(matrix: LedMatrix): DataView {
const dataView = new DataView(new ArrayBuffer(5));
for (let row = 0; row < 5; ++row) {
let rowByte = 0;
for (let column = 0; column < 5; ++column) {
const columnMask = 0x1 << (4 - column);
if (matrix[row][column]) {
rowByte |= columnMask;
}
}
dataView.setUint8(row, rowByte);
}
return dataView;
}

async setText(text: string) {
const bytes = new TextEncoder().encode(text);
if (bytes.length > 20) {
throw new Error("Text must be <= 20 bytes when encoded as UTF-8");
}
return this.queueGattOperation(() =>
this.textCharactertistic.writeValue(bytes),
);
}

async setScrollingDelay(value: number) {
const dataView = new DataView(new ArrayBuffer(2));
dataView.setUint16(0, value, true);
return this.queueGattOperation(() =>
this.scrollingDelayCharacteristic.writeValue(dataView),
);
}

async getScrollingDelay(): Promise<number> {
const dataView = await this.queueGattOperation(() =>
this.scrollingDelayCharacteristic.readValue(),
);
return dataView.getUint16(0, true);
}

async startNotifications(type: TypedServiceEvent): Promise<void> {}

async stopNotifications(type: TypedServiceEvent): Promise<void> {}
}
3 changes: 3 additions & 0 deletions lib/led.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
type FixedArray<T, L extends number> = T[] & { length: L };
type LedRow = FixedArray<boolean, 5>;
export type LedMatrix = FixedArray<LedRow, 5>;
76 changes: 76 additions & 0 deletions src/demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ const recreateUi = async (type: ConnectionType) => {
createButtonSection("A", "buttonachanged"),
createButtonSection("B", "buttonbchanged"),
createAccelerometerSection(),
createLedSection(),
].forEach(({ dom, cleanup }) => {
if (dom) {
document.body.appendChild(dom);
Expand Down Expand Up @@ -385,3 +386,78 @@ const createButtonSection = (
},
};
};

const createLedSection = (): Section => {
if (!(connection instanceof MicrobitWebBluetoothConnection)) {
return {};
}
const ledConnection = connection;

const delayInput = crelt("input") as HTMLInputElement;
const textInput = crelt("input") as HTMLInputElement;
const matrixInput = crelt("textarea") as HTMLTextAreaElement;
const dom = crelt("section", crelt("h2", "LED"), [
crelt("h3", "Matrix"),
crelt("h3", "Text"),
crelt("label", "Text", textInput),
crelt(
"button",
{
onclick: async () => {
await ledConnection.setLedText(textInput.value);
},
},
"Set text",
),
crelt("h3", "Scrolling delay"),
crelt("label", "Scrolling delay", delayInput),
crelt(
"button",
{
onclick: async () => {
const value = await ledConnection.getLedScrollingDelay();
if (value) {
delayInput.value = value.toString();
}
},
},
"Get scrolling delay",
),
crelt(
"button",
{
onclick: async () => {
await ledConnection.setLedScrollingDelay(parseInt(delayInput.value));
},
},
"Set scrolling delay",
),
crelt("h3", "Matrix"),
crelt("label", "Matrix as JSON", matrixInput),
crelt(
"button",
{
onclick: async () => {
const matrix = await ledConnection.getLedMatrix();
matrixInput.value = JSON.stringify(matrix, null, 2);
},
},
"Get matrix",
),
crelt(
"button",
{
onclick: async () => {
const matrix = JSON.parse(matrixInput.value);
await ledConnection.setLedMatrix(matrix);
},
},
"Set matrix",
),
]);

return {
dom,
cleanup: () => {},
};
};