
function RJ45_driverController () {

	if(arguments.callee._singletonInstance){
	    return arguments.callee._singletonInstance;
	}
	arguments.callee._singletonInstance = this;

	var self = this; self.name = "RJ45_driverController"; // MANDATORY

    this.init = function ( platform, architecture ) {
        if ( !self.tcpPort ){
			self.tcpPortName = 'net';
            self.tcpPort = require (self.tcpPortName);
        }
    }

    this.tcpPortName = "";
    this.tcpPort = false;
	this.port = false;
	this.portConnect = false;

	this.queue = [];
    this.busy = false;
    this.step = 0;
    this.currentAction = null;

    this.checkTstamp = new Date().getTime();

    this.shutdownPortTimer = null;
    this.shutDownPortTimeout = 2000;

    this.validationTimer = null;
    this.validationTimeout = 2000;


    this.writeTimer = null;
    this.writeTimeout1 = 300;
    this.writeTimeout2 = 500;

	this.processQueueTimer = null;
	this.processQueueTimeout = 500;

	this.processStepTimer = null;
	this.processStepTimeout = 500

	this.processCommandTimer = null;
	this.processCommandTimeout = 500;


    this.resetCounter = 0;
    this.resetCounterMax = 5;
    this.resetTimeout = 5000;


    /*********************************** ACCES FUNCTIONS ***********************************/
    this.send = function ( command, port, callback) {
        //TODO proces msg
        self.queue.push([[command, port, callback]]);
        if (self.busy) return;
        self.busy = true;
        processQueue();
    }

    this.sendArray = function ( commandArray, portArray, callbackArray){
    	//TODO
    	var finalCommand = [];
    	for ( var i = 0; i < commandArray.length; i++ ){
    		finalCommand [i] = [ commandArray[i], portArray[i], callbackArray[i] ]
    	}
        self.queue.push( finalCommand );
        if (self.busy) return;
        self.busy = true;
        processQueue();
    }

    this.sendPriority = function ( command, port, callback) {
        //TODO proces msg
        self.queue.unshift([[command, port, callback]]);
        if (self.busy) return;
        self.busy = true;
        processQueue();
    }

    this.sendPriorityArray = function ( commandArray, portArray, callbackArray){
        //TODO
        var finalCommand = [];
        for ( var i = 0; i < commandArray.length; i++ ){
            finalCommand [i] = [ commandArray[i], portArray[i], callbackArray[i] ]
        }
        self.queue.unshift( finalCommand );
        if (self.busy) return;
        self.busy = true;
        processQueue();
    }

    // Private functions can exist in the closure too; they can see the state but
    // outsiders can't touch them

    //function private() { ... }
    /*********************************** QUEUE FUNCTION ***********************************/
    function processQueue (){
    	//console.log("Validation: " + "processQueue")
    	self.step = 0;
        var next = self.queue.shift();
        if (!next) {
            self.busy = false;
            return;
        }
        //console.log ( "Pending Comands : " + self.queue.length)
        self.currentAction = next;

        processCommand();
    }

    function processStep () {
    	self.step ++;
    	processCommand ();
    }

    function processCommand () {
    	//console.log("Validation: " + "processCommand")
    	self.checkTstamp = new Date().getTime();
    	if ( self.port ) //console.log ( "Port status: " + self.port.isOpen() )
    	if ( self.port && self.portConnect){
    		self.port.destroy();
    		clearTimeouts ();
            self.processQueueTimer = setTimeout (processCommand, self.processCommandTimeout);
    		return;
    	}
    	clearTimeouts ();
    	self.shutdownPortTimer = setTimeout (shutDownPort, self.shutDownPortTimeout);
        try {
        	//self.currentAction[self.step][1].config.parser = loadParser (self.currentAction[self.step][1].parser.type, self.currentAction[self.step][1].parser.delimiter )
			self.port = new self.tcpPort.Socket();
			//self.currentAction[self.step][1].name
        }catch ( err ){
			console.debug(err)
        	try {
            	clearTimeouts ();
    			self.validationTimer = setTimeout (validationFail, self.validationTimeout);
            	self.currentAction[self.step][2](err, null, self.checkTstamp, validation); //calback (error, data)
            }catch ( error ){
            }
        	return;
        }

        loadCallbacks ();
		self.port.connect(self.currentAction[self.step][1].port, self.currentAction[self.step][1].name);
    };


    /*********************************** WRITING FUNCTIONS ***********************************/

    function writeOnPort() {
    	clearTimeout ( self.shutdownPortTimer );
    	self.shutdownPortTimer = setTimeout (shutDownPort, self.shutDownPortTimeout);
		//var buffer = new Buffer([0xAA, 0x11, 0x01, 0x00, 0x12]);
		self.port.write( self.currentAction[self.step][0], function() {
		});
    }

    this.retry = 0;
    function retryWriteOnPort () {
    	/*if ( self.retry < 3 ){
    		self.retry++;
    		clearTimeout ( self.writeTimer );
            self.writeTimer = setTimeout ( writeOnPort, self.writeTimeout2 );
    	}else {
    		try {
    			clearTimeouts ();
    			self.validationTimer = setTimeout (validationFail, self.validationTimeout);
            	self.currentAction[self.step][2](new Error("Out of retries"), null, self.checkTstamp, validation); //calback (error, data)
            }catch ( error ){
            }
            if ( self.port.isOpen() ){
                self.port.close();
            }
    	}*/
    }

    /*********************************** PARSER FUNCTION ***********************************/

    function loadParser ( type, delimiter ) {
        switch (type){
            case 'readline':
                return self.serialPort.parsers.readline(delimiter)
                break;
            case 'byteDelimiter':
            	return self.serialPort.parsers.byteDelimiter(delimiter)
                break;
            case 'byteLength':
            	return self.serialPort.parsers.byteLength(delimiter)
                break;
            case 'customSerialParser':
            	return delimiter();
                break;
            default :
            	return self.serialPort.parsers.raw
                break;
        }
    }


    /*********************************** DRIVER FUNCTIONS ***********************************/
    function loadCallbacks (){
		self.port.on('connect', function() {
		    console.debug('connected!');
			self.portConnect = true;
			clearTimeout ( self.writeTimer );
			self.writeTimer = setTimeout ( writeOnPort, self.writeTimeout1 );

		});

		self.port.on('data', function(data) {
			data = Buffer.from(data);
            //console.log ( new Date() + ' - Data on RS232, port: '+ self.currentAction[self.step][1].name + " : \n\t\t\t\t\t\t" + data + "\n\t\t\t\t\tEnd data ");
            if (!self.currentAction) return;
            try {
            	clearTimeouts ();
    			self.validationTimer = setTimeout (validationFail, self.validationTimeout);
            	self.currentAction[self.step][2](null, data, self.checkTstamp, validation); //calback (error, data)
            }catch ( error ){
            }
            if ( self.portConnect ){
                self.port.destroy();
            }
		    //console.log(Buffer.from(data, "hex").toString());
		});

		self.port.on('error', function(err) {
		    console.debug('err from SAMSUNG_RJ45');
			try {
            	clearTimeouts ();
    			self.validationTimer = setTimeout (validationFail, self.validationTimeout);
            	self.currentAction[self.step][2](err, null, self.checkTstamp, validation); //calback (error, data)
            }catch ( error ){
            }
            if ( self.portConnect ){
                self.port.destroy();
            }
		});

		self.port.on('end', function() {
		    console.debug('disconnected from SAMSUNG_RJ45');
		    self.portConnect = false;
		});
		self.port.on('close', function() {
		    console.debug('close from SAMSUNG_RJ45');
		    self.portConnect = false;
		});
		self.port.on('timeout', function() {
		    console.debug('timeout from SAMSUNG_RJ45')
		    self.portConnect = false;
		});
    }

    function shutDownPort (){
    	clearTimeout ( self.shutdownPortTimer );
    	try {
    		clearTimeouts ();
			self.validationTimer = setTimeout (validationFail, self.validationTimeout);
        	self.currentAction[self.step][2](new Error("Forced Time out"), null, self.checkTstamp, validation); //calback (error, data)
    	}catch ( error ){
        }
		if ( self.portConnect ){
			self.port.destroy();
		}
    }

    /*********************************** RESPONSE FUNCTIONS ***********************************/

    function validation ( action, sendCheckTstamp, callback ){
        //clearTimeout ( self.validationTimer );
    	//console.log("Validation: " + sendCheckTstamp + ", " + action);
    	//console.log ("Validation: " + self.currentAction[self.step][0] )
    	if (sendCheckTstamp == self.checkTstamp ){
    		if ( action == "next"){
				if ( self.portConnect ){
	                self.port.destroy();
	            }
                //console.log("Validation: " + "executeNext")
    	    	self.checkTstamp = new Date().getTime();
    	    	self.writeRetry = 0;
    	    	clearTimeouts();
    			self.processQueueTimer = setTimeout (processQueue, self.processQueueTimeout);
    		}else if (action == "step"){
				if ( self.portConnect ){
	                self.port.destroy();
	            }
    	    	self.checkTstamp = new Date().getTime();
    	    	self.writeRetry = 0;
    			clearTimeouts();
    			self.processStepTimer = setTimeout (processStep, self.processStepTimeout);
    		}else if (action == "retry"){
				if ( self.portConnect ){
	                self.port.destroy();
	            }
    	    	self.checkTstamp = new Date().getTime();
    	    	self.writeRetry = 0;
    			clearTimeouts();
    			self.processCommandTimer = setTimeout (processCommand, self.processCommandTimeout);
    		}else{
    			//console.log ( "Validation: error in action, consider fail.")
    			clearTimeouts ();
    			validationFail();
    		}
    	}
		else {
    		if (action != "next"){
    			callback ();
    		}
    	}
	}

	function validationFail (){
		//console.log("Validation Fail: " + self.checkTstamp);
    	//console.log ("Validation: " + self.currentAction[self.step][0] )
    	self.checkTstamp = new Date().getTime();
    	self.writeRetry = 0;
    	clearTimeouts();
    	self.processQueueTimer = setTimeout (processQueue, self.processQueueTimeout);
    }

	function clearTimeouts () {
		//console.log("Validation: " + "timeouts start")
    	clearTimeout ( self.shutdownPortTimer );
    	clearTimeout ( self.validationTimer );
    	clearTimeout ( self.writeTimer );
    	clearTimeout ( self.processQueueTimer );
    	clearTimeout ( self.processStepTimer );
    	clearTimeout ( self.processCommandTimer );
    	//console.log("Validation: " + "timeouts end")
    	return;
    }

    /*********************************** CACHE FUNCTIONS ***********************************/
    /**
     * Removes a module from the cache
     */
    function purgeCache(moduleName) {
        // Traverse the cache looking for the files
        // loaded by the specified module name
        searchCache(moduleName, function (mod) {
            delete require.cache[mod.id];
        });

        // Remove cached paths to the module.
        // Thanks to @bentael for pointing this out.
        Object.keys(module.constructor._pathCache).forEach(function(cacheKey) {
            if (cacheKey.indexOf(moduleName)>0) {
                delete module.constructor._pathCache[cacheKey];
            }
        });
    };

    /**
     * Traverses the cache to search for all the cached
     * files of the specified module name
     */
    function searchCache(moduleName, callback) {
        // Resolve the module identified by the specified name
        var mod = require.resolve(moduleName);

        // Check if the module has been resolved and found within
        // the cache
        if (mod && ((mod = require.cache[mod]) !== undefined)) {
            // Recursively go over the results
            (function traverse(mod) {
                // Go over each of the module's children and
                // traverse them
                mod.children.forEach(function (child) {
                    traverse(child);
                });

                // Call the specified callback providing the
                // found cached module
                callback(mod);
            }(mod));
        }
    };
}
