forked from noble/noble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecho.js
executable file
·75 lines (61 loc) · 2.21 KB
/
echo.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
// Connect to a peripheral running the echo service
// https://github.com/noble/bleno/blob/master/examples/echo
// subscribe to be notified when the value changes
// start an interval to write data to the characteristic
//const noble = require('noble');
const noble = require('..');
const ECHO_SERVICE_UUID = 'ec00';
const ECHO_CHARACTERISTIC_UUID = 'ec0e';
noble.on('stateChange', state => {
if (state === 'poweredOn') {
console.log('Scanning');
noble.startScanning([ECHO_SERVICE_UUID]);
} else {
noble.stopScanning();
}
});
noble.on('discover', peripheral => {
// connect to the first peripheral that is scanned
noble.stopScanning();
const name = peripheral.advertisement.localName;
console.log(`Connecting to '${name}' ${peripheral.id}`);
connectAndSetUp(peripheral);
});
function connectAndSetUp(peripheral) {
peripheral.connect(error => {
console.log('Connected to', peripheral.id);
// specify the services and characteristics to discover
const serviceUUIDs = [ECHO_SERVICE_UUID];
const characteristicUUIDs = [ECHO_CHARACTERISTIC_UUID];
peripheral.discoverSomeServicesAndCharacteristics(
serviceUUIDs,
characteristicUUIDs,
onServicesAndCharacteristicsDiscovered
);
});
peripheral.on('disconnect', () => console.log('disconnected'));
}
function onServicesAndCharacteristicsDiscovered(error, services, characteristics) {
console.log('Discovered services and characteristics');
const echoCharacteristic = characteristics[0];
// data callback receives notifications
echoCharacteristic.on('data', (data, isNotification) => {
console.log('Received: "' + data + '"');
});
// subscribe to be notified whenever the peripheral update the characteristic
echoCharacteristic.subscribe(error => {
if (error) {
console.error('Error subscribing to echoCharacteristic');
} else {
console.log('Subscribed for echoCharacteristic notifications');
}
});
// create an interval to send data to the service
let count = 0;
setInterval(() => {
count++;
const message = new Buffer('hello, ble ' + count, 'utf-8');
console.log("Sending: '" + message + "'");
echoCharacteristic.write(message);
}, 2500);
}