-
Notifications
You must be signed in to change notification settings - Fork 1
/
remote.js
82 lines (65 loc) · 1.96 KB
/
remote.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
75
76
77
78
79
80
81
82
var noble = require('noble');
var robot = require('robotjs');
noble.on('stateChange', function(state) {
if (state === 'poweredOn') {
noble.startScanning(); // any service UUID
} else {
console.log('Please power-on the Bluetooth Adapter.');
}
});
noble.on('discover', function(peripheral) {
var localName = peripheral.advertisement.localName;
// find SensorTag based on local name
if (localName && localName.match(/Sensor/)) {
noble.stopScanning();
console.log('Attempting to connect to ' + localName);
connectAndSetUpSensorTag(peripheral);
}
});
function connectAndSetUpSensorTag(peripheral) {
peripheral.connect(function(error) {
console.log('Connected to ' + peripheral.advertisement.localName);
if (error) {
console.log('There was an error connecting ' + error);
return;
}
var serviceUUIDs = ['FFE0'];
var characteristicUUIDs = ['FFE1'];
peripheral.discoverSomeServicesAndCharacteristics(
serviceUUIDs, characteristicUUIDs, onServicesAndCharacteristicsDiscovered);
});
// attach disconnect handler
peripheral.on('disconnect', onDisconnect);
}
function onDisconnect() {
console.log('Peripheral disconnected!');
}
function onServicesAndCharacteristicsDiscovered(error, services, characteristics) {
if (error) {
console.log('Error discovering services and characteristics ' + error);
return;
}
var characteristic = characteristics[0];
// subscribe for notifications
characteristic.notify(true);
// called when notification state changes
characteristic.on('notify', function(isNotifying) {
if (isNotifying) {
console.log('SensorTag remote is ready');
}
});
// called when the data changes
characteristic.on('data', onCharacteristicData);
}
function onCharacteristicData(data, isNotification) {
switch (data[0]) {
case 1:
console.log('right');
robot.keyTap('right');
break;
case 2:
console.log('left');
robot.keyTap('left');
break;
}
}