Test driving Push notification in Bluemix


This post is a continuation of my earlier post ‘Getting started with mobile cloud in Bluemix‘. Here I take a test drive of the push service that Bluemix offers based on the article “Extend an Android app using the Push cloud service” from developerWorks.

This post assumes that you have already completed the changes from my earlier post for the mobile cloud. If you haven’t,  you could clone the code from “mobile data” which is the official IBM version of this app and includes all the changes needed for persisting data in the cloud through their Android.

The Mobile Cloud App I created on Bluemix is “mobtvg“. The main steps to have Push notification service using Bluemix are

  1. GCM services : Get Google API Project number  & GCM API Key
  2. Include the Google Play services library project
  3. Add the jar files to enable Push service
  4. Modify the server side Node.js file to send push notifications to all registered devices
  5. Make necessary code changes
  6. Run the application and test for notification

Here are more details on the above steps

a) GCM services : Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users’ Android-powered device, and also to receive messages from devices on the same connection. The 1st thing to do is get the Google API Project number & GCM API key.

– Click on Google Developer Console

– Click Create Project. Enter Project name & click Create.

– Note the Project Number on top of the page.

– Click API & Auth on left panel. Click API.

– Scroll down and turn-on Google Messaging for Android

–  Click credentials and click “Create new key”. Click server key. Click create

-Copy API key in the Public API access

Now go the Bluemix dashboard and click your application. Click the Push module. In the Configuration tab, scroll down to Google Cloud Messaging and  click ‘Edit’

Enter the Google API Project Number & GCM API key for both the Sandbox & Production configuration and click Save.

4
b) In Eclipse click Windows->Android SDK manager. Scroll down to the bottom and under Extras select Google Play services. Click install. Once the installation is successful import the project as follows File-Import->Android->Existing Android  code into Workspace. Click Next. In the next screen Browse to the path where your ADT bundle is installed and choose the folder

<ADT-Bundle>\ sdk\extras\google\google_play_services

and Click Ok. Also  check ‘Copy project into workspace’. This will copy.

3

Now build the Google Play Services Project. To do this the project. Click Project->Properties->Android and make sure that you select ‘Is library project’ and then click build.

5

Add a reference to the Google Play services in the Androidmanifest.xml

<meta-data

android:name=”com.google.android.gms.version”

android:value=”@integer/google_play_services_version” />

c) Make all the code changes given in Step 4 of “Extend an Android app using the Push cloud service.

d) In MainActivity.java make sure you change the app_name to the name of your app for e.g

public static final String CLASS_NAME = “MainActivity”;

public static final String APP_NAME = “mobtvg“;

Also ensure that under assets folder you have populated the Application ID in the bluemix.properties file

applicationID=<Application ID from Bluemix>

d) Add ibmcloudcode.jar, ibmpush.jar, android-support-v4.jar (from <Android_SDK_Location>/extras/android/support/v4)

e) Now the Mobile Push project need to include this library project. To do this select your Mobile App project. Click Project->Properties->Android. Click Add and select google-play-services-lib. Note: Make sure “Is library project” is unchecked otherwise you are in for a lot of grief.

8

f) Now you need to make changes to the Node.js application to push any changes from the server to all registered devices.  The code for this is in bluelist-push-node. Note; Making changes through the GUI results in an error that “manifest.yml is not in root node”. So I suggest that you take the ‘cf’ route as follows.

– Clone the code using Git

git clone https://hub.jazz.net/git/mobilecloud/bluelist-push

Go to bluelist-push-node folder

i) Open the app.js with your favorite editor and enter the Application ID of your Bluemix application

//Data Values

var values = {

version:”0.3.1″,

//change this to the actual application id of your mobile backend starter

appID : “<APPLICATION ID>”,

host : “https://mobile.ng.bluemix.net&#8221;

}

ii) Open manifest.yml and change host name & name to the name of your application for e.g.

host: mobtvg

disk: 1024M

name: mobtvg

command: node app.js

path: .

domain: ng.bluemix.net

mem: 128M

instances: 1

iii) Once the changes are complete, open a command propmpt and  login into Bluemix using ‘cf’ as follows

– cd to the directory in which Node.js & manifest.yml exist, Do

cf login – a http://api.ng.bluemix.net

cf push mobtvg -p . -m 512M

(Note the changes are pushed to the mobile cloud app on Bluemix)

This will run through and finally give the status that the app is running successfully.

f) Now that all changes are complete the Mobile Cloud with Push can be tested..

g) Click Window->Android Virtual Device Manager. Click the Device definitions. You choose Google Nexus, Nexus 7. Click Create AVD.

Note: Make sure you choose Google API Level Y and not Android x.x.x API Y.

6

Let the AVD come up and display the current items in the grocery list.

h) Login to Bluemix. Click Push and select the Notifications tab and enter a test message for e.g. “This is a notification from Bluemix” and click send.

7

This will result in a Push Notification to be sent to the AVD. You should see this popup on you AVD as shown below

1

i) Add another AVD through Windows-Android Virtual Device manager. While one AVD is running go to Run->Run Configurations->Target Device and choose the newly created AVD.

j) This will start a second AVD which will refresh with the contents of the grocery list. Now adda new item in one of AVD devices. This will result in a Push notification to the other device that the Bluelist has been updated.

2

There you have it.

1) A mobile cloud applications in which changes persist in the cloud and are refreshed each time the Android device is restarted.

2) A Push notification that is sent to all registered devices whenever there is a change to the list.

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

Find me on Google+

Getting started with a Mobile Cloud app with Bluemix


This post gives the key steps to get going in building a Mobile Cloud application on IBM’s Bluemix. This post focuses on using the Android Platform for building the application. IBM Bluemix’es mobile cloud application includes under its hood mobile services like mobile application security, push and mobile data. A Node.js is also thrown in to provide server-side functions.

The Bluemix Mobile architecture is shown below

BuildingMobile

 

As in the previous post an existing Mobile cloud application IBM’s bluelist -base is cloned to get familiarity with the steps involved. The IBM’s bluelist-base app enables the user to maintain a grocery list that persists as mobile data in the cloud instance. To get started perform the following

1) Install ADT + Eclipse bundle from the aforementioned link

2) Unzip and install Eclipse and the ADT bundle

3) Make sure you have the Java JDK for Eclipse. If not install from the following site Java SE Development Kit 8 Downloads

4) Since we will be cloning an existing application and using Eclipse to make the changes we need to install EGit.

5) To do this open Eclipse and select Help-> Install New Software and type in http://download.eclipse.org/egit/updates in the Work with text field and hit enter. You should see the following

1

6) Once EGit is installed the IBM’s bluelist-base App can be cloned as follows

7) In Eclipse click File->Import->Git->Import from Git and click Next

8) Choose Clone URI and Click Next

9) Enter the URI for IBM’s bluelist-base. This shown below

2

10) This will download all the necessary source files and other Android related files and directories into the workspace.

11) After this perform the Steps 2 to Step 6 from the link given Build an Android app using the MobileData cloud service

12) After you make the necessary code changes you are good to go

13) Make sure you right-click and add all the necessary imports required (also Ctrl+Shift + O)

14) Build the Project and make sure that there are no errors

15) You are now ready to run the mobile cloud application. We need to run the mobile app on a Virtual simulator. This can be done as

a) In Eclipse click Window->Android Virtual Device Manager. Click the Device Definitions tab.

b) Choose Nexus 7 (Google) and Click Create AVD.
c) This will open a New Window. Set the following Skin->QVGA and Enter 100 MiB in SD Card size and click OK. This will add this as a AVD.

16) Now run the application.

17) This will bring up the AVD. This takes some time You should see the IBM bluelist showing up as one of the apps.

18) Click on IBM Bluelist. You can add grocery items. These items will persist even if you have to restart your application

3

19) The data is persisted in the IBM’s cloud. This can be checked by logging into BlueMix’es dashboard

4

20) Click the Mobile Data and the data entered in the AVD device will show up in Data Classes drop down.

5

21) The Analytics tab will give a graphical output of the API calls

6

So not the mobile app that is cloud enabled is ready.

Clearly the ability to build Android Apps with the data stored at a cloud opens up numerous possibilities for apps like Evernote, Pocket across several devices.

There you have your first Mobile Cloud App.

Watch this space!

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

Find me on Google+

Get your feet wet with IBM Bluemix


This post provides the initial steps to get started on IBM’s Bluemix (currently in beta). Bluemix is open-standard, cloud based Platform-as-a-Service (PaaS) from IBM. Bluemix allows one to quickly put together mobile, web, Big Data, IoT applications. Bluemix is an implementation of IBM’s Open Cloud Architecture, Cloud Foundry which enables developers to rapidly build, deploy, and manage their cloud applications. The developers can tap into a growing ecosystem of available services and runtime frameworks.

Bluemix uses the Softlayer infrastructure to host the user applications. Clients/developers interact with Bluemix either with HTTP or REST as shown below
8

Here are the steps to get going on Bluemix

First things first

I would suggest that you get all the registrations and installations right away.

Bluemix dashboard– Get started by creating an account on Bluemix. This will provide you access to the Bluemix’s dashboard from which you can quickly create applications (mobile, Web, IoT, BigData) etc

Devops: Register for an account with Devops. Devops allows you to easily develop, deploy and track your code online. Devops also allows you to collaborate with others by forking code from their Git repositories

Cf Interface : Install the Command line interface ‘cf” to Bluemix. The ‘cf’ command interface is built with Google’s Go programming language. With ‘cf ‘you can login to Bluemix, create an application, add services and manage your application. You can also do this from the Bluemix’es dashboard.

Install Git: There are multiple ways to develop code for Bluemix. Git command line happens to be one of them, So it makes sense to have this installed. You can install this from this link https://hub.jazz.net/tutorials/clients#installing_git

Install Node.js:The application that this post discusses is based on a Node.js based application so it will help to have it installed. Node.js is a platform that enables building of fast, scalable network applications and created by Ryan Dahl.

Kicking off Bluemix : A good first application to get moving on in Bluemix is the already available Sentiment Analysis of Twitter. This application uses the Node.js ‘sentiment’ module to perform some basic sentiment analysis.

The quickest and most painless way to get started on Bluemix is to ‘fork’ the code for Sentiment Analysis from Devops.

1) Login to your Devops account. Click the following Sentiments link from Devops, in which I have created a slight modification to the sentiment analysis application. You can also clone the code from GitHub at sentiments.

2) Click the Edit Code button at the top. This will open the files and directories in this project (see picture below)

3) Next click the “Fork’ button on the panel on the left side. This will create a copy of the above code in your own repository (see picture below )

1

4) The Twitter sentiment analysis code is in app.js written in Node.js. You can make changes to the code as needed. I have made a few modifications to the code that I had forked. I added changes which adds a textual output of the Twitter sentiment

;

How to make code changes with Web IDE

5) To make code changes double click the app.js file. This will open up the code window. You can use the GUI based IDE to make the code changes and merge with the master branch, The steps are
a) Make the necessary changes and click the symbol shown

2

3. This will open a new window as shown below

3

4) Click the ‘Stage to change’ button.

5) This will move the changes to Staged. Click the ‘Commit’ button and enter the reason for the change and click the “Submit’

4

6) This will move the changes from ‘Staged’ to ‘Commits for master branch’

7) Now click ‘Push all’ and click ‘Ok’ in the Git Push popup window. This will merge the changes into the master branch.

8) Once this done click ‘Build & Deploy’ button

9) Your changes will transition from ‘Pending’ to ‘OK’. Now click the ‘Manage’ button. This will deploy the application with the latest changes on to Bluemix.

10) Do the following to populate the details for the parameters below  with a Twitter app that you create for your application

var tweeter = new twitter({
consumer_key:  <your API key>,
consumer_secret: <your API secret>,
access_token_key:<your access token >,
access_token_secret: <your access token secret>
});

11) To do this log into http://dev.twitter.com

12) Click My applications where your picture is displayed and then click Create application.

13) Enter the details for Name,Description & Website (can be any valid website) and then click Create Twitter application.. This will create the Twitter application.

1

14) Click the API tab. Scroll down to the bottom and click “Create my access token”.

15) This will generate the Access token & Access token secret. Enter all the details (API Key, API secret, Access Token, Access Token secret into app.js and push to the master branch before deploying on Bluemix

 

Code changes with Git command line

11) Incidentally the changes to code can also be made through the Git command shell as follows

a) git clone https://hub.jazz.net/git/tvganesh/sentiments

b) Modify the code using any editor and save the changes

c) Go the directory containing the files and do

git add *

d) git commit -m “Cosmetic” app.js

e) git push

This will push the changes to the git repository in the master branch

8) Click the ‘Build & deploy’ in the top right corner. You should see this

5

9) Click the ‘Manage’ button which will push the application onto the BlueMix

10) To test this application click the link next to ‘Routes’ . Enter a phrase that you would like to search and hit ‘Go’

6

You should see the application checking Twitter periodically for the tweets.

7

Thats it! You have built your first Bluemix application.

The ability to integrate Node.js into your cloud application allows one to easily create powerful applications.

Hasta la vista! I’ll be back!

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

Find me on Google+

A method to crowd source pothole marking on (Indian) roads


In, India, roads and potholes are 2 sides of the same coin! You cannot think of one in exclusion of another. This post of mine looks at a novel technique of rapidly identifying & marking potholes in (Indian) roads. This approach can be used for any city in the world but is very pertinent to Indian roads.

This idea of mine provides a technique of quickly marking pothole in roads through the method of crowd sourcing

 

Introduction: It is a well known fact that Indian roads are riddled with potholes. Some may even say that there are potholes with patches of road in between them. This disclosure looks at a novel technique of rapidly identifying & marking potholes in (Indian) roads. The approach can be used for any city in the world. However this disclosure will focus on Indian roads. This disclosure proposes a novel technique of crowd-sourcing the marking of potholes on roads rather than having any single government body (NHAI etc) travel on roads to make the markings.

Description: This post proposes a novel crowd-sourced method for pothole marking that will be easy to conduct and extremely rapid The crowd-sourced pothole marking application will be made of the following components namely Pot-hole marking app, Backend server, Map Matching utility, Pothole ranking utility.

Pothole marking App: A location based smartphone app will need to be created preferably both on Android and iOS. The app will display the map with buttons to mark the following

a)   Points in map of potholes

b)   Bad segments of roads with potholes

Backend Server: The backend server will collect all the data (marked potholes) and bad segments of roads and will update a database.  A map-matching utility will map the latitude, longitude of the marked point on to a map. When the geographical location of a pothole is received (latitude, longitude) the backend server will also store the time stamp.

Pothole ranker: This module will run on a periodical basis, say once every 3 minutes. This module will determine all the potholes that have been entered in the last 3 minutes and add to the accumulated count of marked potholes. Each marked pothole will hold the count of the marks and also the time stamp of the mark. It will also rank the criticality of the pothole based on the accumulated count of potholes over the period.

The pothole ranker will maintain the following metrics

  1. Pothole criticality = Total accumulated count/ Total time
  2. Pothole impact measure = Max rate of pothole marks (Pothole marks/hr)
  3. Bad stretches of roads with many potholes =

Number of adjacent potholes/ Distance in meters

cs

Description: This how the scheme will work in practice. The app will be uploaded into Google Play and Apple’s App store.  All users who would like to participate in the pothole marking exercise can download and install the app on their smart phones. These users when they are traveling on a road can mark potholes as they encounter them. It is assumed that the users are passengers in vehicles or pillion riders. The fact that users all over the city can simultaneously mark potholes as they encounter them will make the gathering of pothole data rapid and extremely accurate. A map of a city would need to be generated with the circles/points for locations of potholes, color-coded appropriately. We could use the color red for higher ranked potholes and yellow for lower ranked potholes with intermediate colors like purple, pink etc.  This data can then be used by Government bodies in addressing roads in fixing the roads.

There are three advantages of crowd sourcing the pothole marking

1)   The process of gathering data is rapid

2)   Roads where the traffic is heaviest will have potholes with a higher rank and can be addressed first

3)   The process will be very accurate

Crowd sourcing of pothole marking will have the following benefits

  1. The marking of potholes will be extremely rapid
  2. The potholes will be ranked based on accumulated count
  3. Ranking of potholes can be done on

– Total accumulated count/Total time

– Rate of pothole mark

– Critical segments with major potholes

4. It will be easy to segregate

– Critical potholes
– Max impactful potholes
– Bad road segment

  1. The process will be very accurate

Conclusion: The process of crowd sourcing pothole marking of Indian roads will be extremely efficient in marking potholes and bringing it to the attention of the Government.

A map of a city with the circles for locations of potholes, color-coded appropriately, to indicate higher marked potholes versus the lower ranked potholes could be generated. This map can be used to bring to the attention of the government the really bad roads and terrible road segments. Rather than having a couple of vehicles trying to ply roads and mark roads this will be very fast and extremely accurate.

Afterword: The concept of crowd sourcing for traffic is not new. Waze, which Google bought for close to $2bn does just that. It crowd sources traffic conditions and alerts users of the app. Also I did a Google search on using mobile apps for potholes marking and, not surprisingly, there were others who had also thought of a similar idea in Boston & Florida see the links below

  1. http://www.cityofboston.gov/doit/apps/citizensconnect.asp
  2. http://dailycrowdsource.com/20-resources/projects/421-crowdsourced-pothole-database-to-track-road-repair

However, I personally think that the situation in India is different, where there are ‘roads in between potholes’ ;-). While in the above 2 cases in US, only the location of the potholes is important, my idea ranks potholes based on the accumulated count and the rate of pothole marks. These metrics can be used by the government in addressing those sections of roads where the potholes have a higher rank i.e. where the traffic is highest.

Your thoughts are welcome.

Find me on Google+

A closer look at “Robot Horse on a Trot” in Android


DSC00078This post is result of my dissatisfaction with the awkward and contrived gait of my Robot Walker in my earlier post “Simulating a Robot Walker” in Android. The movements seemed to be a little too contrived for my comfort so I decided to make a robot which has far more natural movements.

You can see the clip at Robot Horse on a canter using Android on Youtube
The complete code can be cloned at GitHub RobotHorse

To do this I pondered on what constitutes a walking motion for any living thing. With a little effort it is clear that the following movements occur during walking

Mechanics of leg movements during walking

  1. The upper part of the leg swings upward and downward pivoted at the hip.
  2. The lower part of the leg, pivoted at the knee, swings in the opposite direction to the upper part of the leg. i.e when the upper part swings upward and counter-clockwise, the lower part of the leg swings downward & clockwise which results in the bend at the knees
  3. When one leg goes up, counterclockwise, the other leg goes down or it swing clockwise and vice versa. See figure below

horse

So with these rules it was easy to make the legs.

Frontal leg (first leg)
The upper part of the leg is connected to the Robot Body through a revoluteJoint with a pivot at the body. The upper leg has a motor and swings between an upper and lower limit
// Create upper leg
upperLeg = new Sprite(x, y, this.mLegTextureRegion, this.getVertexBufferObjectManager());
upperLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, upperLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(upperLeg, upperLegBody, true, true));
this.mScene.attachChild(upperLeg);

//Create an anchor/pivot at the body of the robot
Vector2 anchor1 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT,y/PIXEL_TO_METER_RATIO_DEFAULT);
//Attach upper leg to the body using a revolute joint with a motor
final RevoluteJointDef rJointDef = new RevoluteJointDef();
rJointDef.initialize(upperLegBody, robotBody, anchor1);
rJointDef.enableMotor = true;
rJointDef.enableLimit = true;
rJoint = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef);
rJoint.setMotorSpeed(4);
rJoint.setMaxMotorTorque(15);

//Set upper and lower limits for the swing of the leg
rJoint.setLimits((float)(0 * (Math.PI)/180), (float)(30 * (Math.PI)/180));

//Fire a periodic timer
new IntervalTimer(secs,rJoint);

The lower leg pivoted to the bottom of the upper leg through a revoluteJoint swings in the opposite direction of the upper leg between the reverse angle limts. By the way, I had tried every possible joint between the lower & the upper leg (distanceJoint, weldJoint,prismaticJoint) but the revoluteJoint is clearly the best.

// Create lower leg
lowerLeg= new Sprite(x, (y+50), this.mLegTextureRegion, this.getVertexBufferObjectManager());
lowerLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, lowerLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(lowerLeg, lowerLegBody, true, true));
this.mScene.attachChild(lowerLeg);
Vector2 anchor2 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT, (y+50)/PIXEL_TO_METER_RATIO_DEFAULT);

//Create a revoluteJoint between upper & lower leg
final RevoluteJointDef rJointDef1 = new RevoluteJointDef();
rJointDef1.initialize(lowerLegBody, upperLegBody, anchor2);

// The lower leg swings in opposite direction to upper leg
rJointDef1.enableMotor = true;
rJointDef1.enableLimit = true;
rJoint1 = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef1);
rJoint1.setMotorSpeed(-4);
rJoint.setMaxMotorTorque(15);

//Set upper and lower limits for the swing of the leg
// Set appropriate limits for lower leg
rJoint1.setLimits((float)(-30 * (Math.PI)/180), (float)(0 * (Math.PI)/180));
new IntervalTimer(secs,rJoint1);
Rear Leg (alternate leg)

Every alternate leg moves in the converse direction as the previous leg

//Create the alternative leg
publicvoid createAltLeg(float x, float y, int secs ){
// Create upper part of leg
upperLeg = new Sprite(x, y, this.mLegTextureRegion, this.getVertexBufferObjectManager());
upperLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, upperLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(upperLeg, upperLegBody, true, true));
this.mScene.attachChild(upperLeg);
//Create an anchor/pivot at the body of the robot
Vector2 anchor1 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT,y/PIXEL_TO_METER_RATIO_DEFAULT);
//Attach upper leg to the body using a revolute joint with a motor
final RevoluteJointDef rJointDef = new RevoluteJointDef();
rJointDef.initialize(upperLegBody, robotBody, anchor1);
rJointDef.enableMotor = true;
rJointDef.enableLimit = true;
rJoint = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef);
// This leg swings in the opposite direction of the previous leg
rJoint.setMotorSpeed(-4);
rJoint.setMaxMotorTorque(15);
//Set upper and lower limits for the swing of the leg
rJoint.setLimits((float)(0 * (Math.PI)/180), (float)(30 * (Math.PI)/180));
new IntervalTimer(secs,rJoint);
// Create lower leg
lowerLeg= new Sprite(x, (y+50), this.mLegTextureRegion, this.getVertexBufferObjectManager());
lowerLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, lowerLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(lowerLeg, lowerLegBody, true, true));
this.mScene.attachChild(lowerLeg);
Vector2 anchor2 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT, (y+50)/PIXEL_TO_METER_RATIO_DEFAULT);
//Create a revoluteJoint between upper & lower leg
final RevoluteJointDef rJointDef1 = new RevoluteJointDef();
rJointDef1.initialize(lowerLegBody, upperLegBody, anchor2);
rJointDef1.enableMotor = true;
rJointDef1.enableLimit = true;
rJoint1 = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef1);
//The lower part of the leg has the opposite swing to the upper part
rJoint1.setMotorSpeed(4);
rJoint.setMaxMotorTorque(15);
//Set appropriate upper and lower limits for the swing of the leg
rJoint1.setLimits((float)(-30 * (Math.PI)/180), (float)(0 * (Math.PI)/180));
// Fire a periodic timer
new IntervalTimer(secs,rJoint1);
I attached a horse’s head to the body using a WeldJoint
//Create the horse and attach the head using a Weld Joint
horse = new Sprite(140, 320, this.mHorseTextureRegion, this.getVertexBufferObjectManager());
horseBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, horse, BodyType.DynamicBody, HORSE_FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(horse, horseBody, true, true));
this.mScene.attachChild(horse);
Vector2 anchor = new Vector2(140/PIXEL_TO_METER_RATIO_DEFAULT, 320/PIXEL_TO_METER_RATIO_DEFAULT);
final WeldJointDef weldJointDef = new WeldJointDef();
weldJointDef.initialize(horseBody, robotBody, anchor);
this.mPhysicsWorld.createJoint(weldJointDef);

So now I had a horse that was ready to trot or canter around.

You can see the clip at Robot Horse on a canter using Android
The complete code can be cloned at GitHub RobotHorse

Some issues

Here are some issues with the above code

  • The horse is quite unstable. If I move the phone vertically, the horse tends to tip backwards. The above clip was recorded with the phone lying on a table
  • The motor speeds, torque and the masses of the different objects have to be adjusted very carefully. If the horse’s head or the body is too heavy the legs buckle under the weight
  • Sometimes when I start the simulation the horse seems to bounce off the floor

I have carefully adjusted the mass, friction, motor speeds etc very carefully. Feel free to play around with them.

Comments & suggestions are welcome.

Find me on Google+

“Is it an animal? Is it an insect?” in Android


walker“Is it an animal? Is it an insect?”. The answer is neither. In fact it is my version of a ‘robot walker’ in android using Box2D & AndEngine. I got interested in this simulation after I saw the Theo Jansen walker in JBox2D (look under Joints) . I did take a look at the code for this but I found it difficult to follow so I made my own version of a robot walker.

With the above the robot walker is able to walk awkwardly as seen in the video clip on Youtube – Robot Walker in Android
The entire project can be cloned at GitHub at RobotWalker

In this connection I would like to point yot to an excellent and a fascinating TED talk by the creator Theo Jansen himself on “My creations, a new form of life”. His creations are really jaw- dropping.

Anyway getting back to my post I thought about what would make the insect walk? After some thought I realized that I had to create a swinging motion of the upper part of the leg combined with the lower leg motion which does not bend that much.

So I created a robot body which is a flat rectangular shape

//Create the robot body

robot = new Sprite(100, 360, this.mRobotTextureRegion, this.getVertexBufferObjectManager());

robotBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, robot, BodyType.DynamicBody, BODY_FIXTURE_DEF);

this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(robot, robotBody, true, true));

this.mScene.attachChild(robot);

Creating legs

Then I create 6 different legs spaced apart

createLeg(100,360,1);

createLeg(120,360,1);

createLeg(140,360,1);

createLeg(160,360,1);

createLeg(180,360,1);

createLeg(200,360,1);

createLeg(220,360,1);

createLeg(240,360,1);

The createLeg() creates an upper and lower part of the leg. The upper part of the leg is connected to the body of the robot through a revoluteJoint as follows

Upper Leg

// Create upper leg

upperLeg = new Sprite(x, y, this.mLegTextureRegion, this.getVertexBufferObjectManager());

upperLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, upperLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);

this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(upperLeg, upperLegBody, true, true));

this.mScene.attachChild(upperLeg);

//Create an anchor/pivot at the body of the robot

Vector2 anchor1 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT,y/PIXEL_TO_METER_RATIO_DEFAULT);

//Attach upper leg to the body using a revolute joint with a motor

final RevoluteJointDef rJointDef = new RevoluteJointDef();

rJointDef.initialize(upperLegBody, robotBody, anchor1);

rJointDef.enableMotor = true;

rJointDef.enableLimit = true;

rJoint = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef);

Lower Leg

The lower leg is connected to upper leg through a distance joint

// Create lower leg

lowerLeg= new Sprite(x, (y+50), this.mLegTextureRegion, this.getVertexBufferObjectManager());

lowerLegBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, lowerLeg, BodyType.DynamicBody, LEG_FIXTURE_DEF);

this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(lowerLeg, lowerLegBody, true, true));

this.mScene.attachChild(lowerLeg);

// Connect the lower and upper leg with distance joint

Vector2 anchor2 = new Vector2(x/PIXEL_TO_METER_RATIO_DEFAULT, (y+50)/PIXEL_TO_METER_RATIO_DEFAULT);

//Create a distanceJoint between upper & lower leg

DistanceJointDef distanceJoint1 = new DistanceJointDef();

distanceJoint1.initialize(upperLegBody,lowerLegBody, anchor2,anchor2);

distanceJoint1.collideConnected = true;

distanceJoint1.dampingRatio = 0.5f;

distanceJoint1.frequencyHz = 10.0f;

this.mPhysicsWorld.createJoint(distanceJoint1);

 mqdefault

Creating a walking movement

To create a walking movement I create a timer task which triggers after a delay of 1 second periodically and makes the upper legs’s revoluteJoint swing between angles within an upper and lower limit.

new IntervalTimer(secs,rJoint);

The timer itself reverses the motor every time it fires

class RemindTask extends TimerTask {

RevoluteJoint rj1;;

RemindTask(RevoluteJoint rj){

rj1 = rj;

}

@Override

publicvoid run() {

reverseMotor();

}

publicvoid reverseMotor(){

rj1.setMotorSpeed(-(rj1.getMotorSpeed()));

rj1.setMaxMotorTorque(10);

}

}

With the above the robot walker is able to walk awkwardly as seen in the video Robot Walker in Android

The entire project can be cloned at GitHub at RobotWalker

I will probably be refining this sometime in the future. One good idea is to create a delay between the swings of different legs. Any thoughts suggestions on making the movement more fluid are more than welcome.

Take a look at some cool simulations using AndEngine & Box2D
1. Simulating the domino effect using Box2D and AndEngine
2. Bull in a china shop – Behind the scenes in android
3. Creating a blob in Android using  Box2D physics Engine & AndEngine
4. Blob with an attitude(stiffness) in Android
and a few more
Find me on Google+

Simulating an oscillating revoluteJoint in Android


DSC00074In this post I simulate an oscillating revoluteJoint in Android using Box2D physics engine & AndEngine. While I was attempting this in the context of something larger I found this fairly challenging so I decided to write a separate post on this.  Creating a revoluteJoint was rather trivial.  This was done as follows

Initially I created a static point to act as pivot.  I then used a rectangular shape joined at the pivot. I wanted this to oscillate about the pivot. So the pivot & the rectangular shape were created as follows
circle = new Sprite(100, 320, this.mBallTextureRegion, this.getVertexBufferObjectManager());

circleBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, circle, BodyType.StaticBody, FIXTURE_DEF);

this.mScene.attachChild(circle);

// Create leg

leg = new Sprite(110, 325, this.mLegTextureRegion, this.getVertexBufferObjectManager());

legBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, leg, BodyType.DynamicBody, gameFixtureDef);

this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(leg, legBody, true, true));

this.mScene.attachChild(leg);

Then I created a revoluteJoint between the leg and the circleBody as follows

final RevoluteJointDef rJointDef = new RevoluteJointDef();

rJointDef.initialize(legBody, circleBody, circleBody.getWorldCenter());

rJointDef.enableMotor = true;

rJointDef.enableLimit = true;

rJoint = (RevoluteJoint) this.mPhysicsWorld.createJoint(rJointDef);

rJoint.setMotorSpeed(2);

rJoint.setMaxMotorTorque(100);

rJoint.setLimits((float)(30 * (Math.PI)/180), (float)(270 * (Math.PI)/180));

The revoluteJoint has a lower limit of 30 degrees and an upper limit of 270 degrees.

To make it oscillate I created a Timer task which I fire every second. Every time the timer fires I reverse the motor speed as follows

class IntervalTimer {

Timer timer;

public IntervalTimer(int seconds, RevoluteJoint rj) {

Log.d(“Inside”,“in”);

timer = new Timer(); //At this line a new Thread will be created

timer.scheduleAtFixedRate(new RemindTask(rj), seconds*1000, 1000);

}

class RemindTask extends TimerTask {

RevoluteJoint rj1;;

RemindTask(RevoluteJoint rj){

rj1 = rj;

}

@Override

publicvoid run() {

Log.d(“x”,“x” +“Reversing motor”);

reverseMotor();

}

publicvoid reverseMotor(){

rj1.setMotorSpeed(-(rj1.getMotorSpeed()));

rj1.setMaxMotorTorque(100);

Log.d(“aa”,“speed:”+rj1.getMotorSpeed() + “torque:” + rj1.getMotorTorque());

}

}

}

I then instantiate the timer

new IntervalTimer(5,rJoint);

I now have an oscillating revoluteJoint which can be used in any number of ways.

The video clip is at “Simulating an oscillating revoluteJoint in Android

You can clone the project from GitHub at “oscillatingRevoluteJoint

Find me on Google+

Fun simulation of a Chain in Android


DSC00071In this post I simulate a Chain in Android using AndEngine & Box2D physics. Simulating a Chain is fairly straightforward. Initially I create a static point as an anchor point to suspend the Chain from

You can see the video at Fun simulation of a Chain in Android – I on Youtube

The project can be cloned from GitHib at Chain

 

link[0] = new Sprite((float) 360, (float) 20, this.mLinkTextureRegion, this.getVertexBufferObjectManager());

linkBody[0] = PhysicsFactory.createBoxBody(this.mPhysicsWorld, link[0], BodyType.DynamicBody, FIXTURE_DEF);

this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(link[0], linkBody[0], true, true));

this.mScene.attachChild(link[0]);

Then I create succeeding links to the initial link with revolute joints between them as follows

// Add links to chain with revolute joint between each link

for(int i =1; i < nBodies ; i++){

x[i] = x[i-1] + 8 * Math.cos(PI/4);

y[i] = y[i-1] + 8 * Math.sin(PI/4);

link[i] = new Sprite((float) x[i], (float) y[i], this.mLinkTextureRegion, this.getVertexBufferObjectManager());

linkBody[i] = PhysicsFactory.createBoxBody(this.mPhysicsWorld, link[i], BodyType.DynamicBody, FIXTURE_DEF);

this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(link[i], linkBody[i], true, true));

this.mScene.attachChild(link[i]);

revoluteJointDef = new RevoluteJointDef();

revoluteJointDef.initialize(linkBody[i], linkBody[i-1], linkBody[i-1].getWorldCenter());

revoluteJointDef.enableMotor = false;

revoluteJointDef.motorSpeed = 0;

revoluteJointDef.maxMotorTorque = 0;

this.mPhysicsWorld.createJoint(revoluteJointDef);

Finally I suspend a monkey as the last body to the Chain.

I have added plated for the 2 walls (right & left) and also the floor as collisions can be detected between bodies.

@Override

protectedvoid onManagedUpdate(finalfloat pSecondsElapsed) {

// Check collisions

if(rWall.collidesWith(this) ){

x = this.getX();

y = this.getY();

bText.setPosition(x-40,y – 20);

bText.setText(“Bonk!”);

}

if(lWall.collidesWith(this)){

x = this.getX();

y = this.getY();

bText.setPosition(x + 20,y – 20);

bText.setText(“Thump!”);

}

if(floor.collidesWith(this)){

x = this.getX();

y = this.getY();

bText.setPosition(x – 20,y – 20);

bText.setText(“Thud!”);

}

With all these under gravity we have a nice Chain effect!

You see the video at Fun simulation of a Chain in Android – I

The project can be cloned from GitHib at Chain

Take a look at some cool simulations using AndEngine & Box2D
1. The making of Total Control Android game
2. Simulating an Edge Shape in Android
3. Simulating a Web Joint in Android
4. Modeling a Car in Android
5. A closer look at “Robot horse on a Trot! in Android”
and a couple more
Find me on Google+

Modeling a Car in Android


DSC00065

In this post I give the details of how I modeled a ‘running car’ in Android using AndEngine & Box2D physics.  This post is based on a great blog post by Emanuele Feronato on “Step by step creation of a Box2D car/truck with motors and shocks”.

You can check the video of this simulation at “Modeling a Car using AndEngine & Box2D physics
You can clone the entire project from GitHub at Wheels

So getting down to the “nuts & bolts” of  creating a car we need to create 3 components of the car

1)Car body

2)Axles (left & right)

3)Wheels (left & right)

The car body is connected to the axles through a prismatic joint. Prismatic joint, also known as ‘slider joint’, allows 2 bodies to move relative to each on a single axis of motion. Hence this joint simulates a ‘shock absorber’ effect very nicely. In fact, in the 3rd lap of my video from right to left when the car collides with the left wall you can see the car rocking on its axles. This is done as below

/* Connect the front axle to car using a prismaticJoint */

PrismaticJointDef front = new PrismaticJointDef();

front.initialize(carBody, frontAxle, frontAxle.getWorldCenter(),new Vector2(0f,1f));

front.collideConnected=false;

front.enableMotor=false;

front.enableLimit=true;

front.upperTranslation=0.5f;

front.lowerTranslation=-0.2f;

PrismaticJoint mFront = (PrismaticJoint) mPhysicsWorld.createJoint(front);

The wheels are connected to the axles through a revolute joint. A revolute joint rotates around an anchor point based on a specified motor speed and motor torque as shown below

//Connect rear wheel to rear axle using revoluteJoint
final RevoluteJointDef revoluteJointDef2 =new RevoluteJointDef();
revoluteJointDef2.initialize(wheelBody2, rearAxle, wheelBody2.getWorldCenter());
revoluteJointDef2.enableMotor =true;
revoluteJointDef2.motorSpeed =-50;
revoluteJointDef1.maxMotorTorque = 10;
rj2 =(RevoluteJoint)this.mPhysicsWorld.createJoint(revoluteJointDef2);

I wanted the car to reverse direction when it collided with either the left wall or right wall. In my original code, the car body and the walls were made of rectangle shapes and I was not able to detect the collisions. So I changed the car body and add a left wall and a right wall with sprites and checked for the collisions between these bodies. Fortunately I had done this collision detection in my app “The making of the Dino Pong Android Game”. I was able to check for collisions as shown below .

@Override
protectedvoidonManagedUpdate(finalfloat pSecondsElapsed){
// Check collisions
if(rWall.collidesWith(this)|| lWall.collidesWith(this)){

// On collision reverse speed
rj1.setMotorSpeed(-(rj1.getMotorSpeed()));
rj2.setMotorSpeed(-(rj2.getMotorSpeed()));
}

If you have done all of the above and also managed to utter the magic incantation (which I will not divulge ;-)) you should have a cute running car!  

You can check the video of this simulation at “Modeling a Car using AndEngine & Box2D physics

You can clone the entire project from GitHub at Wheels

   


Take a look at some cool simulations using AndEngine & Box2D
1. Simulating the domino effect using Box2D and AndEngine
2. Bull in a china shop – Behind the scenes in android
3. Simulating an Edge Shape in Android
4. Fun simulation of a Chain in Android
5. “Is it animal? Is it an insect?” in Android
and many more …

Find me on Google+

Simulating a Web Joint in Android


a (1) I got interested in this demo after I saw the Java demo of Box2D physics in Jbox (look in Joints). Moreover my interest in this demo was heightened as the Disney game ‘Cut the rope’ possibly uses some elements of a web joint.

Take a look at the simulation Simulating a Web Joint in Android on Youtube
You can clone the entire project from GitHub at WebJoint

The first task was to create & place Animated Sprites(face) at the corners of a rectangle. I also added distance Joints between them.

Vector2 v1 = new Vector2(p1[0]/PIXEL_TO_METER_RATIO_DEFAULT,p1[1]/PIXEL_TO_METER_RATIO_DEFAULT);

Vector2 v2 = new Vector2(p2[0]/PIXEL_TO_METER_RATIO_DEFAULT,p2[1]/PIXEL_TO_METER_RATIO_DEFAULT);

distanceJoint.initialize(body1, body2, v1, v2);

distanceJoint.collideConnected = true;

distanceJoint.dampingRatio = 1.0f;

distanceJoint.frequencyHz = 10.0f;

this.mPhysicsWorld.createJoint(distanceJoint);

}

I also had to draw connecting lines to represent the joints between the faces The challenge is to update these lines in real time as the bodies oscillate about their mean based on the damping constant. Fortunately I had done this in of my earlier demos “Creating a blob with an attitude”. The key to this is to update the connecting line to the attached bodies through the onUpdate method

@Override

publicvoid onUpdate(finalfloat pSecondsElapsed) {

super.onUpdate(pSecondsElapsed);

if(connectionLine != null)

connectionLine.setPosition(faceA.getX(),faceA.getY(),faceB.getX(),faceB.getY());

}

}

While the Animated Sprites are dynamic bodies I also created 4 pegs (static bodies) that attach to these 4 animated sprites which are suspended in a rectangle formation.

I also added a onAreaTouch listener to enable me to remove bodies interactively. This is a deviation from the demo where the user has to press a key which will remove the bodies in a pre-determined fashin.

To remove the bodies using onAreaTouch was a challenge. So when I remove an Animated Sprite I have to

  1. Remove all connecting lines to the body

  2. Destroy all the joints between the body and other bodies

TO remove the connecting lines I first tried the following

private void removeFace(AnimatedSprite face) {

if(connectionLine1 != null && connectionLine1.collidesWith(face)){

this.mScene.detachChild(connectionLine1);

connectionLine1.dispose();

connectionLine1 = null;

}

if(connectionLine2 != null && connectionLine2.collidesWith(face)){

..

But this did not quite work and it would remove only some of the lines. Then I changed it as follows based on the animated sprite that is being removed in which I specifically remove the connecting lines

if(face.equals(face1)){

Log.d(“Yes”,“Yes”);

destroyLine(connectionLine1);

destroyLine(connectionLine4);

destroyLine(connectionLine5);

}

where destroyLine() is as follow

if(line.isDisposed() == true)

return;

this.mScene.detachChild(line);

final PhysicsConnector linePhysicsConnector= this.mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(line);

this.mPhysicsWorld.unregisterPhysicsConnector(linePhysicsConnector);

line.dispose();

line = null;

}

To destroy all the distance joints which the bodies has we have to iterate through all of the joints as follows

// Determine all joints connected to Animated Sprite & destroy

ArrayList<JointEdge> jointsEdge = facePhysicsConnector.getBody().getJointList();

for(int i=0; i < jointsEdge.size(); i++){

Joint j = jointsEdge.get(i).joint;

this.mPhysicsWorld.destroyJoint(j);

j=null;

}

Finally the face is removed as follows

this.mPhysicsWorld.unregisterPhysicsConnector(facePhysicsConnector);

this.mPhysicsWorld.destroyBody(facePhysicsConnector.getBody());

this.mScene.unregisterTouchArea(face);

this.mScene.detachChild(face);

Anyway occasionally I do get a SIGSEGV in update thread if I remove face as follows lower right, lower left, upper left. Some orders work well for e.g. Upper left, lower left, lower right etc.

If you figure out what I am missing do let me know.

Take a look at the simulation Simulating a Web Joint in Android

You can clone the entire project from GitHub at WebJoint

Find me on Google+