-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
93 lines (79 loc) · 2.6 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
var express = require('express');
var morgan = require('morgan');
var compress = require('compression');
var bodyParser = require('body-parser');
var app = express();
var spawn = require('child_process').spawn;
var child = spawn('sudo', ['node', 'sensor.js' ]);
var TermostatModel = require('./js/models/termostat');
var mongoose = require('mongoose');
var config = require('./js/config');
var Termostat = require('./js/objects/termostat');
//emit an event on termperature change and only if auto mode if on
mongoose.connect(config.database);
var termostat = new Termostat();
termostat.init();
process.on('SIGINT',function(){
termostat.close();
process.exit();
});
app.use(morgan('dev'));
app.use(compress());
app.use(bodyParser.json());
app.use(express.static(__dirname + '/static'));
app.listen(5000);
console.log('server running');
function resGet(url,object,getMethod){
app.get('/api/' + url, function(req, res){
res.json(object[getMethod]());
});
}
resGet('mode',termostat,'getMode');
resGet('temperature',termostat,'getTemperature');
resGet('termostat',termostat,'getTermostat');
resGet('hysteresis',termostat,'getHysteresis');
resGet('humidity',termostat,'getHumidity');
resGet('manualSwitch',termostat,'getManualSwitchValue');
resGet('termostatSwitch',termostat,'getTermostatSwitchValue');
app.get('/api/state', function(req, res){
res.json(termostat);
});
setInterval(function(){
termostat.getTermostatSwitch()
.then(function(out){
termostat.termostatSwitch = out;
return termostat.getManualSwitch();
})
.then(function(out){
termostat.manualSwitch = out;
});
},2000);
function resPost(url,object,setMethod){
app.post('/api/' + url + '/:value', function(req, res){
var value = req.params.value;
console.log('use auth middleware here');
object[setMethod](value);
res.json({success: true});
});
}
resPost('auto',termostat,'setMode');
resPost('termostat',termostat,'setTermostat');
resPost('hysteresis',termostat,'setHysteresis');
resPost('manualSwitch',termostat,'setManualSwitch');
resPost('termostatSwitch',termostat,'setTermostatSwitch');
child.on('error', function(err){
console.log(err);
});
child.stdout.on('data', function(data){
var output = data.toString().trim().split(',');
var temperature = Number(output[0]);
var humidity = Number(output[1]);
if(temperature != termostat.getTemperature()){
termostat.setTemperature(temperature);
termostat.emit('temperatureChange');
}
if(humidity != termostat.getHumidity()){
termostat.setHumidity(humidity);
//termostat.emit('humidityChange'); //- not using humidity, but left as a place holder
}
});