Permalink
Browse files

Support for passing a "catch-all" handler function to `modbus-stack.S…

…erver`.
  • Loading branch information...
1 parent d77b31d commit 8c0595da8af1705ab7fd79cf303db1318f6ed1b7 @TooTallNate committed Jan 5, 2011
Showing with 17 additions and 7 deletions.
  1. +17 −7 lib/server.js
View
@@ -7,27 +7,37 @@ var FUNCTION_CODES = modbus.FUNCTION_CODES;
function Server (handlers) {
- this.handlers = handlers || {};
+ if (typeof handlers == 'function') {
+ this.on('request', handlers);
+ } else {
+ this.on('request', this._handler);
+ this.handlers = handlers || {};
+ }
net.Server.call(this, this._setupConn);
}
require('util').inherits(Server, net.Server);
module.exports = Server;
Server.prototype._setupConn = function(stream) {
- var self = this;
+ var self = this;
var response = new modbus.ModbusResponseStack(stream);
response.on('request', function(request) {
- if (request.functionCode in self.handlers) {
- self.handlers[request.functionCode](request, response);
- } else {
- response.writeException(1);
- }
+ self.emit('request', request, response);
if (stream.readable && stream.writable) {
self._setupConn(stream);
}
});
}
+// Called for every 'request' event, when a "handlers" Object was passed.
+Server.prototype._handler = function(request, response) {
+ if (request.functionCode in this.handlers) {
+ this.handlers[request.functionCode].call(this, request, response);
+ } else {
+ response.writeException(1);
+ }
+}
+
function createServer (handlers) {
return new Server(handlers);
}

0 comments on commit 8c0595d

Please sign in to comment.