-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathble-client.js
106 lines (93 loc) · 2.62 KB
/
ble-client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
class BalenaBLE {
constructor() {
this.device = null;
this.led = null;
this.cpuVendor = null;
this.cpuSpeed = null;
this.onDisconnected = this.onDisconnected.bind(this);
}
/* the LED characteristic providing on/off capabilities */
async setLedCharacteristic() {
const service = await this.device.gatt.getPrimaryService(0xfff0);
const characteristic = await service.getCharacteristic(
"d7e84cb2-ff37-4afc-9ed8-5577aeb8454c"
);
// characteristic.startNotifications();
this.led = characteristic;
await this.led.startNotifications();
this.led.addEventListener(
"characteristicvaluechanged",
handleLedStatusChanged
);
}
/* the Device characteristic providing CPU information */
async setDeviceCharacteristic() {
const service = await this.device.gatt.getPrimaryService(0xfff1);
const vendor = await service.getCharacteristic(
"d7e84cb2-ff37-4afc-9ed8-5577aeb84542"
);
this.cpuVendor = vendor;
const speed = await service.getCharacteristic(
"d7e84cb2-ff37-4afc-9ed8-5577aeb84541"
);
this.cpuSpeed = speed;
}
/* request connection to a BalenaBLE device */
async request() {
let options = {
filters: [
{
name: "balenaBLE"
}
],
optionalServices: [0xfff0, 0xfff1]
};
if (navigator.bluetooth == undefined) {
alert("Sorry, Your device does not support Web BLE!");
return;
}
this.device = await navigator.bluetooth.requestDevice(options);
if (!this.device) {
throw "No device selected";
}
this.device.addEventListener("gattserverdisconnected", this.onDisconnected);
}
/* connect to device */
async connect() {
if (!this.device) {
return Promise.reject("Device is not connected.");
}
await this.device.gatt.connect();
}
/* read LED state */
async readLed() {
await this.led.readValue();
}
/* read CPU manufacturer */
async readCPUVendor() {
let vendor = await this.cpuVendor.readValue();
return decode(vendor);
}
/* read CPU speed */
async readCPUSpeed() {
let speed = await this.cpuSpeed.readValue();
return decode(speed);
}
/* change LED state */
async writeLed(data) {
await this.led.writeValue(Uint8Array.of(data));
await this.readLed();
}
/* disconnect from peripheral */
disconnect() {
if (!this.device) {
return Promise.reject("Device is not connected.");
}
return this.device.gatt.disconnect();
}
/* handler to run when device successfully disconnects */
onDisconnected() {
alert("Device is disconnected.");
location.reload();
}
}