Skip to content

Commit

Permalink
Websocket bugfix (#750)
Browse files Browse the repository at this point in the history
* Close connection on error'

* Log errors when sending messages to websocket

* Send poweredOn when connecting and forward state changes

* Make sure the event handler are setup before sending poweredOn
  • Loading branch information
hadrienk authored and sandeepmistry committed Feb 11, 2018
1 parent c6cd04d commit 3cfb558
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
14 changes: 10 additions & 4 deletions lib/websocket/bindings.js
Expand Up @@ -19,6 +19,7 @@ var NobleBindings = function() {

this._ws.on('open', this._onOpen.bind(this));
this._ws.on('close', this._onClose.bind(this));
this._ws.on('error', this._onClose.bind(this));

var _this = this;
this._ws.on('message', function(event) {
Expand All @@ -40,7 +41,6 @@ NobleBindings.prototype._onOpen = function() {

NobleBindings.prototype._onClose = function() {
console.log('on -> close');

this.emit('stateChange', 'poweredOff');
};

Expand Down Expand Up @@ -119,10 +119,16 @@ NobleBindings.prototype._onMessage = function(event) {
}
};

NobleBindings.prototype._sendCommand = function(command) {
NobleBindings.prototype._sendCommand = function(command, errorCallback) {
var message = JSON.stringify(command);

this._ws.send(message);
this._ws.send(message, function(error) {
if (error != null) {
console.warn("could not send command", command, error);
if (typeof errorCallback === "function") {
errorCallback(error);
}
}
});
};

NobleBindings.prototype.startScanning = function(serviceUuids, allowDuplicates) {
Expand Down
23 changes: 17 additions & 6 deletions ws-slave.js
Expand Up @@ -25,18 +25,29 @@ if (serverMode) {

ws = ws_;

sendEvent({
type: 'stateChange',
state: noble.state
});

ws.on('message', onMessage);

ws.on('close', function() {
console.log('ws -> close');

noble.stopScanning();
});

noble.on('stateChange', function(state) {
sendEvent({
type: 'stateChange',
state: state
});
});

// Send poweredOn if already in this state.
if (noble.state == "poweredOn") {
sendEvent({
type: 'stateChange',
state: "poweredOn"
});
}


});
} else {
ws = new WebSocket('ws://' + host + ':' + port);
Expand Down

0 comments on commit 3cfb558

Please sign in to comment.