-
Notifications
You must be signed in to change notification settings - Fork 11
/
tc-websocket.js
87 lines (77 loc) · 2.21 KB
/
tc-websocket.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
const WebSocketClient = require('./websocket-client');
function WebsocketTransceiver (log, host, port = 80, ioTimeout = 500) {
this.log = log;
this.host = host;
this.port = port;
this._queue = [];
this._busy = false;
this.lastInputTime = 0;
this.ioTimeout = ioTimeout;
this.ws = new WebSocketClient(log);
}
WebsocketTransceiver.prototype.setCallback = function (callback) {
this.callback = callback;
};
WebsocketTransceiver.prototype.init = function () {
this.ws.open('ws://' + this.host + ':' + this.port);
this.ws.onmessage = this.wsCallback.bind(this);
};
WebsocketTransceiver.prototype.send = function (message) {
var msg = null;
if (message.code) {
msg = message.code + '/' + message.pulse + '/' + message.protocol;
} else if (message.type && message.message) {
try {
msg = JSON.stringify(message);
} catch (e) { this.log(e); }
}
if (msg == null) return;
this._queue.push(msg);
if (this._busy) return;
this._busy = true;
this.processQueue();
};
WebsocketTransceiver.prototype.processQueue = function (inData) {
var next = inData === undefined ? this._queue.shift() : inData;
if (!next) {
this._busy = false;
return;
}
var curTime = new Date().getTime();
if (curTime - this.lastInputTime < this.ioTimeout) {
setTimeout(this.processQueue.bind(this, next), this.ioTimeout);
} else {
this.ws.send(next);
}
};
WebsocketTransceiver.prototype.wsCallback = function (data) {
if (data.startsWith('OK')) {
this.processQueue();
return;
}
this.lastInputTime = new Date().getTime();
if (data.startsWith('{')) {
try {
const message = JSON.parse(data);
this.callback(message);
} catch (e) { this.log(e); }
return;
}
if (data.startsWith('pilight')) {
this.log(data);
return;
}
var content = data.split('/');
if (content.length >= 2) {
var value = content[0];
var pulse = content[1].replace('\n', '').replace('\r', '');
var protocol = content[2];
if (protocol) {
protocol = protocol.replace('\n', '').replace('\r', '');
} else {
protocol = 1;
}
this.callback({ code: Number(value), pulse: Number(pulse), protocol: Number(protocol) });
}
};
module.exports = WebsocketTransceiver;