Setting/getting pins from the web in Node.js

Discussion in 'General Programming Discussion' started by francescomm, Dec 14, 2013.

  1. francescomm

    francescomm Member

    Joined:
    Dec 14, 2013
    Messages:
    80
    Likes Received:
    4
    Just a quick hack to pilot/read the UDOO from the web/lan, requires node, node-udoo, and that you run this script in node:

    Code:
    ubuntu@udoo:~/nodeweb$ node /home/ubuntu/nodeweb/main.js
    Server running at port 8080/ Node v0.10.22 arm
    
    After this the UDOO will be accessible from the lan (or the web if you configure your routers right).

    Code:
    http://<UDOO ip>/set/?p10=hi
    
    will light up a led connected to pin 10


    Code:
    // Example of accessing pins from the web
    // copyleft Francesco Munafò
    
    // Use as you wish.
    // This is not throughly tested code, just a quick hack prototype
    // It does seem to work though
    
    // Sample:
    
    // API to get pin values
    // http://127.0.0.1:8080/get/?p12&p13&p10
    // result: {"p12":"false","p13":"false","p10":"false"}
    
    // API to set pin values
    // http://127.0.0.1:8080/set/?p12=hi&p13=lo&p10=hi
    // result should be ignored same as below with no params
    
    // if you connect to http://127.0.0.1:8080/ with no params you can see a little web page sample to handle pins 10-13 by clicking links.
    
    
    
    var udoo = require('udoo');
    var util = require('util');
    var http = require('http');
    var url = require('url') ;
    var fs = require('fs');
    var querystring=require('querystring');
    
    udoo.reset()
    
    
    http.createServer(function (req, res) {
    	var parsedUrl = url.parse(req.url,true);
    	var getData = parsedUrl.query;
    	var urlData = parsedUrl.pathname;
    
    	var postData = "";
    	res.outputPins=[];
    	res.pinsAdded=0;
    	res.pinsDone=0;
    	res.done=false;
    	
    	req.on('data', function (chunk) {
    		postData += chunk;
    	});
    	req.on('end', function () {
    		handleRequest(req,res,urlData,getData,querystring.parse(postData));
    	});
    }).listen(8080);
    
    var postHTML1 = 
      '<html><head><title>Control Panel</title></head>' +
      '<body>' +
      '<div>10 | <a href="/set/?p10=hi">on</a>' +' <a href="/set/?p10=lo">off</a></div>' +
      '<div>11 | <a href="/set/?p11=hi">on</a>' +' <a href="/set/?p11=lo">off</a></div>' +
      '<div>12 | <a href="/set/?p12=hi">on</a>' +' <a href="/set/?p12=lo">off</a></div>' +
      '<div>13 | <a href="/set/?p13=hi">on</a>' +' <a href="/set/?p13=lo">off</a></div>';
      '<div>all <a href="/get/?p10&p11&p12&p13" target="_blank">get</a></div>';
    var postHTML2 = 
      '</body></html>';
    var postHTML = postHTML1+postHTML2;
    
    
    function handleRequest(req,res,urlData,getData,postData) {
        var pin,val;
        var doSet=false;
        var doGet=false;
        var callbacks=[];
       
        
        
          
        // Suggested use is /get/ as a directory with final slash
         if(urlData=="/get" || urlData=="/get/" || urlData=="/get.php") {
            doSet=false;
            doGet=true;
        } else if(urlData=="/set" || urlData=="/set/" || urlData=="/set.php") {
            doSet=true;   
            doGet=false;
        } else {
            res.end(postHTML);
            return;
        }
        
        var pins=[];
        var pinsCount=0;
        var done=false;
    
        for(var it in getData) {
        	pin=(it);
            val=getData[it];
            
            if(pin.substr(0,1)=="p") {
                pin=pin.substr(1);
                pin=parseInt(pin);
                console.log("\nPIN: "+pin+" "+val);
                if(doSet) {
                    var led=udoo.outputPin(pin);    
                    if(val==="hi" || val=="on" || val=="high" || val=="255") {
                        led.setHigh();
                    } else if(val==="lo" || val=="off" || val=="low" || val=="0") {
                        led.setLow();
                    } else {
                        led.set(parseInt(val)); // NOT SUPPORTED YET BY NODEUDOO
                    }
                    
                } else {
                    res.pinsAdded++;
                    var led=udoo.inputPin(pin);
                    // console.log("\nSEARCH "+'p'+pin+"=?");
                    getAndSave(led,pin,res);
                }
            }
        }
        res.done=true;
        // console.log("\nTEST "+res.outputPinsCount+">="+pinsCount);
        if(res.pinsDone>=res.pinsAdded) {
           console.log("done after loop.");
           shootout(res);
        }
        
        
    }
    
    function getAndSave(led,apin,res) {
        var apin2=apin;
        led.get(function(err,val) {
            var tmp=0+apin2;
            res.outputPins["p"+tmp]=val;
            if(res.done) console.log("GOT(d) "+'p'+tmp+"="+val);
            else console.log("GOT "+'p'+tmp+"="+val);
            res.pinsDone++;
            if(res.done && res.pinsDone>=res.pinsAdded) {
                console.log("done after received data.");
                shootout(res);
                res.pinsDone=-1;
            }
       });
    }
    function shootout(res) {
            // res.write("URL "+util.inspect(urlData));
            // res.write("GET "+util.inspect(getData));
            // res.write("POST "+util.inspect(postData));
            console.log(res.outputPins);
            var out="{";
            var sep="";
            for(var it in res.outputPins) {
                out+=sep+'"'+it+'":"'+res.outputPins[it]+'"';
                sep=",";
            }
            out+='}';
            if(out=="{}") {
                res.setHeader("Content-Type", "text/html");
                res.writeHead(200);
                res.end(postHTML);
            } else {
                res.setHeader("Content-Type", "text/plain");
                res.writeHead(200);
                // res.write(postHTML1);
                // res.write(out);
                // res.end(postHTML2);
               res.end(out);
            }
            // console.log("\nCLOSE.");
    }
    
    
    console.log('Server running at port 8080/ Node '+process.version+ ' '+process.arch);
    
    Have fun!

    UDOO Rocks.
     
  2. Rickor

    Rickor New Member

    Joined:
    Nov 30, 2013
    Messages:
    9
    Likes Received:
    1

Share This Page