Friday, July 25, 2014

Raspberry Pi Servo Motor Controller using Node JS

This post is basically to support the below video, I have posted in Youtube regarding one of my fun projects that I'm working on my Raspberry Pi.
Project - Raspberry Pi Servo Motor Controller using Node JS
Project is to build a small Node JS application that runs a web socket server in my Raspberry Pi, which then enable my iPhone to connect to the web server using an ordinary browser like Safari through Web Socket Protocol to send its  Gyroscope data back to Raspberry Pi. Then web server will use this data to send PWM (Pulse Width Modulation) signals to it's selected GPIO pins connected to a servo motor.
By doing this I'll be able to control the servo motor using my iPhone over a LAN.

I know there are many ways you can achieve the same results, But I wanted use these selected technologies, so I can learn them better (and have FUN of doing it). I haven't used any Servo Controller Shields in this project either. Enjoy the video below.


Here is the code :
Server : app.js

1:  var express = require('express');  
2:  var app = express();  
3:  var server = require('http').createServer(app);  
4:  var fs = require('fs');  
5:  var WebSocketServer = require('websocket').server;  
6:  var piblaster = require("pi-blaster.js");  
7:    
8:    
9:  var clients = [ ];  
10:    
11:  //Getting request from browser  
12:  //and send response back  
13:  app.get ('/', function(req, res){    
14:    
15:     fs.readFile('ws.html', 'utf8', function(err, text){  
16:        res.send(text);  
17:      });  
18:  });  
19:    
20:  //Listening to Port 1337 for incoming messages  
21:  server.listen(1337, function (){  
22:    console.log((new Date()) + " Server is listening on port 1337... ");  
23:  });  
24:    
25:  websock = new WebSocketServer({  
26:    httpServer: server  
27:  });  
28:    
29:  //WebSocket Server  
30:    
31:  websock.on('request', function(request) {  
32:      
33:    console.log((new Date()) + ' Connection from origin ' + request.origin + '.');  
34:    
35:    var connection = request.accept(null, request.origin);  
36:      
37:    console.log((new Date()) + ' Connection accepted.');  
38:    
39:    //Incoming Data handling  
40:    connection.on('message', function(message) {  
41:    
42:      console.log('Data: ' + message.utf8Data);  
43:      
44:      var data = message.utf8Data;  
45:      data = data.slice(1,3);  
46:    
47:      // If incoming data is > 2 send a signal to pin 17  
48:      // Set GPIO pin 17 to a PWM of 24%  
49:      // Truns the Servo to it's right  
50:      if (Number(data)>2){      
51:        piblaster.setPwm(17, 0.24);  
52:      }  
53:    
54:      // If incoming data is > 2 send a signal to pin 17  
55:      // Set GPIO pin 17 to a PWM of 6%  
56:      // Truns the Servo to it's left  
57:      if (Number(data)<(-2)){      
58:        piblaster.setPwm(17, 0.06);  
59:      }  
60:    
61:      // If incoming data is > 2 send a signal to pin 17  
62:      // Set GPIO pin 17 to a PWM of 15%  
63:      // Truns the Servo to it's center position  
64:      if (Number(data)==0){      
65:        piblaster.setPwm(17, 0.15);  
66:      }  
67:    
68:    });  
69:      
70:    connection.on('close', function (connection){  
71:      //close connection  
72:      piblaster.setPwm(17, 0);  
73:    });  
74:    
75:    function closePin(){  
76:      piblaster.setPwm(17, 0);  
77:    }  
78:    
79:  });  


Client Page : ws.html


 <!doctype html>  
 <html>  
 <head>  
       <meta charset="utf-8">  
      <title>WebSockets - Simple chat</title>  
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  
 </head>  
 <body>  
      <div id="content"></div>  
      <div>  
           <span id="status">Connecting...</span>  
      </div>  
   
 <script type="text/javascript">  
      $(function () {  
           // Position Variables  
           var x           = 0;  
           var y           = 0;  
           var z           = 0;  
   
           // Speed - Velocity  
           var vx           = 0;  
           var vy           = 0;  
           var vz           = 0;  
   
           // Acceleration  
           var ax           = 0;  
           var ay           = 0;  
           var az           = 0;  
           var ai           = 0;  
           var arAlpha = 0;  
           var arBeta      = 0;  
           var arGamma = 0;  
   
           var delay      = 200;  
           var vMultiplier = 0.01;                 
           var alpha      = 0;  
             
           var alpha      = 0;  
           var beta      = 0;  
           var gamma      = 0;  
             
           var content     = $('#content');  
           var status      = $('#status');  
   
        // if user is running mozilla then use it's built-in WebSocket  
        window.WebSocket = window.WebSocket || window.MozWebSocket;  
             
            if (!window.WebSocket) {  
                content.html($('<p>', { text: 'Sorry, but your browser doesn\'t '  
                                                        + 'support WebSockets.'} ));  
                input.hide();  
                $('span').hide();  
                return;  
           }  
             
             
        var connection = new WebSocket('ws://'+document.domain+':1337');  
   
        connection.onopen = function () {  
   
                status.text('You are connected to ThanboPi Server.' +  
                                    'Move your device and Have Fun!!');  
        };  
   
        connection.onerror = function (error) {  
           content.html($('<p>', { text: 'Sorry, but there\'s some problem with your '  
                                                   + 'connection or the server is down.' } ));  
        };  
   
   
        if (window.DeviceMotionEvent!=undefined) {  
   
                window.ondevicemotion = function(event) {  
                     ax = Math.round((event.accelerationIncludingGravity.x * 1));  
                     ay = Math.round(Math.abs(event.accelerationIncludingGravity.y * 1));  
                     az = Math.round(Math.abs(event.accelerationIncludingGravity.z * 1));            
                     ai = Math.round(event.interval * 100) / 100;  
                     rR = event.rotationRate;  
                     if (rR != null) {  
                          arAlpha = Math.round(rR.alpha);  
                          arBeta      = Math.round(rR.beta);  
                          arGamma = Math.round(rR.gamma);  
                     }            
                }  
                                                
                window.ondeviceorientation = function(event) {  
                     alpha = Math.round(event.alpha);  
                     beta = Math.round(event.beta);  
                     gamma = Math.round(event.gamma);  
                }       
             
                setInterval(function() {  
                     connection.send('x' + ax);  
                }, delay);                 
           }  
             
      });  
 </script>  
 </body>  
 </html>       
   


Schematic for this project is fairly simple on, but I'll post is anyway,



Components : RPI, Breadboard, a 1K resistor and a Basic Servo Motor

PS: If you need to know more details with regards to libraries, frameworks and hardware I'm using in this project, please ask your questions in the comment section. I would happily assist you.

Wednesday, July 04, 2012

Magento - Lost connection to MySQL server

I have been facing this issue for past few hours when I tried to do a bulk insert from Magento database through a custom module to our DWH. Datawarehouse is running MYSQL server on CentOS 6.2. I was doing a full dump of customers, products and orders from our Magento store to the Datawarehouse for the first time. But I couldn't  even get  more than 2k customers to the DWH database. Magento module returns an error "Error 2013 : Lost connection to MySQL server".

After doing some reading on the internet I found that, this is nothing to do with Magento or my custom module. It was just the way MYSQL server was configured.  Luckily it was a easy fix :).  Just change the max_allowed_packet parameter.

In CentOS go to /etc/my.cnf and add or edit the following under [mysqld] section
[mysqld]
max_allowed_packet= 16M 

I had 16M to suit my particular situation, choose a value that suites you. This should work, at least it worked for me ;), also recommend to have look at the wait_timeout parameter as well since few people mentioned that as well.

Tuesday, May 22, 2012

Catch of the Day Flash Sale SCAM!!!

Catchoftheday.com.au has announced a "Flash Sale" that is "catch of the day" put up a "Deal" every hour, and it went all day long today. They had attractive "DEALS" such as Diablo 3 PC Game which is around $90, just for $20, An Apple TV 3rd Gen worth of $109 just for $39, and many more "DEALS" like that for an unbelievable price. Unfortunately whole thing was a SCAM!!. First I have tried to buy Diablo 3, I was at the checkout screen in 40 seconds, but they said "Item is SOLD OUT". Then Amazon Kindle, same thing happen less than 90 seconds, Next I tried to buy Apple TV, same thing happen again, I was in the checkout page less than 50 seconds, SOLD OUT!!. Have a look at the screen shot this is even after I came back to main page.











NEVER caught in to this CatchofTheDay.com.au's SCAMs!!!!

Sunday, May 13, 2012

How to create an external database connection from a Magento Module

I reckon that many of you have already done this so many times, but as a newcomer to Magento, it took me a while to figure this out. So this tutorial is solely for newcomers like me, so they can save some time.

In this tutorial I'm going to show you how to connect to a external database (other than Magento database) using a custom Magento module. I’ll be using a Magento Basic Model and a Resource Model to connect to this external database. I'll also be using an index controller action to show you that this really works :).

This is what my custom module is going to do, Module name will be “Blog”, and it will connect to a database called “externaldb”. This database will have a table call “blog”. So my module will connect to this external database and read the data from the blog table. Yep, it ‘s so simple! :D

First create an empty module in you Magento instance. (Hope you already know how to do this, if not click here to learn how to do it)

Your Module structure will look like below,



Creating the config.xml file

Config.xml file plays a major part in Magento and it does the same in this case. All connection details to the external database can be placed in config.xml of your module (app/code/local/youmodulename/etc/config.xml), plus your read and write adapter details will also go in here.

Your config.xml will looks like below,


    
        
         0.1.0
  
 
 
  
   
    Externaldb_Blog_Model
    blog_resources
   
   
    Externaldb_Blog_Model_Resource
    
     
      blog
<![CDATA[localhost]]> <![CDATA[someuser]]> <![CDATA[somepassword]]> <![CDATA[externaldb]]> <![CDATA[mysql4]]> <![CDATA[SET NAMES utf8]]> <![CDATA[pdo_mysql]]> 1 blog_default blog_default
standard Externaldb_Blog externaldb


The section that you really need to understand in above XML, (with regards to the external database connection) is between "resources" tags. Because it contains the externaldb connection details, read and write adapter configurations.
 You can see I have created a "blog_default" section with connection details of the external database. Additionally, read and write adapter that uses “blog_default” connection.

Note that "blog" in "blog_read" and "blog_write" are the module group name. You cannot have anything else since I'm going to use the resource model to connect to the database.

Model Class for Blog module 

Following is the code for Blog Model (app/code/local/Externaldb/Blog/Model/Blogpost.php),
/**
 * Description of Externaldb_Blog_Model_Blogpost
 *
 * @author thanura
 */

class Externaldb_Blog_Model_Blogpost extends Mage_Core_Model_Abstract{
 public function _construct() {
  $this->_init('blog/blogpost');
 }
 
 public function readDataFromResource(){
  return $this->getResource()->readDataFromTable();
 }
 
}


Resource Model Class associate with the Blog Model

Here is the code for Blog resource model (app/code/local/Externaldb/Blog/Model/Resource/Blogpost.php),

/**
 * Description of Externaldb_Blog_Model_Resource_Blogpost
 *
 * @author thanura
 */
class Externaldb_Blog_Model_Resource_Blogpost extends Mage_Core_Model_Resource_Db_Abstract{
 
 public function _construct() {
  $this->_init('blog/blogpost', 'blog_id');
 }
 
 //This function is to load the data using the Read Adapert
 //to show you that I have connected to the external db
 public function readDataFromTable(){
  $readAdapter = $this->_getReadAdapter();
  
  $select = $this->_getReadAdapter()->select()
     ->from($this->getMainTable());
            
        $data = $readAdapter->fetchAll($select);
        
        return($data);
 }
}

Index Controller

Following simple controller will access the Blog Model call to connect to the external database and  retrieve data from blogpost table
/**
 * Description of Index Controller for External DB Module
 *
 * @author thanura
 */

class Externaldb_Blog_IndexController extends Mage_Core_Controller_Front_Action{
 
 public function indexAction(){
  $model  = Mage::getModel('blog/blogpost');
  $results = $model->readDataFromResource();
  
  var_dump($results);
 }
 
}


So thats all about it, now you can connect to a different database using a custom Magento Module. Hopefully this tutorial will help some of you guys out there, and if you have any questions, feel free to ask me. I'll try my best to answer them.
Enjoy!!

Thursday, June 09, 2011

Easy way to control your iTunes - MyTunesController

MyTunesController allows you to have a simple control over your iTunes. It just sits on you menu bar, which gives you easy access to the controls. It supports Lyrics as well. But if you need more functionality other than the basic Play/Pause/Skip Next or Previous , then you are looking at something like YouControl. But for me MyTunesController do Job!!
Download MyTunesController for free.

Friday, April 01, 2011

A “Like” button from Google! - The “Google +1 Button”

Google has unveiled their spick-and-span feature to be, the Google +1 Button a "tour guide" who will help people to discover more relevant content that is recommended by their friends and contacts.
So in near future, having a Google +1 button on your web pages will let users recommend your web content, so that their friends and contacts also see these recommendations when they do a google search in similar context.

Friday, December 03, 2010

BarCamp Apache Sydney 2010

Anyone interesting in BarCamps, The Apache BarCamp Sydney 2010 will be running at University of Sydney on 11th December 2010. The event is free and open for public. Details are available at http://barcamp.org/BarCampApacheSydney
See you there!