forked from lachendeKatze/relay-click
-
Notifications
You must be signed in to change notification settings - Fork 0
/
relayClick.js
67 lines (59 loc) · 1.93 KB
/
relayClick.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
(function() {
'use strict';
class RelayClick {
/**
* customize your project here to reflect the uuid of your service and characteristics.
*/
constructor() {
this.deviceName = 'relays';
this.serviceUUID = '917649a0-d98e-11e5-9eec-0002a5d5c51b';
this.characteristic1UUID = '917649a1-d98e-11e5-9eec-0002a5d5c51b';
this.device = null;
this.server = null;
// The cache allows us to hold on to characeristics for access in response to user commands
this._characteristics = new Map();
}
connect(){
return navigator.bluetooth.requestDevice({
filters: [{
services:[this.serviceUUID]
}]
})
.then(device => {
this.device = device;
return device.gatt.connect();
})
.then(server => {
this.server = server;
return Promise.all([
server.getPrimaryService(this.serviceUUID)
.then(service=>{
return Promise.all([
this._cacheCharacteristic(service, this.characteristic1UUID),
// this._cacheCharacteristic(service, 'uuidCharacteristic2Here'),
])
})
]);
})
}
_cacheCharacteristic(service, characteristicUuid){
return service.getCharacteristic(characteristicUuid)
.then(characteristic => {
this._characteristics.set(characteristicUuid, characteristic);
});
}
_readCharacteristic(characteristicUuid) {
let characteristic = this._characteristics.get(characteristicUuid);
return characteristic.readValue()
.then(value => {
value - value.buffer ? value : new DataView(value);
return value;
});
}
_writeCharacteristic(characteristicUuid, value){
let characteristic = this._characteristics.get(characteristicUuid);
return characteristic.writeValue(value);
}
}
window.relayClick = new RelayClick();
})();