-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.html
97 lines (86 loc) · 2.97 KB
/
service.html
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Connect</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script>
let gatt;
const disconnect = () => {
gatt && gatt.disconnect();
};
const connect = () => {
const options = {
filters: [
{ namePrefix: 'Thingy' },
],
optionalServices: ['7b340000-105b-2b38-3a74-2932f884e90e']
};
let busy = false;
let service;
navigator.bluetooth.requestDevice(options).then((device) => {
console.log('Device: ' + JSON.stringify(device));
return device.gatt.connect();
})
.then((g) => {
gatt = g;
// Get our custom service
return gatt.getPrimaryService('7b340000-105b-2b38-3a74-2932f884e90e');
})
.then((s) => {
service = s;
// Get the RGB LED characteristic
return service.getCharacteristic('7b340001-105b-2b38-3a74-2932f884e90e');
})
.then((characteristic) => {
const colorPicker = document.querySelector('#color');
colorPicker.removeAttribute('disabled');
colorPicker.addEventListener('input', (event) => {
const col = event.target.value; // #bbggrr
const rgb = new Uint8Array([
parseInt(col.substr(5, 2), 16),
parseInt(col.substr(3, 2), 16),
parseInt(col.substr(1, 2), 16)]);
if (busy) return;
busy = true;
characteristic.writeValue(rgb).then(() => {
busy = false;
});
}, false);
// Get the Vibration characteristic
return service.getCharacteristic('7b340002-105b-2b38-3a74-2932f884e90e');
})
.then((characteristic) => {
const vibl = document.querySelector('#vibrateleft');
const vibr = document.querySelector('#vibrateright');
vibl.removeAttribute('disabled');
vibr.removeAttribute('disabled');
const vibChange = (event) => {
console.log(vibl.value, vibr.value);
if (busy) return;
busy = true;
const v = new Uint8Array([vibl.value, vibr.value]);
characteristic.writeValue(v).then(() => {
busy = false;
});
}
vibl.addEventListener('input', vibChange, false);
vibr.addEventListener('input', vibChange, false);
})
.then(() => {
console.log('Done!');
})
.catch(function (error) {
console.log('Something went wrong.', error);
});
}
</script>
</head>
<body>
<button class="btn btn-large" onclick="connect()">Connect to Web Bluetooth</button>
<button class="btn btn-large" onclick="disconnect()">Disconnect device</button>
<input type="color" id="color" value="#e66465" disabled />
<input type="range" id="vibrateleft" min="0" max="255" value="0" disabled />
<input type="range" id="vibrateright" min="0" max="255" value="0" disabled />
</body>
</html>