@@ -3,13 +3,13 @@ var io = require('socket.io').listen(app, {
33 'log level' : 1
44} ) ;
55var fs = require ( 'fs' ) ;
6-
6+
77app . listen ( 8500 ) ;
8-
8+ console . log ( 'listening on port 8500' ) ;
99
1010// server web pages
1111function handler ( req , res ) {
12- console . log ( 'Connection from %j ' , req . connection . remoteAddress ) ;
12+ console . log ( 'connection %j %s %s ' , req . connection . remoteAddress , req . method , req . url ) ;
1313 fs . readFile ( __dirname + '/index.html' ,
1414 function ( err , data ) {
1515 if ( err ) {
@@ -24,21 +24,31 @@ function handler (req, res) {
2424
2525// for each client connection, subscribe to mqtt and push updates
2626io . sockets . on ( 'connection' , function ( socket ) {
27-
2827 var mqtt = require ( 'mqtt' ) ;
2928 var client = mqtt . createClient ( 1883 , 'localhost' , function ( err , client ) {
3029 keepalive: 1000
3130 } ) ;
31+ // set of per client local variables
32+ var powercumulative = 0 ;
33+ var powerlasttime = new Date ( ) . getTime ( ) ; // UNIX time in ms
3234
3335 client . on ( 'connect' , function ( ) {
3436 client . subscribe ( 'sensors/+/+' ) ;
3537
3638 client . on ( 'message' , function ( topic , message ) {
37- console . log ( 'topic: ' + topic + ' payload: ' + message ) ;
38- socket . broadcast . emit ( 'data' , { topic : topic , value : message } ) ;
39+ // console.log('topic: ' + topic + ' payload: ' + message);
40+ socket . emit ( 'data' , { topic : topic , value : message } ) ;
41+ if ( topic == "sensors/power/0" ) {
42+ var powercurrenttime = new Date ( ) . getTime ( ) ;
43+ var duration = ( powercurrenttime - powerlasttime ) / 1000.0 ;
44+ var powerused = parseInt ( message , 10 ) * ( duration / 3600.0 ) ;
45+ powercumulative += powerused ;
46+ // console.log("duration ", duration, "powerused ", powerused, "cumulative ", powercumulative);
47+ socket . emit ( 'data' , { topic : "powercumulative" , value : powercumulative . toFixed ( 3 ) } ) ;
48+ powerlasttime = powercurrenttime ;
49+ }
3950 } ) ;
4051 } ) ;
41-
4252} ) ;
4353
4454
0 commit comments