-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathBluetoothAgent.js
302 lines (300 loc) · 12.1 KB
/
BluetoothAgent.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
'use strict';
const maxDevices = 8;
var Playbulb = require("./Playbulb");
var YeeBTLamp = require("./YeeBTLamp");
var properties = require ("./properties.json");
exports.BluetoothAgent = function (handler) {
var that = this;
this.numberOfDevices = 0;
this.noble = require('noble');
this.smartType = "Bluetooth";
this.btDevices = [];
this.peripheralPairingStates = {};
this.peripherals = {};
this.cbHandler = handler;
this.powerState = "startUp"
this.scanState = "off"
this.discoveryInProgress = null;
this.stopScanningTimer = null;
this.startScanningTimer = null;
var unknownDevices = {}
this.discoverDevices= function(){
//console.log("BluetoothAgent: discovering")
that.discoveryInProgress = true;
if (that.startScanningTimer) {
that.startScanningTimer = null;
clearTimeout(that.startScanningTimer)
}
if ( (that.powerState=="poweredOn") && (that.scanState=="off") ) {
//console.log("BluetoothAgent: discoverDevices - Scanning")
that.noble.startScanning([],false);
} else {
that.startScanningTimer = (that.powerState != "poweredOn" ? 2000 : 10000)
that.startScanningTimer = setTimeout(that.discoverDevices, that.startScanningTimer );
}
//console.log("Discover ends")
}.bind(this)
this.reconnect = function(peripheral, cb){
this.connectDevice(peripheral, function(error, pbBulb){
if (error) {
console.log("BluetoothAgent:reconnecting error " + error);
if (cb) {
cb(error, null);
};
} else {
pbBulb.periph.discoverAllServicesAndCharacteristics();
pbBulb.periph.on('servicesDiscover', function (services) {
services.map(function (service) {
service.on('characteristicsDiscover', function (characteristics) {
characteristics.map(function (characteristic) {
pbBulb.processCharacteristic(characteristic);
});
});
});
});
if (cb) {
cb(null,periperhal);
};
}
});
}.bind(this);
this.connectDevice = function(peripheral,cb) {
var pbPrefix;
this.connectPeripheral(peripheral, function (error,btBulb) {
if (error) {
console.log("BluetoothAgent:connectDevice " + peripheral.advertisement.localName + " error connecting " + error);
cb(error,null)
return;
}
if (peripheral.state == "connected") {
btBulb = that.findDevice(peripheral.advertisement.localName,false)
if (!btBulb) {
var pbType = null;
if (that.numberOfDevices < maxDevices) {
var devType = that.getDeviceType(peripheral.advertisement.localName)
btBulb = that.createBulbObject(devType.managerType, peripheral.advertisement.localName, devType.pbType, peripheral, that.cbHandler, that);
that.btDevices.push(btBulb);
that.numberOfDevices++;
cb(null,btBulb)
console.log("BluetoothAgent:connectDevice: creating bulb localName=" + btBulb.periph.advertisement.localName +
" uniqueName=" + btBulb.uniqueName + " pbType=" + pbType + " MAC=" + btBulb.periph.uuid.toUpperCase() + " #devices=" + that.numberOfDevices);
} else {
console.log("BluetoothAgent:connectDevice " + peripheral.advertisement.localName + " too many bluetooth devices we already have " + that.numberOfDevices)
cb("too many bluetooth devices",null)
}
} else {
console.log("BluetoothAgent:connectDevice " + peripheral.advertisement.localName + " already in devices array")
}
} else {
console.log("BluetoothAgent:connectDevice " + peripheral.advertisement.localName + " device cant connect, do not know why")
throw " device cant connect, do not know why";
cb(" device cant connect, do not know why",null)
}
});
}.bind(this);
this.connectPeripheral = function(peripheral, cb) {
this.scanStop( function(error,discoverInProgress) {
if (peripheral.state=="connected") {
cb(null, peripheral);
if (discoverInProgress) {
this.startScanningTimer = setTimeout(this.discoverDevices,5000);
};
} else {
peripheral.connect( function (error,btBulb) {
if (error) {
if (peripheral.state != "connected") {
console.log("BluetoothAgent: " + peripheral.advertisement.localName + " device cant connect state=" + peripheral.state)
throw error;
cb(error, null);
}
}
cb(null, peripheral);
if (discoverInProgress) {
that.startScanningTimer = setTimeout(that.discoverDevices,5000);
};
});
};
});
}.bind(this);
this.scanStop = function(cb) {
//var savedDiscoveryInProgress=this.discoveryInProgress;
//this.discoveryInProgress = false;
if (this.stopScanningTimer) {
this.stopScanningTimer = null;
clearTimeout(this.stopScanningTimer)
} // NOT SURE THIS IS NEEDED
if (this.startScanningTimer) {
this.startScanningTimer = null;
clearTimeout(this.startScanningTimer)
}
if (this.scanState=="off") {
if (cb) {
cb(null, this.discoveryInProgress);
};
} else {
this.noble.stopScanning(function(){
if (cb) {
cb(null,this.discoveryInProgress);
};
});
}
}.bind(this);
this.createBulbObject = function(type) {
//console.log("BluetoothAgent: createBulbObject: type=" + type)
var args = Array.from(arguments)
var instance;
if (type=="YeeBTLamp") {
//console.log("DEBUG args[0]=" + args[0] + " args[1]=" + args[1] + "args[2]=" + args[2] + " args[3].uuid=" + args[3].uuid)
return new (Function.prototype.bind.apply(YeeBTLamp.YeeBTLamp, args));
} else if (type=="Playbulb") {
//console.log("DEBUG args=" + args + " sliced=" + args.slice[1]);
return new (Function.prototype.bind.apply(Playbulb.Playbulb, args));
} else {
console.log("BluetoothAgent: createBulbObject: Unknown Type " + type)
}
};
this.findDevice = function(name,unique) {
//console.log("BluetoothAgent: findDevice: We have " + this.btDevices.length + " Devices" )
var obj = null;
var tmpPb = null;
if (this.btDevices.length>0) {
for ( tmpPb in this.btDevices) {
//console.log("BluetoothAgent: findDevice: checking name=" + name + " pbDevice=" + this.btDevices[tmpPb].playbulbName)
if ( ( (this.btDevices[tmpPb].playbulbName==name) && (!unique) ) || ( (this.btDevices[tmpPb].uniqueName==name) && (unique) ) ) {
console.log("BluetoothAgent: findDevice: Found name=" + name + " pbDevice=" + this.btDevices[tmpPb].playbulbName)
obj=this.btDevices[tmpPb];
} else {
//console.log("BluetoothAgent: findDevice: didnt find name=" + name + " pbDevice=" + this.btDevices[tmpPb].playbulbName + " " + this.btDevices[tmpPb].uniqueName)
}
}
}
return obj;
}.bind(this);
this.getDeviceType = function(peripheralName) {
var enabledTypes = (function () {
var tmp="";
var enabledTypes = []
process.argv.forEach((val, index) => {
tmp == "" ? tmp = index + ":" + val : tmp = tmp + "," + index + ":" + val
if (index > 1) {
enabledTypes[index-2] = val;
}
});
//console.log("bluetoothAgent: input arguments are " + tmp + " enabledtypes (overriding properties.json)=" + enabledTypes);
return enabledTypes;
})();
var pbPrefix;
var pbType = "Unknown"
var valid = false;
var managerPrefix;
var managerType;
var tmp;
var tmp0;
for (managerPrefix in properties.ManagerPrefixes) {
if ( (peripheralName) && (peripheralName.substring(0,managerPrefix.length) == managerPrefix)) {
managerType = properties.ManagerPrefixes[managerPrefix];
for (pbPrefix in properties[managerType].AdvertismentPrefixTypes) {
if (peripheralName.substring(0,pbPrefix.length) == pbPrefix) {
pbType = properties[managerType].AdvertismentPrefixTypes[pbPrefix];
if ( (enabledTypes.length!=0) && (enabledTypes.includes(managerType)) ) {
valid = true;
} else if (enabledTypes.length==0) {
valid = properties[managerType].AdvertismentPrefixTypes[pbPrefix]
} else {
valid = false
}
}
}
}
}
//console.log("bluetoothAgent: valid=" + valid + " managerType=" + managerType + " pbType=" + pbType)
return {"valid" : valid, "managerType" : managerType, "pbType" : pbType};
};
this.noble.on('discover', function (peripheral) {
var parsedPrefix = this.getDeviceType(peripheral.advertisement.localName)
//console.log("BluetoothAgent:onNoble: name=" + peripheral.advertisement.localName + " pbType=" + parsedPrefix.pbType + " ManagerTypes =" + tmp0 + " prefixTypes=" + tmp);
if (parsedPrefix.valid) {
console.log("BluetoothAgent:onNoble: Valid BT Device found " + peripheral.advertisement.localName + " pbType=" + parsedPrefix.pbType )
//console.log("BluetoothAgent:onNoble: name=" + peripheral.advertisement.localName + " pbType=" + parsedPrefix.pbType + " ManagerTypes =" + tmp0 + " prefixTypes=" + tmp);
if (!that.peripherals[peripheral.uuid]) {
that.peripherals[peripheral.uuid] = peripheral;
if (that.stopScanningTimer) {
that.stopScanningTimer = null;
clearTimeout(that.stopScanningTimer)
}
//console.log("BluetoothAgent: on discover: DEBUG scheduling end to scanning in 3 seconds");
that.stopScanningTimer = setTimeout(that.scanStop,3000);
/* that.stopScanningTimer = setTimeout(function() {
that.noble.stopScanning();
}
, 3000) */ // Stop scanning 5000 - reset when peripheral found
}
} else {
if (! unknownDevices[peripheral.id] )
{
console.log("BluetoothAgent: Device not supported " + peripheral.advertisement.localName + " id=" + peripheral.id);
unknownDevices[peripheral.id] = peripheral.id
}
}
}.bind(this));
this.handleStateChange = function(state) {
console.log("BluetoothAgent: state changed received -" + state + " old powerState=" + this.powerState)
this.powerState=state;
console.log("BluetoothAgent: state changed received -" + state + " new powerState=" + this.powerState)
if (state === 'poweredOn') {
console.log("BluetoothAgent: Powered On")
};
}.bind(this);
this.handleScanStart = function(message) {
console.log("BluetoothAgent: Scan starts")
this.scanState="on"
}.bind(this);
this.handleScanStop = function(message) {
console.log("BluetoothAgent: Scan stops ")
that.scanState = "off"
//var savedDiscoveryInProgress = that.discoveryInProgress;
//that.discoveryInProgress = false;
var uuid;
for (uuid in that.peripherals) {
//console.log("Process for " + that.peripherals[uuid].advertisement.localName + " id=" + that.peripherals[uuid].id + " index=" + uuid)
if ( (that.peripherals[uuid]) && (that.peripherals[uuid].state != "connected") && (that.peripherals[uuid].state != "connecting") ){
//console.log("calling connect device for " + that.peripherals[uuid].advertisement.localName + " id=" + " index=" + uuid)
that.connectDevice(that.peripherals[uuid], function(error, pbBulb){
if (error) {
console.log("error connecting to device " + error + " for " + that.peripherals[uuid].advertisement.localName )
}
if (pbBulb) {
pbBulb.periph.discoverAllServicesAndCharacteristics();
pbBulb.periph.on('servicesDiscover', function (services) {
services.map(function (service) {
service.on('characteristicsDiscover', function (characteristics) {
characteristics.map(function (characteristic) {
pbBulb.processCharacteristic(characteristic);
});
});
});
});
} else {
console.log("BluetoothAgent:handleScanStop:Weird error pbBulb not found for " + that.peripherals[uuid].id )
}
});
} else {
console.log("Weird error peripheral state is not correct for " + that.peripherals[uuid].id + " state=" + that.peripherals[uuid].state )
}
}
//that.discoveryInProgress = savedDiscoveryInProgress;
//if ( (!that.startScanningTimer) && (savedDiscoveryInProgress) ) {
/*
if (!that.startScanningTimer) {
that.startScanningTimer = setTimeout(that.discoverDevices,5000);
}*/
}.bind(this);
this.noble.on('stateChange',this.handleStateChange);
this.noble.on('scanStop',this.handleScanStop );
this.noble.on('scanStart',this.handleScanStart );
this.noble.on('warning', function(message) {
console.log("Nobel warning " + message)
throw message
});
return this;
}.bind(this);