Permalink
Browse files

Fire an 'error' event when a slave (server) responds with an exceptio…

…n code. Don't fire a 'response' event.
  • Loading branch information...
1 parent c14defd commit 03df208f027113011254e99a386f9f39050c0360 @TooTallNate committed Dec 31, 2010
View
@@ -122,13 +122,22 @@ ModbusRequestStack.prototype._onData = function(chunk) {
this._onData();
} else if (this.responseHeader && this._resFunctionCode >= 1 && this.bufferlist.length >= (this.responseHeader.length-2)) {
// We have the complete response.
- var response = client.RESPONSES[this._resFunctionCode].call(this, this.bufferlist);
- this.bufferlist.advance(this.responseHeader.length-2);
- // Explicitly set the 'functionCode' property.
- response.functionCode = this._resFunctionCode;
- delete this._resFunctionCode;
- // Modbus request/response complete; invoke callbacks and cleanup!
- this.emit('response', response);
+ if (this._resFunctionCode & EXCEPTION_BIT) {
+ // An exception was returned as the response!
+ var code = this.bufferlist.take(1)[0];
+ this.bufferlist.advance(1);
+ var err = new Error(exports.EXCEPTION_CODES[code]);
+ err.errno = code;
+ this.emit('error', err);
+ } else {
+ var response = client.RESPONSES[this._resFunctionCode].call(this, this.bufferlist);
+ this.bufferlist.advance(this.responseHeader.length-2);
+ // Explicitly set the 'functionCode' property.
+ response.functionCode = this._resFunctionCode;
+ delete this._resFunctionCode;
+ // Modbus request/response complete; invoke callbacks and cleanup!
+ this.emit('response', response);
+ }
this.cleanup();
}
}
@@ -0,0 +1,22 @@
+var fs = require('fs');
+var assert = require('assert');
+var modbus = require('modbus-stack');
+
+exports['readInputRegisters response'] = function() {
+ var dump = fs.createReadStream(__dirname + "/responses/readInputRegisters.exception.IllegalDataAddress.dump");
+ var req = new modbus.ModbusRequestStack(dump);
+ var gotResponse = false;
+ var gotError = false;
+ req.on('response', function(res) {
+ // This shoud not be invoked
+ gotResponse = true;
+ });
+ req.on('error', function(e) {
+ gotError = true;
+ assert.equal(e.errno, 2);
+ });
+ dump.on('close', function() {
+ assert.ok(!gotResponse, "The 'response' event was fired");
+ assert.ok(gotError, "The 'error' event was never fired");
+ });
+}

0 comments on commit 03df208

Please sign in to comment.