var MSSQL = require( 'mssql/msnodesqlv8' );
var isSQLConnected = '';
function Scales( IP, PORT )
{
//console.log( "hey: " + MSSQL );
//
this.Socket = new require( 'net' ).Socket();
this.SQL = MSSQL;
//
this.liveSQLConfig = {
};
this.localSQLConfig = {
};
this.SQLConfig = '';
//
this.devEnvironment = "live";
this.routerIP = IP;
this.routerPORT = PORT;
this.Weight = "0.0kg";
this.Timeout = 10000;
// this.connectedToRouter = false;
this.cachedWeightValue = 0;
this.reconnectOnError = true;
this.recursiveTimerRef = null;
this.closeConnectionOnFirstDataReceive = false;
this.printValueToConsole = true;
this.isSQLConnected = false;
}
Scales.prototype = {
constructor: Scales,
Init: function()
{
if ( this.devEnvironment == "live" )
{
this.SQLConfig = this.liveSQLConfig;
}
else
{
this.SQLConfig = this.localSQLConfig;
}
if ( !this.reconnectOnError )
{
console.log( 'Reconnecting...' );
}
//
this.Socket.on( 'error', function()
{
ME.onErrorEventHandler();
} );
return this;
},
Process: function()
{
ME = this;
//console.log( 'CONNECTED TO: ' + ME.routerIP );
this.Socket.connect( this.routerPORT, this.routerIP, function()
{
clearTimeout( ME.recursiveTimerRef ); // once connected timer should be cleared
ME.reconnectOnError = true; //once connected it should be allowed to execute onErrorEventHandler if error occurs and connection breaks
console.log( 'CONNECTED TO: ' + ME.routerIP + ':' + ME.routerPORT );
ME.Socket.on( 'data', function( data )
{
if ( ME.isSQLConnected == false )
{
ME.isSQLConnected = true;
console.log( 'Connecting to SQL...' );
ME.SQL.connect( ME.SQLConfig, function( err )
{
if ( err )
{
console.log( 'SQL: ' + err );
}
else
{
console.log( 'SQL Connection Successful...' );
ME.onDataEventHandler( data );
};
} );
} //
} );
} );
},
connectToSQLServer: function()
{
//
},
onDataEventHandler: function( data )
{
//console.log( this.routerIP );
this.Weight = data.toString().trim().replace( /\s/g, '' ).replace( /US/g, '' ).replace( /ST/g, '' ).replace( /GS/g, '' ).replace( /,/g, '' ).replace( /GS/g, '' ).replace( /-/g, '' );
if ( this.printValueToConsole )
{
console.log( this.routerIP );
}
if ( this.Weight != this.cachedWeightValue && this.Weight.length <= 10 )
{
if ( this.printValueToConsole )
{
console.log( this.Weight );
this.printValueToConsole = false;
}
this.cachedWeightValue = this.Weight;
}
// Close the client socket completely
if ( this.closeConnectionOnFirstDataReceive ) //if want to perform something/check/test ONLY on the very first string we receive
{
this.Socket.destroy();
}
}
}
module.exports = Scales;