var WebSocket = require('ws');
var debug = require('debug')('signalk:ws');


function connectDelta(hostname, callback) {
  var url = "ws://" + hostname + "/signalk/stream?stream=delta&context=self";
  if (typeof Primus != 'undefined') {
    var signalKStream = Primus.connect(url, {
      reconnect: {
        maxDelay: 15000,
        minDelay: 500,
        retries: Infinity
      }
    });
    signalKStream.on('data', callback);
  } else {
    connection = new WebSocket(url);
    connection.onopen = function(msg) {
      debug("open");
    };

    connection.onerror = function(error) {
      debug("error:" + error);
    };
    connection.onmessage = function(msg) {
      callback(JSON.parse(msg.data));
    };
  }
}

module.exports = {
  connectDelta: connectDelta
}
@@ -110,19 +110,82 @@
 callback
-) %7B
+, onConnect, onDisconnect) %7B%0A  debug(%22Connecting to %22 + hostname);
 %0A  var u
@@ -289,24 +289,51 @@
 defined') %7B%0A
+    debug(%22Using Primus%22);%0A
     var sign
@@ -521,20 +521,169 @@
 ;%0A  
-%7D else %7B%0A   
+  return %7B%0A      disconnect: function() %7B%0A        signalKStream.destroy();%0A        debug('Disconnected');%0A      %7D%0A    %7D%0A  %7D else %7B%0A    debug(%22Using ws%22);%0A    var
  con
@@ -769,24 +769,43 @@
 ug(%22open%22);%0A
+      onConnect();%0A
     %7D;%0A%0A    
@@ -969,16 +969,133 @@
 %0A    %7D;%0A
+    return %7B%0A      disconnect: function() %7B%0A        connection.close();%0A        debug('Disconnected');%0A      %7D%0A    %7D%0A
   %7D%0A%7D%0A%0Am

Add onConnect and onDisconnect callbacks and return 'connection' object with disconnect option