forked from zettajs/zetta-auto-scout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auto_scout.js
91 lines (75 loc) · 2.47 KB
/
auto_scout.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
var util = require('util');
var crypto = require('crypto');
var Scout = require('zetta-scout');
var AutoScout = module.exports = function() {
var args = Array.prototype.slice.call(arguments);
this.filter = args[0];
this.constructor = args[1];
this.params = args.slice(2);
if (!(this instanceof AutoScout)) {
var scout = new AutoScout();
scout.filter = this.filter;
scout.constructor = this.constructor;
scout.params = this.params;
return scout;
}
Scout.call(this);
};
util.inherits(AutoScout, Scout);
AutoScout.prototype._hash = function() {
var stringifiedParams = JSON.stringify(this.params);
var hash = crypto.createHash('sha1');
hash.update(stringifiedParams);
return hash.digest('hex');
};
AutoScout.prototype.init = function(cb) {
var filter = typeof this.filter === 'string'
? { type: this.filter }
: this.filter;
var deviceHash = this._hash();
filter.hash = deviceHash;
var query = this.server.where(filter);
var applyArgs = [].concat(this.params || []);
applyArgs.unshift(this.constructor);
var self = this;
this.server.find(query, function(err, results) {
if (err) {
return cb(err);
};
if (!self._deviceInstance) {
if (results.length) {
var result = results[0];
applyArgs.unshift(result);
var device = self.provision.apply(self, applyArgs);
} else {
var device = self.discover.apply(self, applyArgs);
}
// device is not always populated in the case of .provision
if (device) {
device.hash = deviceHash;
device.save(function() {
delete device.hash;
});
}
} else {
var machine = self._deviceInstance.instance;
machine.hash = deviceHash;
if (results.length) {
machine.id = results[0].id; // must set id before machine_config runs
machine.name = results[0].name;
}
machine._generate(self._deviceInstance.config);
self.server.registry.save(machine, function(err){
delete machine.hash;
self.server._jsDevices[machine.id] = machine;
self.server.emit('deviceready', machine);
if (results.length) {
self.server._log.emit('log','scout', 'Device (' + machine.type + ') ' + machine.id + ' was provisioned from registry.' );
} else {
self.server._log.emit('log','scout', 'Device (' + machine.type + ') ' + machine.id + ' was discovered' );
}
});
}
cb();
});
};