From 7140d77669cd0ff431675ea09caf39d5a20ab51e Mon Sep 17 00:00:00 2001 From: norcal82 Date: Wed, 26 Aug 2015 00:15:08 -0700 Subject: [PATCH 1/3] added mongoose and moved scripts/models to external files --- index.html | 111 +---------------------------------- models/station.coffee | 10 ++++ models/station.js | 13 +++++ scripts/main.coffee | 131 ++++++++++++++++++++++++++++++++++++++++++ scripts/main.js | 86 +++++++++++++++++++++++++++ server.coffee | 51 ++++++++-------- 6 files changed, 269 insertions(+), 133 deletions(-) create mode 100644 models/station.coffee create mode 100644 models/station.js create mode 100644 scripts/main.coffee create mode 100644 scripts/main.js diff --git a/index.html b/index.html index 3ee90c2..344b5c8 100644 --- a/index.html +++ b/index.html @@ -8,116 +8,7 @@ - - +

diff --git a/models/station.coffee b/models/station.coffee
new file mode 100644
index 0000000..c9919c5
--- /dev/null
+++ b/models/station.coffee
@@ -0,0 +1,10 @@
+mongoose = require('mongoose');
+
+Schema = mongoose.Schema;
+
+StationSchema = new Schema({
+    count: Number
+});
+
+module.exports = mongoose.model('Station', StationSchema);
+Station = mongoose.model('Station', StationSchema)
diff --git a/models/station.js b/models/station.js
new file mode 100644
index 0000000..dc98985
--- /dev/null
+++ b/models/station.js
@@ -0,0 +1,13 @@
+// Generated by CoffeeScript 1.9.3
+(function() {
+  var StationSchema, mongoose;
+
+  mongoose = require('mongoose');
+
+  StationSchema = new mongoose.Schema({
+    count: Number
+  });
+
+  module.exports = mongoose.model('Station', StationSchema);
+
+}).call(this);
diff --git a/scripts/main.coffee b/scripts/main.coffee
new file mode 100644
index 0000000..00d623d
--- /dev/null
+++ b/scripts/main.coffee
@@ -0,0 +1,131 @@
+socket = io.connect('http://localhost:3000', 'force new connection': true)
+$ ->
+
+  generateChart = (target, data, color) ->
+
+  # senders
+
+  send = ->
+    socket.emit 'clieantMessage', 'whats up from send', navigator.platform
+    return
+
+  #  spinner
+
+  waiting = ->
+    $('pre').text('Waiting').css('color', 'dodgerblue').fadeIn 'fast'
+    return
+
+  get = 0
+  post = 0
+  del = 0
+  put = 0
+  color_palette = [
+    '#1abc9c'
+    '#3498db'
+    '#e74c3c'
+    '#f39c12'
+  ]
+  socket.on 'getRequest', (data) ->
+    console.log 'get reuqest'
+    get = get + 1
+    # dry uppppppp
+    chart1.load columns: [
+      [
+        'GET'
+        get
+      ]
+      [
+        'POST'
+        post
+      ]
+      [
+        'DELETE'
+        del
+      ]
+      [
+        'PUT'
+        put
+      ]
+    ]
+    return
+  socket.on 'station_created', (data) ->
+    console.log 'new station created and registered'
+    console.log data
+    return
+  sensor_counts = [ 'station: 2' ]
+  sensor_counts1 = [ 'station: 5' ]
+  socket.on 'countRecieved', (data) ->
+    post = post + 1
+    chart1.load columns: [
+      [
+        'GET'
+        get
+      ]
+      [
+        'POST'
+        post
+      ]
+      [
+        'DELETE'
+        del
+      ]
+      [
+        'PUT'
+        put
+      ]
+    ]
+    console.log 'count is incremented'
+    console.log data
+    if data._id == '2'
+      sensor_counts.push data._count
+      console.log 'station 2'
+      if sensor_counts.length == 30
+        console.log 'arr is 5'
+        console.log sensor_counts
+        sensor_counts.splice 1, 1
+        console.log sensor_counts
+    else
+      sensor_counts1.push data._count
+      if sensor_counts1.length == 30
+        sensor_counts1.splice 1, 1
+    chart.load columns: [
+      sensor_counts
+      sensor_counts1
+    ]
+    return
+  chart = c3.generate(
+    data:
+      columns: [
+        sensor_counts
+        sensor_counts1
+      ]
+      type: 'area-spline'
+    color: pattern: color_palette)
+  chart1 = c3.generate(
+    bindto: '#chart1'
+    data:
+      columns: [
+        [
+          'GET'
+          get
+        ]
+        [
+          'POST'
+          post
+        ]
+        [
+          'DELETE'
+          del
+        ]
+        [
+          'PUT'
+          put
+        ]
+      ]
+      type: 'donut'
+    donut: title: 'HTTP Actions'
+    color: pattern: color_palette)
+  return
+
+# ---
+# generated by js2coffee 2.1.0
diff --git a/scripts/main.js b/scripts/main.js
new file mode 100644
index 0000000..4f2670f
--- /dev/null
+++ b/scripts/main.js
@@ -0,0 +1,86 @@
+// Generated by CoffeeScript 1.9.3
+(function() {
+  var socket;
+
+  socket = io.connect('http://localhost:3000', {
+    'force new connection': true
+  });
+
+  $(function() {
+    var chart, chart1, color_palette, del, generateChart, get, post, put, send, sensor_counts, sensor_counts1, waiting;
+    generateChart = function(target, data, color) {};
+    send = function() {
+      socket.emit('clieantMessage', 'whats up from send', navigator.platform);
+    };
+    waiting = function() {
+      $('pre').text('Waiting').css('color', 'dodgerblue').fadeIn('fast');
+    };
+    get = 0;
+    post = 0;
+    del = 0;
+    put = 0;
+    color_palette = ['#1abc9c', '#3498db', '#e74c3c', '#f39c12'];
+    socket.on('getRequest', function(data) {
+      console.log('get reuqest');
+      get = get + 1;
+      chart1.load({
+        columns: [['GET', get], ['POST', post], ['DELETE', del], ['PUT', put]]
+      });
+    });
+    socket.on('station_created', function(data) {
+      console.log('new station created and registered');
+      console.log(data);
+    });
+    sensor_counts = ['station: 2'];
+    sensor_counts1 = ['station: 5'];
+    socket.on('countRecieved', function(data) {
+      post = post + 1;
+      chart1.load({
+        columns: [['GET', get], ['POST', post], ['DELETE', del], ['PUT', put]]
+      });
+      console.log('count is incremented');
+      console.log(data);
+      if (data._id === '2') {
+        sensor_counts.push(data._count);
+        console.log('station 2');
+        if (sensor_counts.length === 30) {
+          console.log('arr is 5');
+          console.log(sensor_counts);
+          sensor_counts.splice(1, 1);
+          console.log(sensor_counts);
+        }
+      } else {
+        sensor_counts1.push(data._count);
+        if (sensor_counts1.length === 30) {
+          sensor_counts1.splice(1, 1);
+        }
+      }
+      chart.load({
+        columns: [sensor_counts, sensor_counts1]
+      });
+    });
+    chart = c3.generate({
+      data: {
+        columns: [sensor_counts, sensor_counts1],
+        type: 'area-spline'
+      },
+      color: {
+        pattern: color_palette
+      }
+    });
+    chart1 = c3.generate({
+      bindto: '#chart1',
+      data: {
+        columns: [['GET', get], ['POST', post], ['DELETE', del], ['PUT', put]],
+        type: 'donut'
+      },
+      donut: {
+        title: 'HTTP Actions'
+      },
+      color: {
+        pattern: color_palette
+      }
+    });
+  });
+
+}).call(this);
diff --git a/server.coffee b/server.coffee
index b6099f0..99796fe 100644
--- a/server.coffee
+++ b/server.coffee
@@ -1,30 +1,33 @@
-app     = require('express')()
+express = require('express')
+app     = express()
 server  = require('http').Server(app)
 io      = require('socket.io')(server)
 request = require('request')
-morgan = require('morgan')
+morgan  = require('morgan')
+mongoose = require('mongoose')
 
 base_uri = 'http://localhost:3000'
+mongo_uri = 'http://localhost:28017/serverStatus'
 index = '/'
-
+app.use("/scripts", express.static(__dirname + '/scripts'));
 # logging
 app.use(morgan('combined'))
-# mongoose = require('mongoose');
 
-# mongoose.connect('mongodb://localhost:27017/graph');
+mongoose.connect('mongodb://localhost:27017/graph');
 
-# db = mongoose.connection
-# db.on 'error', console.error.bind(console, 'connection error:')
-# db.once 'open', (callback) ->
-#   console.log "mongo connection"
+db = mongoose.connection
+db.on 'error', console.error.bind(console, 'connection error:')
+db.once 'open', (callback) ->
+  console.log "mongo connection"
 
-# Schema = mongoose.Schema;
+Schema = mongoose.Schema;
 
-# stationSchema = new mongoose.Schema({
-#     count: Number
-# });
+StationSchema = new Schema({
+    count: Number
+});
 
-# module.exports = mongoose.model('Station', stationSchema);
+module.exports = mongoose.model('Station', StationSchema);
+Station = mongoose.model('Station', StationSchema)
 
 bodyParser = require('body-parser');
 app.use(bodyParser.json()); # support json encoded bodies
@@ -61,17 +64,19 @@ app.get index, (req, res) ->
 
 # POSTS
 app.post '/api/station', (req, res) ->
-  # station = new Station
+  Station = mongoose.model('Station', '/models/station.js');
+  station = new Station
   station_id = req.body.id
   count      = req.body.count
-  # station.count = req.body.count
-  # save data
-  # station.save (err) ->
-  #   if err
-  #     res.send err
-  io.sockets.emit 'countRecieved', { _id: station_id, _count: count   }
-  res.json({_id: station_id, _message: "created station "+ station_id})
-
+  station.count = req.body.count
+  station.save (err) ->
+    if err
+      res.send err
+    io.sockets.emit 'countRecieved', { _id: station_id, _count: count   }
+    res.json({_id: station_id, _message: "created station "+ station_id})
+    station.find {}, (err, stations) ->
+        # do thangs
+      console.log(stations)
 
 # app.post 'log', (req, res) -> # creates a new log message
 #   data

From 2b8dbf33f8216c763bfb6fcac31c6735d8e1e7e0 Mon Sep 17 00:00:00 2001
From: norcal82 
Date: Fri, 28 Aug 2015 00:20:57 -0700
Subject: [PATCH 2/3] cleaned up code. broke it :/

---
 index.html                                 |  10 +-
 scripts/main.coffee                        | 160 ++++++---------------
 scripts/main.js                            | 106 +++++++-------
 server.coffee                              |  57 ++++----
 server.js                                  | 133 +++++++++++++++++
 {models => untitled folder}/station.coffee |   1 +
 {models => untitled folder}/station.js     |   0
 7 files changed, 269 insertions(+), 198 deletions(-)
 create mode 100644 server.js
 rename {models => untitled folder}/station.coffee (99%)
 rename {models => untitled folder}/station.js (100%)

diff --git a/index.html b/index.html
index 344b5c8..c442e75 100644
--- a/index.html
+++ b/index.html
@@ -4,11 +4,6 @@
   
   Simple Socket IO
   
-  
-  
-  
-  
-  
 
 
   

@@ -17,6 +12,11 @@
   
+ + + + + diff --git a/scripts/main.coffee b/scripts/main.coffee index 00d623d..932cb16 100644 --- a/scripts/main.coffee +++ b/scripts/main.coffee @@ -1,131 +1,61 @@ socket = io.connect('http://localhost:3000', 'force new connection': true) -$ -> - - generateChart = (target, data, color) -> - - # senders - send = -> - socket.emit 'clieantMessage', 'whats up from send', navigator.platform - return - - # spinner +$ -> + CHART_MAX = 30 + get = 0 + post = 0 + del = 0 + put = 0 + color_palette = ['#1abc9c', '#3498db', '#e74c3c', '#f39c12'] + request_columns = [['GET', get], ['POST', post], ['DELETE', del], ['PUT', put]] + sensor_counts = [ 'station: 2' ] + sensor_counts1 = [ 'station: 5' ] + sensor_columns = [sensor_counts, sensor_counts1] - waiting = -> - $('pre').text('Waiting').css('color', 'dodgerblue').fadeIn 'fast' - return + generateCharts - get = 0 - post = 0 - del = 0 - put = 0 - color_palette = [ - '#1abc9c' - '#3498db' - '#e74c3c' - '#f39c12' - ] socket.on 'getRequest', (data) -> - console.log 'get reuqest' get = get + 1 - # dry uppppppp - chart1.load columns: [ - [ - 'GET' - get - ] - [ - 'POST' - post - ] - [ - 'DELETE' - del - ] - [ - 'PUT' - put - ] - ] - return - socket.on 'station_created', (data) -> - console.log 'new station created and registered' + console.log 'get request' console.log data - return - sensor_counts = [ 'station: 2' ] - sensor_counts1 = [ 'station: 5' ] - socket.on 'countRecieved', (data) -> + updateChart(chart1, request_columns) + + socket.on 'postRequest', (data) -> post = post + 1 - chart1.load columns: [ - [ - 'GET' - get - ] - [ - 'POST' - post - ] - [ - 'DELETE' - del - ] - [ - 'PUT' - put - ] - ] - console.log 'count is incremented' + console.log 'post request' console.log data + if data._id == '2' sensor_counts.push data._count - console.log 'station 2' - if sensor_counts.length == 30 - console.log 'arr is 5' - console.log sensor_counts + if sensor_counts.length == CHART_MAX sensor_counts.splice 1, 1 - console.log sensor_counts else sensor_counts1.push data._count - if sensor_counts1.length == 30 + if sensor_counts1.length == CHART_MAX sensor_counts1.splice 1, 1 - chart.load columns: [ - sensor_counts - sensor_counts1 - ] - return - chart = c3.generate( - data: - columns: [ - sensor_counts - sensor_counts1 - ] - type: 'area-spline' - color: pattern: color_palette) - chart1 = c3.generate( - bindto: '#chart1' - data: - columns: [ - [ - 'GET' - get - ] - [ - 'POST' - post - ] - [ - 'DELETE' - del - ] - [ - 'PUT' - put - ] - ] - type: 'donut' - donut: title: 'HTTP Actions' - color: pattern: color_palette) - return + updateChart(chart, sensor_columns) + + socket.on 'station_created', (data) -> + console.log 'new station created and registered' + console.log data + + socket.emit 'startup', { client: 'pong' } + + generateCharts = -> + chart = c3.generate + data: + columns: sensor_columns + type: 'area-spline' + color: pattern: color_palette + + chart1 = c3.generate + bindto: '#chart1' + data: + columns: sensor_columns + type: 'donut' + donut: title: 'HTTP Actions' + color: pattern: color_palette + + updateChart = (chart, columns) -> chart.load columns -# --- -# generated by js2coffee 2.1.0 +console.error $.extend({arr: [1,2,3,4]},{types: 'this'}) diff --git a/scripts/main.js b/scripts/main.js index 4f2670f..8779306 100644 --- a/scripts/main.js +++ b/scripts/main.js @@ -7,80 +7,82 @@ }); $(function() { - var chart, chart1, color_palette, del, generateChart, get, post, put, send, sensor_counts, sensor_counts1, waiting; - generateChart = function(target, data, color) {}; - send = function() { - socket.emit('clieantMessage', 'whats up from send', navigator.platform); - }; - waiting = function() { - $('pre').text('Waiting').css('color', 'dodgerblue').fadeIn('fast'); - }; + var CHART_MAX, color_palette, del, generateCharts, get, post, put, request_columns, sensor_columns, sensor_counts, sensor_counts1, updateChart; + CHART_MAX = 30; get = 0; post = 0; del = 0; put = 0; color_palette = ['#1abc9c', '#3498db', '#e74c3c', '#f39c12']; + request_columns = [['GET', get], ['POST', post], ['DELETE', del], ['PUT', put]]; + sensor_counts = ['station: 2']; + sensor_counts1 = ['station: 5']; + sensor_columns = [sensor_counts, sensor_counts1]; + generateCharts; socket.on('getRequest', function(data) { - console.log('get reuqest'); get = get + 1; - chart1.load({ - columns: [['GET', get], ['POST', post], ['DELETE', del], ['PUT', put]] - }); - }); - socket.on('station_created', function(data) { - console.log('new station created and registered'); + console.log('get request'); console.log(data); + return updateChart(chart1, request_columns); }); - sensor_counts = ['station: 2']; - sensor_counts1 = ['station: 5']; - socket.on('countRecieved', function(data) { + socket.on('postRequest', function(data) { post = post + 1; - chart1.load({ - columns: [['GET', get], ['POST', post], ['DELETE', del], ['PUT', put]] - }); - console.log('count is incremented'); + console.log('post request'); console.log(data); if (data._id === '2') { sensor_counts.push(data._count); - console.log('station 2'); - if (sensor_counts.length === 30) { - console.log('arr is 5'); - console.log(sensor_counts); - sensor_counts.splice(1, 1); - console.log(sensor_counts); + if (sensor_counts.length === CHART_MAX) { + return sensor_counts.splice(1, 1); } } else { sensor_counts1.push(data._count); - if (sensor_counts1.length === 30) { + if (sensor_counts1.length === CHART_MAX) { sensor_counts1.splice(1, 1); + return updateChart(chart, sensor_columns); } } - chart.load({ - columns: [sensor_counts, sensor_counts1] - }); }); - chart = c3.generate({ - data: { - columns: [sensor_counts, sensor_counts1], - type: 'area-spline' - }, - color: { - pattern: color_palette - } + socket.on('station_created', function(data) { + console.log('new station created and registered'); + return console.log(data); }); - chart1 = c3.generate({ - bindto: '#chart1', - data: { - columns: [['GET', get], ['POST', post], ['DELETE', del], ['PUT', put]], - type: 'donut' - }, - donut: { - title: 'HTTP Actions' - }, - color: { - pattern: color_palette - } + socket.emit('startup', { + client: 'pong' }); + generateCharts = function() { + var chart, chart1; + chart = c3.generate({ + data: { + columns: sensor_columns, + type: 'area-spline' + }, + color: { + pattern: color_palette + } + }); + return chart1 = c3.generate({ + bindto: '#chart1', + data: { + columns: sensor_columns, + type: 'donut' + }, + donut: { + title: 'HTTP Actions' + }, + color: { + pattern: color_palette + } + }); + }; + return updateChart = function(chart, columns) { + return chart.load(columns); + }; }); + console.error($.extend({ + arr: [1, 2, 3, 4] + }, { + types: 'this' + })); + }).call(this); diff --git a/server.coffee b/server.coffee index 99796fe..004f473 100644 --- a/server.coffee +++ b/server.coffee @@ -1,25 +1,34 @@ -express = require('express') -app = express() -server = require('http').Server(app) -io = require('socket.io')(server) -request = require('request') -morgan = require('morgan') +express = require('express') +app = express() +server = require('http').Server(app) +io = require('socket.io')(server) +request = require('request') +morgan = require('morgan') mongoose = require('mongoose') -base_uri = 'http://localhost:3000' -mongo_uri = 'http://localhost:28017/serverStatus' -index = '/' +port_number = process.argv[2] || 3000 + +server.listen port_number +console.log "listening on: " + port_number + +base_uri = 'http://localhost:3000' +mongodb_uri = 'http://localhost:28017/serverStatus' +index = '/' + app.use("/scripts", express.static(__dirname + '/scripts')); + # logging app.use(morgan('combined')) -mongoose.connect('mongodb://localhost:27017/graph'); +mongoose.connect('mongodb://localhost:27017/graph') db = mongoose.connection db.on 'error', console.error.bind(console, 'connection error:') db.once 'open', (callback) -> console.log "mongo connection" + +# move Schema = mongoose.Schema; StationSchema = new Schema({ @@ -29,15 +38,11 @@ StationSchema = new Schema({ module.exports = mongoose.model('Station', StationSchema); Station = mongoose.model('Station', StationSchema) + bodyParser = require('body-parser'); app.use(bodyParser.json()); # support json encoded bodies app.use(bodyParser.urlencoded({ extended: true })); # support encoded bodies - -port_number = 3000 -server.listen port_number -console.log "Sever started on port: " + port_number - io.on 'connection', (socket) -> socket.emit 'startup', { server: 'ping' } @@ -72,19 +77,12 @@ app.post '/api/station', (req, res) -> station.save (err) -> if err res.send err - io.sockets.emit 'countRecieved', { _id: station_id, _count: count } + io.sockets.emit 'postRequest', { _id: station_id, _count: count } res.json({_id: station_id, _message: "created station "+ station_id}) station.find {}, (err, stations) -> # do thangs console.log(stations) -# app.post 'log', (req, res) -> # creates a new log message -# data -# message: '' -# time: '' - -# res.json data - # append to log file. logstalgia on production logs! #TODO: figure out routes # add logging helper for crud actions, socket stuff @@ -97,6 +95,13 @@ postRequest1 = -> getRequest = -> request.get(base_uri + index) -# setInterval(postRequest, 2000) -# setInterval(postRequest1, 1500) -# setInterval(getRequest, 1000) +setInterval(postRequest, 2000) +setInterval(postRequest1, 1500) +setInterval(getRequest, 1000) + +request mongodb_uri, (error, response, body) -> + if !error and response.statusCode == 200 + data = JSON.parse body + console.log data.host + console.log data.version + console.log data.uptime diff --git a/server.js b/server.js new file mode 100644 index 0000000..90ce8ff --- /dev/null +++ b/server.js @@ -0,0 +1,133 @@ +// Generated by CoffeeScript 1.9.3 +(function() { + var Schema, Station, StationSchema, app, base_uri, bodyParser, db, express, getRequest, index, io, mongodb_uri, mongoose, morgan, port_number, postRequest, postRequest1, request, server; + + express = require('express'); + + app = express(); + + server = require('http').Server(app); + + io = require('socket.io')(server); + + request = require('request'); + + morgan = require('morgan'); + + mongoose = require('mongoose'); + + port_number = process.argv[2] || 3000; + + server.listen(port_number); + + console.log("listening on: " + port_number); + + base_uri = 'http://localhost:3000'; + + mongodb_uri = 'http://localhost:28017/serverStatus'; + + index = '/'; + + app.use("/scripts", express["static"](__dirname + '/scripts')); + + app.use(morgan('combined')); + + mongoose.connect('mongodb://localhost:27017/graph'); + + db = mongoose.connection; + + db.on('error', console.error.bind(console, 'connection error:')); + + db.once('open', function(callback) { + return console.log("mongo connection"); + }); + + Schema = mongoose.Schema; + + StationSchema = new Schema({ + count: Number + }); + + module.exports = mongoose.model('Station', StationSchema); + + Station = mongoose.model('Station', StationSchema); + + bodyParser = require('body-parser'); + + app.use(bodyParser.json()); + + app.use(bodyParser.urlencoded({ + extended: true + })); + + io.on('connection', function(socket) { + return socket.emit('startup', { + server: 'ping' + }); + }); + + app.get(index, function(req, res) { + io.sockets.emit('getRequest', {}); + return res.sendFile(__dirname + '/index.html'); + }); + + app.post('/api/station', function(req, res) { + var count, station, station_id; + Station = mongoose.model('Station', '/models/station.js'); + station = new Station; + station_id = req.body.id; + count = req.body.count; + station.count = req.body.count; + return station.save(function(err) { + if (err) { + res.send(err); + } + io.sockets.emit('postRequest', { + _id: station_id, + _count: count + }); + res.json({ + _id: station_id, + _message: "created station " + station_id + }); + return station.find({}, function(err, stations) { + return console.log(stations); + }); + }); + }); + + postRequest = function() { + return request.post(base_uri + '/api/station').form({ + id: '5', + count: Math.floor(Math.random() * 600) + 1 + }); + }; + + postRequest1 = function() { + return request.post(base_uri + '/api/station').form({ + id: '2', + count: Math.floor(Math.random() * 600) + 1 + }); + }; + + getRequest = function() { + return request.get(base_uri + index); + }; + + setInterval(postRequest, 2000); + + setInterval(postRequest1, 1500); + + setInterval(getRequest, 1000); + + request(mongodb_uri, function(error, response, body) { + var data; + if (!error && response.statusCode === 200) { + data = JSON.parse(body); + console.log(data.host); + console.log(data.version); + return console.log(data.uptime); + } + }); + +}).call(this); diff --git a/models/station.coffee b/untitled folder/station.coffee similarity index 99% rename from models/station.coffee rename to untitled folder/station.coffee index c9919c5..7034464 100644 --- a/models/station.coffee +++ b/untitled folder/station.coffee @@ -7,4 +7,5 @@ StationSchema = new Schema({ }); module.exports = mongoose.model('Station', StationSchema); + Station = mongoose.model('Station', StationSchema) diff --git a/models/station.js b/untitled folder/station.js similarity index 100% rename from models/station.js rename to untitled folder/station.js From 4f2d538dfe782ec154ca55bdd99d647f8208b45c Mon Sep 17 00:00:00 2001 From: norcal82 Date: Sat, 29 Aug 2015 12:25:59 -0700 Subject: [PATCH 3/3] cleaned up code.setup gulp --- {scripts => dev/js}/main.coffee | 47 +++++---- {scripts => dev/js}/main.js | 70 ++++++------- dev/scss/main.scss | 9 ++ dev/templates/index.jade | 19 ++++ gulpfile.coffee | 94 +++++++++++++++++ gulpfile.js | 111 +++++++++++++++++++++ html/index.html | 1 + index.html | 22 ---- {untitled folder => models}/station.coffee | 0 {untitled folder => models}/station.js | 8 +- prod/css/main.css | 1 + prod/index.html | 19 ++++ prod/js/main.js | 78 +++++++++++++++ prod/js/main.min.js | 1 + server.coffee | 21 ++-- server.js | 24 +++-- 16 files changed, 415 insertions(+), 110 deletions(-) rename {scripts => dev/js}/main.coffee (59%) rename {scripts => dev/js}/main.js (54%) create mode 100644 dev/scss/main.scss create mode 100644 dev/templates/index.jade create mode 100644 gulpfile.coffee create mode 100644 gulpfile.js create mode 100644 html/index.html delete mode 100644 index.html rename {untitled folder => models}/station.coffee (100%) rename {untitled folder => models}/station.js (53%) create mode 100644 prod/css/main.css create mode 100644 prod/index.html create mode 100644 prod/js/main.js create mode 100644 prod/js/main.min.js diff --git a/scripts/main.coffee b/dev/js/main.coffee similarity index 59% rename from scripts/main.coffee rename to dev/js/main.coffee index 932cb16..d04c346 100644 --- a/scripts/main.coffee +++ b/dev/js/main.coffee @@ -8,11 +8,26 @@ $ -> put = 0 color_palette = ['#1abc9c', '#3498db', '#e74c3c', '#f39c12'] request_columns = [['GET', get], ['POST', post], ['DELETE', del], ['PUT', put]] - sensor_counts = [ 'station: 2' ] - sensor_counts1 = [ 'station: 5' ] + sensor_counts = [ 'station: 2', 1 ] + sensor_counts1 = [ 'station: 5', 5 ] sensor_columns = [sensor_counts, sensor_counts1] - generateCharts + # generateCharts = -> + chart = c3.generate + data: + columns: sensor_columns + type: 'area-spline' + color: pattern: color_palette + + chart1 = c3.generate + bindto: '#chart1' + data: + columns: request_columns + type: 'donut' + donut: title: 'HTTP Actions' + color: pattern: color_palette + + # generateCharts socket.on 'getRequest', (data) -> get = get + 1 @@ -24,6 +39,7 @@ $ -> post = post + 1 console.log 'post request' console.log data + updateChart(chart1, request_columns) if data._id == '2' sensor_counts.push data._count @@ -36,26 +52,13 @@ $ -> updateChart(chart, sensor_columns) socket.on 'station_created', (data) -> - console.log 'new station created and registered' - console.log data + # console.log 'new station created and registered' + # console.log data socket.emit 'startup', { client: 'pong' } - generateCharts = -> - chart = c3.generate - data: - columns: sensor_columns - type: 'area-spline' - color: pattern: color_palette - - chart1 = c3.generate - bindto: '#chart1' - data: - columns: sensor_columns - type: 'donut' - donut: title: 'HTTP Actions' - color: pattern: color_palette - - updateChart = (chart, columns) -> chart.load columns + updateChart = (chart, data) -> + chart.load + columns: data -console.error $.extend({arr: [1,2,3,4]},{types: 'this'}) + # console.error $.extend({arr: [1,2,3,4]},{types: 'this'}) diff --git a/scripts/main.js b/dev/js/main.js similarity index 54% rename from scripts/main.js rename to dev/js/main.js index 8779306..ca84161 100644 --- a/scripts/main.js +++ b/dev/js/main.js @@ -7,7 +7,7 @@ }); $(function() { - var CHART_MAX, color_palette, del, generateCharts, get, post, put, request_columns, sensor_columns, sensor_counts, sensor_counts1, updateChart; + var CHART_MAX, chart, chart1, color_palette, del, get, post, put, request_columns, sensor_columns, sensor_counts, sensor_counts1, updateChart; CHART_MAX = 30; get = 0; post = 0; @@ -15,10 +15,31 @@ put = 0; color_palette = ['#1abc9c', '#3498db', '#e74c3c', '#f39c12']; request_columns = [['GET', get], ['POST', post], ['DELETE', del], ['PUT', put]]; - sensor_counts = ['station: 2']; - sensor_counts1 = ['station: 5']; + sensor_counts = ['station: 2', 1]; + sensor_counts1 = ['station: 5', 5]; sensor_columns = [sensor_counts, sensor_counts1]; - generateCharts; + chart = c3.generate({ + data: { + columns: sensor_columns, + type: 'area-spline' + }, + color: { + pattern: color_palette + } + }); + chart1 = c3.generate({ + bindto: '#chart1', + data: { + columns: request_columns, + type: 'donut' + }, + donut: { + title: 'HTTP Actions' + }, + color: { + pattern: color_palette + } + }); socket.on('getRequest', function(data) { get = get + 1; console.log('get request'); @@ -29,6 +50,7 @@ post = post + 1; console.log('post request'); console.log(data); + updateChart(chart1, request_columns); if (data._id === '2') { sensor_counts.push(data._count); if (sensor_counts.length === CHART_MAX) { @@ -42,47 +64,15 @@ } } }); - socket.on('station_created', function(data) { - console.log('new station created and registered'); - return console.log(data); - }); + socket.on('station_created', function(data) {}); socket.emit('startup', { client: 'pong' }); - generateCharts = function() { - var chart, chart1; - chart = c3.generate({ - data: { - columns: sensor_columns, - type: 'area-spline' - }, - color: { - pattern: color_palette - } - }); - return chart1 = c3.generate({ - bindto: '#chart1', - data: { - columns: sensor_columns, - type: 'donut' - }, - donut: { - title: 'HTTP Actions' - }, - color: { - pattern: color_palette - } + return updateChart = function(chart, data) { + return chart.load({ + columns: data }); }; - return updateChart = function(chart, columns) { - return chart.load(columns); - }; }); - console.error($.extend({ - arr: [1, 2, 3, 4] - }, { - types: 'this' - })); - }).call(this); diff --git a/dev/scss/main.scss b/dev/scss/main.scss new file mode 100644 index 0000000..9568417 --- /dev/null +++ b/dev/scss/main.scss @@ -0,0 +1,9 @@ +body { background-color: white; } +h1 { + &:hover { + background-color: dodgerblue; + } + } +.color { + color: blue; +} diff --git a/dev/templates/index.jade b/dev/templates/index.jade new file mode 100644 index 0000000..13601c7 --- /dev/null +++ b/dev/templates/index.jade @@ -0,0 +1,19 @@ +doctype html +html(lang='en') + head + meta(charset='UTF-8') + title Simple Socket IO + link(rel='stylesheet', href='https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css') + link(rel='stylesheet', href='prod/css/main.css') + script(src='https://cdn.socket.io/socket.io-1.3.5.js') + script(src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js') + script(src='https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js') + script(src='https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js') + script(src='prod/js/main.js') + + body(style='background:#fff;') + pre(style='background:#eee;font-size:18px;padding:20px;'). + #chart(width='600', height='400') + br + br + #chart1(width='600', height='400') diff --git a/gulpfile.coffee b/gulpfile.coffee new file mode 100644 index 0000000..d359445 --- /dev/null +++ b/gulpfile.coffee @@ -0,0 +1,94 @@ +'use strict' +gulp = require('gulp') +jade = require('gulp-jade') +minifyHTML = require('gulp-minify-html') +sass = require('gulp-sass') +coffee = require('gulp-coffee') +minifycss = require('gulp-minify-css') +autoprefixer = require('gulp-autoprefixer') +jshint = require('gulp-jshint') +uglify = require('gulp-uglify') +stylish = require('jshint-stylish') +rename = require('gulp-rename') +concat = require('gulp-concat') +notify = require('gulp-notify') +gutil = require('gulp-util'); +plumber = require('gulp-plumber') +browserSync = require('browser-sync') + +reload = browserSync.reload + +# gulp.task 'coffee', -> +# gulp.src('./src/*.coffee').pipe(coffee(bare: true).on('error', gutil.log)).pipe gulp.dest('./public/') + + +target = + template_src: 'dev/templates/*.jade' + sass_src: 'dev/scss/**/*.scss' + cs_src: 'dev/js/*.coffee' + js_lint_src: [ 'js/**/*.js' ] + js_uglify_src: [ '' ] + js_concat_src: [ 'js/**/*.js' ] + css_dest: 'prod/css' + js_dest: 'prod/js' + +gulp.task 'compile-coffee', -> + gulp.src(target.cs_src) + .pipe(coffee({bare: true}).on('error', gutil.log)) + .pipe(gulp.dest('./prod/js')) + +gulp.task 'minify-html', -> + opts = + comments: false + spare: true + gulp.src('./prod/*.html').pipe(minifyHTML(opts)).pipe gulp.dest('html') + +gulp.task 'sass', -> + gulp.src(target.sass_src).pipe(plumber()).pipe(sass()).pipe(autoprefixer('last 2 version', '> 1%', 'ie 8', 'ie 9', 'ios 6', 'android 4')).pipe(minifycss()).pipe(concat('main.css')).pipe(gulp.dest(target.css_dest)).pipe reload(stream: true) + # .pipe(notify({message: 'SCSS processed!'})); // notify when done + +# lint my custom js +gulp.task 'js-lint', -> + gulp.src(target.js_lint_src).pipe(jshint()).pipe jshint.reporter(stylish) + # present the results in a beautiful way + +# minify all js files that should not be concatinated +gulp.task 'js-uglify', -> + gulp.src(target.js_uglify_src).pipe(uglify()).pipe(rename((dir, base, ext) -> + # give the files a min suffix + trunc = base.split('.')[0] + trunc + '.min' + ext + )).pipe gulp.dest(target.js_dest) + # where to put the files + # .pipe(notify({ message: 'JS uglified'})); // notify when done + +# minify & concatinate all other js +gulp.task 'js-concat', -> + gulp.src(target.js_concat_src).pipe(uglify()).pipe(concat('main.min.js')).pipe gulp.dest(target.js_dest) + # where to put the files + # .pipe(notify({message: 'JS concatinated'})); // notify when done + +# Static server +gulp.task 'browser-sync', -> + browserSync + proxy: 'http://localhost:3000' + + +gulp.task 'templates', -> + gulp.src('dev/templates/*.jade').pipe(plumber()).pipe(jade(pretty: true)).pipe(gulp.dest('./prod/')).pipe reload(stream: true) + +# Default task to be run with `gulp` +gulp.task 'default', [ + 'templates' + 'browser-sync' + 'sass' +], -> + gulp.watch target.template_src, [ + 'templates' + 'minify-html' + ] + gulp.watch target.sass_src, [ 'sass' ] + gulp.watch target.cs_src, ['compile-coffee'] + gulp.watch target.js_lint_src, [ 'js-lint' ] + gulp.watch target.js_minify_src, [ 'js-uglify' ] + gulp.watch target.js_concat_src, [ 'js-concat' ] diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..039728c --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,111 @@ +// Generated by CoffeeScript 1.9.3 +(function() { + 'use strict'; + var autoprefixer, browserSync, coffee, concat, gulp, gutil, jade, jshint, minifyHTML, minifycss, notify, plumber, reload, rename, sass, stylish, target, uglify; + + gulp = require('gulp'); + + jade = require('gulp-jade'); + + minifyHTML = require('gulp-minify-html'); + + sass = require('gulp-sass'); + + coffee = require('gulp-coffee'); + + minifycss = require('gulp-minify-css'); + + autoprefixer = require('gulp-autoprefixer'); + + jshint = require('gulp-jshint'); + + uglify = require('gulp-uglify'); + + stylish = require('jshint-stylish'); + + rename = require('gulp-rename'); + + concat = require('gulp-concat'); + + notify = require('gulp-notify'); + + gutil = require('gulp-util'); + + plumber = require('gulp-plumber'); + + browserSync = require('browser-sync'); + + reload = browserSync.reload; + + target = { + template_src: 'dev/templates/*.jade', + sass_src: 'dev/scss/**/*.scss', + cs_src: 'dev/js/*.coffee', + js_lint_src: ['js/**/*.js'], + js_uglify_src: [''], + js_concat_src: ['js/**/*.js'], + css_dest: 'prod/css', + js_dest: 'prod/js' + }; + + gulp.task('compile-coffee', function() { + return gulp.src(target.cs_src).pipe(coffee({ + bare: true + }).on('error', gutil.log)).pipe(gulp.dest('./prod/js')); + }); + + gulp.task('minify-html', function() { + var opts; + opts = { + comments: false, + spare: true + }; + return gulp.src('./prod/*.html').pipe(minifyHTML(opts)).pipe(gulp.dest('html')); + }); + + gulp.task('sass', function() { + return gulp.src(target.sass_src).pipe(plumber()).pipe(sass()).pipe(autoprefixer('last 2 version', '> 1%', 'ie 8', 'ie 9', 'ios 6', 'android 4')).pipe(minifycss()).pipe(concat('main.css')).pipe(gulp.dest(target.css_dest)).pipe(reload({ + stream: true + })); + }); + + gulp.task('js-lint', function() { + return gulp.src(target.js_lint_src).pipe(jshint()).pipe(jshint.reporter(stylish)); + }); + + gulp.task('js-uglify', function() { + return gulp.src(target.js_uglify_src).pipe(uglify()).pipe(rename(function(dir, base, ext) { + var trunc; + trunc = base.split('.')[0]; + return trunc + '.min' + ext; + })).pipe(gulp.dest(target.js_dest)); + }); + + gulp.task('js-concat', function() { + return gulp.src(target.js_concat_src).pipe(uglify()).pipe(concat('main.min.js')).pipe(gulp.dest(target.js_dest)); + }); + + gulp.task('browser-sync', function() { + return browserSync({ + proxy: 'http://localhost:3000' + }); + }); + + gulp.task('templates', function() { + return gulp.src('dev/templates/*.jade').pipe(plumber()).pipe(jade({ + pretty: true + })).pipe(gulp.dest('./prod/')).pipe(reload({ + stream: true + })); + }); + + gulp.task('default', ['templates', 'browser-sync', 'sass'], function() { + gulp.watch(target.template_src, ['templates', 'minify-html']); + gulp.watch(target.sass_src, ['sass']); + gulp.watch(target.cs_src, ['compile-coffee']); + gulp.watch(target.js_lint_src, ['js-lint']); + gulp.watch(target.js_minify_src, ['js-uglify']); + return gulp.watch(target.js_concat_src, ['js-concat']); + }); + +}).call(this); diff --git a/html/index.html b/html/index.html new file mode 100644 index 0000000..95d98e3 --- /dev/null +++ b/html/index.html @@ -0,0 +1 @@ +Simple Socket IO


some new things

\ No newline at end of file diff --git a/index.html b/index.html deleted file mode 100644 index c442e75..0000000 --- a/index.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - Simple Socket IO - - - -

-  
-
-
-
- - - - - - - - - diff --git a/untitled folder/station.coffee b/models/station.coffee similarity index 100% rename from untitled folder/station.coffee rename to models/station.coffee diff --git a/untitled folder/station.js b/models/station.js similarity index 53% rename from untitled folder/station.js rename to models/station.js index dc98985..d1925fc 100644 --- a/untitled folder/station.js +++ b/models/station.js @@ -1,13 +1,17 @@ // Generated by CoffeeScript 1.9.3 (function() { - var StationSchema, mongoose; + var Schema, Station, StationSchema, mongoose; mongoose = require('mongoose'); - StationSchema = new mongoose.Schema({ + Schema = mongoose.Schema; + + StationSchema = new Schema({ count: Number }); module.exports = mongoose.model('Station', StationSchema); + Station = mongoose.model('Station', StationSchema); + }).call(this); diff --git a/prod/css/main.css b/prod/css/main.css new file mode 100644 index 0000000..c8f352f --- /dev/null +++ b/prod/css/main.css @@ -0,0 +1 @@ +body{background-color:#fff}h1:hover{background-color:#1e90ff}.color{color:#00f} \ No newline at end of file diff --git a/prod/index.html b/prod/index.html new file mode 100644 index 0000000..33afdd7 --- /dev/null +++ b/prod/index.html @@ -0,0 +1,19 @@ + + + + + Simple Socket IO + + + + + + + + + +

+    


+
+ + \ No newline at end of file diff --git a/prod/js/main.js b/prod/js/main.js new file mode 100644 index 0000000..ca84161 --- /dev/null +++ b/prod/js/main.js @@ -0,0 +1,78 @@ +// Generated by CoffeeScript 1.9.3 +(function() { + var socket; + + socket = io.connect('http://localhost:3000', { + 'force new connection': true + }); + + $(function() { + var CHART_MAX, chart, chart1, color_palette, del, get, post, put, request_columns, sensor_columns, sensor_counts, sensor_counts1, updateChart; + CHART_MAX = 30; + get = 0; + post = 0; + del = 0; + put = 0; + color_palette = ['#1abc9c', '#3498db', '#e74c3c', '#f39c12']; + request_columns = [['GET', get], ['POST', post], ['DELETE', del], ['PUT', put]]; + sensor_counts = ['station: 2', 1]; + sensor_counts1 = ['station: 5', 5]; + sensor_columns = [sensor_counts, sensor_counts1]; + chart = c3.generate({ + data: { + columns: sensor_columns, + type: 'area-spline' + }, + color: { + pattern: color_palette + } + }); + chart1 = c3.generate({ + bindto: '#chart1', + data: { + columns: request_columns, + type: 'donut' + }, + donut: { + title: 'HTTP Actions' + }, + color: { + pattern: color_palette + } + }); + socket.on('getRequest', function(data) { + get = get + 1; + console.log('get request'); + console.log(data); + return updateChart(chart1, request_columns); + }); + socket.on('postRequest', function(data) { + post = post + 1; + console.log('post request'); + console.log(data); + updateChart(chart1, request_columns); + if (data._id === '2') { + sensor_counts.push(data._count); + if (sensor_counts.length === CHART_MAX) { + return sensor_counts.splice(1, 1); + } + } else { + sensor_counts1.push(data._count); + if (sensor_counts1.length === CHART_MAX) { + sensor_counts1.splice(1, 1); + return updateChart(chart, sensor_columns); + } + } + }); + socket.on('station_created', function(data) {}); + socket.emit('startup', { + client: 'pong' + }); + return updateChart = function(chart, data) { + return chart.load({ + columns: data + }); + }; + }); + +}).call(this); diff --git a/prod/js/main.min.js b/prod/js/main.min.js new file mode 100644 index 0000000..4544d0a --- /dev/null +++ b/prod/js/main.min.js @@ -0,0 +1 @@ +(function(){var t;t=io.connect("http://localhost:3000",{"force new connection":!0}),$(function(){var e,n,o,c,r,s,l,a,i,u,p,g;return e=30,r=0,s=0,o=0,l=0,n=["#1abc9c","#3498db","#e74c3c","#f39c12"],a=[["GET",r],["POST",s],["DELETE",o],["PUT",l]],u=["station: 2"],p=["station: 5"],i=[u,p],t.on("getRequest",function(t){return r+=1,console.log("get request"),console.log(t),g(chart1,a)}),t.on("postRequest",function(t){if(s+=1,console.log("post request"),console.log(t),"2"===t._id){if(u.push(t._count),u.length===e)return u.splice(1,1)}else if(p.push(t._count),p.length===e)return p.splice(1,1),g(chart,i)}),t.on("station_created",function(t){return console.log("new station created and registered"),console.log(t)}),t.emit("startup",{client:"pong"}),c=function(){var t,e;return t=c3.generate({data:{columns:i,type:"area-spline"},color:{pattern:n}}),e=c3.generate({bindto:"#chart1",data:{columns:i,type:"donut"},donut:{title:"HTTP Actions"},color:{pattern:n}})},g=function(t,e){return t.load(e)}}),console.error($.extend({arr:[1,2,3,4]},{types:"this"}))}).call(this); \ No newline at end of file diff --git a/server.coffee b/server.coffee index 004f473..620d0b2 100644 --- a/server.coffee +++ b/server.coffee @@ -6,6 +6,10 @@ request = require('request') morgan = require('morgan') mongoose = require('mongoose') +bodyParser = require('body-parser'); +app.use(bodyParser.json()); # support json encoded bodies +app.use(bodyParser.urlencoded({ extended: true })); # support encoded bodies + port_number = process.argv[2] || 3000 server.listen port_number @@ -15,7 +19,8 @@ base_uri = 'http://localhost:3000' mongodb_uri = 'http://localhost:28017/serverStatus' index = '/' -app.use("/scripts", express.static(__dirname + '/scripts')); +app.use("/prod/css", express.static(__dirname + '/prod/css')); +app.use("/prod/js", express.static(__dirname + '/prod/js')); # logging app.use(morgan('combined')) @@ -38,31 +43,21 @@ StationSchema = new Schema({ module.exports = mongoose.model('Station', StationSchema); Station = mongoose.model('Station', StationSchema) - -bodyParser = require('body-parser'); -app.use(bodyParser.json()); # support json encoded bodies -app.use(bodyParser.urlencoded({ extended: true })); # support encoded bodies - io.on 'connection', (socket) -> socket.emit 'startup', { server: 'ping' } app.get index, (req, res) -> io.sockets.emit 'getRequest', {} - res.sendFile __dirname + '/index.html' + res.sendFile __dirname + '/prod/index.html' # app.get '/api/station/:id', (req, res) -> # res.json({ message: 'get @ /api endpoint' }) - # gets last saved values - # PUTS # app.put '/api/station/:id', (req, res) -> # console.log req.params.id - # data = { message: 'put @ /api endpoint' } - # res.json(data) - # udpates the ui # app.post '/api/station/sensor', (req, res) -> @@ -97,7 +92,7 @@ getRequest = -> setInterval(postRequest, 2000) setInterval(postRequest1, 1500) -setInterval(getRequest, 1000) +setInterval(getRequest, 3000) request mongodb_uri, (error, response, body) -> if !error and response.statusCode == 200 diff --git a/server.js b/server.js index 90ce8ff..f09ba6e 100644 --- a/server.js +++ b/server.js @@ -16,6 +16,14 @@ mongoose = require('mongoose'); + bodyParser = require('body-parser'); + + app.use(bodyParser.json()); + + app.use(bodyParser.urlencoded({ + extended: true + })); + port_number = process.argv[2] || 3000; server.listen(port_number); @@ -28,7 +36,9 @@ index = '/'; - app.use("/scripts", express["static"](__dirname + '/scripts')); + app.use("/prod/css", express["static"](__dirname + '/prod/css')); + + app.use("/prod/js", express["static"](__dirname + '/prod/js')); app.use(morgan('combined')); @@ -52,14 +62,6 @@ Station = mongoose.model('Station', StationSchema); - bodyParser = require('body-parser'); - - app.use(bodyParser.json()); - - app.use(bodyParser.urlencoded({ - extended: true - })); - io.on('connection', function(socket) { return socket.emit('startup', { server: 'ping' @@ -68,7 +70,7 @@ app.get(index, function(req, res) { io.sockets.emit('getRequest', {}); - return res.sendFile(__dirname + '/index.html'); + return res.sendFile(__dirname + '/prod/index.html'); }); app.post('/api/station', function(req, res) { @@ -118,7 +120,7 @@ setInterval(postRequest1, 1500); - setInterval(getRequest, 1000); + setInterval(getRequest, 3000); request(mongodb_uri, function(error, response, body) { var data;