Skip to content

Commit

Permalink
Initial public commit
Browse files Browse the repository at this point in the history
  • Loading branch information
fabe committed Oct 21, 2015
0 parents commit 3d5d1f7
Show file tree
Hide file tree
Showing 15 changed files with 1,334 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .bowerrc
@@ -0,0 +1,3 @@
{
"directory" : "public/components"
}
7 changes: 7 additions & 0 deletions .gitignore
@@ -0,0 +1,7 @@
.DS_Store
node_modules
bower_components
.sass-cache
helper
npm-debug.log
public/components
1 change: 1 addition & 0 deletions .nvmrc
@@ -0,0 +1 @@
0.12.7
71 changes: 71 additions & 0 deletions README.md
@@ -0,0 +1,71 @@
# interval

This is a project for a class at the University of Applied Sciences Potsdam. The goal was to create an IoT-Device, preferably with NodeJS and Johnny Five. The two-week long class was supervised by Fabian Morón Zirfas.

*Interval* is a sleep tracker that grabs values from an accelerometer (in this case the MPU6050) and visualizes movement throughout the night. Tracking can be started and ended via a website that runs on NodeJS, which is also the place where the visualization happens.

## Hardware
For this project, I’ve used a [Raspberry Pi A+](https://www.raspberrypi.org/products/model-a-plus/) hooked up with an [Edimax WiFi USB Adapter](http://amzn.com/B003MTTJOY). The accelerometer in use is the [MPU-6050](http://amzn.com/B008BOPN40). See the [Fritzing Sketch for correct installation](http://i.imgur.com/hGOfs6k.jpg).

I attached the accelerometer to a wooden board for more accurate tracking and placed it next to my pillow. See the prototype below:

![](http://i.imgur.com/GIVh0hq.jpg)

The final product should be invisible and hidden underneath the sheets/bed.

## Software
NodeJS and MongoDB is running on the Raspberry Pi. I get the accelerometer data through the (specific) [mpu6050 module](https://github.com/jstapels/mpu6050/). For installation instructions I collected some [helpful links](#helpful-links) below.

I set up [forever](https://github.com/foreverjs/forever) on my Raspberry Pi so that my server is always up and running. Otherwise just use `npm start` to start. Make sure that the database is running (`sudo mongod start` or `sudo /etc/init.d/mongod start`).

Communication between frontend and backend happens either via AJAX (for data) or socket.io (for starting/ending tracking).

If you want to change the styling of the page please use [Compass](http://compass-style.org/) via the `comapass watch` command in the root of the project. The stylesheets can be found in the `/sass` directory. Output is in `/public/css`.

For templating [Jade](http://jade-lang.com/) is used, the views are located in `/views`.

Also, run `bower install` to get all frontend components (located in `/public/components`)!

## Screenshot
As stated before, tracking can be started and ended on the website. The visualization also happens there. The higher the values, the lighter is the sleep at that time. Low values indicate a deep sleep phase.
![](http://i.imgur.com/8URxoBU.png)
![](http://i.imgur.com/RbOPvCf.jpg)

## Concerns and Outlook
Unfortunately the visualization and tracking of the accelerometer data is not as accuate and unambiguous as I’ve hoped, so there is definitely some work to do.

I could imagine interesting addtions to the hardware, such as sensors for air quality, temperature, brightness, or even more accelerometers that are attached to the body. Autonomous starting and ending of the tracking could be a cool feature on the software side.

## Helpful Links
- [Install NodeJS on Raspberry Pi](https://www.bitpi.co/2015/02/12/install-nodejs-on-raspberry-pi/)
- [Installing mongodb on Raspberry Pi (using pre-compiled binaries)](http://www.widriksson.com/install-mongodb-raspberrypi/)
- [Raspberry Pi MongoDB Installation – The working guide!](http://c-mobberley.com/wordpress/2013/10/14/raspberry-pi-mongodb-installation-the-working-guide/)
- [Interfacing Raspberry Pi and MPU-6050](http://blog.bitify.co.uk/2013/11/interfacing-raspberry-pi-and-mpu-6050.html)
- [Reading data from the MPU-6050 on the Raspberry Pi](http://blog.bitify.co.uk/2013/11/reading-data-from-mpu-6050-on-raspberry.html)
- [General Information on Accelerometers](http://www.hobbytronics.co.uk/accelerometer-info)
- [MPU6050 module for node-i2c (fixed version)](https://github.com/miniben-90/mpu6050/commit/1c8d08444944367018d463c27217ca0159fa142d)
- [MPU6050 calculations from johnny-five](https://github.com/rwaldron/johnny-five/blob/06b5127d54ec2874910e8d505ed897bc339c9e58/lib/accelerometer.js)
- [How do I backup my Raspberry Pi?](http://raspberrypi.stackexchange.com/a/312)

## License
The MIT License (MIT)

Copyright (c) 2015 Fabian Schultz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
21 changes: 21 additions & 0 deletions bower.json
@@ -0,0 +1,21 @@
{
"name": "interval",
"main": "index.js",
"version": "0.0.0",
"authors": [
"Fabian Schultz <desk@fabianschultz.com>"
],
"description": "Tracking sleep with a Raspberry Pi and the MPU6050.",
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"dependencies": {
"moment": "~2.10.6",
"morris.js": "~0.5.1"
}
}
25 changes: 25 additions & 0 deletions config.rb
@@ -0,0 +1,25 @@
require 'compass/import-once/activate'
# Require any additional compass plugins here.

# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "public/css"
sass_dir = "sass"
images_dir = "public/img"
javascripts_dir = "public/js"

# You can select your preferred output style here (can be overridden via the command line):
output_style = :compressed

# To enable relative paths to assets via compass helper functions. Uncomment:
# relative_assets = true

# To disable debugging comments that display the original location of your selectors. Uncomment:
# line_comments = false


# If you prefer the indented syntax, you might want to regenerate this
# project again passing --syntax sass, or you can uncomment this:
# preferred_syntax = :sass
# and then run:
# sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass
236 changes: 236 additions & 0 deletions index.js
@@ -0,0 +1,236 @@
/* REQUIRES/GLOBALS
========================================================================== */
var express = require('express'),
app = express(),
server = require('http').createServer(app),
cron = require('cron'),
mpu6050 = require('mpu6050'),
mpu = new mpu6050(),
io = require('socket.io'),
fs = require('fs'),
jade = require('jade'),
socket = io.listen(server),
mongoose = require('mongoose'),
Schema = mongoose.Schema,
trigger = 0,
accelValues = [],
port = 80;



/* EXPRESS
========================================================================== */
app.use('/', express.static(__dirname + '/public'));
if (app.get('env') === 'development') {
app.locals.pretty = true;
}



/* JADE
========================================================================== */
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');



/* MONGOOSE/DATABASE
========================================================================== */
mongoose.connect('mongodb://127.0.0.1:27017/nights');

// Require all mongoose models
fs.readdirSync(__dirname + '/models').forEach(function(filename) {
if (~filename.indexOf('.js')) require(__dirname + '/models/' + filename)
});

// Declare mongoose collections
var Details = mongoose.model('details');
var Accel = mongoose.model('accel');

mpu.initialize();



/* CONTROLS
========================================================================== */
// Start/End tracking via socket msg.
socket.on('connection', function(client) {
client.on('message', function(message) {
if (mpu.testConnection()) {
if(message == 1) {
mpu.setSleepEnabled(0);
trigger = -1;
startNight();
} else if(message == 0) {
mpu.setSleepEnabled(1);
trigger = 0;
endNight();
}
}
});
});



/* CRONJOBS
========================================================================== */
var everySecond = cron.job("* * * * * *", function(){
var accel = mpu.getMotion6();
accelValues.push({
aX: accel[0],
aY: accel[1],
aZ: accel[2],
gX: accel[3],
gY: accel[4],
gZ: accel[5]
});
});

var everyMinute = cron.job("0 * * * * *", function(){
var aX = average(accelValues, "aX");
var aY = average(accelValues, "aY");
var aZ = average(accelValues, "aZ");
var gX = average(accelValues, "gX");
var gY = average(accelValues, "gY");
var gZ = average(accelValues, "gZ");
var Ax = angles("x", [aX, aY, aZ]);
var Ay = angles("y", [aX, aY, aZ]);

accelValues = [];
saveAccel(aX, aY, aZ, gX, gY, gZ, Ax, Ay);
});



/* FUNCTIONS
========================================================================== */
// Save one accelerometer value.
function saveAccel(aX, aY, aZ, gX, gY, gZ, Ax, Ay) {
Details.find(function(err, data) {
if (err) throw err;
var nightId = data[0]._id;

var motion = new Accel({
nightId: nightId,
timestamp: new Date().toISOString(),
aX: aX,
aY: aY,
aZ: aZ,
gX: gX,
gY: gY,
gZ: gZ,
Ax: Ax,
Ay: Ay
});

console.log(motion);
motion.save(function(err) {
if (err) {
mpu.setSleepEnabled(1);
mpu.setSleepEnabled(0);
mpu.initialize();
console.log(err);
} else {
console.log('Accelerometer values saved!');
}
});
}).sort([['start', 'descending']]).limit(1);
};

// Calculate angle from x, y and z.
function angles(layer, data) {
var x, y, z, rads;

x = data[0] / 16384;
y = data[1] / 16384;
z = data[2] / 16384;

if(layer == "y") {
rads = Math.atan2(y, Math.hypot(x, z));
} else {
rads = Math.atan2(x, Math.hypot(y, z));
}

var angle = rads * (180 / Math.PI);
return angle.toPrecision(6);
};

// Start night/tracking.
function startNight() {
var night = new Details({
start: new Date().toISOString(),
end: new Date().toISOString()
});

night.save(function(err) {
if (err) {
console.log(err);
} else {
console.log('Night started.');
}

});

everySecond.start();
everyMinute.start();
};

// End night/tracking.
function endNight() {
Details.find(function(err, data) {
if(err) throw err;
var nightId = data[0]._id;
Details.findOneAndUpdate({_id: nightId}, { end: new Date().toISOString() }, {}, function(err) {
if(err) throw err;
});
}).sort([['start', 'descending']]).limit(1);

everySecond.stop();
everyMinute.stop();

console.log('Night ended.');
}

// Get average number (object, key as string [e.g. "x", "y"])
function average(obj, key) {
var sum = 0;
for(var i = 0; i < obj.length; i++){
sum += obj[i][key];
}

var avg = sum/obj.length;
return avg.toPrecision(6);
}



/* API
========================================================================== */
// Set up root route
app.get('/', function (req, res) {
Details.find(function(err, data) {
res.render('index', { nights: data, trigger: trigger });
}).sort([['start', 'descending']]).limit(3);
});

// Set up /details API
app.get('/details', function (req, res) {
Details.find(function(err, details) {
if(err) throw err;
res.send(details);
})
});

// Set up /accel API
app.get('/accel/:nightId', function (req, res) {
Accel.find({nightId: req.params.nightId}, function(err, accel) {
res.send(accel);
})
});



/* RUN SERVER
========================================================================== */
console.log('Listening on port http://localhost:' + port);
server.listen(port, '0.0.0.0');
19 changes: 19 additions & 0 deletions models/accel.js
@@ -0,0 +1,19 @@
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var accelSchema = new Schema({
nightId: Schema.ObjectId,
timestamp: String,
aX: Number,
aY: Number,
aZ: Number,
gX: Number,
gY: Number,
gZ: Number,
Ax: Number,
Ay: Number
}, {
versionKey: false
});

mongoose.model('accel', accelSchema, 'accel');

0 comments on commit 3d5d1f7

Please sign in to comment.