|
@@ -0,0 +1,61 @@
|
|
1
|
+var noble = require('noble');
|
|
2
|
+const ECHO_SERVICE_UUID = 'ec00';
|
|
3
|
+const ECHO_CHARACTERISTIC_UUID = 'ec0e';
|
|
4
|
+
|
|
5
|
+noble.on('stateChange', state => {
|
|
6
|
+ if (state === 'poweredOn') {
|
|
7
|
+ console.log('Scanning');
|
|
8
|
+ noble.startScanning([ECHO_SERVICE_UUID]);
|
|
9
|
+ } else {
|
|
10
|
+ noble.stopScanning();
|
|
11
|
+ }
|
|
12
|
+});
|
|
13
|
+
|
|
14
|
+noble.on('discover', peripheral => {
|
|
15
|
+ // connect to the first peripheral that is scanned
|
|
16
|
+ noble.stopScanning();
|
|
17
|
+ const name = peripheral.advertisement.localName;
|
|
18
|
+ console.log(`Connecting to '${name}' ${peripheral.id}`);
|
|
19
|
+ connectAndSetUp(peripheral);
|
|
20
|
+});
|
|
21
|
+
|
|
22
|
+function connectAndSetUp(peripheral) {
|
|
23
|
+ peripheral.connect(error => {
|
|
24
|
+ // specify the services and characteristics to discover
|
|
25
|
+ const serviceUUIDs = [ECHO_SERVICE_UUID];
|
|
26
|
+ const characteristicUUIDs = [ECHO_CHARACTERISTIC_UUID];
|
|
27
|
+ peripheral.discoverSomeServicesAndCharacteristics(
|
|
28
|
+ serviceUUIDs,
|
|
29
|
+ characteristicUUIDs,
|
|
30
|
+ onServicesAndCharacteristicsDiscovered
|
|
31
|
+ );
|
|
32
|
+ });
|
|
33
|
+ peripheral.on('disconnect', () => console.log('disconnected'));
|
|
34
|
+}
|
|
35
|
+
|
|
36
|
+function onServicesAndCharacteristicsDiscovered(error, services, characteristics) {
|
|
37
|
+ console.log(123123123123123)
|
|
38
|
+ console.log('Discovered services and characteristics');
|
|
39
|
+ const echoCharacteristic = characteristics[0];
|
|
40
|
+ // data callback receives notifications
|
|
41
|
+ echoCharacteristic.on('data', (data, isNotification) => {
|
|
42
|
+ console.log('Received: "' + data + '"');
|
|
43
|
+ });
|
|
44
|
+ // subscribe to be notified whenever the peripheral update the characteristic
|
|
45
|
+ echoCharacteristic.subscribe(error => {
|
|
46
|
+ if (error) {
|
|
47
|
+ console.error('Error subscribing to echoCharacteristic');
|
|
48
|
+ } else {
|
|
49
|
+ console.log('Subscribed for echoCharacteristic notifications');
|
|
50
|
+ }
|
|
51
|
+ });
|
|
52
|
+
|
|
53
|
+ // create an interval to send data to the service
|
|
54
|
+ let count = 0;
|
|
55
|
+ setInterval(() => {
|
|
56
|
+ count++;
|
|
57
|
+ const message = new Buffer('hello, ble ' + count, 'utf-8');
|
|
58
|
+ console.log("Sending: '" + message + "'");
|
|
59
|
+ echoCharacteristic.write(message);
|
|
60
|
+ }, 2500);
|
|
61
|
+}
|