diff --git a/README.md b/README.md new file mode 100644 index 0000000..01f3f00 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +Welcome \ No newline at end of file diff --git a/app-old.js b/app-old.js deleted file mode 100644 index 073aba9..0000000 --- a/app-old.js +++ /dev/null @@ -1,96 +0,0 @@ -var kickstart = require('kickstart').withConfig({'name': 'localhost', 'port': 8080, 'path': __dirname}); -var Noduino = new require('./libs/Noduino')({'debug': true}); -var Socket = function(options) { this.io = null; this.sockets = {}; this.arduinos = []; this.checkSocket(); }; -Socket.prototype.checkSocket = function() { if (this.io == null) { this.io = require('socket.io'); } }; -Socket.prototype.bootstrap = function() { - var that = this; - this.io.sockets.on('connection', function(socket) { - that.sockets[socket.id] = socket; - - /** - * Handle incoming requests for connect to an arduino board - */ - that.sockets[socket.id].on('board.connect', function(data) { - if (!data) { - var data = {}; } - if (!data.id) { - data.id = 0; } - - if (that.arduinos[data.id]) { - return socket.emit('response', {'msg': 'board.connect', 'response': 'ready' }); } - Noduino.connect({'type': 'serial'}, function(err, board) { - that.arduinos[data.id] = board; - socket.emit('response', {'msg': 'board.connect', 'response': (!err ? 'ready' : 'failed') }); - }); - }); - }); -}; -Socket.prototype.listen = function(port) { this.io = this.io.listen(port); this.bootstrap(); }; - -var NoduinoServer = new Socket(); -NoduinoServer.listen(8090); - -var srv = kickstart.srv(); - -srv.all('/', function(req, res) { - var examples = { - 'basics': [ '> ls /dev | grep usb', - 'crw-rw-rw- 1 root wheel 18, 17 24 Feb 22:54 cu.usbmodem1d11', - 'crw-rw-rw- 1 root wheel 18, 16 24 Feb 22:00 tty.usbmodem1d11'].join('\n'), - 'node': [ '> npm install', - '> node app.js', - 'Listening on http://localhost:8080'].join('\n'), - 'toggleLED': ["var Noduino = new require('./libs/Noduino')({'debug': true});", - "Noduino.connect({'type': 'socket'}, function(err, board) {", - " if (err) { return console.log(err); }", - " board.withLED({pin: 13}, function(err, LED) {", - " if (err) { return console.log(err); }", - "", - " LED.blink(250);", - " });", - "});"].join('\n'), - 'connect': [ "var Noduino = new require('./libs/Noduino')({'debug': true});", - "Noduino.connect({'type': 'socket'}, function(err, board) {", - " if (err) { return console.log(err); }", - " ", - " console.log('Connected to board');", - "});"].join('\n'), - 'listenButton': [ "var Noduino = new require('./libs/Noduino')({'debug': true});", - "Noduino.connect({'type': 'socket'}, function(err, board) {", - " if (err) { return console.log(err); }", - " ", - " board.withButton({pin: 9}, function(err, Button)) {", - " Button.on(cnst.HIGH, function(mode) {", - " console.log('pushed!');", - " });", - " Button.on(cnst.LOW, function(mode) {", - " console.log('released!');", - " });", - " })", - "});"].join('\n'), - 'analogRead': [ 'noduino.connect(function(err, board) {', - ' if (err) { return console.log(\'failed to connect!\'); }', - ' console.log(\'connected\');', - '});'].join('\n'), - 'digitalRead': [ 'noduino.connect(function(err, board) {', - ' board.registerPin({pin: 9}, function(err, pin) {', - ' pin.digitalRead(function(err, value) {', - ' console.log(\'received value: \' + value);', - ' });', - ' })', - '});'].join('\n'), - 'digitalWrite': [ 'noduino.connect(function(err, board) {', - ' board.registerPin({pin: 9}, function(err, pin) {', - ' pin.digitalWrite(const.HIGH, function(err, value) {', - ' console.log(\'set pin to value: \' + value);', - ' });', - ' })', - '});'].join('\n') - - - } - res.render('home', {title: 'noduino', 'examples': examples}); -}); - -var router = kickstart.listen(); -console.log("Listening on http://%s:%d", kickstart.conf().name, router.address().port); \ No newline at end of file diff --git a/app.js b/app.js deleted file mode 100644 index 073aba9..0000000 --- a/app.js +++ /dev/null @@ -1,96 +0,0 @@ -var kickstart = require('kickstart').withConfig({'name': 'localhost', 'port': 8080, 'path': __dirname}); -var Noduino = new require('./libs/Noduino')({'debug': true}); -var Socket = function(options) { this.io = null; this.sockets = {}; this.arduinos = []; this.checkSocket(); }; -Socket.prototype.checkSocket = function() { if (this.io == null) { this.io = require('socket.io'); } }; -Socket.prototype.bootstrap = function() { - var that = this; - this.io.sockets.on('connection', function(socket) { - that.sockets[socket.id] = socket; - - /** - * Handle incoming requests for connect to an arduino board - */ - that.sockets[socket.id].on('board.connect', function(data) { - if (!data) { - var data = {}; } - if (!data.id) { - data.id = 0; } - - if (that.arduinos[data.id]) { - return socket.emit('response', {'msg': 'board.connect', 'response': 'ready' }); } - Noduino.connect({'type': 'serial'}, function(err, board) { - that.arduinos[data.id] = board; - socket.emit('response', {'msg': 'board.connect', 'response': (!err ? 'ready' : 'failed') }); - }); - }); - }); -}; -Socket.prototype.listen = function(port) { this.io = this.io.listen(port); this.bootstrap(); }; - -var NoduinoServer = new Socket(); -NoduinoServer.listen(8090); - -var srv = kickstart.srv(); - -srv.all('/', function(req, res) { - var examples = { - 'basics': [ '> ls /dev | grep usb', - 'crw-rw-rw- 1 root wheel 18, 17 24 Feb 22:54 cu.usbmodem1d11', - 'crw-rw-rw- 1 root wheel 18, 16 24 Feb 22:00 tty.usbmodem1d11'].join('\n'), - 'node': [ '> npm install', - '> node app.js', - 'Listening on http://localhost:8080'].join('\n'), - 'toggleLED': ["var Noduino = new require('./libs/Noduino')({'debug': true});", - "Noduino.connect({'type': 'socket'}, function(err, board) {", - " if (err) { return console.log(err); }", - " board.withLED({pin: 13}, function(err, LED) {", - " if (err) { return console.log(err); }", - "", - " LED.blink(250);", - " });", - "});"].join('\n'), - 'connect': [ "var Noduino = new require('./libs/Noduino')({'debug': true});", - "Noduino.connect({'type': 'socket'}, function(err, board) {", - " if (err) { return console.log(err); }", - " ", - " console.log('Connected to board');", - "});"].join('\n'), - 'listenButton': [ "var Noduino = new require('./libs/Noduino')({'debug': true});", - "Noduino.connect({'type': 'socket'}, function(err, board) {", - " if (err) { return console.log(err); }", - " ", - " board.withButton({pin: 9}, function(err, Button)) {", - " Button.on(cnst.HIGH, function(mode) {", - " console.log('pushed!');", - " });", - " Button.on(cnst.LOW, function(mode) {", - " console.log('released!');", - " });", - " })", - "});"].join('\n'), - 'analogRead': [ 'noduino.connect(function(err, board) {', - ' if (err) { return console.log(\'failed to connect!\'); }', - ' console.log(\'connected\');', - '});'].join('\n'), - 'digitalRead': [ 'noduino.connect(function(err, board) {', - ' board.registerPin({pin: 9}, function(err, pin) {', - ' pin.digitalRead(function(err, value) {', - ' console.log(\'received value: \' + value);', - ' });', - ' })', - '});'].join('\n'), - 'digitalWrite': [ 'noduino.connect(function(err, board) {', - ' board.registerPin({pin: 9}, function(err, pin) {', - ' pin.digitalWrite(const.HIGH, function(err, value) {', - ' console.log(\'set pin to value: \' + value);', - ' });', - ' })', - '});'].join('\n') - - - } - res.render('home', {title: 'noduino', 'examples': examples}); -}); - -var router = kickstart.listen(); -console.log("Listening on http://%s:%d", kickstart.conf().name, router.address().port); \ No newline at end of file diff --git a/examples.snippet b/examples.snippet index ca2c3f7..dbf6a3e 100644 --- a/examples.snippet +++ b/examples.snippet @@ -8,68 +8,40 @@ crw-rw-rw- 1 root wheel 18, 16 24 Feb 22:00 tty.usbmodem1d11 > node app.js Listening on http://localhost:8080 -###toggleLED -require(['libs/Noduino', 'libs/Noduino.Socket'], function(NoduinoObj, Connector) { - var Noduino = new NoduinoObj({debug: true, host: 'http://localhost:8090'}, Connector); - Noduino.connect(function(err, board) { - if (err) { return console.log(err); } - board.withLED({pin: 13}, function(err, LED) { - if (err) { return console.log(err); } - - LED.blink(250); - LED.on('change', function() } - console.log('LED changed to ' + (data.mode == Noduino.HIGH ? '[on]' : '[off]')); - }); - }); - }) -}); ###connect -require(['libs/Noduino', 'libs/Noduino.Socket'], function(NoduinoObj, Connector) { - var Noduino = new NoduinoObj({debug: true, host: 'http://localhost:8090'}, Connector); - Noduino.connect(function(err, board) { - if (err) { return console.log(err); } +var Noduino = new NoduinoObj({debug: true, host: 'http://localhost:8090'}, Connector); +Noduino.connect(function(err, board) { + if (err) { return console.log(err); } - console.log('Connected to board'); - }); + console.log('Connected to board'); }); -###listenButton -var Noduino = new require('./libs/Noduino')({'debug': true}); -Noduino.connect({'type': 'socket'}, function(err, board) { +###toggleLED +var Noduino = new NoduinoObj({debug: true, host: 'http://localhost:8090'}, Connector); +Noduino.connect(function(err, board) { if (err) { return console.log(err); } - board.withButton({pin: 9}, function(err, Button)) { - Button.on(cnst.HIGH, function(mode) { - console.log('pushed!'); - }); - - Button.on(cnst.LOW, function(mode) { - console.log('released!'); + board.withLED({pin: 13}, function(err, LED) { + if (err) { return console.log(err); } + + LED.blink(250); + LED.on('on', function() } + console.log('LED is on!'); }); - }) + }); }); - -###analogRead -noduino.connect(function(err, board) { - if (err) { return console.log('failed to connect!'); } - console.log('connected'); -}); +###listenButton +var Noduino = new NoduinoObj({debug: true, host: 'http://localhost:8090'}, Connector); +Noduino.connect(function(err, board) { + if (err) { return console.log(err); } + board.withButton({pin: 13}, function(err, Button) { + if (err) { return console.log(err); } -###digitalRead -noduino.connect(function(err, board) { - board.registerPin({pin: 9}, function(err, pin) { - pin.digitalRead(function(err, value) { - console.log('received value: ' + value); + Button.on('push', function() } + console.log('Button pushed'); }); + + Button.push(); }); }); - -###digitalWrite -noduino.connect(function(err, board) { - board.registerPin({pin: 9}, function(err, pin) { - pin.digitalWrite(const.HIGH, function(err, value) { - console.log('set pin to value: ' + value); - }); - }) -}); \ No newline at end of file diff --git a/examples/http_analogled.js b/examples/http_analogled.js deleted file mode 100644 index ba77a61..0000000 --- a/examples/http_analogled.js +++ /dev/null @@ -1,21 +0,0 @@ -var arduino = require('./duino/'); - -var board = new arduino.Board({debug: true}); -var aled = new arduino.Led({board: board, pin: 9}); - -board.on('ready', function(){ - var app = require('express').createServer(); - - app.get('/', function(req, res){ - res.send(''); - }); - - app.get('/fade/:level', function(req, res){ - aled.brightLevel(req.param('level')); - res.send('set to: ' + req.param('level')); - }); - - app.listen(8080); - - console.log('Listening on http://127.0.0.1:8080'); -}); diff --git a/examples/http_ledonoff.js b/examples/http_ledonoff.js deleted file mode 100644 index a579ae9..0000000 --- a/examples/http_ledonoff.js +++ /dev/null @@ -1,26 +0,0 @@ -var arduino = require('../duino/'); - -var board = new arduino.Board({debug: true}); -var led = new arduino.Led({board: board}); - -board.on('ready', function(){ - var app = require('express').createServer(); - - app.get('/', function(req, res){ - res.send('ON OFF'); - }); - - app.get('/on', function(req, res){ - led.on(); - res.redirect('/'); - }); - - app.get('/off', function(req, res){ - led.off(); - res.redirect('/'); - }); - - app.listen(8080); - - console.log('Listening on http://127.0.0.1:8080'); -}); \ No newline at end of file diff --git a/examples/test.blinkLED.js b/examples/test.blinkLED.js new file mode 100644 index 0000000..1a09068 --- /dev/null +++ b/examples/test.blinkLED.js @@ -0,0 +1,18 @@ +var requirejs = require('requirejs'); +requirejs.config({nodeRequire: require}); + +requirejs(['../public/scripts/libs/Noduino', '../public/scripts/libs/Noduino.Serial', '../public/scripts/libs/Logger'], function (NoduinoObj, NoduinoConnector, Logger) { + var Noduino = new NoduinoObj({'debug': false}, NoduinoConnector, Logger); + Noduino.connect(function(err, board) { + if (err) { return console.log(err); } + + board.withLED({pin: 12}, function(err, LED) { + if (err) { return console.log(err); } + + LED.blink(250); + LED.on('on', function(e) { + console.log('LED is on!'); + }); + }); + }); +}); \ No newline at end of file diff --git a/examples/test.readAnalogIn.js b/examples/test.readAnalogIn.js new file mode 100644 index 0000000..2aa2b93 --- /dev/null +++ b/examples/test.readAnalogIn.js @@ -0,0 +1,15 @@ +var requirejs = require('requirejs'); +requirejs.config({nodeRequire: require}); + +requirejs(['../public/scripts/libs/Noduino', '../public/scripts/libs/Noduino.Serial', '../public/scripts/libs/Logger'], function (NoduinoObj, NoduinoConnector, Logger) { + var Noduino = new NoduinoObj({'debug': false}, NoduinoConnector, Logger); + Noduino.connect(function(err, board) { + if (err) { return console.log(err); } + + board.withAnalogInput({pin: 'A0'}, function(err, AnalogInput) { + AnalogInput.on('change', function(a) { + console.log('read value: ' + a.value); + }); + }); + }); +}); \ No newline at end of file diff --git a/examples/test.walkLED.js b/examples/test.walkLED.js new file mode 100644 index 0000000..f19ff85 --- /dev/null +++ b/examples/test.walkLED.js @@ -0,0 +1,90 @@ +var requirejs = require('requirejs'); +requirejs.config({nodeRequire: require}); + +var maxLEDs = 6; +var current = 1; +var direction = -1; +var curInterval = 100; +var currentStepper = null; +var LEDlist = []; +var sorting = [12, 11, 10, 9, 8, 7]; + +/** + * Set LED up and running. If all LEDs are connected start the blinking sequence + * @param object led + */ +function readyLED(led) { + LEDlist[sorting.indexOf(led.pin)] = led; + if (LEDlist.length == maxLEDs) { + startSequence(-1, curInterval); } +} + +/** + * Add Button and watch for push event + * @param object Button + */ +function addButton(Button) { + Button.on('push', function(e) { + var newDirection = direction; + + switch (Button.pin) { + case '04': newDirection = -1; break; + case '02': newDirection = 1; break; + } + + if (newDirection != direction) { + startSequence(newDirection, curInterval); + } + }); +} + +/** + * Iterate through LEDs + * This code is noduino-free, no need to modify this + */ +function stepper() { + var next = current + direction; + if (next == maxLEDs + 1) { + next = 1; } + if (next == 0) { + next = maxLEDs; } + current = next; + for (var i = 1; i <= maxLEDs; i++) { + LEDlist[i-1].setOff(); } + LEDlist[(current-1)].setOn(); +} + +/** + * Start blinking sequence if all LEDs are up and running + */ +function startSequence(step, interval) { + if (LEDlist.length != maxLEDs) { + return; }; + + clearInterval(currentStepper); + direction = step || 1; + currentStepper = setInterval(function() { + return stepper(); + }, interval); +} + +requirejs(['../public/scripts/libs/Noduino', '../public/scripts/libs/Noduino.Serial', '../public/scripts/libs/Logger'], function (NoduinoObj, NoduinoConnector, Logger) { + var Noduino = new NoduinoObj({'debug': true}, NoduinoConnector, Logger); + Noduino.connect(function(err, board) { + if (err) { return console.log(err); } + + board.withLED({pin: 12}, function(err, LED) { readyLED(LED); }); + board.withLED({pin: 11}, function(err, LED) { readyLED(LED); }); + board.withLED({pin: 10}, function(err, LED) { readyLED(LED); }); + board.withLED({pin: 9}, function(err, LED) { readyLED(LED); }); + board.withLED({pin: 8}, function(err, LED) { readyLED(LED); }); + board.withLED({pin: 7}, function(err, LED) { readyLED(LED); }); + board.withButton({pin: 2}, function(err, Button) { addButton(Button); }); + board.withButton({pin: 4}, function(err, Button) { addButton(Button); }); + board.withAnalogInput({pin: 'A0'}, function(err, AnalogInput) { + AnalogInput.on('change', function(a) { + curInterval = a.value; startSequence(direction, curInterval); + }); + }); + }); +}); \ No newline at end of file diff --git a/public/images/glyphicons-halflings-white.png b/public/images/glyphicons-halflings-white.png new file mode 100644 index 0000000..a20760b Binary files /dev/null and b/public/images/glyphicons-halflings-white.png differ diff --git a/public/scripts/app.main.js b/public/scripts/app.main.js new file mode 100755 index 0000000..fb6360a --- /dev/null +++ b/public/scripts/app.main.js @@ -0,0 +1,7 @@ +var p = '/scripts/vendor/'; +require(["jquery", p + "dropdown.js", p + "prettify.js", "./scripts/examples.js"], function($, dd, pf, examples) { + $(document).ready(function(e) { + prettyPrint(); + examples.bind(); + }); +}); \ No newline at end of file diff --git a/public/scripts/app.walkLED.js b/public/scripts/app.walkLED.js new file mode 100755 index 0000000..6cfb1ac --- /dev/null +++ b/public/scripts/app.walkLED.js @@ -0,0 +1,112 @@ +var pv = '/scripts/vendor/'; +var pl = '/scripts/libs/'; +require(["jquery", pv + "dropdown.js", pv + "prettify.js", pl + 'Noduino.js', pl + 'Noduino.Socket.js', pl + 'Logger.HTML.js'], function($, dd, p, NoduinoObj, Connector, Logger) { + var Noduino = null; + + var walkLED = { + listLED: [], + listButton: {}, + current: 1, + direction: 1, + sorting: [12, 11, 10, 9, 8, 7], + maxLEDs: 6, + interval: 320}; + + var readyLED = function(led) { + walkLED.listLED[walkLED.sorting.indexOf(led.pin)] = led; + if (walkLED.listLED.length == walkLED.maxLEDs) { + Noduino.log('success', 'Loaded all LEDs'); + startSequence(-1, walkLED.interval); + } + }; + + function addButton(Button, dir) { + walkLED.listButton[Button.pin] = Button; + + Button.on('release', function(e) { + $('#btn-' + e.pin).removeClass('btn-warning'); + }); + + Button.on('push', function(e) { + var newDirection = walkLED.direction; + + switch (e.pin) { + case '04': newDirection = -1; break; + case '02': newDirection = 1; break; + } + + Noduino.log('gui', 'Pushed Button ' + e.pin); + $('#btn-' + e.pin).addClass('btn-warning'); + + if (newDirection != walkLED.direction) { + startSequence(newDirection, walkLED.interval); + } + }); + } + + function stepper() { + var next = walkLED.current + walkLED.direction; + if (next == walkLED.maxLEDs + 1) { + next = 1; } + if (next == 0) { + next = walkLED.maxLEDs; } + walkLED.current = next; + $('#leds .btn').removeClass('btn-warning'); + for (var i = 1; i <= walkLED.maxLEDs; i++) { + walkLED.listLED[i-1].setOff(); } + walkLED.listLED[(walkLED.current-1)].setOn(); + Noduino.log('gui', 'setting on LED #led-' + walkLED.current); + $('#led-' + walkLED.current).addClass('btn-warning'); + } + + function startSequence(step, interval) { + if (walkLED.listLED.length != walkLED.maxLEDs) { + return; }; + + clearInterval(walkLED.currentStepper); + walkLED.direction = step || 1; + walkLED.currentStepper = setInterval(function() { + return stepper(); + }, interval); + } + + var createObjects = function(board) { + board.withLED({pin: 12}, function(err, LED) { readyLED(LED); }); + board.withLED({pin: 11}, function(err, LED) { readyLED(LED); }); + board.withLED({pin: 10}, function(err, LED) { readyLED(LED); }); + board.withLED({pin: 9}, function(err, LED) { readyLED(LED); }); + board.withLED({pin: 8}, function(err, LED) { readyLED(LED); }); + board.withLED({pin: 7}, function(err, LED) { readyLED(LED); }); + board.withButton({pin: 2}, function(err, Button) { addButton(Button); $('#btn-02').click(function(e) {e.preventDefault(); Button.setOn(); Button.setOff(); }); }); + board.withButton({pin: 4}, function(err, Button) { addButton(Button); $('#btn-04').click(function(e) {e.preventDefault(); Button.setOn(); Button.setOff(); }); }); + board.withAnalogInput({pin: 'A0'}, function(err, AnalogInput) { + $('#interval-slide').change(function(e) { + AnalogInput.set($('#interval-slide').val()); + }); + + AnalogInput.on('change', function(a) { + //$('#interval-slide').val(a.value); + //$('#interval-value').val(a.value + 'ms'); + walkLED.interval = a.value; startSequence(walkLED.direction, walkLED.interval); + }); + }); + + }; + + $(document).ready(function(e) { + $('#connect').click(function(e) { + e.preventDefault(); + + if (!Noduino || !Noduino.connected) { + Noduino = new NoduinoObj({debug: true, host: 'http://localhost:8090', logger: {container: '#connection-log'}}, Connector, Logger); + Noduino.connect(function(err, board) { + $('#connection-status .alert').addClass('hide'); + if (err) { + $('#connection-status .alert-error').removeClass('hide'); } + else { + $('#connection-status .alert-success').removeClass('hide'); createObjects(board); } + }); + } + }); + }); +}); \ No newline at end of file diff --git a/public/scripts/example-1.js b/public/scripts/example-1.js index e7b5941..7d4629a 100755 --- a/public/scripts/example-1.js +++ b/public/scripts/example-1.js @@ -4,9 +4,8 @@ define(function() { } Example.handle = function() { - - require(['libs/Noduino', 'libs/Noduino.Socket'], function(NoduinoObj, Connector) { - var Noduino = new NoduinoObj({debug: true, host: 'http://localhost:8090'}, Connector); + require(['/scripts/libs/Noduino.js', '/scripts/libs/Noduino.Socket.js', '/scripts/libs/Logger.js'], function(NoduinoObj, Connector, Logger) { + var Noduino = new NoduinoObj({debug: false, host: 'http://localhost:8090'}, Connector, Logger); Noduino.connect(function(err, board) { $('#e1-exampleConnection .alert').addClass('hide'); if (err) { @@ -15,7 +14,6 @@ define(function() { $('#e1-exampleConnection .alert-success').removeClass('hide'); } }); }); - }; return Example; diff --git a/public/scripts/example-2.js b/public/scripts/example-2.js index be9af7b..140307e 100755 --- a/public/scripts/example-2.js +++ b/public/scripts/example-2.js @@ -6,8 +6,8 @@ define(function() { Example2.handle = function() { var that = this; - require(['libs/Noduino', 'libs/Noduino.Socket'], function(NoduinoObj, Connector) { - var Noduino = new NoduinoObj({debug: true, host: 'http://localhost:8090'}, Connector); + require(['/scripts/libs/Noduino.js', '/scripts/libs/Noduino.Socket.js', '/scripts/libs/Logger.js'], function(NoduinoObj, Connector, Logger) { + var Noduino = new NoduinoObj({debug: false, host: 'http://localhost:8090'}, Connector, Logger); Noduino.connect(function(err, board) { $('#e2-exampleConnection .alert').addClass('hide'); if (err) { @@ -21,12 +21,16 @@ define(function() { }; + Example2.stop = function() { + this.led.stopBlinking(); + }; + Example2.start = function(pin, interval) { var that = this; if (!that.led) { this.board.withLED({pin: pin}, function(err, LED) { if (err) { return console.log(err); } - + that.led = LED; that.led.blink(interval); that.led.on('change', function(data) { diff --git a/public/scripts/example-3.js b/public/scripts/example-3.js index f9deb2a..f41fb54 100755 --- a/public/scripts/example-3.js +++ b/public/scripts/example-3.js @@ -5,8 +5,8 @@ define(function() { Example3.handle = function() { - require(['libs/Noduino', 'libs/Noduino.Socket'], function(NoduinoObj, Connector) { - var Noduino = new NoduinoObj({debug: true, host: 'http://localhost:8090'}, Connector); + require(['/scripts/libs/Noduino.js', '/scripts/libs/Noduino.Socket.js', '/scripts/libs/Logger.js'], function(NoduinoObj, Connector, Logger) { + var Noduino = new NoduinoObj({debug: false, host: 'http://localhost:8090'}, Connector, Logger); Noduino.connect(function(err, board) { $('#e3-exampleConnection .alert').addClass('hide'); if (err) { @@ -14,7 +14,7 @@ define(function() { else { $('#e3-exampleConnection .alert-success').removeClass('hide'); } - board.withButton({pin: 6}, function(err, Button) { + board.withButton({pin: 4}, function(err, Button) { Button.on('change', function(B) { if (B.pushed) { $('#e3-exampleConnection #buttonStatus').html('pushed'); diff --git a/public/scripts/events.js b/public/scripts/examples.js similarity index 95% rename from public/scripts/events.js rename to public/scripts/examples.js index 4ac8b71..af23e3e 100755 --- a/public/scripts/events.js +++ b/public/scripts/examples.js @@ -22,6 +22,11 @@ define(function() { }); }); + $('#e2-buttonStop').click(function(e) { + e.preventDefault(); + e2.stop(); + }); + $('#e2-buttonStart').click(function(e) { e.preventDefault(); $('#e2-secondStep .alert').addClass('hide'); diff --git a/public/scripts/init.js b/public/scripts/init.js deleted file mode 100755 index 430eae2..0000000 --- a/public/scripts/init.js +++ /dev/null @@ -1,23 +0,0 @@ -/* init.js */ -var socket = null; -var Noduino = function(options) { if (!this.socket) { this.socket = io.connect(options.host); } this.callbacks = {}; var that = this; this.socket.on('response', function(data) { var err = data, board = {}; switch(data.msg) { case 'board.connect': if (data.response == 'ready') {err=null;} that.callbacks[data.msg](err, board); break;} }) }; -Noduino.prototype.connect = function(options, callback) { if (!callback) { callback = options; } this.callbacks['board.connect'] = callback; this.socket.emit('board.connect'); }; - -$(document).ready(function(e) { - $('#buttonConnect').click(function(e) { - e.preventDefault(); - - var noduino = new Noduino({host: 'http://localhost:8090'}); - $('#exampleConnection .alert').addClass('hide'); - $('#exampleConnection .alert-info').removeClass('hide'); - $('#exampleConnection .alert-info').html('Trying to connect to your Arduino…'); - noduino.connect(function(err, board) { - $('#exampleConnection .alert').addClass('hide'); - if (err) { - $('#exampleConnection .alert-error').removeClass('hide'); } - else { - $('#exampleConnection .alert-success').removeClass('hide'); } - }); - }); - -}); \ No newline at end of file diff --git a/public/scripts/libs/AnalogInput.js b/public/scripts/libs/AnalogInput.js index 66bf1bd..6bffbbe 100644 --- a/public/scripts/libs/AnalogInput.js +++ b/public/scripts/libs/AnalogInput.js @@ -1,44 +1,78 @@ +/** + * AnalogInput.js – Reading data from analog input + * This file is part of noduino (c) 2012 Sebastian Müller + * + * @package noduino + * @author Sebastian Müller + * @license MIT License – http://www.opensource.org/licenses/mit-license.php + * @url https://github.com/semu/noduino + */ + define(function() { + /** + * Create AnalogInput + * @param object options set options like pin + * @param object Connector switch between Serial or Socket mode + */ function AnalogInput(options, Connector) { if (false === (this instanceof AnalogInput)) { return new AnalogInput(options); } - this.c = Connector; - this.pin = options.pin; - this.events = {}; - this.value = null; + this.c = Connector; + this.pin = options.pin; + this.events = {}; + this.value = null; + this.tolerance = 3; this.watch(); } - AnalogInput.prototype.watch = function() { - this.c.watchAnalogIn(this); - } - + /** + * Run binded events for given event + * @param string event + */ + AnalogInput.prototype.emit = function(event) { + if (!this.events[event]) { + return; } + for (var i = 0; i < this.events[event].length; i++) { + this.events[event][i](this); + } + }; + + /** + * Bind event to AnalogInput + * @param string event name of event + * @param function callback + */ AnalogInput.prototype.on = function(event, callback) { if (!this.events[event]) { this.events[event] = []; } this.events[event].push(callback); }; + /** + * Update value of AnlogInput + * @param integer value + * @param function callback + */ AnalogInput.prototype.set = function(value, callback) { var tmp = this.value - value; - if (tmp > -2 && tmp < 2) { + if (tmp > (-1 * this.tolerance) && tmp < this.tolerance) { return; } + if (this.value != value) { - this.value = value; + this.value = value; this.emit('change'); } }; - - AnalogInput.prototype.emit = function(event, callback) { - if (!this.events[event]) { - return; } - for (var i = 0; i < this.events[event].length; i++) { - this.events[event][i](this); - } - }; + + /** + * Watch AnalogInput for new incoming data + */ + AnalogInput.prototype.watch = function() { + this.c.watchAnalogIn(this); + } return AnalogInput; }); \ No newline at end of file diff --git a/public/scripts/libs/Board.js b/public/scripts/libs/Board.js index e47e965..52d0c7b 100644 --- a/public/scripts/libs/Board.js +++ b/public/scripts/libs/Board.js @@ -1,14 +1,20 @@ -var cnst = { - 'LED': 0x31, - 'DIGITAL_OUT': 0x31, - 'BOTTON': 0x32, - 'ANALOG_IN': 0x33, - 'HIGH': 'on', - 'LOW': 'off', -}; +/** + * Board.js – Arduino Board Controller + * This file is part of noduino (c) 2012 Sebastian Müller + * + * @package noduino + * @author Sebastian Müller + * @license MIT License – http://www.opensource.org/licenses/mit-license.php + * @url https://github.com/semu/noduino + */ -define(['./LED', './Button', './AnalogInput', './DigitalOutput', './Speaker'], function(LEDObj, ButtonObj, AnalogInputObj, DigitalOutObj, SpeakerObj) { +define(['./LED.js', './Button.js', './AnalogInput.js', './DigitalOutput.js', './Speaker.js'], function(LEDObj, ButtonObj, AnalogInputObj, DigitalOutObj, SpeakerObj) { + /** + * Create Board + * @param object options set options like pin + * @param object Connector switch between Serial or Socket mode + */ function Board(options, Connector) { if (false === (this instanceof Board)) { return new Board(options); } @@ -18,40 +24,87 @@ define(['./LED', './Button', './AnalogInput', './DigitalOutput', './Speaker'], this.pinMapping = {}; }; - Board.prototype.pinType = function(pin) { - return this.pinMapping[pin]; - } - - Board.prototype.pinAvailable = function(pin) { - return (this.pinMapping[pin]); - }; - + /** + * Write to digital output on pin + * @param integer pin pin number + * @param string mod pin mode + * @param function callback + */ Board.prototype.digitalWrite = function(pin, mode, next) { this.c.digitalWrite(pin, mode, function(err) { if (err) { return next(err); } }); }; - - Board.prototype.withLED = function(options, next) { - return this.with(this.c.TYPE_LED, options, next); - }; - Board.prototype.withButton = function(options, next) { - return this.with(this.c.TYPE_BUTTON, options, next); + /** + * Check if pin is already in use + * @param integer pin pin number + * @return boolean + */ + Board.prototype.pinAvailable = function(pin) { + return (this.pinMapping[pin] ? true : false); }; + + /** + * Get type of pin on board + * @param integer pin pin number + * @return mixed + */ + Board.prototype.pinType = function(pin) { + return this.pinMapping[pin]; + } + /** + * Create AnalogInput object on board + * @param object options + * @param function callback + */ Board.prototype.withAnalogInput = function(options, next) { - return this.with(this.c.TYPE_ANALOGIN, options, next); + this.with(this.c.TYPE_ANALOGIN, options, next); } - Board.prototype.withSpeaker = function(options, next) { - return this.with(this.c.TYPE_SPEAKER, options, next); + /** + * Create Button object on board + * @param object options + * @param function callback + */ + Board.prototype.withButton = function(options, next) { + this.with(this.c.TYPE_BUTTON, options, next); }; + /** + * Create DigitalOutput object on board + * @param object options + * @param function callback + */ Board.prototype.withDigitalOutput = function(options, next) { - return this.with(this.c.TYPE_DIGITALOUT, options, next); + this.with(this.c.TYPE_DIGITALOUT, options, next); + }; + + /** + * Create LED object on board + * @param object options + * @param function callback + */ + Board.prototype.withLED = function(options, next) { + this.with(this.c.TYPE_LED, options, next); + }; + + /** + * Create Speaker object on board + * @param object options + * @param function callback + */ + Board.prototype.withSpeaker = function(options, next) { + this.with(this.c.TYPE_SPEAKER, options, next); }; + /** + * Handle object creation + * @param string what object type + * @param object options + * @param function callback + */ Board.prototype.with = function(what, options, next) { if (this.pinAvailable(options.pin)) { return next(new Error('PIN already in use')); } @@ -69,9 +122,7 @@ define(['./LED', './Button', './AnalogInput', './DigitalOutput', './Speaker'], case this.c.TYPE_BUTTON: this.c.withButton(options.pin, function(err, pin) { if (err) { return next(err); } - var c = new ButtonObj({"pin": pin, "type": what}, that.c); - console.log(c); - next(null, c); + next(null, new ButtonObj({"pin": pin, "type": what}, that.c)); }); break; case this.c.TYPE_ANALOGIN: diff --git a/public/scripts/libs/Button.js b/public/scripts/libs/Button.js index 23e7e9f..f65a7a0 100644 --- a/public/scripts/libs/Button.js +++ b/public/scripts/libs/Button.js @@ -1,3 +1,13 @@ -define(['./DigitalInput'], function(Button) { +/** + * Button.js – Button Controller + * This file is part of noduino (c) 2012 Sebastian Müller + * + * @package noduino + * @author Sebastian Müller + * @license MIT License – http://www.opensource.org/licenses/mit-license.php + * @url https://github.com/semu/noduino + */ + +define(['./DigitalInput.js'], function(Button) { return Button; }); \ No newline at end of file diff --git a/public/scripts/libs/DigitalInput.js b/public/scripts/libs/DigitalInput.js index fda408c..7064942 100644 --- a/public/scripts/libs/DigitalInput.js +++ b/public/scripts/libs/DigitalInput.js @@ -1,3 +1,13 @@ +/** + * DigitalInput.js – Basic DigitalInput Controller0 + * This file is part of noduino (c) 2012 Sebastian Müller + * + * @package noduino + * @author Sebastian Müller + * @license MIT License – http://www.opensource.org/licenses/mit-license.php + * @url https://github.com/semu/noduino + */ + define(function() { function DigitalInput(options, Connector) { @@ -5,7 +15,7 @@ define(function() { return new DigitalInput(options); } this.c = Connector; - this.pin = options.pin; + this.pin = this.c.normalizePin(options.pin); this.pushed = false; this.events = {}; diff --git a/public/scripts/libs/LED.js b/public/scripts/libs/LED.js index 37826df..f2b837b 100644 --- a/public/scripts/libs/LED.js +++ b/public/scripts/libs/LED.js @@ -1,17 +1,21 @@ -define(['./DigitalOutput'], function(LED) { +define(['./DigitalOutput.js'], function(LED) { LED.prototype.toggle = function(callback) { if (this.mode == this.c.LOW) { return this.setOn(callback); } this.setOff(callback); }; + + LED.prototype.stopBlinking = function() { + if (this.interval) { + clearInterval(this.interval); } + } LED.prototype.blink = function(interval) { if (interval*1 < 25) { interval = 50; } - if (this.interval) { - clearInterval(this.interval); } - + this.stopBlinking(); + var that = this; this.interval = setInterval(function(){ that.toggle(); diff --git a/public/scripts/libs/Logger.HTML.js b/public/scripts/libs/Logger.HTML.js new file mode 100644 index 0000000..40a92d2 --- /dev/null +++ b/public/scripts/libs/Logger.HTML.js @@ -0,0 +1,62 @@ +define(function() { + + function HTMLLogger(options) { + if (false === (this instanceof HTMLLogger)) { + return new HTMLLogger(options); } + + this.container = 'connection-log'; + this.counter = 0; + }; + + HTMLLogger.prototype.setOption = function(key, value) { + this[key] = value; + }; + + HTMLLogger.prototype.setContainer = function(selector) { + this.container = selector; + }; + + HTMLLogger.prototype.msg = function(level, msg) { + if (!msg) { + msg = level; + level = 'info'; + } + + this.addMessage(level, msg); + }; + + HTMLLogger.prototype.colorizeLogLevel = function(level) { + var levelclass = ''; + switch (level) { + case 'info': + break; + case 'gui': + levelclass = 'label-important'; + break; + case 'success': + levelclass = 'label-success'; + break; + case 'socket-write': + levelclass = 'label-info'; + break; + case 'socket-read': + levelclass = 'label-warning'; + break; + } + + return '' + level + ''; + }; + + HTMLLogger.prototype.addMessage = function(level, msg) { + $("#connection-log").append($('
$ > ' + Date.now() + ' – ' + this.colorizeLogLevel(level) + ' ' + msg + '
')); + // var objDiv = document.getElementById("connection-log"); + // objDiv.scrollTop = objDiv.scrollHeight; + + this.counter++; + if (this.counter > 18) { + $("#connection-log .item:nth-child(1)").remove(); + } + }; + + return HTMLLogger; +}); \ No newline at end of file diff --git a/public/scripts/libs/Logger.js b/public/scripts/libs/Logger.js new file mode 100644 index 0000000..8858d52 --- /dev/null +++ b/public/scripts/libs/Logger.js @@ -0,0 +1,29 @@ +define(function() { + + function ConsoleLogger(options) { + if (false === (this instanceof ConsoleLogger)) { + return new ConsoleLogger(options); } + if (!options) { + var options = {}; } + + this.delegate = null; + this.debug = options.debug || false; + }; + + ConsoleLogger.prototype.msg = function(level, msg) { + if (!msg) { + msg = level; + level = 'info'; + } + + this.addMessage(level, msg); + }; + + ConsoleLogger.prototype.addMessage = function(level, msg) { + if (!this.debug) { + return; } + console.log(arguments); + }; + + return ConsoleLogger; +}); \ No newline at end of file diff --git a/public/scripts/libs/Noduino.Serial.js b/public/scripts/libs/Noduino.Serial.js index 1c0410e..7a7be72 100644 --- a/public/scripts/libs/Noduino.Serial.js +++ b/public/scripts/libs/Noduino.Serial.js @@ -7,6 +7,15 @@ define(function(require, exports, module) { this.options = options; this.boards = []; this.board = null; + this.logger = null; + }; + + SerialNoduino.prototype.setLogger = function(Logger) { + this.logger = Logger; + }; + + SerialNoduino.prototype.log = function(level, msg) { + this.logger.msg(level, msg); }; SerialNoduino.prototype.connection = 'serial'; @@ -35,7 +44,7 @@ define(function(require, exports, module) { new Board({'debug': this.options.debug || false}, function(err, board) { if (err) { return next(new Error('Unable to connect')); } - // Disabled multi board support now + // Disabled multi board support now, but keep in mind… that.boards = [board]; that.board = 0; @@ -60,11 +69,10 @@ define(function(require, exports, module) { } SerialNoduino.prototype.digitalWrite = function(pin, mode, next) { - console.log('set ' + pin + ': ' + mode); this.current().digitalWrite(pin, mode, next); }; - SerialNoduino.prototype.watchAnalogIn = function(AnalogInput) { + SerialNoduino.prototype.watchAnalogIn = function(AnalogInput, callback) { var that = this; setInterval(function () { that.current().analogRead(AnalogInput.pin); @@ -72,14 +80,13 @@ define(function(require, exports, module) { this.current().on('data', function(m) { m = m.split('::'); - var eventPin = m[0]*1; - if (m[0].indexOf('A') > -1) { - eventPin = m[0]; } - - var event = {pin: eventPin, 'state': m[1]*1}; + var event = {pin: that.normalizePin(m[0]), 'state': m[1]*1}; + + if (callback) { + return callback(event); } + if (event.pin == AnalogInput.pin) { - AnalogInput.set(event.state); - } + AnalogInput.set(event.state); } }); } @@ -91,20 +98,13 @@ define(function(require, exports, module) { return ("00" + pin).substr(-2); }; - - SerialNoduino.prototype.log = function (level, message) { - console.log(message); - } - - SerialNoduino.prototype.digitalRead = function(pin) { - console.log(pin); pin = this.normalizePin(pin); this.log('info', 'digitalRead from pin ' + pin); this.write('02' + pin + this.normalizeVal(0)); }; - SerialNoduino.prototype.watchDigitalIn = function(DigitalIn) { + SerialNoduino.prototype.watchDigitalIn = function(DigitalIn, callback) { var that = this; setInterval(function () { @@ -113,8 +113,11 @@ define(function(require, exports, module) { this.current().on('data', function(m) { m = m.split('::'); - var event = {pin: m[0]*1, 'state': m[1]*1}; - + var event = {pin: that.normalizePin(m[0]), 'state': m[1]*1}; + + if (callback) { + return callback(event); } + if (event.pin == DigitalIn.pin) { if (event.state == 0 && DigitalIn.isOn()) { DigitalIn.setOff(); @@ -124,32 +127,7 @@ define(function(require, exports, module) { } } }); - } - - - - /* SerialNoduino.prototype.watchDigitalIn = function(Button) { - var that = this; - - setInterval(function () { - that.digitalRead(Button.pin); - }, 50); - - this.current().on('data', function(m) { - m = m.split('::'); - var event = {pin: m[0]*1, 'state': m[1]*1}; - - if (event.pin == Button.pin) { - if (event.state == 0 && Button.pushed) { - Button.release(); - } - if (event.state == 1 && !Button.pushed) { - Button.push(); - } - } - }); - } */ + }; return SerialNoduino; -}); - +}); \ No newline at end of file diff --git a/public/scripts/libs/Noduino.Socket.js b/public/scripts/libs/Noduino.Socket.js index 712d15f..37ecf13 100644 --- a/public/scripts/libs/Noduino.Socket.js +++ b/public/scripts/libs/Noduino.Socket.js @@ -15,13 +15,21 @@ define(function(require, exports, module) { this.options = options; this.boards = []; this.board = null; - + this.logger = null; this.io = null; this.sockets = []; this.callbacks= {}; this.checkSocket(); }; + SocketNoduino.prototype.setLogger = function(Logger) { + this.logger = Logger; + }; + + SocketNoduino.prototype.log = function(level, msg) { + return this.logger.msg(level, msg); + }; + SocketNoduino.prototype.connection = 'serial'; SocketNoduino.prototype.HIGH = '255'; SocketNoduino.prototype.LOW = '000'; @@ -42,7 +50,6 @@ define(function(require, exports, module) { SocketNoduino.prototype.checkSocket = function() { /** This is Client code: This works in your web browser */ if (!this.io) { - console.log('connect to: ' + this.options.host); this.io = io.connect(this.options.host); this.boards[0] = Board; } @@ -82,19 +89,20 @@ define(function(require, exports, module) { this.callbacks['board.connect'] = []; } this.callbacks['board.connect'].push(next); - - this.io.emit('board.connect'); + this.log('sending command through socket'); + this.pushSocket('board.connect'); return; } + SocketNoduino.prototype.pushSocket = function(type, data) { + this.log('socket-write', type + ': ' + JSON.stringify(data)); + this.io.emit(type, data); + } + SocketNoduino.prototype.write = function(cmd, callback) { this.log('info', 'writing: ' + cmd); - this.io.emit('serial', {'type': 'write', 'write': cmd, 'id': this.io.socket.sessionid}); - }; - - SocketNoduino.prototype.sendCommand = function(cmd, callback) { - // this.io.emit('serial', {'send': cmd}); + this.pushSocket('serial', {'type': 'write', 'write': cmd, 'id': this.io.socket.sessionid}); }; SocketNoduino.prototype.pinMode = function(pin, val) { @@ -113,17 +121,12 @@ define(function(require, exports, module) { return ("00" + pin).substr(-2); }; - SocketNoduino.prototype.log = function (level, message) { - console.log(message); - } - SocketNoduino.prototype.withLED = function(pin, next) { this.pinMode(pin, this.MODE_OUT); next(null, pin); }; SocketNoduino.prototype.withButton = function(pin, next) { - console.log('in NoduinoSocket.withButton'); this.pinMode(pin, this.MODE_IN); next(null, pin); }; @@ -144,39 +147,36 @@ define(function(require, exports, module) { }; SocketNoduino.prototype.watchAnalogIn = function(AnalogInput) { - return; - - var that = this; - setInterval(function () { - that.current().analogRead(AnalogInput.pin); - }, 50); - - this.current().on('data', function(m) { - m = m.split('::'); - var eventPin = m[0]*1; - if (m[0].indexOf('A') > -1) { - eventPin = m[0]; } - var event = {pin: eventPin, 'state': m[1]*1}; - if (event.pin == AnalogInput.pin) { - AnalogInput.set(event.state); + this.analogRead(AnalogInput.pin); + this.io.on('response', function(data) { + if (data.type == 'analogRead' && data.pin == AnalogInput.pin) { + that.log('socket-read', JSON.stringify(data)); + var event = {pin: data.pin, value: data.value*1}; + if (event.pin == AnalogInput.pin) { + AnalogInput.set(event.value); + } } }); } - SocketNoduino.prototype.digitalRead = function (DigitalIn) { - pin = this.normalizePin(DigitalIn.pin); - this.io.emit('serial', {'type': 'digitalRead', 'pin': pin}); + SocketNoduino.prototype.analogRead = function (pin) { + this.pushSocket('serial', {'type': 'analogRead', 'pin': this.normalizePin(pin)}); } + SocketNoduino.prototype.digitalRead = function (pin) { + this.pushSocket('serial', {'type': 'digitalRead', 'pin': this.normalizePin(pin)}); + } SocketNoduino.prototype.watchDigitalIn = function(DigitalIn) { var that = this; + this.digitalRead(DigitalIn.pin); this.io.on('response', function(data) { - if (data.type == 'digitalRead') { - console.log(data); + if (data.type == 'digitalRead' && data.pin == DigitalIn.pin) { + that.log('socket-read', JSON.stringify(data)); + if (data.value == 1) { DigitalIn.setOn(); } else { diff --git a/public/scripts/libs/Noduino.js b/public/scripts/libs/Noduino.js index 4a573f4..ee0b24c 100644 --- a/public/scripts/libs/Noduino.js +++ b/public/scripts/libs/Noduino.js @@ -1,18 +1,37 @@ -define(['./Board'], function (objBoard, ConnectorSerial, ConnectorSocket) { - +define(['./Board.js'], function (objBoard) { /** * Create Noduini object for handling general access * @param object options */ - function Noduino(options, Connector) { + function Noduino(options, Connector, Logger) { if (false === (this instanceof Noduino)) { return new Noduino(options); } - this.c = new Connector(options); + this.c = new Connector(options) + this.logger = new Logger(options); this.options = options; this.options.type = this.c.connection; + this.connected = false; + + this.setLoggerOptions(); + this.setLogger(); + }; + + Noduino.prototype.setLoggerOptions = function() { + if (!this.options.logger) { + return; } + for (var n in this.options.logger) { + this.logger.setOption(n, this.options.logger[n]); } + }; + + Noduino.prototype.setLogger = function() { + this.c.setLogger(this.logger); }; + Noduino.prototype.log = function(level, msg) { + this.c.log(level, msg); + } + Noduino.prototype.write = function(data) { this.c.write(data); } @@ -20,17 +39,24 @@ define(['./Board'], function (objBoard, ConnectorSerial, ConnectorSocket) { Noduino.prototype.digitalRead = function(pin) { this.c.digitalRead(pin); } + + Noduino.prototype.watchAnalogIn = function(pin, callback) { + this.c.watchAnalogIn(pin, callback); + } Noduino.prototype.watchDigitalIn = function(pin, callback) { this.c.watchDigitalIn(pin, callback); } Noduino.prototype.connect = function(options, callback) { + this.log('connecting to noduino'); + if (!callback) { callback = options; options = {}; } var that = this; this.c.connect(options, function(err, board) { if (err) { return callback(err); } + that.connected = true; callback(null, new objBoard(options, that.c)); }); } diff --git a/public/scripts/libs/Speaker.js b/public/scripts/libs/Speaker.js index 781410f..7532d8b 100644 --- a/public/scripts/libs/Speaker.js +++ b/public/scripts/libs/Speaker.js @@ -1,4 +1,4 @@ -define(['./DigitalOutput'], function (Speaker) { +define(['./DigitalOutput.js'], function (Speaker) { Speaker.prototype.isMuted = function() { return !this.active; diff --git a/public/scripts/main.js b/public/scripts/main.js deleted file mode 100755 index 03d22e9..0000000 --- a/public/scripts/main.js +++ /dev/null @@ -1,6 +0,0 @@ -require(["jquery", "prettify", "events"], function($, p, events) { - $(document).ready(function(e) { - prettyPrint(); - events.bind(); - }); -}); \ No newline at end of file diff --git a/public/scripts/domready.js b/public/scripts/vendor/domready.js similarity index 100% rename from public/scripts/domready.js rename to public/scripts/vendor/domready.js diff --git a/public/scripts/vendor/dropdown.js b/public/scripts/vendor/dropdown.js new file mode 100644 index 0000000..f1f6c33 --- /dev/null +++ b/public/scripts/vendor/dropdown.js @@ -0,0 +1,92 @@ +/* ============================================================ + * bootstrap-dropdown.js v2.0.1 + * http://twitter.github.com/bootstrap/javascript.html#dropdowns + * ============================================================ + * Copyright 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================ */ + + +!function( $ ){ + + "use strict" + + /* DROPDOWN CLASS DEFINITION + * ========================= */ + + var toggle = '[data-toggle="dropdown"]' + , Dropdown = function ( element ) { + var $el = $(element).on('click.dropdown.data-api', this.toggle) + $('html').on('click.dropdown.data-api', function () { + $el.parent().removeClass('open') + }) + } + + Dropdown.prototype = { + + constructor: Dropdown + + , toggle: function ( e ) { + var $this = $(this) + , selector = $this.attr('data-target') + , $parent + , isActive + + if (!selector) { + selector = $this.attr('href') + selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 + } + + $parent = $(selector) + $parent.length || ($parent = $this.parent()) + + isActive = $parent.hasClass('open') + + clearMenus() + !isActive && $parent.toggleClass('open') + + return false + } + + } + + function clearMenus() { + $(toggle).parent().removeClass('open') + } + + + /* DROPDOWN PLUGIN DEFINITION + * ========================== */ + + $.fn.dropdown = function ( option ) { + return this.each(function () { + var $this = $(this) + , data = $this.data('dropdown') + if (!data) $this.data('dropdown', (data = new Dropdown(this))) + if (typeof option == 'string') data[option].call($this) + }) + } + + $.fn.dropdown.Constructor = Dropdown + + + /* APPLY TO STANDARD DROPDOWN ELEMENTS + * =================================== */ + + $(function () { + $('html').on('click.dropdown.data-api', clearMenus) + $('body').on('click.dropdown.data-api', toggle, Dropdown.prototype.toggle) + }) + +}( window.jQuery ); \ No newline at end of file diff --git a/public/scripts/prettify.js b/public/scripts/vendor/prettify.js similarity index 100% rename from public/scripts/prettify.js rename to public/scripts/vendor/prettify.js diff --git a/public/scripts/require-jquery.js b/public/scripts/vendor/require-jquery.js similarity index 100% rename from public/scripts/require-jquery.js rename to public/scripts/vendor/require-jquery.js diff --git a/public/styles/init.css b/public/styles/init.css index cd7416d..f353c00 100644 --- a/public/styles/init.css +++ b/public/styles/init.css @@ -93,3 +93,8 @@ form.well{padding:14px;} .response.error{color:red;} label.label{display:inline;} #e2-secondStep select{margin-right:4px;} +.exampleLinks{margin-top:8px;} +.range{margin-bottom:0px;position:relative;top:-9px;margin-left:12px;width:373px;} +.interval{margin-bottom:0px;position:relative;top:-9px;margin-left:12px;width:60px;} +.collectedTags{margin-top:14px;} +#connection-log{height:358px;overflow:hidden;padding-top:4px;overflow-x:hidden;margin-bottom:16px;} diff --git a/public/styles/init.less b/public/styles/init.less index 64f07cf..3892d53 100755 --- a/public/styles/init.less +++ b/public/styles/init.less @@ -814,4 +814,32 @@ label.label { display: inline; } #e2-secondStep select { margin-right: 4px; -} \ No newline at end of file +} +.exampleLinks { + margin-top: 8px; +} +.range { + margin-bottom: 0px; + position: relative; + top: -9px; + margin-left: 12px; + width: 373px; +} +.interval { + margin-bottom: 0px; + position: relative; + top: -9px; + margin-left: 12px; + width: 60px; +} +.collectedTags { + margin-top: 14px; +} + +#connection-log { + height: 358px; + overflow: hidden; + padding-top: 4px; + overflow-x: hidden; + margin-bottom: 16px; +} diff --git a/public/wiring/walkLED.fzz b/public/wiring/walkLED.fzz new file mode 100644 index 0000000..c3a75ce Binary files /dev/null and b/public/wiring/walkLED.fzz differ diff --git a/public/wiring/walkLED.png b/public/wiring/walkLED.png new file mode 100644 index 0000000..e5dedd8 Binary files /dev/null and b/public/wiring/walkLED.png differ diff --git a/srv.app.js b/srv.app.js index fa09519..038160d 100644 --- a/srv.app.js +++ b/srv.app.js @@ -1,3 +1,12 @@ +/** + * srv.app.js – Handling HTTP:80 Requests + * This file is part of noduino (c) 2012 Sebastian Müller + * + * @package noduino + * @author Sebastian Müller + * @license MIT License – http://www.opensource.org/licenses/mit-license.php + * @url https://github.com/semu/noduino + */ define(['kickstart', 'module', 'path', 'fs'], function (kickstart, module, path, fs) { var kickstart = kickstart.withConfig({'name': 'localhost', 'port': 8080, 'path': './'}); var srv = kickstart.srv(); @@ -13,8 +22,12 @@ define(['kickstart', 'module', 'path', 'fs'], function (kickstart, module, path, } srv.all('/', function(req, res) { - res.render('home', {title: 'noduino', 'examples': examples}); + res.render('home', {jsApp: 'main', active: 'home', title: 'noduino', 'examples': examples}); }); - + + srv.all('/examples/walkLED.html', function(req, res) { + res.render('example-walkLED', {jsApp: 'walkLED', active: 'examples', title: 'noduino', 'examples': examples}); + }); + return {'kickstart': kickstart, 'srv': srv}; }); \ No newline at end of file diff --git a/srv.socket.js b/srv.socket.js index aaf1872..d745266 100644 --- a/srv.socket.js +++ b/srv.socket.js @@ -1,50 +1,86 @@ -define(['socket.io', 'public/scripts/libs/Noduino', 'public/scripts/libs/Noduino.Serial'], function(io, Noduino, Connector) { +/** + * srv.web.js – Handling Socket.IO Requests + * This file is part of noduino (c) 2012 Sebastian Müller + * + * @package noduino + * @author Sebastian Müller + * @license MIT License – http://www.opensource.org/licenses/mit-license.php + * @url https://github.com/semu/noduino + */ +define(['socket.io', 'public/scripts/libs/Noduino', 'public/scripts/libs/Noduino.Serial', 'public/scripts/libs/Logger'], function(io, Noduino, Connector, Logger) { + /** + * Define SocketHandler + * @param object socket Socket.IO + */ var SocketHandler = function(socket) { this.sockets = {}; this.arduinos = {}; this.handler = socket.listen(8090); + this.pinCache = {}; this.bindings(); }; + /** + * Get selected Arduino + */ SocketHandler.prototype.current = function() { return this.arduinos[0]; }; + /** + * Connect Bindings + */ SocketHandler.prototype.bindings = function() { var io = this.handler, that = this; io.sockets.on('connection', function(socket) { that.sockets[socket.id] = socket; + /** + * Incoming Serial Request + */ that.sockets[socket.id].on('serial', function(data) { switch (data.type) { case 'write': that.current().write(data.write); break; + case 'analogRead': + var curPin = data.pin; + that.current().watchAnalogIn({'pin': data.pin}, function(m) { + if (!m.pin || m.pin == null || m.pin == NaN) { + return; } + + if (m.state != that.pinCache[m.pin] && curPin == m.pin) { + socket.emit('response', {'type': 'analogRead', 'pin': m.pin, 'value': m.state}); + that.pinCache[m.pin] = m.state; + } + }); + break; case 'digitalRead': - var currentValue = null; - that.current().watchDigitalIn(data.pin*1, function(m) { - if (currentValue == null || currentValue != m.state) { - socket.emit('response', {'type': 'digitalRead', 'pin': m.ping, 'value': m.state}); - currentValue = m.state; + var curPin = data.pin; + that.current().watchDigitalIn({'pin': data.pin}, function(m) { + if (!m.pin || m.pin == null || m.pin == NaN) { + return; } + + if (m.state != that.pinCache[m.pin] && curPin == m.pin) { + socket.emit('response', {'type': 'digitalRead', 'pin': m.pin, 'value': m.state}); + that.pinCache[m.pin] = m.state; } }); break; } - console.log(data); }); - that.sockets[socket.id].on('command.send', function(data) { - console.log(data); - }); - + /** + * Connect to Arduino + */ that.sockets[socket.id].on('board.connect', function(data) { if (that.current() && that.current().connected == true) { return socket.emit('response', {'msg': 'board.connect', 'response': 'ready'}); } - that.arduinos[0] = new Noduino({'debug': true}, Connector); + that.arduinos[0] = new Noduino({'debug': true}, Connector, Logger); that.current().connect(function(err, board) { that.current().connected = false; if (err) { return socket.emit('response', {'msg': 'board.connect', 'response': 'failed'}); } @@ -56,5 +92,5 @@ define(['socket.io', 'public/scripts/libs/Noduino', 'public/scripts/libs/Noduino }); }; - return new SocketHandler(io, Noduino, Connector); + return new SocketHandler(io, Noduino, Connector, Logger); }); \ No newline at end of file diff --git a/srv.web.js b/srv.web.js index c827793..61d5d5e 100644 --- a/srv.web.js +++ b/srv.web.js @@ -1,6 +1,18 @@ +/** + * srv.web.js – Load HTTP Handler and Socket Bridge + * This file is part of noduino (c) 2012 Sebastian Müller + * + * @package noduino + * @author Sebastian Müller + * @license MIT License – http://www.opensource.org/licenses/mit-license.php + * @url https://github.com/semu/noduino + */ var requirejs = require('requirejs'); requirejs.config({nodeRequire: require}); +/** + * Load Socket.IO and HTTP Server + */ requirejs(['./srv.app', './srv.socket'],function(app, io) { var kickstart = app.kickstart; var router = kickstart.listen(); diff --git a/test.blinkLED.js b/test.blinkLED.js deleted file mode 100644 index 1fe51cf..0000000 --- a/test.blinkLED.js +++ /dev/null @@ -1,17 +0,0 @@ -var requirejs = require('requirejs'); -requirejs.config({nodeRequire: require}); - -requirejs(['public/scripts/libs/Noduino', 'public/scripts/libs/Noduino.Serial'], function (NoduinoObj, NoduinoConnector) { - - var Noduino = new NoduinoObj({'debug': true}, NoduinoConnector); - Noduino.connect(function(err, board) { - if (err) { return console.log(err); } - - board.withLED({pin: 13}, function(err, LED) { - if (err) { return console.log(err); } - - LED.blink(250); - }); - }); - -}); \ No newline at end of file diff --git a/test.check.js b/test.check.js deleted file mode 100644 index 87b5ff7..0000000 --- a/test.check.js +++ /dev/null @@ -1,76 +0,0 @@ -var requirejs = require('requirejs'); -requirejs.config({nodeRequire: require}); - -requirejs(['libs/Noduino', 'libs/Noduino.Serial'], function (NoduinoObj, NoduinoConnector) { - var maxLEDs = 6; - var current = 1; - var direction = -1; - var curInterval = 100; - var currentStepper = null; - var LEDlist = []; - var sorting = [13, 12, 11, 10, 9, 8]; - - function readyLED(led) { - LEDlist[sorting.indexOf(led.pin)] = led; - if (LEDlist.length == maxLEDs) { - startSequence(-1, curInterval); } - } - - function addButton(Button, dir) { - Button.on('push', function(e) { - var newDirection = direction; - - switch (Button.pin) { - case 6: newDirection = -1; break; - case 3: newDirection = 1; break; - } - - if (newDirection != direction) { - startSequence(newDirection, curInterval); - } - }); - } - - function stepper() { - var next = current + direction; - if (next == maxLEDs + 1) { - next = 1; } - if (next == 0) { - next = maxLEDs; } - current = next; - for (var i = 1; i <= maxLEDs; i++) { - LEDlist[i-1].setOff(); } - LEDlist[(current-1)].setOn(); - } - - function startSequence(step, interval) { - if (LEDlist.length != maxLEDs) { - return; }; - - clearInterval(currentStepper); - direction = step || 1; - currentStepper = setInterval(function() { - return stepper(); - }, interval); - } - - var Noduino = new NoduinoObj({'debug': true}, NoduinoConnector); - Noduino.connect(function(err, board) { - if (err) { return console.log(err); } - - - board.withLED({pin: 13}, function(err, LED) { readyLED(LED); }); - board.withLED({pin: 12}, function(err, LED) { readyLED(LED); }); - board.withLED({pin: 11}, function(err, LED) { readyLED(LED); }); - board.withLED({pin: 10}, function(err, LED) { readyLED(LED); }); - board.withLED({pin: 9}, function(err, LED) { readyLED(LED); }); - board.withLED({pin: 8}, function(err, LED) { readyLED(LED); }); - board.withButton({pin: 3}, function(err, Button) { addButton(Button); }); - board.withButton({pin: 6}, function(err, Button) { addButton(Button); }); - board.withAnalogInput({pin: 'A0'}, function(err, AnalogInput) { - AnalogInput.on('change', function(a) { - curInterval = a.value; startSequence(direction, curInterval); - }); - }); - }); -}); \ No newline at end of file diff --git a/test.walkLED.js b/test.walkLED.js deleted file mode 100644 index 6cfc588..0000000 --- a/test.walkLED.js +++ /dev/null @@ -1,74 +0,0 @@ -var requirejs = require('requirejs'); -requirejs.config({nodeRequire: require}); - -requirejs(['public/scripts/libs/Noduino', 'public/scripts/libs/Noduino.Serial'], function (NoduinoObj, NoduinoConnector) { - var maxLEDs = 5; - var current = 1; - var direction = -1; - var curInterval = 100; - var currentStepper = null; - var LEDlist = []; - var sorting = [13, 11, 10, 9, 8]; - - function readyLED(led) { - LEDlist[sorting.indexOf(led.pin)] = led; - if (LEDlist.length == maxLEDs) { - startSequence(-1, curInterval); } - } - - function addButton(Button, dir) { - Button.on('push', function(e) { - var newDirection = direction; - - switch (Button.pin) { - case 6: newDirection = -1; break; - case 3: newDirection = 1; break; - } - - if (newDirection != direction) { - startSequence(newDirection, curInterval); - } - }); - } - - function stepper() { - var next = current + direction; - if (next == maxLEDs + 1) { - next = 1; } - if (next == 0) { - next = maxLEDs; } - current = next; - for (var i = 1; i <= maxLEDs; i++) { - LEDlist[i-1].setOff(); } - LEDlist[(current-1)].setOn(); - } - - function startSequence(step, interval) { - if (LEDlist.length != maxLEDs) { - return; }; - - clearInterval(currentStepper); - direction = step || 1; - currentStepper = setInterval(function() { - return stepper(); - }, interval); - } - - var Noduino = new NoduinoObj({'debug': true}, NoduinoConnector); - Noduino.connect(function(err, board) { - if (err) { return console.log(err); } - - board.withLED({pin: 13}, function(err, LED) { readyLED(LED); }); - board.withLED({pin: 11}, function(err, LED) { readyLED(LED); }); - board.withLED({pin: 10}, function(err, LED) { readyLED(LED); }); - board.withLED({pin: 9}, function(err, LED) { readyLED(LED); }); - board.withLED({pin: 8}, function(err, LED) { readyLED(LED); }); - board.withButton({pin: 3}, function(err, Button) { addButton(Button); }); - board.withButton({pin: 6}, function(err, Button) { addButton(Button); }); - board.withAnalogInput({pin: 'A0'}, function(err, AnalogInput) { - AnalogInput.on('change', function(a) { - curInterval = a.value; startSequence(direction, curInterval); - }); - }); - }); -}); \ No newline at end of file diff --git a/views/example-walkLED.jade b/views/example-walkLED.jade new file mode 100755 index 0000000..d3e0678 --- /dev/null +++ b/views/example-walkLED.jade @@ -0,0 +1,80 @@ +header#overview + .page-header + h1 Adjustable LED Walker + small Control walking direction and adjust speed + .row + .span12 + .hero-unit + img(src="/wiring/walkLED.png") + p Use the example wiring from above and this interface for getting startet with noduino. Read values from an analog input device like a potentiometer and watch for pressed buttons, all basic functions are shown within this example. The needed + code .fzz + | file for making changes with the awesome + a(href="http://fritzing.org") Fritzing Application + | is included as well. If you want to share your own wirings or found a bug please create a + a(href="http://github.com/semu/noduino") Pull Request on GitHub + | ! + + .page-header + h1 HTML5 WebSocket Interface + small Using Socket.IO and Node.js + .row.interface#controls + .span12 + .btn-toolbar(style="margin-bottom: 9px") + .btn-group + a.btn(href="#")#connect + i.icon-refresh + | Connect to Arduino + | + .btn-group + .btn.btn-dir#btn-04 «« + | + .btn-group#leds + a.btn.disabled#led-1 #1 + a.btn.disabled#led-2 #2 + a.btn.disabled#led-3 #3 + a.btn.disabled#led-4 #4 + a.btn.disabled#led-5 #5 + a.btn.disabled#led-6 #6 + | + .btn-group + .btn.btn-dir#btn-02 »» + .btn-group + input.range#interval-slide(type="range", min="0", max="1024", step="1", value="320") + input.interval#interval-value(type="input", value="320ms",disabled="disabled") + .row.info#connection-status + .span12 + .alert.alert-info Please connect to your Arduino using the button. + .alert.hide.alert-error Unable to connect to Arduino! + .alert.hide.alert-success Connection to Arduino established! + .row.debug + .span12 + pre#connection-log + .item $ > Not connected to noduino! + .row + .span12 + p This interface is defined in + code views/example-walkLED.jade + | , all needed JavaScript is stored in + code public/scrupts/app.walkLED.js + | using + a(href="#") RequireJS + | for loading dependencies. Please see RequireJS's manual for loading your scripts. Logging is done with the customized + code Logger.HTML.js + | in + code scripts/libs/ + | . + + .page-header + h1 Just Node.js + small Acces Arduino components without HTML5 interface + .row + .span12 + p The wiring above can be used to test the included HTML web interface and the Node.js access as well. Connect your Arduino to you computer and start catching events happening on your Arduino with JavaScript. For sure you can easily fire events on your Arduino too! + pre + | $ > git clone git://github.com/semu/noduino.git noduino + | $ > cd noduino/ + | $ > npm install + | $ > cd examples/ + | $ > node test.walkLED.js + p After starting test.walkLED.js you are able to push the buttons in your wiring and see the LEDs blinking as you commanded. Use the analog input for changing walking speed. Binding events work as you might know from using Mootools, use AnalogInput.on(), LED.on() and Button.on() to bind custom functions to events like on, off, change, push or release. Not all functions are documented or even demonstrated with an example application, for getting used to noduino make sure to have a look at test.blinkLED.js and test.readAnalogIn.js. + \ No newline at end of file diff --git a/views/home.jade b/views/home.jade index dac01e4..6820c5f 100755 --- a/views/home.jade +++ b/views/home.jade @@ -83,12 +83,20 @@ section#homeContent p select.span2#e2-pinValue option(value=13) PIN: 13 + option(value=12) PIN: 12 + option(value=11) PIN: 11 + option(value=10) PIN: 10 + option(value=09) PIN: 09 input.span3#e2-interval(type="text",placeholder="Interval in Miliseconds") | a.btn(href="#", style="margin-top: 1px;")#e2-buttonStart i.icon-retweet | Start blinking LED | + a.btn(href="#", style="margin-top: 1px;")#e2-buttonStop + i.icon-off + | Stop + | label.label#e2-status(style="position: relative; top: -2px;") LED off .alert.hide.alert-info Please connect to your Arduino using the button. .alert.hide.alert-error Connect to Arduino first! @@ -113,4 +121,42 @@ section#homeContent | Connect to Arduino .alert.alert-info Please connect to your Arduino using the button. .alert.hide.alert-error Unable to connect to Arduino! - .alert.hide.alert-success Connected! Button is \ No newline at end of file + .alert.hide.alert-success Connected! Button is + .page-header + h1 Getting started with noduino + small AnalogInput, DigitalInputs and some nice LEDs + .row + .span12 + .hero-unit + img(src="/wiring/walkLED.png") + p Use the example wiring from above and the provided example in + code examples/walkLED.js + | for getting started using noduino. Read values from an analog input device like a potentiometer and watch for pressed buttons, all basic functions are shown in the example files. The needed + code .fzz + | file for making changes with the awesome + a(href="http://fritzing.org") Fritzing Application + | is included as well! If you create other wirings or find bugs in the provided ones please greate a + a(href="http://github.com/semu/noduino") Pull Request on GitHub + | ! + .row + .span12 + p.exampleLinks + a.btn.btn-success(href="/examples/walkLED.html") + i.icon-gift.icon-white + | View Example + .page-header + h1 About noduino + small Thank You Open Source! + .row + .span12 + p The + a(href="#") noduino + | project was founded by + a(href="#") Sebastian Müller + | for fun and as a proof of concept for Node.js controlling external components over a dynamic web interface using HTML5 WebSockets. Thanks to the awesome + a(href="#") Arduino + | project and the German + a(href="#") Fritzing Project + | it's easy to get started with basic prototyping. The already existing + a(href="#") duino + | project helped developing the first steps and is now an imported part of noduino's core components. Thanks to the Open Source community, you made this possible! Keep the good work up… diff --git a/views/includes/snippet.jade b/views/includes/snippet.jade deleted file mode 100755 index d6fbd24..0000000 --- a/views/includes/snippet.jade +++ /dev/null @@ -1,2 +0,0 @@ -p I'm a - span Snippet \ No newline at end of file diff --git a/views/layout.jade b/views/layout.jade index 4ce9172..600176e 100755 --- a/views/layout.jade +++ b/views/layout.jade @@ -5,7 +5,7 @@ html(lang="en") link(rel="stylesheet", href="/styles/bootstrap/init.css") link(rel="stylesheet", href="/styles/prettify.css") link(rel="stylesheet", href="/styles/init.css") - script(data-main="scripts/main", type="text/javascript", src="/scripts/require-jquery.js") + script(data-main="/scripts/app." + jsApp, type="text/javascript", src="/scripts/vendor/require-jquery.js") script(type="text/javascript", src="http://localhost:8090/socket.io/socket.io.js") // script(type="text/javascript", src="/scripts/init.js") // script(type="text/javascript", src="/scripts/prettify.js") @@ -15,8 +15,14 @@ html(lang="en") .container div.nav-collapse ul.nav - li.active - a(href="#") Home + li(class=(active == 'home' ? 'active' : '')) + a(href="/") Home + li.dropdown(class=(active == 'examples' ? 'active' : '')) + a.dropdown-toggle(href="#",data-toggle="dropdown") Example Wiring + b.caret + ul.dropdown-menu + li + a(href="/examples/walkLED.html") Adjustable LED Walker li a(href="https://github.com/semu/noduino") View on GitHub » div.nav-collapse.pull-right @@ -47,4 +53,4 @@ html(lang="en") a(href="#") twitter bootstrap framework | . Icons from a(href="#") Glyphicons Free - | . 2012 Baby! \ No newline at end of file + | . \ No newline at end of file