-
Notifications
You must be signed in to change notification settings - Fork 58
/
server.js
177 lines (151 loc) · 5.87 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
// server.js - NodeJS server for the PiThermServer project.
/*
Parses data from DS18B20 temperature sensor and serves as a JSON object.
Uses node-static module to serve a plot of current temperature (uses highcharts).
Tom Holderness 03/01/2013
Ref: www.cl.cam.ac.uk/freshers/raspberrypi/tutorials/temperature/
*/
// Load node modules
var fs = require('fs');
var sys = require('sys');
var http = require('http');
var sqlite3 = require('sqlite3');
// Use node-static module to server chart for client-side dynamic graph
var nodestatic = require('node-static');
// Setup static server for current directory
var staticServer = new nodestatic.Server(".");
// Setup database connection for logging
var db = new sqlite3.Database('./piTemps.db');
// Write a single temperature record in JSON format to database table.
function insertTemp(data){
// data is a javascript object
var statement = db.prepare("INSERT INTO temperature_records VALUES (?, ?)");
// Insert values into prepared statement
statement.run(data.temperature_record[0].unix_time, data.temperature_record[0].celsius);
// Execute the statement
statement.finalize();
}
// Read current temperature from sensor
function readTemp(callback){
fs.readFile('/sys/bus/w1/devices/28-00000400a88a/w1_slave', function(err, buffer)
{
if (err){
console.error(err);
process.exit(1);
}
// Read data from file (using fast node ASCII encoding).
var data = buffer.toString('ascii').split(" "); // Split by space
// Extract temperature from string and divide by 1000 to give celsius
var temp = parseFloat(data[data.length-1].split("=")[1])/1000.0;
// Round to one decimal place
temp = Math.round(temp * 10) / 10;
// Add date/time to temperature
var data = {
temperature_record:[{
unix_time: Date.now(),
celsius: temp
}]};
// Execute call back with data
callback(data);
});
};
// Create a wrapper function which we'll use specifically for logging
function logTemp(interval){
// Call the readTemp function with the insertTemp function as output to get initial reading
readTemp(insertTemp);
// Set the repeat interval (milliseconds). Third argument is passed as callback function to first (i.e. readTemp(insertTemp)).
setInterval(readTemp, interval, insertTemp);
};
// Get temperature records from database
function selectTemp(num_records, start_date, callback){
// - Num records is an SQL filter from latest record back trough time series,
// - start_date is the first date in the time-series required,
// - callback is the output function
var current_temp = db.all("SELECT * FROM (SELECT * FROM temperature_records WHERE unix_time > (strftime('%s',?)*1000) ORDER BY unix_time DESC LIMIT ?) ORDER BY unix_time;", start_date, num_records,
function(err, rows){
if (err){
response.writeHead(500, { "Content-type": "text/html" });
response.end(err + "\n");
console.log('Error serving querying database. ' + err);
return;
}
data = {temperature_record:[rows]}
callback(data);
});
};
// Setup node http server
var server = http.createServer(
// Our main server function
function(request, response)
{
// Grab the URL requested by the client and parse any query options
var url = require('url').parse(request.url, true);
var pathfile = url.pathname;
var query = url.query;
// Test to see if it's a database query
if (pathfile == '/temperature_query.json'){
// Test to see if number of observations was specified as url query
if (query.num_obs){
var num_obs = parseInt(query.num_obs);
}
else{
// If not specified default to 20. Note use -1 in query string to get all.
var num_obs = -1;
}
if (query.start_date){
var start_date = query.start_date;
}
else{
var start_date = '1970-01-01T00:00';
}
// Send a message to console log
console.log('Database query request from '+ request.connection.remoteAddress +' for ' + num_obs + ' records from ' + start_date+'.');
// call selectTemp function to get data from database
selectTemp(num_obs, start_date, function(data){
response.writeHead(200, { "Content-type": "application/json" });
response.end(JSON.stringify(data), "ascii");
});
return;
}
// Test to see if it's a request for current temperature
if (pathfile == '/temperature_now.json'){
readTemp(function(data){
response.writeHead(200, { "Content-type": "application/json" });
response.end(JSON.stringify(data), "ascii");
});
return;
}
// Handler for favicon.ico requests
if (pathfile == '/favicon.ico'){
response.writeHead(200, {'Content-Type': 'image/x-icon'});
response.end();
// Optionally log favicon requests.
//console.log('favicon requested');
return;
}
else {
// Print requested file to terminal
console.log('Request from '+ request.connection.remoteAddress +' for: ' + pathfile);
// Serve file using node-static
staticServer.serve(request, response, function (err, result) {
if (err){
// Log the error
sys.error("Error serving " + request.url + " - " + err.message);
// Respond to the client
response.writeHead(err.status, err.headers);
response.end('Error 404 - file not found');
return;
}
return;
})
}
});
// Start temperature logging (every 5 min).
var msecs = (60 * 5) * 1000; // log interval duration in milliseconds
logTemp(msecs);
// Send a message to console
console.log('Server is logging to database at '+msecs+'ms intervals');
// Enable server
server.listen(8000);
// Log message
console.log('Server running at http://localhost:8000');