Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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();
fetchCurrent(CITYID, function (current) {
context.current = current;
});
fetchForecast(CITYID, 6, function (forecast) {
context.forecast = forecast;
update(function () {
var pushToClients = function (sock) {
sock.emit('weather', Mustache.render(TEMPLATE, context));
};
io.on('connect', pushToClients);
pushToClients(io);