var httpreq = require('httpreq'); var fs = require('fs'); var Mustache = require('mustache'); ///CONFIG var APPID = "fdc3690e6f9a7572128fe4012b4a2500" var CITYID = "2945024" /// STATICS var directions = {NNE:11.25,NE:33.75,ENE:56.25,E:78.75,ESE:101.25,SE:123.75,SSE:146.25,S:168.75,SSW:191.25,SW:213.75,WSW:236.25,W:258.75,WNW:281.25,NW:303.75,NNW:326.25,N:348.75} var iconBaseURL = 'http://openweathermap.org/img/w/'; var TEMPLATE = ''; fs.readFile('modules/weather/template.mustache', 'utf-8', function (err, data) { TEMPLATE = data; }); function pad(n, width, z) { z = z || '0'; n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; } function fetchCurrent (cityid, cb) { var url = "http://api.openweathermap.org/data/2.5/weather?units=metric&id="+cityid+"&appid="+APPID; httpreq.get(url, function (err, res) { var dat = JSON.parse(res.body); cb({ temp: dat.main.temp, wind: {speed: dat.wind.speed, dir: degToDirection(dat.wind.deg)}, pressure: dat.main.pressure, humidity: dat.main.humidity, main: dat.weather[0].main, desc: dat.weather[0].description, icon: iconBaseURL+dat.weather[0].icon+'.png' }); }); } function fetchForecast (cityid, count, cb) { var url = "http://api.openweathermap.org/data/2.5/forecast?units=metric&id="+cityid+"&appid="+APPID; httpreq.get(url, function (err, res) { var dat = JSON.parse(res.body).list.slice(0,count); cb(dat.map(function (d) { var date = new Date(d.dt*1000); return { time: pad(date.getHours(),2)+':'+pad(date.getMinutes(),2), temp: d.main.temp, wind: {speed: d.wind.speed, dir: degToDirection(d.wind.deg)}, main: d.weather[0].main, desc: d.weather[0].description, icon: iconBaseURL+d.weather[0].icon+'.png' } })); }); } function degToDirection(deg) { var dir = 'N'; for (i in directions) { if (deg > directions[i]) { dir = i; } } return dir; } module.exports = function (io) { var context = {}; var update = function (firstUpdateCb) { var then = function () { if (context.current && context.forecast) { firstUpdateCb(); then = function () {} } }; fetchCurrent(CITYID, function (current) { context.current = current; then(); }); fetchForecast(CITYID, 6, function (forecast) { context.forecast = forecast; then(); }); }; update(function () { var pushToClients = function (sock) { sock.emit('weather', Mustache.render(TEMPLATE, context)); }; io.on('connect', pushToClients); pushToClients(io); }); setInterval(update, 10*60*1000); }