forked from ivesdebruycker/maxcube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxcube-lowlevel.js
90 lines (71 loc) · 2.04 KB
/
maxcube-lowlevel.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
var net = require('net');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var Promise = require('bluebird');
function MaxCubeLowLevel(ip, port){
this.ip = ip;
this.port = port;
this.socket = new net.Socket();
this.isConnected = false;
initSocket.call(this);
}
util.inherits(MaxCubeLowLevel, EventEmitter);
function initSocket () {
var self = this;
var previousPacketData = '';
this.socket.on('data', function(dataBuff) {
var dataStr = dataBuff.toString('utf-8');
if (!dataStr.endsWith('\r\n')) {
previousPacketData = dataStr;
return;
}
dataStr = previousPacketData + dataStr;
previousPacketData = '';
// multiple commands possible
var commandArr = dataStr.split("\r\n");
commandArr.forEach(function (command) {
if (command) {
var commandType = command.substr(0, 1);
var payload = command.substring(2) + "\r\n"; // reappend delimiter
self.emit('command', { type: commandType, payload: payload });
}
});
});
this.socket.on('close', function() {
self.isConnected = false;
self.emit('closed');
});
this.socket.on('error', function(err) {
console.error(err);
self.emit('error');
});
}
function connect () {
var self = this;
if (self.isConnected) {
self.connectionPromise = Promise.resolve();
} else if (!(self.connectionPromise && self.connectionPromise.isPending())) {
self.connectionPromise = new Promise(function(resolve, reject) {
self.socket.connect(self.port, self.ip, function() {
self.isConnected = true;
self.emit('connected');
resolve();
});
});
}
return self.connectionPromise;
}
function close () {
this.socket.destroy();
}
function send (dataStr) {
this.socket.write(dataStr);
}
function isConnected () {
return this.isConnected;
}
MaxCubeLowLevel.prototype.connect = connect;
MaxCubeLowLevel.prototype.close = close;
MaxCubeLowLevel.prototype.send = send;
MaxCubeLowLevel.prototype.isConnected = isConnected;
module.exports = MaxCubeLowLevel;