-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathDevice.js
98 lines (77 loc) · 2.1 KB
/
Device.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
var net = require('net');
var util = require('util');
var events = require('events');
var proto = require('./protocol');
module.exports = Device;
function Device(conf) {
events.EventEmitter.call(this, conf);
var self = this;
this.backlog = [];
this.device_id = conf.device_id;
this.device_ip = conf.device_ip;
this.control_sock = net.createConnection(65001, this.device_ip,
function () {
self.emit('connected');
});
this.request_encoder = new proto.RequestEncoder();
this.reply_decoder = new proto.ReplyDecoder();
this.request_encoder.pipe(this.control_sock);
this.control_sock.pipe(this.reply_decoder);
this.reply_decoder.on('reply', function onReply(msg) {
var buf, item, cb, err;
if (msg.error_message)
err = new Error(msg.error_message);
if (self.backlog.length > 0) {
item = self.backlog.shift();
cb = item.callback;
clearTimeout(item.timeout);
cb(err, {name: msg.getset_name,
value: msg.getset_value});
} else {
console.log('unexpected reply');
}
});
this.on('CTS', function () {
if (self.backlog.length > 0) {
self.request_encoder.send(self.backlog[0].request);
} else {
console.log('CTS with empty backlog');
}
});
}
util.inherits(Device, events.EventEmitter);
Device.prototype.get = function (name, cb) {
get_set.call(this, name, cb);
}
Device.prototype.set = function (name, value, cb) {
get_set.call(this, name, value, cb);
}
function get_set(name, value, cb) {
var which = 'set';
if ((arguments.length == 2) && (typeof (value) == 'function')) {
cb = value;
value = null;
which = 'get';
}
var msg = {
type: proto.types.getset_req,
getset_name: name
};
if (which == 'set')
msg.getset_value = value;
this._request(msg, cb);
}
Device.prototype._request = function (msg, cb) {
var self = this;
var to = setTimeout(function () {
var unanswered = self.backlog.shift();
var cb = unanswered.callback;
var err = new Error('request timeout');
cb(err);
if (self.backlog.length > 0)
self.emit('CTS');
}, 2500);
this.backlog.push({request: msg, callback: cb, timeout: to});
if (this.backlog.length === 1)
this.emit('CTS');
}