-
Notifications
You must be signed in to change notification settings - Fork 23
/
Emitter.js
114 lines (76 loc) · 2.33 KB
/
Emitter.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
var _ = require('underscore'),
Q = require('q'),
path = require('path'),
exec = require('child_process').exec,
util = require('util');
module.exports = Emitter;
Emitter.SCRIPT = 'build/codesend';
function Emitter(options) {
this.options = options;
}
/**
* Send a decimal code through 433Mhz (and return a promise).
*
* @param code Decimal code
* @param [options] Options to configure pin or pulseLength
* options.pin Pin on which send the code
* options.pulseLength Pulse length
* @param [callback] Callback(error, stdout)
* @return Promise
*/
Emitter.prototype.sendCode = function (code, options, callback) {
var deferred = Q.defer();
//NoOp as default callback
if(!_.isFunction(callback)) {
callback = _.noop;
}
//Check arguments length
if(arguments.length === 0 || arguments.length > 3) {
return deferred.reject(new Error('Invalid parameters. sendCode(code, [options, callback])'));
}
//Check if code is a number (and parse it)
code = parseInt(code);
if(!_.isNumber(code)) {
return deferred.reject(new Error('First parameter must be a integer'));
}
//Tidy up
switch(arguments.length) {
//function(code)
case 1:
options = this.options;
break;
//function(code, options || callback)
case 2:
//function(code, callback)
if(_.isFunction(options)) {
callback = options;
options = this.options;
//function(code, options)
} else if (_.isObject(options)) {
_.defaults(options, this.options);
//function(code, ???)
} else {
return deferred.reject(new Error('Second parameter must be a function (callback) or an object (options)'));
}
break;
//function(code, options, callback)
default:
_.defaults(options, this.options);
break;
}
//Send the code
exec([path.join(__dirname, Emitter.SCRIPT),
'--code', code,
'--pin', options.pin,
'--pulse-length', options.pulseLength
].join(' '), function (error, stdout, stderr) {
error = error || stderr;
if(error) {
deferred.reject(error);
} else {
deferred.resolve(stdout);
}
callback(error, stdout);
});
return deferred.promise;
};