Commits

Vassil Kalkov committed 037c42b

Init - working

Comments (0)

Files changed (13)

+node_modules
+*.*~
+config.js
+.project
+
+/**
+ * Module dependencies.
+ */
+
+var express = require('express')
+   ,config = require(__dirname + '/config.js').config
+   ,couchDBMiddleware = require(__dirname + '/couchdb.js')
+   ,helpers = require(__dirname + '/helpers/date_helper.js')
+  // ,sio = require('../../lib/socket.io')
+   ,app = module.exports = express.createServer();
+
+// Configuration
+/*
+app.configure('kalkov.dyndns.org', function(){
+    app.use(function(req, res, next){
+        
+        };
+        next();
+    });
+});
+*/
+app.configure('development', function(){
+    app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
+});
+
+app.configure('production', function(){
+    app.use(express.errorHandler()); 
+});
+
+app.configure(function(){
+    app.set('views', __dirname + '/views');
+    app.set('view engine', 'jade');
+    app.use(express.bodyParser());
+    app.use(express.methodOverride());
+    app.use(couchDBMiddleware());
+    app.use(app.router);
+
+    //app.use(express.static(__dirname + '/public'));
+});
+
+//Helpers
+app.helpers({
+  time_ago_in_words: helpers.time_ago_in_words
+});
+
+
+// Routes
+require('./routes')(app).listen(config.port);
+console.log("is_it_hot_ui is listening on port %d in %s mode", config.port, app.settings.env);
+
+/*
+var io = sio.listen(app)
+  , nicknames = {};
+
+io.sockets.on('connection', function (socket) {
+  socket.on('user message', function (msg) {
+    socket.broadcast.emit('user message', socket.nickname, msg);
+  });
+
+  socket.on('nickname', function (nick, fn) {
+    if (nicknames[nick]) {
+      fn(true);
+    } else {
+      fn(false);
+      nicknames[nick] = socket.nickname = nick;
+      socket.broadcast.emit('announcement', nick + ' connected');
+      io.sockets.emit('nicknames', nicknames);
+    }
+  });
+
+  socket.on('disconnect', function () {
+    if (!socket.nickname) return;
+
+    delete nicknames[socket.nickname];
+    socket.broadcast.emit('announcement', socket.nickname + ' disconnected');
+    socket.broadcast.emit('nicknames', nicknames);
+  });
+});
+*/

config_example.js

+module.exports.config = {
+    port: 3050,
+    couchdb: {
+      database: 'db_name',
+      host: 'http://127.0.0.1',
+      port: 5984,
+      cradleConfig: {
+          cache: true,
+          raw: false,
+          auth: { username: 'user', password: 'pass' }
+      }
+  }
+};

controllers/save_design_docs.js

+var assert = require('assert');
+var cradle = require('cradle');
+
+module.exports = function(req, res, next){
+    
+    req.db.save('_design/sensors', {
+        views: {
+          sensors_today: {
+            map: function(doc) {
+                   var d=new Date();
+                   if(d.getDate() < 10){ var today_date = "0" + d.getDate()}
+                   else {var today_data = getDate()}
+
+                   str = d.getFullYear()+"_"+(d.getMonth()+1)+"_"+today_date;
+
+                   if(doc._id.search(str) != -1) {
+                     emit(str, doc);
+                   }
+                 }
+          },
+          
+          sensors_last_minute: {
+            map: function(doc) {
+                   var d=new Date();
+                   if(d.getDate() < 10){ var today_date = "0" + d.getDate()}
+                   else {var today_data = getDate()}
+
+                   str = d.getFullYear()+"_"+(d.getMonth()+1)+"_"+today_date+"@"+d.getHours()+":"+d.getMinutes();
+
+                   if(doc._id.search(str) != -1) {
+                     emit(doc.time, doc);
+                   }
+            }
+          },
+          
+          sensors_last_hour: {
+            map: function(doc) {
+                   var d=new Date();
+                   if(d.getDate() < 10){ var today_date = "0" + d.getDate()}
+                   else {var today_data = getDate()}
+
+                   str = d.getFullYear()+"_"+(d.getMonth()+1)+"_"+today_date+"@"+d.getHours();
+
+                   if(doc._id.search(str) != -1) {
+                     emit(str, doc);
+                   }
+                 }
+          },
+          
+          sensor_room1: {
+            map: function(doc) {
+                   var d=new Date();
+                   if(d.getDate() < 10){ var today_date = "0" + d.getDate()}
+                   else {var today_data = getDate()}
+
+                   str = d.getFullYear()+"_"+(d.getMonth()+1)+"_"+today_date+"@"+d.getHours();
+
+                   if(doc._id.search(str) != -1 && doc.name == 'room1' ) {
+                     emit(doc.time, doc);
+                   }
+          }
+           
+        }
+      }
+    }
+  , function(err){
+    if(err)
+      throw err;
+    res.send("OK");
+  });
+  
+}

controllers/sensors.js

+var assert = require('assert');
+var express = require('express');
+var date = require('date-utils');
+
+var renderOutput = function(doc){return "Total : " + doc;}    
+
+var renderDocsRaw = function(res, docs){
+  var output = [];
+  docs.forEach(function (row) {
+    output.push(row._id);
+    output.push("Address: " + row.address + "Temp: "+row.data);
+  });
+  res.send(output.join("\r\n"));
+}
+
+exports.index = function (req, res) {
+  var d=new Date();
+  if(d.getDate() < 10){ var today_date = "0" + d.getDate()}
+  else {var today_data = getDate()}
+
+  var minutes_str = d.getFullYear()+"_"+(d.getMonth()+1)+"_"+today_date+"@"+d.getHours()+":"+d.getMinutes();
+
+  req.db.view('sensors/sensors_last_minute',{descending: true}, function (err, docs) {	
+      res.render('sensors', { sensors: docs, title: "Sensors" });
+  });
+};
+
+
+exports.room1 = function (req, res) {
+  var d=new Date();
+  if(d.getDate() < 10){ var today_date = "0" + d.getDate()}
+  else {var today_data = getDate()}
+
+  var minutes_str = d.getFullYear()+"_"+(d.getMonth()+1)+"_"+today_date+"@"+d.getHours();
+
+  req.db.view('sensors/sensor_room1',{descending: true}, function (err, docs) {	
+      res.render('sensors', { sensors: docs, title: "Sensors" });
+  });
+};
+
+exports.create = function (req, res, next) {
+  
+}
+
+exports.update = function (req, res, next) {
+  
+}
+
+var config = require(__dirname + '/config.js').config;
+var cradle = require('cradle');
+var connection = new(cradle.Connection)
+                    (config.couchdb.host, 
+                     config.couchdb.port, 
+                     config.couchdb.cradleConfig);
+
+module.exports = function couchDBMiddleware() {
+
+    return function couchDBMiddlerware(req, res, next) {
+
+        var dbName = config.couchdb.database || req.headers.host.replace(/\./g, '-');
+        if (dbName.match(/\:/)) dbName = dbName.split(':')[0];
+
+	if (dbName.match(/^\d/)) dbName = 'localhost';
+
+        if (!req.db) {
+
+            console.log('connection dbName:', dbName);
+
+            req.db = connection.database(dbName); 
+
+            req.db.name = dbName;
+
+            next();
+
+        } else {
+
+            next();
+
+        }
+
+    };
+
+};

helpers/date_helper.js

+var express = require('express');
+
+exports.time_ago_in_words = function time_ago_in_words(from) {
+   return distance_of_time_in_words(new Date().getTime(), from)
+  }
+
+  function distance_of_time_in_words(to, from) {
+    seconds_ago = ((to  - from) / 1000);
+    minutes_ago = Math.floor(seconds_ago / 60)
+
+    //if(minutes_ago == 0) { return "less than a minute";}
+    if(seconds_ago <= 0) {return "now"}
+    if(minutes_ago < 1 && seconds_ago > 0 ) { return Math.round(seconds_ago) + "sec";}
+    if(minutes_ago == 1) { return "a minute";}
+    if(minutes_ago < 59) { return minutes_ago + " minutes";}
+    if(minutes_ago < 90) { return " about 1 hour";}
+    hours_ago  = Math.round(minutes_ago / 60);
+    if(minutes_ago < 1440) { return "about " + hours_ago + " hours";}
+    if(minutes_ago < 2880) { return "1 day";}
+    days_ago  = Math.round(minutes_ago / 1440);
+    if(minutes_ago < 43200) { return days_ago + " days";}
+    if(minutes_ago < 86400) { return "about 1 month";}
+    months_ago  = Math.round(minutes_ago / 43200);
+    if(minutes_ago < 525960) { return months_ago + " months";}
+    if(minutes_ago < 1051920) { return "about 1 year";}
+    years_ago  = Math.round(minutes_ago / 525960);
+    return "over " + years_ago + " years"
+  }
+  
+{
+    "name": "is_it_hot_ui"
+  , "version": "0.0.1"
+  , "private": true
+  , "dependencies": {
+      "express": "2.5.0"
+    , "jade": ">= 0.0.1"
+    , "cradle": "latest"
+    , "date-utils": "latest"
+    , "socket.io": "latest"
+  }
+}

public/stylesheets/style.css

+body {
+  padding: 50px;
+  font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
+}
+
+a {
+  color: #00B7FF;
+}
+/*
+ * GET home page.
+ */
+
+module.exports = function(app){
+    app.get('/sensors', require("../controllers/sensors").index);
+    app.get('/sensors/room1', require("../controllers/sensors").room1);
+    app.post('/sensors', require("../controllers/sensors").create);
+    app.get('/save_design_docs', require("../controllers/save_design_docs"));
+    app.get("/",function(req, res){
+      res.render('index', { title: 'Express' })
+    });
+    return app;
+}
+h1= title
+p Welcome to #{title}

views/layout.jade

+!!!
+html
+  head
+    title= title
+    link(rel='stylesheet', href='/stylesheets/style.css')
+  body!= body

views/sensors.jade

+if (sensors[0])
+  h2 address : #{sensors[0].value.address}
+  h2 name : #{sensors[0].value.name}
+else
+  h2 Empty  
+ul#sensors
+  each sensor in sensors
+    li(class='sensor-' + sensor.value._id) #{time_ago_in_words(sensor.value.time)} | #{sensor.value.data} |