-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
285 lines (262 loc) · 11.3 KB
/
index.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BLE Angle Guide</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding-bottom: 20px;
/* keeps the padding-bottom from causing the body to overflow the viewport */
box-sizing: border-box;
font-weight: lighter;
font-family: Helvetica, sans-serif;
}
svg {
max-width: 800px;
}
button {
background-color: teal;
color: white;
padding: 10px 20px;
border-radius: 5px;
font-size: 1.2em;
border: none;
}
button:disabled {
filter: saturate(0%);
}
button:where(:hover, :active) {
filter: saturate(150%);
}
button:is(:active :not(:disabled)) {
transform: scale(0.95);
}
button.disconnect {
color: red;
outline: 1px solid red;
background-color: white;
}
#connection {
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
#connection-failed, #bluetooth-not-supported {
color: red;
font-size: 0.8em;
display: none;
}
#noscript {
margin-left: 20px;
margin-right: 20px;
}
</style>
</head>
<body>
<noscript><div id="noscript">This page uses JavaScript to connect a sensor using WebBluetooth and update the display using that sensor data.</div></noscript>
<svg viewBox="-120 -110 240 130">
<defs>
<radialGradient id="radial-fade">
<stop offset="0%" stop-color="white" />
<stop offset="100%" stop-color="white" stop-opacity="0"/>
</radialGradient>
</defs>
<g transform="scale(1, -1)">
<polyline id="actual-angle-history" stroke="salmon" stroke-width="1" stroke-linecap="round" fill="none" />
<!-- this circle is for fading out the angle history plot as it reaches the center -->
<circle cx="0" cy="0" r="25" fill="url(#radial-fade)" />
<text id="actual-angle-text" transform="scale(1, -1)" x="0" y="0" text-anchor="middle" font-size="30"
fill="black">
0.0°
</text>
<path id="dial-arc" d="M -100 0 A 100 100 0 0 0 100 0" fill="none" stroke="black" stroke-width="2" stroke-linecap="round"/>
<g id="actual-angle-indicator" transform="rotate(45)">
<circle cx="100" cy="0" r="5" fill="salmon" />
</g>
<g id="target-angle-indicator-right">
<g class="target-angle-indicator-translation" transform="translate(101)">
<polyline points="-30,0 0,0" stroke="teal" stroke-width="0.5" fill="none" />
<text class="target-angle-indicator-text" x="2" y="-5" text-anchor="start" font-size="7" fill="black"
transform="scale(1, -1)">0.0°</text>
<circle cx="5" cy="0" r="5" fill="transparent" />
<path class="target-angle-indicator-arrow" d="M 0,0 l 10,3 l 0,-6 Z" fill="teal" />
</g>
</g>
<g id="target-angle-indicator-left">
<g class="target-angle-indicator-translation" transform="translate(-101)">
<polyline points="30,0 0,0" stroke="teal" stroke-width="0.5" fill="none" />
<text class="target-angle-indicator-text" x="-2" y="-5" text-anchor="end" font-size="7" fill="black"
transform="scale(1, -1)">0.0°</text>
<circle cx="5" cy="0" r="5" fill="transparent" />
<path class="target-angle-indicator-arrow" d="M 0,0 l -10,3 l 0,-6 Z" fill="teal" />
</g>
</g>
</g>
</svg>
<div id="connection">
<button id="connectBtn">Connect</button>
<div id="connection-failed">Failed to connect</div>
<div id="bluetooth-not-supported">This browser does not support <a href="https://caniuse.com/web-bluetooth">WebBluetooth</a></div>
</div>
<script>
let targetAngle = degreesToRadians(20);
setTargetAngle(degreesToRadians(20));
setActualAngleIndicatorAndText(null);
const svg = document.querySelector('svg');
let draggedIndicator = null;
for (let side of ['left', 'right']) {
const indicator = document.querySelector(`#target-angle-indicator-${side}`);
indicator.addEventListener('mousedown', e => {
// Prevent text highlighting when dragging the indicator.
e.preventDefault();
draggedIndicator = side;
});
}
window.addEventListener('mouseup', e => {
draggedIndicator = null;
});
window.addEventListener('mousemove', e => {
if (draggedIndicator === null) {
return;
}
const dialRect = document.getElementById('dial-arc').getBoundingClientRect();
const dialBottomMid = {
x: dialRect.left + dialRect.width / 2,
y: dialRect.bottom
};
const dx = e.clientX - dialBottomMid.x;
const dy = dialBottomMid.y - e.clientY;
// Because dy is clamped here, atan will return an angle from [0, PI]
let angle = Math.atan2(Math.max(0, dy), dx);
if (draggedIndicator === 'left') {
angle = Math.PI - Math.max(Math.PI / 2, angle);
} else {
angle = Math.min(Math.PI / 2, angle);
}
setTargetAngle(Math.min(Math.PI / 3, angle));
});
function degreesToRadians(degrees) {
return degrees / 180 * Math.PI;
}
function radiansToDegrees(radians) {
return radians / Math.PI * 180;
}
function setTargetAngle(angle) {
let degrees = radiansToDegrees(angle);
degrees = Math.round(degrees * 2) / 2;
angle = degreesToRadians(degrees);
document.querySelector('#target-angle-indicator-right').style.transform =
`rotate(${angle}rad)`;
document.querySelector('#target-angle-indicator-left').style.transform =
`rotate(-${angle}rad)`;
document.querySelector('#target-angle-indicator-right text').textContent = `${radiansToDegrees(angle).toFixed(1)}°`;
document.querySelector('#target-angle-indicator-left text').textContent = `${radiansToDegrees(angle).toFixed(1)}°`;
targetAngle = angle;
}
function normalizeAngle(angle) {
return Math.abs(angle);
}
function setActualAngleIndicatorAndText(angle) {
const indicator = document.getElementById('actual-angle-indicator');
const text = document.getElementById('actual-angle-text');
if (angle === null) {
indicator.style.transform = `rotate(0rad)`;
text.textContent = `--.-°`;
} else {
indicator.style.transform =
`rotate(${angle}rad)`;
text.textContent = `${radiansToDegrees(Math.PI / 2 - Math.abs(angle - Math.PI / 2)).toFixed(1)}°`;
}
}
const button = document.getElementById('connectBtn');
setButtonToConnect();
if (!('bluetooth' in navigator)) {
button.disabled = true;
document.getElementById('bluetooth-not-supported').style.display = 'unset';
}
function setButtonToConnect() {
button.textContent = 'Connect';
button.classList.remove('disconnect');
button.onclick = connectBLE;
}
function setButtonToDisconnect() {
button.textContent = 'Disconnect';
button.classList.add('disconnect');
button.onclick = disconnectBLE;
}
let angleSamples = [];
let gattServer = null;
async function disconnectBLE() {
if (gattServer) {
await gattServer.disconnect();
gattServer = null;
}
setActualAngleIndicatorAndText(null);
angleSamples = [];
setButtonToConnect();
}
async function connectBLE(bluetoothState) {
try {
document.getElementById('connection-failed').style.removeProperty('display');
const SERVICE_UUID = 'b3f787c6-77c9-49c1-bd93-3692eb94d2ca';
const ANGLE_CHARACTERISTIC_UUID = '6ec6e014-9fe0-4e14-97a1-bbf221d19dec';
const device = await navigator.bluetooth.requestDevice({
filters: [{ services: [SERVICE_UUID] }]
});
gattServer = await device.gatt.connect();
setButtonToDisconnect();
device.addEventListener('gattserverdisconnected', e => {
setButtonToConnect();
});
const service = await gattServer.getPrimaryService(SERVICE_UUID);
const angleCharacteristic = await service.getCharacteristic(ANGLE_CHARACTERISTIC_UUID);
angleCharacteristic.addEventListener('characteristicvaluechanged', e => {
const dataView = e.target.value;
const [x, y, z] = [0, 2, 4].map(i => dataView.getInt16(i, true) / 16384);
let normalizedZ = z / Math.sqrt(x*x + y*y + z*z);
//angleSamples.push(normalizeAngle(Math.atan2(x, z)));
angleSamples.push(Math.acos(normalizedZ));
angleSamples = angleSamples.slice(-100);
const smoothedSamples = exponentialMovingAverage(angleSamples, 0.3);
function pointForAngle(angle, idx) {
const r = 100 * Math.pow((101 - idx) / 100, 2);
const x = r * Math.cos(angle);
const y = r * Math.sin(angle);
return `${x},${y}`;
}
document.getElementById('actual-angle-history')
.setAttribute('points', smoothedSamples.toReversed().map(pointForAngle));
setActualAngleIndicatorAndText(smoothedSamples.at(-1));
});
angleCharacteristic.startNotifications();
} catch (e) {
document.getElementById('connection-failed').style.display = 'unset';
console.error(e);
setButtonToConnect();
}
}
function exponentialMovingAverage(samples, alpha) {
let result = [];
for (let x of samples) {
if (result.length === 0) {
result.push(x);
} else {
result.push(alpha * x + (1 - alpha) * result.at(-1));
}
}
return result;
}
</script>
</body>
</html>