-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain1.js
74 lines (64 loc) · 2.07 KB
/
main1.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
var passwordIndex = 0;
var passwordService;
var userName;
function login() {
passwordIndex++;
passwordService = null;
connectAndGetService()
.then(() => {
return registerUserNameNotifications();
})
.then(() => {
document.getElementById("status").innerHTML = "Connected. Pending user approval...";
return registerPasswordNotification();
})
.catch(error => { window.alert(error); });
}
function connectAndGetService() {
return navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalServices: ["cf6b0353-17fe-481a-8328-62891fb8aefd"]
})
.then(device => device.gatt.connect())
.then(server => {
return server.getPrimaryService("cf6b0353-17fe-481a-8328-62891fb8aefd");
})
.then(service => {
passwordService = service;
});
}
function registerUserNameNotifications() {
return passwordService.getCharacteristic('cf6b0e6f-17fe-481a-8328-62891fb8aefd')
.then(characteristic => {
return characteristic.startNotifications().then(() => {
characteristic.addEventListener('characteristicvaluechanged', onUserName);
})
});
}
function onUserName(event) {
var value = event.target.value;
userName = String.fromCharCode.apply(null, new Uint8Array(value.buffer));
writePasswordID();
}
function writePasswordID() {
return passwordService.getCharacteristic('cf6b9fb0-17fe-481a-8328-62891fb8aefd').
then(characteristic => {
var buffer = new ArrayBuffer(1);
var mdata = new DataView(buffer);
mdata.setInt8(0, passwordIndex);
return characteristic.writeValue(mdata.buffer);
});
}
function registerPasswordNotification() {
return passwordService.getCharacteristic('cf6b44ac-17fe-481a-8328-62891fb8aefd')
.then(characteristic => {
return characteristic.startNotifications().then(() => {
characteristic.addEventListener('characteristicvaluechanged', onPassword);
})
})
}
function onPassword(event) {
var value = event.target.value;
var password = String.fromCharCode.apply(null, new Uint8Array(value.buffer));
document.getElementById("status").innerHTML = 'User name: ' + userName + ' password: ' + password;
}