-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathble_nus.js
More file actions
170 lines (158 loc) · 5.31 KB
/
ble_nus.js
File metadata and controls
170 lines (158 loc) · 5.31 KB
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
'use strict';
const bleNusServiceUUID = '6e400001-b5a3-f393-e0a9-e50e24dcca9e';
const bleNusCharRXUUID = '6e400002-b5a3-f393-e0a9-e50e24dcca9e';
const bleNusCharTXUUID = '6e400003-b5a3-f393-e0a9-e50e24dcca9e';
const MTU = 20;
var bleDevice = {};
var nusService = {};
var rxCharacteristic = {};
var txCharacteristic = {};
var connected = {};
var bleBusy = false;
for (const cube of ["cube1", "cube2"]) {
bleDevice[cube] = null;
nusService[cube] = null;
rxCharacteristic[cube] = null;
txCharacteristic[cube] = null;
connected[cube] = false;
}
function connectionToggle(cube) {
if (connected[cube]) {
disconnect(cube);
} else {
connect(cube);
}
}
// Sets button to either Connect or Disconnect
function changeConnectionState(state, cube) {
connected[cube] = state;
if (state) {
setButtonShadow(cube, cube + "_clientConnectButton", "Disconnect")
openFullscreen(document.body);
} else {
setButtonShadow("", cube + "_clientConnectButton", "Connect")
document.exitFullscreen();
}
}
function connect(cube) {
if (!checkBluetooth()) {
terminal_writeln('WebBluetooth API is not available on your browser.\r\n' +
'Please make sure the Web Bluetooth flag is enabled.');
return;
}
terminal_writeln('Requesting Bluetooth Device...');
navigator.bluetooth.requestDevice({
filters: [{services: [bleNusServiceUUID]}]
})
.then(device => {
bleDevice[cube] = device;
terminal_writeln('Found ' + device.name);
terminal_writeln('Connecting to GATT Server...');
const onDisconnectedCube = function () {
onDisconnected(cube);
};
bleDevice[cube].addEventListener('gattserverdisconnected', onDisconnectedCube);
return device.gatt.connect();
})
.then(server => {
terminal_writeln('Locate NUS service');
return server.getPrimaryService(bleNusServiceUUID);
}).then(service => {
nusService[cube] = service;
terminal_writeln('Found NUS service: ' + service.uuid);
})
.then(() => {
terminal_writeln('Locate RX characteristic');
return nusService[cube].getCharacteristic(bleNusCharRXUUID);
})
.then(characteristic => {
rxCharacteristic[cube] = characteristic;
terminal_writeln('Found RX characteristic');
})
.then(() => {
terminal_writeln('Locate TX characteristic');
return nusService[cube].getCharacteristic(bleNusCharTXUUID);
})
.then(characteristic => {
txCharacteristic[cube] = characteristic;
terminal_writeln('Found TX characteristic');
})
.then(() => {
terminal_writeln('Enable notifications');
return txCharacteristic[cube].startNotifications();
})
.then(() => {
terminal_writeln('Notifications started');
txCharacteristic[cube].addEventListener('characteristicvaluechanged',
handleNotifications);
changeConnectionState(true, cube);
terminal_writeln('\r\n' + bleDevice[cube].name + ' Connected.');
})
.catch(error => {
terminal_writeln('' + error);
if(bleDevice[cube] && bleDevice[cube].gatt.connected)
{
bleDevice[cube].gatt.disconnect();
}
});
}
function disconnect(cube) {
if (!bleDevice[cube]) {
terminal_writeln('No Bluetooth Device connected...');
return;
}
terminal_writeln('Disconnecting from Bluetooth Device...');
if (bleDevice[cube].gatt.connected) {
bleDevice[cube].gatt.disconnect();
changeConnectionState(false, cube);
terminal_writeln('Bluetooth Device connected: ' + bleDevice[cube].gatt.connected);
} else {
terminal_writeln('> Bluetooth Device is already disconnected');
}
}
function onDisconnected(cube) {
changeConnectionState(false, cube);
terminal_writeln('\r\n' + bleDevice[cube].name + ' Disconnected.');
}
function handleNotifications(event) {
terminal_write('notification');
let value = event.target.value;
// Convert raw data bytes to character values and use these to
// construct a string.
let str = "";
for (let i = 0; i < value.byteLength; i++) {
str += String.fromCharCode(value.getUint8(i));
}
terminal_writeln(str);
}
function nusSendString(s, cube, log=true) {
if (bleDevice[cube] && bleDevice[cube].gatt.connected) {
if (log) terminal_writeln("send: " + s);
let val_arr = new Uint8Array(s.length)
for (let i = 0; i < s.length; i++) {
let val = s[i].charCodeAt(0);
val_arr[i] = val;
}
sendNextChunk(val_arr, cube);
} else {
terminal_writeln('Not connected to a device yet.');
}
}
function sendNextChunk(a, cube) {
let chunk = a.slice(0, MTU);
rxCharacteristic[cube].writeValue(chunk)
.then(function() {
if (a.length > MTU) {
bleBusy = true;
sendNextChunk(a.slice(MTU), cube);
} else {
bleBusy = false;
}
})
.catch(function(error) {
if (error == "NetworkError: GATT operation already in progress.") {
console.log(error + ' Retrying...');
delay(50).then(() => sendNextChunk(a, cube));
}
});
}