Skip to content

Instantly share code, notes, and snippets.

@cristian-t
Created September 14, 2015 17:05
Show Gist options
  • Save cristian-t/d84c26f6dfef1a506029 to your computer and use it in GitHub Desktop.
Save cristian-t/d84c26f6dfef1a506029 to your computer and use it in GitHub Desktop.
node-sensortag EventEmitter leak example
var SensorTag = require( "sensortag" );
var EventEmitter = require( "events" );
var tags = {};
var tagCount = 0;
SensorTag.CC2540.SCAN_DUPLICATES = true;
SensorTag.CC2650.SCAN_DUPLICATES = true;
function startDiscover()
{
if( tagCount > 0 ) return;
console.log( "Starting discovery listener..." );
SensorTag.discoverAll( onDiscover );
setTimeout( connectToDiscovered , 5000 );
}
function connectToDiscovered()
{
if( tagCount > 0 )
{
SensorTag.stopDiscoverAll( onDiscover );
for( var id in tags )
{
tags[ id ].connect();
}
}
else
{
console.log( "...nothing found...yet" );
setTimeout( connectToDiscovered , 5000 );
}
}
function onDiscover( tag )
{
if( tags.hasOwnProperty( tag.uuid ) )
{
tags[ tag.uuid ].discoveredCount++;
return;
}
console.log( "Discovered: " + tag.uuid );
tags[ tag.uuid ] = new Tag( tag );
tagCount++;
}
function Tag( tag )
{
this.tag = tag;
this.humidityInterval = null;
this.disconnected = false;
this.discoveredCount = 1;
}
Tag.prototype.log = function( msg ) {
console.log( "[" + this.tag.uuid + "] " + msg );
};
Tag.prototype.connect = function() {
this.log( "Discovered " + this.discoveredCount + " time(s)" );
this.log( "Connecting..." );
var self = this;
this.tag.connectAndSetUp( function( error ) {
if( error )
{
self.log( "Error connecting..." );
return;
}
self.log( "Connected..." );
self.tag.enableHumidity( function( error ) {
if( error )
{
self.log( "Humidity error: " + error );
}
} );
self.humidityInterval = setInterval( self.readHumidity.bind( self ) , 1000 );
self.log( "Disconnect event count (tag): " + self.tag.listeners( "disconnect" ).length );
self.log( "Disconnect event count (tag._peripheral): " + self.tag._peripheral.listeners( "disconnect" ).length );
self.log( "Disconnect event count (tag._peripheral,direct): " + self.tag._peripheral._events.disconnect.length );
} );
this.tag.on( "disconnect" , function() {
if( this.disconnected ) return;
this.disconnected = true;
self.destroy();
} );
};
Tag.prototype.disconnect = function() {
var self = this;
this.tag.disconnect( function() {
self.log( "Disconnected..." );
} );
};
Tag.prototype.destroy = function() {
this.log( "Destroyed..." );
if( this.humidityInterval !== null ) clearInterval( this.humidityInterval );
delete tags[ this.tag.uuid ];
tagCount--;
startDiscover();
};
Tag.prototype.readHumidity = function() {
this.tag.readHumidity( this.humidityCallback.bind( this ) );
};
Tag.prototype.humidityCallback = function( error , temp , hum ) {
if( error ) this.log( "Humidity error: " + error );
else this.log( temp + " " + hum );
};
startDiscover();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment