forked from timofei-iatsenko/node-modbus-rtu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserial-helper.js
More file actions
96 lines (76 loc) · 2.32 KB
/
Copy pathserial-helper.js
File metadata and controls
96 lines (76 loc) · 2.32 KB
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
var Promise = require("bluebird");
var _ = require('lodash');
module.exports = SerialHelper;
function SerialHelper(serialPort, options) {
var self = this;
this.queue = [];
this._options = options;
this.serialPort = serialPort;
this.buffers = [];
this.currentTask = null;
this.serialPort.on("open", function () {
self.processQueue();
});
var onData = _.debounce(function () {
var buffer = Buffer.concat(self.buffers);
self._options.debug && console.log('resp', buffer);
self.currentTask.deferred.resolve(buffer);
self.buffers = [];
}, options.endPacketTimeout);
serialPort.on('data', function (data) {
if (self.currentTask) {
self.buffers.push(data);
onData(data);
}
});
}
SerialHelper.prototype._write = function(buffer, deferred) {
this._options.debug && console.log('write', buffer);
this.serialPort.write(buffer, function (error) {
if (error)
deferred.reject(error);
});
return deferred.promise.timeout(this._options.responseTimeout, 'Response timeout exceed!');
};
SerialHelper.prototype.processQueue = function () {
var self = this;
function continueQueue() {
setTimeout(function(){
self.processQueue();
}, self._options.queueTimeout); //pause between calls
}
if (this.queue.length) {
this.currentTask = this.queue[0];
this._write(this.currentTask.buffer, this.currentTask.deferred)
.catch(function(err){
self.currentTask.deferred.reject(err)
})
.finally(function () {
//remove current task
self.queue.shift();
continueQueue();
}).done();
} else {
continueQueue();
}
};
SerialHelper.prototype.write = function (buffer) {
var deferred = {};
deferred.promise = new Promise(function (resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
});
var task = {
deferred: deferred,
buffer: buffer
};
this.queue.push(task);
deferred.promise.abort = function() {
var _self = this;
if (deferred.promise.isPending()) {
deferred.reject();
_.pull(_self.queue, task);
}
};
return deferred.promise;
};