forked from tillbaks/node-itach
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
executable file
·206 lines (182 loc) · 6.67 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
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
var request = require('request'),
net = require('net'),
events = require('events'),
_ = require('underscore'),
crypto = require('crypto'),
ERRORCODES = {
'001': 'Invalid command. Command not found.',
'002': 'Invalid module address (does not exist).',
'003': 'Invalid connector address (does not exist).',
'004': 'Invalid ID value.',
'005': 'Invalid frequency value.',
'006': 'Invalid repeat value.',
'007': 'Invalid offset value.',
'008': 'Invalid pulse count.',
'009': 'Invalid pulse data.',
'010': 'Uneven amount of <on|off> statements.',
'011': 'No carriage return found.',
'012': 'Repeat count exceeded.',
'013': 'IR command sent to input connector.',
'014': 'Blaster command sent to non-blaster connector.',
'015': 'No carriage return before buffer full.',
'016': 'No carriage return.',
'017': 'Bad command syntax.',
'018': 'Sensor command sent to non-input connector.',
'019': 'Repeated IR transmission failure.',
'020': 'Above designated IR <on|off> pair limit.',
'021': 'Symbol odd boundary.',
'022': 'Undefined symbol.',
'023': 'Unknown option.',
'024': 'Invalid baud rate setting.',
'025': 'Invalid flow control setting.',
'026': 'Invalid parity setting.',
'027': 'Settings are locked'
};
const DELAY_BETWEEN_COMMANDS = 5000;
var
callbacks = {},
messageQueue = [],
_currentRequestID = 0;
var _addToCallbacks = function (done, predefinedId) {
var id;
if (!predefinedId) {
console.log('node-itach :: generating new id for IR transmittion');
console.log('node-itach :: currently callbacks hash contains %d', Object.keys(callbacks).length);
_currentRequestID++;
id = _currentRequestID;
}
else
id = predefinedId;
callbacks[id] = done;
return id;
},
_resolveCallback = function (id, err) {
if (callbacks[id]) {
console.log('node-itach :: status:%s resolving callback with id %s', err ? 'error' : 'success', id);
callbacks[id](err || false);
delete callbacks[id];
} else {
console.error('node-itach :: cannot find callback with id %s in callbacks hash', id);
}
};
var iTach = function (config) {
config = _.extend({
port: 4998,
timeout: 20000,
module: 1
}, config);
if (!config.host) {
throw new Error('Host is required for this module to function');
}
var isSending = false;
this.learn = function (done) {
var options = {
method: 'GET',
uri: "http://" + config.host + '/api/v1/irlearn',
json: true
};
return request(options, function (error, response, learnObject) {
if (error) {
done && done(JSON.stringify(error));
} else if (response.statusCode != 200) {
done && done(JSON.stringify(learnObject));
} else {
done && done(false, learnObject);
}
});
};
var _send = function () {
var self = this;
if (!messageQueue.length) {
console.log('Message queue is empty. returning...')
return;
}
isSending = true;
console.log('Taking next message from the queue.')
var message = messageQueue.shift(),
id = message[0],
data = message[1];
var socket = net.connect(config.port, config.host);
socket.setTimeout(config.timeout);
console.log('Connecting to ' + config.host + ':' + config.port);
socket.on('connect', function () {
console.log('node-itach :: connected to ' + config.host + ':' + config.port);
console.log('node-itach :: sending data', data);
socket.write(data + "\r\n");
});
socket.on('close', function () {
console.log('node-itach :: disconnected from ' + config.host + ':' + config.port);
});
socket.on('error', function (err) {
console.error('node-itach :: error :: ', err);
done(err);
socket.destroy();
});
socket.on('timeout', function () {
console.error('node-itach :: error :: ', 'Timeout');
done('Timeout');
socket.destroy();
});
socket.on('data', function (data) {
data = data.toString().replace(/[\n\r]$/, "");
console.log("node-itach :: received data: " + data);
var parts = data.split(','),
status = parts[1],
id = parts[2];
if (status === 'busyIR') {
// This shound not happen if this script is the only device connected to the itach
// add rate limiter
return _resolveCallback(id, 'Add Rate Limiter to the blaster');
} else if (status.match(/^ERR/)) {
var err = ERRORCODES[parts[1].split('IR')[1]];
console.error('node-itach :: error :: ' + data + ': ' + err);
return _resolveCallback(parts[2], err);
} else if (parts[0] === 'setstate') {
_resolveCallback(parts[1]);
} else if (parts[0] !== 'setstate') {
_resolveCallback(id);
}
socket.destroy();
isSending = false;
// go to the next message in the queue if any
if (messageQueue.length) {
console.log('Delay before going to another item in a queue...');
// for some reason my samsung tv needs this timeout.
setTimeout(function () {
_send();
}, DELAY_BETWEEN_COMMANDS);
}
});
};
this.send = function (input, done) {
if (!input) throw new Error('Missing input');
var data,
ir = (input.ir != null);
if (ir)
parts = input.ir.split(',');
else
parts = input.serial.split(',');
if (ir && typeof input.module !== 'undefined') {
parts[1] = '1:' + input.module;
}
var id;
if (ir) {
id = _addToCallbacks(done);
parts[2] = id;
}
else {
id = parts[1];
_addToCallbacks(done, id);
}
if (ir && typeof input.repeat !== 'undefined') {
parts[4] = input.repeat;
}
data = parts.join(',');
// add to queue
messageQueue.push([id, data]);
if (!isSending) {
_send();
}
};
}
module.exports = iTach;