-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (82 loc) · 2.27 KB
/
index.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
const noble = require('noble');
const Device = require('./device');
const falilaSensorBeacon = require('./falila-sensor-beacon');
const CloudProvider = require('./providers/provider');
const config = require('./config.json');
/**
* Connected devices
* @global
*/
const devices = {};
/**
* Cloud Provider access
* @global
*/
const provider = new CloudProvider(config);
function startScanning() {
// Restart scanning
if (noble.state === 'poweredOn') {
noble.startScanning([], true);
} else {
throw new Error('BLE poweredOff');
}
}
function stopScanning() {
noble.stopScanning();
}
/**
* Called when a new device is discovered
*/
var connected = false
function onDiscover(beaconInst) {
const id = beaconInst.address.replace(/:/g, '');
if (connected) {
return
}
var device = null;
// must reuse device objects!
if (devices[id]) {
device = devices[id]
} else {
device = new Device(beaconInst);
}
console.log(`Connecting: ${device.id}`);
//must stop scanning to initiate a connection
connected = true
stopScanning()
// Connect to device and setup
device.setUp()
.then(() => {
device.onLuxometerChange((d, lux) => {
const telemetry = {
deviceID: d.id,
light: lux.toFixed(1),
};
provider.sendTelemetry(telemetry);
});
// Store in list of known devices
devices[device.id] = device;
// Set disconnect handler
device.bleDevice.on('disconnect', function disconnectHandler() {
console.log(`${device.id}: disconnected`);
device.bleDevice.removeListener('disconnect', disconnectHandler);
device.resetState();
connected = false
startScanning();
});
})
.catch((error) => {
console.log(error)
device.bleDevice.disconnect();
connected = false
startScanning();
});
}
noble.on('scanStop', () => {
console.log('Scanning stopped');
});
noble.on('scanStart', () => {
console.log('Scanning started');
});
falilaSensorBeacon.discoverAll(onDiscover);