view nodescore.js @ 54:66bf613fb818

pre clean up push - moved vars into scoreB.js - called up with requirejs added requirejs dep
author tzara <rc-web@kiben.net>
date Wed, 19 Dec 2012 13:36:19 +0000
parents a0ae699ac444
children 474c1ad1e811
line wrap: on
line source
/*
////////////////////////////////////////////

nodescore server
nodescore.kiben.net
nodescore@kiben.net

////////////////////////////////////////////
*/

var sio = require('socket.io')
, http = require('http')
, ch = require('chronometer')
, fs = require('fs')
, static = require('node-static');

var requirejs = require('requirejs');

requirejs.config({
    //Pass the top-level main.js/index.js require
    //function to requirejs so that node modules
    //are loaded relative to the top-level JS file.
    nodeRequire: require,
    findNestedDependencies: true

});

// run webserver serving static html
////////////////////////////////////////////
var clientFiles = new static.Server('/usr/share/nodescore/www');
var httpServer = http.createServer(
    function(request, response) {
	request.addListener('end', function () {
	    clientFiles.serve(request, response);	    
	    process.setMaxListeners(0);
	});    
    });

httpServer.listen(8889);

var pinging=0
console.log("ping set to 0")

//requirejs(['socketsstuff'],function(socketsstuff) {});


////////////////////////////////////////////
// connect to websockets 
////////////////////////////////////////////

io = sio.listen(httpServer)
, nicknames = {};

//var sequencer = require('./sequencer')

io.set('log level', 1); // reduce logging
io.sockets.on('connection', function (socket) {

    socket.on('nickname', function (nick, fn) {
	if (nicknames[nick]) {
	    fn(true);
	} else {
	    fn(false);
	    nicknames[nick] = socket.nickname = nick;
	    socket.broadcast.emit('announcement', nick + ' connected');
	    io.sockets.emit('nicknames', nicknames);
	}
    });  

    /// chat user messages to screens and to log file
    // date format for filename

    var da = new Date(); var dtstring = da.getFullYear()+ '-' + da.getMonth()+ '-' + da.getDate();

    ////////////////////////
    /// log messages to file
    socket.on('user message', function (msg) {
	fs.open('logs/chatlog-'+dtstring+'.txt', 'a', 666, function( e, id ) {	
	    //time format for message stamp
	    var dt = new Date();var timestring = dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds();
	    
	    socket.broadcast.emit('user message', socket.nickname, msg);
	    
	    var fs = require('fs'), str = msg;
	    fs.write( id, timestring+" " + socket.nickname + ": "+ msg+"\n", null, 'utf8', function(){});
	});	
    });
  
//  /*
    ////////////////////////////////////////////
    // chronometer + sequencer controls (all this should be modularised)
    ////////////////////////////////////////////

    socket.on('stopWatch', function (state) { stopWatch(state);});
    socket.on('stopChr', function () { stopChr();});    
    socket.on('resetChr', function () { resetChr();});
    socket.on('startSeq', function () { startChr();});  
    var chronstate=0;

    // send the date/time every second

    xdatetime =  setInterval(function () {
	d =  ch.xdateTime()
	socket.broadcast.emit('dateTime', d)
	socket.emit('dateTime', d)	
    }, 1000)
    
    
    // if not already started start the chronometer and sequencer    
    function startChr(socket) { if (chronstate !== 1) { 
	chronstate = 1; 
	chronCtrl(1,100);
	step(seqA);step(seqB); step(seqC); step(seqD);	    
    } 
			      }
     
    // if not already started start the chronometer    
    function stopWatch(state) { if (chronstate !== 1) {
	if (state==1){
	    chronstate = 1; 
	    chronCtrl(1,100);}
    }
				
				// if get 0 then stop the chron
				if (state==0){
				    chronstate = 0; 
				    clearInterval(xstopwatch);
				}
				// if get 2 then reset the chron
				if (state==2){
				    chronstate = 0; 
				    c=ch.zeroChron()
				    socket.broadcast.emit('chronFromServer', c)
				    socket.emit('chronFromServer', c)
				}
			      } 


//////////////////////////////
//    /* this should be moved to its own file chronometer.js

    function chronCtrl (state,interval){
	console.log("=========================== chronstate=" + chronstate)
	if (state==1){
	    var date = new Date()
	    var starttime = new Date().getTime() / 1000;
	    //var interval = 1020 - date.getMilliseconds();
	    xstopwatch =  setInterval(function () {
		var nowtime = new Date().getTime() / 1000;
		now = nowtime-starttime
		hours = parseInt( now / 3600 ) % 24;
		minutes = parseInt( now / 60 ) % 60;
		seconds = parseInt(now  % 60);
		milliseconds = Math.floor((now-seconds)*10)%60;
		time = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds) + "."+milliseconds;
		//console.log(time)
		socket.broadcast.emit('chronFromServer', time)
		socket.emit('chronFromServer', time)
	    }, 100)
    }
	if (state==0) {
	    clearInterval(xstopwatch);
	     }	
    }
//*/

    // stop the chronometer   

    function stopChr() {console.log("stop chron................................................")
			chronCtrl(0)
			chronstate=0
		       }  

    function pad(number) { return (number < 10 ? '0' : '') + number }
    function resetChr() {//clearInterval();
	chronstate = 0;
	zecsec = 0; seconds = 0; 
	mins = 0; hours = 0; 
	chronstate = 0; 
	var chron = pad(hours) +":"+pad(mins)+ ':'+ pad(seconds)+ ":"+ zecsec
	// send 0.0.0 values to display
	socket.broadcast.emit('chronFromServer', chron)
	socket.emit('chronFromServer', chron)
    }


    ////////////////////////////////////////////
    // magic square sequencer (this should be modularised)
    ////////////////////////////////////////////
    
    // all the variables this sequencer needs are in scoreB.js

    requirejs(['scoreB'],function(scoreB) {});

    var sequencerState = 0;
    var countdowntick = function(seq){

	 // var tempoms = Math.floor(60000/seq.mm)
	 var tempoms = Math.floor(60000/seq.mm)
	 
	 var timemultiplier=1000
	 var outcount = 4; var incount=4;
	 var time = ((seq.durations[seq.counter]+1) *timemultiplier) + 30000 + (outcount*tempoms);
	 var time = Math.floor(time)
	 var ztime = time; 
	 var totaltime = Math.floor(time/tempoms)
	 var unit = seq.units[seq.counter];
	 var voice = seq.voice;
	 console.log(time)
	 // initiate first page here
	 socket.broadcast.emit("pageFlipfromserver", voice, unit, time, seq.mm,seq.counter);
	 socket.emit("pageFlipfromserver", voice, unit, time, seq.mm,seq.counter);
	 
	 function sequenCer() {
	     //    console.log(ztime)
	     if (ztime >= 0 ){
		 
		// basic unit is still the second/1000ms - change this to tempoms? no i dont think so
		// count in and count out
		////////////////////////////////////////////
		
		 var counter = Math.floor(ztime/tempoms)
		 //console.log(counter)
		 if (counter >= 0 ){
		     socket.broadcast.emit('counterText', voice, seq.counter, counter);
		     socket.emit('counterText', voice, seq.counter, counter);
		     
		     if (counter <= outcount ) {              
			 socket.broadcast.emit('countinFromServer', voice, counter, "","stop in: ", "red", "transparent");
		     }
		     
		     if (counter > (totaltime)-incount  && counter <= totaltime ) {
			 socket.broadcast.emit('countinFromServer', voice, counter-(totaltime-incount), "","play in: ", "green","transparent");
			 socket.emit('countinFromServer', voice, counter-(totaltime-incount), "","play in: ", "green","transparent");
		     }
		     
		     if (counter == (totaltime)-incount ) {
			 socket.broadcast.emit('countinFromServer', voice, "+", "","playing.. ", "green","transparent");
			socket.emit('countinFromServer', voice, "+", "","playing.. ", "green","transparent");
		     }
		     
		     // remove displayed number with " " at end of both countin/out
		     
		     if (counter == 0 ) {
			 socket.broadcast.emit('countinFromServer', voice, "", "","", "green","transparent");
			 socket.broadcast.emit('counterText', voice, seq.counter, "");
			 socket.emit('counterText', voice, seq.counter, "");
		     }
		 }		    
				
		 // on each beat do:
		 

		 // push out the pulse to metronome	
		 seq.metrobeat = (seq.metrobeat+1)%seq.beatsinbar ;
     		 socket.broadcast.emit('metroPulse', tempoms, voice,seq.metrobeat); 
		 socket.emit('metroPulse', tempoms, voice,seq.metrobeat);
	     }
	     
	     // flip the page 
	     if (counter == 0){
		 seq.counter = (seq.counter + 1) % seq.durations.length	    		
		socket.broadcast.emit("pageFlipfromserver", voice, unit, time, seq.mm,seq.counter);
		 //delete tockTock;	
		 step(seq);     
	     }
	     
	     // decrement the time 
	     ztime -= tempoms
	 }
	 
	 var pulse = setInterval(sequenCer, tempoms);
	 
	 socket.on('stopSeq', function () {
	     //donaldduck = mickeymouse + 7
	     sequenCer.clearInterval
	     console.log("sequencer stopping...")	    
	     // grrr why wont this clearInterval work
	     sequencerState = 0
	     clearInterval(pulse)
	     stopChr();
	 });
     };

    step = function (seq) {
	//clearInterval(seq.boo);
	clearInterval(countdowntick);
	countdowntick(seq)
	sequencerState=1;
    };
  
    socket.on('resetSeq', function () { 
	console.log("reset")
	resetChr();		
    });

    
    ////////////////////////////////////////////  
    // some latency calculations
    ///////////////////////////////////////////
    
    /*
      a ping is periodically broadcast to all connected clients each
      connected returns a pong to the server via an "emit" and in turn
      the server returns each unique client a report of the latency
      via another emit - the emit only sends to the source of the
      request, whereas the broadcast.emit..  broadcasts.. ie to all
      connected clients
      
      TODO: smooth range and average out results to remove erratic ping
      times.

      TODO:
      The result then needs to be used to stagger outgoing messages to
      compensate for latency - how much compensation is more connected
      to the time that any audio/video feed needs to encode/decode as
      the latency of the route from node A to node B is inavoidable?!
      so maybe latency is irrelevant in this context - we just need to
      stagger signals according to encoding decoding times.. hmmm
    */


// periodically broadcast a ping
    function serverTime(freq) {
	if (pinging==0){ st = setInterval(function() {
	    var pinging=1;
	    var d = new Date(); var n = d.getTime(); 
	    socket.emit("timeFromServer", n); 
	}, 1000);   } else console.log("already pinging")
    }
    // receive the pong calculate the latency and
    // return the response to the client

    socket.on("clientTimeResponse", function(x) {
	var d = new Date(); var n = d.getTime();
	var latency = (n-x)/2;
	//console.log("SERVERTIME:"+x + " LATENCY:" + latency);
	socket.emit("latencyFromServer", latency);
    });	      
    
    // this is the trigger from the control client to start the process
    // maybe remove this and have latency connections constantly running
    
    /*
      socket.on("getLatencies", function(x){
      serverTime(x);
      });
    */
    
    serverTime(1000);
    
    socket.on('disconnect', function(client) {	
	console.log(socket.nickname + " is gone..." )
	clearInterval(st);
	
	if (!socket.nickname) return;
	
	delete nicknames[socket.nickname];
	socket.broadcast.emit('announcement', socket.nickname + ' disconnected');
	socket.broadcast.emit('nicknames', nicknames);
    });


});
//});
//exports.io = io;
//exports.sio = sio;
exports.socket= io.sockets;
exports.httpServer = httpServer;