forked from ZHONG007/node-modbus-serial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpport.js
232 lines (197 loc) · 6.45 KB
/
tcpport.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
"use strict";
var util = require("util");
var events = require("events");
var EventEmitter = events.EventEmitter || events;
var net = require("net");
var modbusSerialDebug = require("debug")("modbus-serial");
var crc16 = require("../utils/crc16");
/* TODO: const should be set once, maybe */
var MODBUS_PORT = 502; // modbus port
var MAX_TRANSACTIONS = 256; // maximum transaction to wait for
var MIN_DATA_LENGTH = 6;
var MIN_MBAP_LENGTH = 6;
var CRC_LENGTH = 2;
/**
* Simulate a modbus-RTU port using modbus-TCP connection.
*
* @param ip
* @param options
* options.port: Nonstandard Modbus port (default is 502).
* options.localAddress: Local IP address to bind to, default is any.
* options.family: 4 = IPv4-only, 6 = IPv6-only, 0 = either (default).
* @constructor
*/
var TcpPort = function(ip, options) {
var modbus = this;
this.openFlag = false;
this.callback = null;
this._transactionIdWrite = 1;
this._externalSocket = null;
if(typeof ip === "object") {
options = ip;
}
if (typeof(options) === "undefined") options = {};
this.connectOptions = {
host: ip || options.ip,
port: options.port || MODBUS_PORT,
localAddress: options.localAddress,
family: options.family
};
if(options.socket) {
if(options.socket instanceof net.Socket) {
this._externalSocket = options.socket;
this.openFlag = this._externalSocket.readyState === "opening" || this._externalSocket.readyState === "open";
} else {
throw new Error("invalid socket provided");
}
}
// handle callback - call a callback function only once, for the first event
// it will triger
var handleCallback = function(had_error) {
if (modbus.callback) {
modbus.callback(had_error);
modbus.callback = null;
}
};
// init a socket
this._client = this._externalSocket || new net.Socket();
if (options.timeout) this._client.setTimeout(options.timeout);
this._client.on("data", function(data) {
var buffer;
var crc;
var length;
// data recived
modbusSerialDebug({ action: "receive tcp port strings", data: data });
// check data length
while (data.length > MIN_MBAP_LENGTH) {
// parse tcp header length
length = data.readUInt16BE(4);
// cut 6 bytes of mbap and copy pdu
buffer = Buffer.alloc(length + CRC_LENGTH);
data.copy(buffer, 0, MIN_MBAP_LENGTH);
// add crc to message
crc = crc16(buffer.slice(0, -CRC_LENGTH));
buffer.writeUInt16LE(crc, buffer.length - CRC_LENGTH);
// update transaction id and emit data
modbus._transactionIdRead = data.readUInt16BE(0);
modbus.emit("data", buffer);
// debug
modbusSerialDebug({ action: "parsed tcp port", buffer: buffer, transactionId: modbus._transactionIdRead });
// reset data
data = data.slice(length + MIN_MBAP_LENGTH);
}
});
this._client.on("connect", function() {
modbus.openFlag = true;
modbusSerialDebug("TCP port: signal connect");
handleCallback();
});
this._client.on("close", function(had_error) {
modbus.openFlag = false;
modbusSerialDebug("TCP port: signal close: " + had_error);
handleCallback(had_error);
modbus.emit("close");
modbus.removeAllListeners();
});
this._client.on("error", function(had_error) {
modbus.openFlag = false;
modbusSerialDebug("TCP port: signal error: " + had_error);
handleCallback(had_error);
});
this._client.on("timeout", function() {
// modbus.openFlag is left in its current state as it reflects two types of timeouts,
// i.e. 'false' for "TCP connection timeout" and 'true' for "Modbus response timeout"
// (this allows to continue Modbus request re-tries without reconnecting TCP).
modbusSerialDebug("TCP port: TimedOut");
handleCallback(new Error("TCP Connection Timed Out"));
});
/**
* Check if port is open.
*
* @returns {boolean}
*/
Object.defineProperty(this, "isOpen", {
enumerable: true,
get: function() {
return this.openFlag;
}
});
EventEmitter.call(this);
};
util.inherits(TcpPort, EventEmitter);
/**
* Simulate successful port open.
*
* @param callback
*/
TcpPort.prototype.open = function(callback) {
if(this._externalSocket === null) {
this.callback = callback;
this._client.connect(this.connectOptions);
} else if(this.openFlag) {
modbusSerialDebug("TCP port: external socket is opened");
callback(); // go ahead to setup existing socket
} else {
callback(new Error("TCP port: external socket is not opened"));
}
};
/**
* Simulate successful close port.
*
* @param callback
*/
TcpPort.prototype.close = function(callback) {
this.callback = callback;
// DON'T pass callback to `end()` here, it will be handled by client.on('close') handler
this._client.end();
this.removeAllListeners();
};
/**
* Simulate successful destroy port.
*
* @param callback
*/
TcpPort.prototype.destroy = function(callback) {
this.callback = callback;
if (!this._client.destroyed) {
this._client.destroy();
}
};
/**
* Send data to a modbus-tcp slave.
*
* @param data
*/
TcpPort.prototype.write = function(data) {
if(data.length < MIN_DATA_LENGTH) {
modbusSerialDebug("expected length of data is to small - minimum is " + MIN_DATA_LENGTH);
return;
}
// remember current unit and command
this._id = data[0];
this._cmd = data[1];
// remove crc and add mbap
var buffer = Buffer.alloc(data.length + MIN_MBAP_LENGTH - CRC_LENGTH);
buffer.writeUInt16BE(this._transactionIdWrite, 0);
buffer.writeUInt16BE(0, 2);
buffer.writeUInt16BE(data.length - CRC_LENGTH, 4);
data.copy(buffer, MIN_MBAP_LENGTH);
modbusSerialDebug({
action: "send tcp port",
data: data,
buffer: buffer,
unitid: this._id,
functionCode: this._cmd,
transactionsId: this._transactionIdWrite
});
// send buffer to slave
this._client.write(buffer);
// set next transaction id
this._transactionIdWrite = (this._transactionIdWrite + 1) % MAX_TRANSACTIONS;
};
/**
* TCP port for Modbus.
*
* @type {TcpPort}
*/
module.exports = TcpPort;