-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
298 lines (261 loc) · 9.14 KB
/
server.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//required modules
var http = require('http');
var request = require('request');
var schedule = require('node-schedule');
var fs = require('fs');
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var Routine = require('./models/routine');
//bodyparser stuff
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', express.static(__dirname + '/public'));
require('./routes')(app);
exports = app;
//constants
const PORT=8080;
const settings = 'settings.json';
const darkSkyBaseURL = 'https://api.darksky.net/forecast/';
const darkSkyQueryString = '?units=us&language=en&exclude=[minutely,alerts,flags,hourly]';
const dailyQuoteBaseURL = 'http://quotes.rest/qod.json?category=inspire';
const sayCommand = 'http://localhost:5005/master%20room/say/';
//read config. values from settings.json configuration file
var configuration = JSON.parse(
fs.readFileSync(settings)
);
mongoose.Promise = global.Promise;
mongoose.connect(configuration.mongoUrl);
//misc variables
var weatherOutput;
var currentWeather;
var dailyForecast;
var morningPrompt;
var logging = true;
var quoteOutput;
var qotd;
var fullweatherSpeech;
var currentDate = new Date();
var year = currentDate.getFullYear();
var month = currentDate.getMonth();
var day = currentDate.getDate();
var hueBridgeIp;
getHueBridgeIp();
eveningRoutine();
morningRoutine();
frontPorchLightOnRoutine();
frontPorchLightOffRoutine();
addRoutinesFromDB();
app.post('/createRoutine', function (req, res) {
newRoutine(req, res);
res.sendStatus(200);
});
app.post('/deleteRoutine', function (req, res) {
cancelRoutine(req.body.name);
res.sendStatus(200);
});
function newRoutine(req) {
console.log("adding routine to scheduler");
var newRule = new schedule.RecurrenceRule();
var newRuleName = req.body.name;
newRule.dayOfWeek = req.body.dayOfWeek;
newRule.minute = req.body.minute;
newRule.hour = req.body.hour;
schedule.scheduleJob(newRuleName, newRule, function() {
console.log(newRuleName + ' routine just popped, boi!');
if (req.body.message) {
textToSpeech(req.body.message);
}
if (req.body.getWeather) {
getWeather();
}
if (req.body.getQotd) {
getQotd();
}
});
}
function eveningRoutine() {
var eveningRule = new schedule.RecurrenceRule();
eveningRule.dayOfWeek = new schedule.Range(0, 6, 1);
eveningRule.minute = 30;
eveningRule.hour = 8;
var eveningRuleName = 'eveningRoutine';
// var eveningRoutine = schedule.scheduleJob(eveningRuleName, eveningRule, function() {
// console.log("evening routine starting");
// setLights({url: 'http://' + hueBridgeIp + '/api/JFrRiCjcmLRcI8v7RLq1QEpQXZp4UyjXtdjylYyC/lights/1/state/', method: 'PUT', json: {"on":true, "bri":100}});
// playFavorite('sleep');
// setShuffle('on');
// setVolume(15);
// })
}
function frontPorchLightOnRoutine() {
var eveningRule = new schedule.RecurrenceRule();
eveningRule.dayOfWeek = new schedule.Range(0, 6, 1);
eveningRule.minute = 30;
eveningRule.hour = 19;
var eveningRuleName = 'frontPorchLightOnRoutine';
// var eveningRoutine = schedule.scheduleJob(eveningRuleName, eveningRule, function() {
// console.log("turning on front porch light");
// setLights({url: 'http://' + hueBridgeIp + '/api/JFrRiCjcmLRcI8v7RLq1QEpQXZp4UyjXtdjylYyC/lights/2/state/', method: 'PUT', json: {"on":true, "bri":200}});
// })
}
function frontPorchLightOffRoutine() {
var eveningRule = new schedule.RecurrenceRule();
eveningRule.dayOfWeek = new schedule.Range(0, 6, 1);
eveningRule.minute = 30;
eveningRule.hour = 5;
var eveningRuleName = 'frontPorchLightOffRoutine';
// var eveningRoutine = schedule.scheduleJob(eveningRuleName, eveningRule, function() {
// console.log("turning off front porch light");
// setLights({url: 'http://' + hueBridgeIp + '/api/JFrRiCjcmLRcI8v7RLq1QEpQXZp4UyjXtdjylYyC/lights/2/state/', method: 'PUT', json: {"on":false}});
// })
}
function morningRoutine() {
var morningRule = new schedule.RecurrenceRule();
morningRule.dayOfWeek = new schedule.Range(1, 5, 1);
morningRule.minute = 30;
morningRule.hour = 5;
var morningRuleName = 'morningRoutine';
// var morningRoutine = schedule.scheduleJob(morningRuleName, morningRule, function() {
// console.log("morning routine starting");
// setLights({url: 'http://' + hueBridgeIp + '/api/JFrRiCjcmLRcI8v7RLq1QEpQXZp4UyjXtdjylYyC/lights/1/state/', method: 'PUT', json: {"on":true, "bri":254}});
// playFavorite('starred');
// setShuffle('on');
// setVolume(20);
// })
}
function setShuffle(setting) {
request('http://localhost:5005/master%20room/shuffle/' + setting, function (error, response, body) {
if (handleResponse(error, response, body)) {
console.log("successfully set shuffle");
}
})
}
function setVolume(setting) {
request('http://localhost:5005/master%20room/volume/' + setting, function (error, response, body) {
if (handleResponse(error, response, body)) {
console.log("successfully set volume to " + setting + ' on sonos');
}
})
}
function playFavorite(playlist) {
request('http://localhost:5005/master%20room/favorite/' + playlist, function (error, response, body) {
if (handleResponse(error, response, body)) {
console.log("successfully started " + playlist + " playlist.");
}
})
}
function textToSpeech(text) {
request(sayCommand + encodeURIComponent(text), function (error, response, body) {
if (handleResponse(error, response, body)) {
console.log("successfully sent text to sonos");
}
})
}
function setLights(settings) {
request(settings, function(error, response, body) {
if (handleResponse(error, response, body)) {
console.log('successfully set lights');
}
})
}
function getWeather() {
var requestURL = darkSkyBaseURL + configuration.darksky + '/' + configuration.latitude + ',' + configuration.longitude + darkSkyQueryString;
//sending request to darksky api to get weather information
console.log("getting weather");
console.log("Hitting API for weather: " + requestURL);
request(requestURL, function (error, response, body) {
if (handleResponse(error, response, body)) {
var currentDateUNIX = new Date(year, month, day).getTime() / 1000;
console.log("current UNIX time " + currentDateUNIX);
weatherOutput = JSON.parse(body);
var daily = weatherOutput.daily.data;
for (var i = 0; i < daily.length; i++) {
if (daily[i].time === currentDateUNIX) {
console.log("found the proper daily routine");
console.log(' daily weather ' + weatherOutput.daily);
currentWeather = 'Current weather is ' + weatherOutput.currently.summary + '. Weekly weather is ' + weatherOutput.daily.summary + '. Temperature is ' + weatherOutput.currently.temperature + '. Precipitation chance is ' + weatherOutput.currently.precipProbability + '.';
dailyForecast = "The daily Forecast is " + daily[i].summary;
textToSpeech(currentWeather + ' ' + dailyForecast);
break;
}
}
}
})
}
function getQotd() {
//sending request to get a daily quote
console.log("getting qotd");
console.log("Hitting PI for qotd: " + dailyQuoteBaseURL);
request(dailyQuoteBaseURL, function (error, response, body) {
if (handleResponse(error, response, body)) {
quoteOutput = JSON.parse(body);
//get first quote in array passed back
qotd = 'quote of the day is by: ' + quoteOutput.contents.quotes[0].author + '. It is: ' + quoteOutput.contents.quotes[0].quote;
textToSpeech(qotd);
}
})
}
function addRoutinesFromDB() {
Routine.find(function(err, routines) {
if (err) {
res.send(err);
} else {
for (var i = 0; i < routines.length;i++) {
//todo convert this to a more generic method that can be used by newRoutine(req);
var newRule = new schedule.RecurrenceRule();
newRule.dayOfWeek = routines[i].dayOfWeek;
newRule.minute = routines[i].minute;
newRule.hour = routines[i].hour;
var message = routines[i].message;
var weather = routines[i].getWeather;
var qotd = routines[i].getQotd;
var name = routines[i].name;
schedule.scheduleJob(name, newRule, function(message, weather, qotd, name) {
console.log(name + ' routine just popped, boi!');
if (message) {
textToSpeech(message);
}
if (weather) {
getWeather();
}
if (qotd) {
getQotd();
}
}.bind(null, message, weather, qotd, name));
}
}
})
}
function getHueBridgeIp() {
request('https://www.meethue.com/api/nupnp', function (error, response, body) {
console.log("looking for hueBridgeIp...");
if (handleResponse(error, response, body)) {
var json = JSON.parse(body);
hueBridgeIp = json[0].internalipaddress;
console.log('hue ip is ' + hueBridgeIp);
}
})
}
function cancelRoutine(routineName) {
var jobs = schedule.scheduledJobs;
console.log("entering cancelling job ");
for(var i in jobs)
{
console.log(jobs[i].name);
if (jobs[i].name == routineName) {
console.log("cancelling job " + jobs[i].name);
jobs[i].cancel();
break;
}
}
}
app.listen(PORT);
function handleResponse(error, response, body) {
if (!error && response.statusCode == 200 && logging) {
console.log(body);
return true;
}
}