/ android

Sending Data from a BeagleBone Black to an Android Tablet

The beagle board community has always amazed me. They strive to design and produce low cost embedded systems. This is clearly an amazing task. And I also believe amazingly hard.

A true open hardware, community-supported embedded computer for developers and hobbyists. Ride the 1GHz edge with the Sitara™ ARM® Cortex-A8 processor, boot Linux in under 10 seconds and get started on development in less than 5 minutes with just a single USB cable.

Says the information on the web-site. And what they say is true. I have had one of these on me for some time now. And got to play with it.

BeagleBone

Leaving aside the hardware. Writing software for such an amazing device is just so fun!!

The new BeagleBone Black comes with Node.js installed with couple neat libraries such as the BoneScript (https://github.com/jadonk/bonescript). With this library it is possible to get analog data from the pins using Node.js

A sample code could be viewed below;

// Creates a websocket with socket.io
// Make sure to install socket.io: terminal, goto /var/lib/cloud9 and enter: npm install socket.io
// Installing this takes a few minutes; wait until the installation is complete

var path = require('path');
var fs = require('fs');
var b = require('bonescript');

var app = require('http').createServer(function (request, response) {
    console.log('request starting...');
    
	var filePath = '.' + request.url;
	if (filePath == './')
		filePath = './index.html';
		
	var extname = path.extname(filePath);
	var contentType = 'text/html';
	switch (extname) {
		case '.js':
			contentType = 'text/javascript';
			break;
		case '.css':
			contentType = 'text/css';
			break;
	}
	
	path.exists(filePath, function(exists) {
	
		if (exists) {
			fs.readFile(filePath, function(error, content) {
				if (error) {
					response.writeHead(500);
					response.end();
				}
				else {
					response.writeHead(200, { 'Content-Type': contentType });
					response.end(content, 'utf-8');
				}
			});
		}
		else {
			response.writeHead(404);
			response.end();
		}
	});
	
});


app.listen(8090);

var io = require('socket.io').listen(app);

// socket.io options go here
io.set('log level', 3);   // reduce logging - set 1 for warn, 2 for info, 3 for debug
io.set('browser client minification', true);  // send minified client
io.set('browser client etag', true);  // apply etag caching logic based on version number

console.log('Server running on: http://' + getIPAddress() + ':8090');


io.sockets.on('connection', function (socket) {
  socket.on('readData', function (data) {
    console.log(data);
    if (data == 'true'){
        //this is where sensor reads happen... need to make this a little more
        //modular... 
        
          socket.emit('1stsensorvalue', b.analogRead('P9_36'));
          socket.broadcast.emit('1stsensorvalue', b.analogRead('P9_36'));
    }
  });
});





// Get server IP address on LAN
function getIPAddress() {
  var interfaces = require('os').networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];
    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
        return alias.address;
    }
  }
  return '0.0.0.0';
}

The html file can be found below;

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <title>BeagleBone Black Demo</title>
 
    <!-- jQuery and jQuery Mobile -->
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script src="js/high/highcharts.js"></script>
    <script src="js/high/modules/exporting.js"></script>

    <!-- Code for socket.io and device orientation handling -->
    <script>
        var socket = io.connect();
        var datalog = [];
        var all_data = [];
        var chart;
        var myVar = setInterval(function(){readDatafromB()},1000)
        var series;
        var latest_data;
        var time_interval;
        var current_time;
        time_interval=1000;
        current_time=-1000;
        
        
           socket.on('1stsensorvalue', function (data) {
                console.log(data);
                $("#data1").val(data);
                latest_data = data;
                datalog.push({
                            x: current_time,
                            y: data
                        });
            });
        
        function readDatafromB(){
            socket.emit('readData','true');
        }
        
       $(function () {
    $(document).ready(function() {
        Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });
    
        var chart;
$('#container').highcharts({
            chart: {
                zoomType: 'x',
                spacingRight: 20,
                animation: Highcharts.svg, // don't animate in old IE
                marginRight: 10,
                events: {
                    load: function() {
    
                        // set up the updating of the chart each second
                        var series = this.series[0];
                        setInterval(function() {
                            current_time = current_time+1000, // current time
                            series.addPoint([current_time, latest_data], true, true);
                        }, 1000);
                    }
                }
            },
            title: {
                text: 'Live random data'
            },

            xAxis: {
                tickPixelInterval: 150
            },
            yAxis: {
                title: {
                    text: 'Voltage'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function() {
                        return '<b>'+ this.series.name +'</b><br/>'+
                        Highcharts.numberFormat(this.y, 2); +', '+
                        Highcharts.numberFormat(this.x, 2);
                }
            },
            legend: {
                enabled: true
            },
            exporting: {
                enabled: true
            },
            series: [{
                name: 'Random data',
                data: (function() {
                    // generate an array of random data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;
    
                    for (i = -50; i <= 0; i++) {
                        data.push({
                            x: current_time,
                            y: latest_data
                        });
                    }
                    console.log(data);
                    return data;
                })()
            }]
        });
    });
    
});

        
    </script>
</head>
<body onload="readDatafromB();" >
<!-- Home -->
<div data-role="page" id="page1">
    <div data-theme="a" data-role="header">
        <h3>
            Oghma Test
        </h3>
    </div>
    <div data-role="content">
        <div data-role="fieldcontain">
            <label for="data1">
                Data:
            </label>
            <input id="data1" type="input" name="data1" min="0" max="100"
            data-highlight="false" data-theme="b">
        </div>
        <div data-role="fieldcontain">
            <label for="datarate">
                Data Rate:
            </label>
            <input id="datarate" type="input" name="datarate" value="0" min="0" max="100"
            data-highlight="false" data-theme="b"><input type="button" name="on" id="data_rate" value="Change">
        </div>
        <div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
    </div>
</div>
</body>
</html>

Probably not the best way to sample data. But hey, this is free code you are looking at. Will fix it on later.

Now the great thing is that, I can actually use the Cordova (cordova.apache.org) library to get this to work over an Android tablet. Hence I would be able to actually interact with a BeagleBoard using a Android tablet. How cool is that!

Now the thing is that I can not give you all the code. As I am writing the more important parts for my work work. However feel free to ask questions. I will see if I can answer them.

Have fun!

John Roach

John Roach

I am John Roach, a devops architect. Find more information here: https://johnroach.io/about/

Read More
Sending Data from a BeagleBone Black to an Android Tablet
Share this