-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
59 lines (48 loc) · 1.6 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
var dgram = require('dgram');
const PORT = 5050;
const DEFAULT_TRIES = 5;
const DEFAULT_DELAY = 1000;
module.exports = Xbox;
function Xbox(ip, id) {
this.ip = ip;
this.id = id;
return this;
}
Xbox.prototype.powerOn = function(options, callback) {
options = options || {};
callback = callback || function() {};
if (typeof options === 'function') {
callback = options;
options = {};
}
// Retry up to options.tries times
for (var i = 0; i < (options.tries || DEFAULT_TRIES); i++) {
setTimeout((function(xbox, i) {
return function() {
xbox.sendOn();
// If wait was specified, callback after last try, otherwise, callback after first try
if (options.waitForCallback && i + 1 === options.tries) {
callback();
} else if (!options.waitForCallback && i === 0) {
callback();
}
}
})(this, i), i * (options.delay || DEFAULT_DELAY));
}
};
Xbox.prototype.sendOn = function(callback) {
callback = callback || function() {};
// Open socket
var socket = dgram.createSocket('udp4');
// Create payload
var powerPayload = new Buffer('\x00' + String.fromCharCode(this.id.length) + this.id + '\x00'),
powerPayloadLength = new Buffer(String.fromCharCode(powerPayload.length)),
powerHeader = Buffer.concat([new Buffer('dd0200', 'hex'), powerPayloadLength, new Buffer('0000', 'hex')]),
powerPacket = Buffer.concat([powerHeader, powerPayload]);
// Send
socket.send(powerPacket, 0, powerPacket.length, PORT, this.ip, function(err) {
if (err) return callback(err);
socket.close();
callback();
});
};