Add local weather caching mechanism

This commit is contained in:
Samer Albahra
2015-07-02 19:19:56 -05:00
parent 199399ff5e
commit 66b4d1ccbd
6 changed files with 122 additions and 24 deletions

View File

@@ -1,12 +1,23 @@
var express = require( "express" ),
weather = require( "./routes/weather.js" ),
port = process.env.PORT || 3000;
app = express();
var express = require( "express" ),
weather = require( "./routes/weather.js" ),
mongoose = require( "mongoose" ),
Cache = require( "./models/Cache" ),
CronJob = require( "cron" ).CronJob,
port = process.env.PORT || 3000;
app = express();
if ( !process.env.PORT ) {
require( "dotenv" ).load();
}
// Connect to local MongoDB instance
mongoose.connect( "localhost" );
// If the database connection cannot be established, throw an error
mongoose.connection.on( "error", function() {
console.error( "MongoDB Connection Error. Please make sure that MongoDB is running." );
} );
// Handle requests matching /weatherID.py where ID corresponds to the
// weather adjustment method selector.
// This endpoint is considered deprecated and supported for prior firmware
@@ -23,3 +34,29 @@ var server = app.listen( port, "127.0.0.1", function() {
console.log( "OpenSprinkler Weather Service now listening on port %s", port );
} );
// Schedule a cronjob daily to consildate the weather cache data, runs daily
new CronJob( "0 * * * * *", function() {
// Find all records in the weather cache
Cache.find( {}, function( err, records ) {
// Cycle through each record
records.forEach( function( record ){
// If the record contains any unaveraged data, then process the record
if ( record.currentHumidityCount > 0 ) {
// Average the humidity by dividing the total over the total data points collected
record.yesterdayHumidity = record.currentHumidityTotal / record.currentHumidityCount;
// Reset the current humidity data for the new day
record.currentHumidityTotal = 0;
record.currentHumidityCount = 0;
// Save the record in the database
record.save();
}
} );
} );
}, null, true, "UTC" );