forked from profezzorn/lightsaber-web-bluetooth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.html
387 lines (331 loc) · 9.88 KB
/
test.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<head>
<style>
@font-face {
font-family: StarJedi;
src: url(Starjedi.ttf);
}
.preset {
border-radius: 15px 50px;
border: 2px solid #6060aa;
background: #101040;
color: #FFFFFF;
width: 250px;
height: 80px;
text-align: center;
margin: 3px;
padding: 8px;
position: relative;
text-overflow:clip;
overflow: hidden;
}
.track {
border-radius: 15px 50px;
border: 2px solid #6060aa;
background: #101040;
color: #FFFFFF;
width: 250px;
height: 80px;
text-align: center;
margin: 3px;
padding: 8px;
position: relative;
text-overflow:clip;
overflow: hidden;
}
.title {
font-family: StarJedi;
font-size: 250%;
line-height: 0.8;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
body {
background: black;
color: lightblue;
};
</style>
</head>
<body onload='Init();'>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js').then(function() {
console.log('Service Worker Registered'); });
}
</script>
<script>
var rx;
var tx;
var pw;
var status;
var send_buf = [];
var current_packet;
var sending = false;
var callback_queue = [];
var status_cb;
var buffer = "";
var track_lines;
function SendNext() {
if (!current_packet) {
if (!send_buf.length) {
sending = false;
return;
}
current_packet = send_buf[0];
send_buf = send_buf.slice(1);
}
console.log("Sending " + (new TextDecoder().decode(current_packet)));
sending = true;
tx.writeValue(current_packet).then(
function(v) { current_packet = 0; SendNext(); },
function(e) {
console.log('rejected', e);
// Do gatt.connect and re-send password?
window.setTimeout(SendNext, 1000);
});
}
function OnRX(event) {
var data = new TextDecoder().decode(event.target.value);
buffer += data;
var tmp = buffer.split("-+=END_OUTPUT=+-");
if (tmp.length > 1) {
buffer = tmp[1];
var ret = tmp[0];
tmp = ret.split("-+=BEGIN_OUTPUT=+-\n");
if (tmp.length > 1) ret = tmp[1];
ret = ret.split("\r").join("");
console.log('> ' + ret);
if (callback_queue.length) {
callback_queue[0](ret);
callback_queue = callback_queue.slice(1);
}
}
}
function concatTypedArrays(a, b) { // a, b TypedArray of same type
var c = new (a.constructor)(a.length + b.length);
c.set(a, 0);
c.set(b, a.length);
return c;
}
function Send(cmd) {
// needs to fail on timeout
return new Promise(function(resolve, reject) {
var data = new TextEncoder('utf-8').encode(cmd + '\n');
if (send_buf.length && send_buf[send_buf.length-1].length != 20) {
data = concatTypedArrays(send_buf[send_buf.length-1], data);
send_buf = send_buf.slice(0, send_buf.length-1);
}
while (data.length) {
send_buf.push(data.slice(0, 20));
data = data.slice(20);
}
callback_queue.push(resolve);
console.log("======SEND BUF BEGIN===");
for (var i = 0; i < send_buf.length; i++) {
console.log(new TextDecoder().decode(send_buf[i]));
}
console.log("======SEND BUF END===");
if (!sending) SendNext();
});
}
function OnStatus(event) {
console.log("ONSTATUS");
var data = new TextDecoder().decode(event.target.value);
console.log('STATUS> ' + data);
if (status_cb) {
status_cb(data);
status_cb = 0;
}
}
function SendPW(password) {
// needs to fail on timeout
return new Promise(function(resolve, reject) {
status_cb = resolve;
pw.writeValue(new TextEncoder('utf-8').encode(password));
});
}
function showCurrentPreset(preset) {
const preset_tags = document.getElementsByClassName('preset');
for (var i = 0; i < preset_tags.length; i++) {
if (i == preset) {
preset_tags[i].style.background = '#505080';
} else {
preset_tags[i].style.background = '#101040';
}
}
}
function showCurrentTrack(track) {
const preset_tags = document.getElementsByClassName('track');
for (var i = 0; i < preset_tags.length; i++) {
if (track_lines[i] == track) {
preset_tags[i].style.background = '#505080';
} else {
preset_tags[i].style.background = '#101040';
}
}
}
async function SetPreset(n) {
// showCurrentPreset(n);
await Send("set_preset " + n);
showCurrentPreset(n);
}
async function PlayTrack(track) {
await Send("play_track " + track);
showCurrentTrack(track);
}
function SendField() {
var value = document.getElementById('textField').value + '\n';
document.getElementById('textField').value = "";
let encoder = new TextEncoder('utf-8');
tx.writeValue(encoder.encode(value));
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var updating_volume = false;
var new_volume = -1;
async function UpdateVolume() {
var volume_tag = document.getElementById('volume');
var volume = volume_tag.value;
if (updating_volume) {
new_volume = volume;
return;
}
updating_volume = true;
while (true) {
await Send("set_volume " + volume);
volume_tag.value = volume;
if (new_volume != -1) break;
volume = new_volume;
new_volume = -1;
}
updating_volume = false;
}
function dumpChar(c) {
console.log('> UUID: ' + c.uuid);
console.log('> Broadcast: ' + c.properties.broadcast);
console.log('> Read: ' + c.properties.read);
console.log('> Write w/o response: ' + c.properties.writeWithoutResponse);
console.log('> Write: ' + c.properties.write);
console.log('> Notify: ' + c.properties.notify);
console.log('> Indicate: ' + c.properties.indicate);
console.log('> Signed Write: ' + c.properties.authenticatedSignedWrites);
console.log('> Queued Write: ' + c.properties.reliableWrite);
console.log('> Writable Auxiliaries: ' + c.properties.writableAuxiliaries);
}
async function Run() {
let serviceUuid = '713d0000-389c-f637-b1d7-91b361ae7678';
let rxUuid = '713d0002-389c-f637-b1d7-91b361ae7678';
let txUuid = '713d0003-389c-f637-b1d7-91b361ae7678';
let pwUuid = '713d0004-389c-f637-b1d7-91b361ae7678';
let statusUuid = '713d0005-389c-f637-b1d7-91b361ae7678';
console.log('Requesting Bluetooth Device...');
const device = await navigator.bluetooth.requestDevice({
// acceptAllDevices: true,
// optionalServices: [serviceUuid],
filters: [{services: [serviceUuid]}]
});
console.log('Connecting to GATT Server...');
const server = await device.gatt.connect();
console.log(server)
console.log('Getting Service...');
const service = await server.getPrimaryService(serviceUuid);
console.log(service)
console.log('Getting Characteristics...');
rx = await service.getCharacteristic(rxUuid);
tx = await service.getCharacteristic(txUuid);
pw = await service.getCharacteristic(pwUuid);
status = await service.getCharacteristic(statusUuid);
if (1) {
dumpChar(rx);
dumpChar(tx);
dumpChar(pw);
dumpChar(status);
}
console.log("StartNotify");
await rx.startNotifications();
rx.addEventListener('characteristicvaluechanged', OnRX);
await status.startNotifications();
status.addEventListener('characteristicvaluechanged', OnStatus);
console.log("Sending PW");
var password = document.getElementById('password').value;
var status = await SendPW(password);
if (status == "OK") {
console.log("Authenticated.");
localStorage.password = password;
} else {
console.log("WRONG PASSWORD!");
// TODO: something
}
var preset;
var presets = [];
var preset_string = await Send("list_presets");
const lines = preset_string.split("\n");
for (var l = 0; l < lines.length; l++) {
var tmp = lines[l].split("=");
console.log(tmp);
if (tmp.length > 1) {
if (tmp[0] == "FONT") {
if (preset) presets.push(preset);
preset = {}
}
preset[tmp[0]] = tmp.slice(1).join("=");
}
}
console.log(presets);
preset_string = "";
for (var i = 0; i < presets.length; i++) {
var p = presets[i];
preset_string += "<div class=preset onclick='SetPreset(" + i + ")'>";
preset_string += "<span class=title>" + p.NAME.replace("\\n", "<br>") + "</span>";
preset_string += "</div>";
}
document.getElementById('presets').innerHTML = preset_string;
var track_string = await Send("list_tracks");
track_lines = track_string.split("\n");
track_string = "";
for (var l = 0; l < track_lines.length; l++) {
var track = track_lines[l];
console.log(escape(track));
if (track.length > 4) {
var tmp = track.split('/');
var title = tmp[tmp.length - 1].split('.')[0].toLowerCase();
console.log(title);
// TODO: quote track properly
track_string += "<div class=track onclick='PlayTrack(\"" + escape(track) + "\")'>";
track_string += "<span class=title>" + title + "</span>";
track_string += "</div>";
}
}
document.getElementById('tracks').innerHTML = track_string;
while (true) {
const preset = await Send("get_preset");
showCurrentPreset(preset);
const track = await Send("get_track");
showCurrentTrack(track.split("\n")[0]);
const volume = await Send("get_volume");
document.getElementById('volume').value = parseInt(volume);
const voltage = await Send("battery_voltage");
document.getElementById('voltage').innerHTML = voltage;
// TODO: temp
await sleep(5000);
}
}
function Init() {
if (localStorage.password) {
document.getElementById('password').value = localStorage.password;
}
}
</script>
<center>
Enter Password: <input type=password id=password onkeydown="if (event.keyCode == 13) Run();"><button type=button onclick='Run()'>Connect</button>
</center>
<br>
<!-- Send Command: <input type=text id=textField onkeydown="if (event.keyCode == 13) SendField();"><br> -->
Volume: <input id=volume type=range min=0 max=2000 oninput='UpdateVolume();' onchange='UpdateVolume();'>
Voltage: <span id=voltage>---</span><br>
<div id=presets width=260 style='float:left;'></div>
<div id=tracks width=260 style='float:left;'></div>
</body>