Advance using of eloquent in Laravel 4

This article is going to show you some advance using of eloquent that didn’t show in laravel documentation.

“SELECT” Query

SELECT DISTINCT category FROM phones LIMIT 20

Phone::select(array("category"))->distinct()->take(20)->get();

SELECT id,name FROM phones ORDER BY created_at DESC

Phone::orderBy("created_at","desc")->get(array("id,name"));

SELECT * FROM phones WHERE status=”publish” AND name LIKE “John%”

Phone::select("*")->where("status","=","publish")->where("name","like","John%")->get()

SELECT * FROM phones WHERE (id BETWEEN 1 AND 100) OR (image not like ‘%iPhone%’);

Phone::whereBetween("id",array(1,10))->orWhere("image","not like", "%iPhone%")->get();

Quick guide on installation laravel homestead in OS X

A very quick guide on installation Laravel in your Vagrant within 5 minutes. I will be explained in very roughly, if your are looking for more details please checking laravel home page.

1. Installing VirtualBox & Vagrant

Download and install both VirtualBox and Vagrant if you are not installed yet.Both of it is required in running homestead.

2. Adding Homestead Vagrant box

Open terminal and execute following commands to adding Homestead Vagrant Box. It take quite a long time to download. For me, I take almost 20 minutes to download.

vagrant box add laravel/homestead

3. Clone The Homestead Repository

Clone the git repository by following commands.

git clone https://github.com/laravel/homestead.git Homestead

Continue reading

Constraints of multiple layouts listview for android

Programming listview with multiple layout is very easy with android built in method. It is very useful but be careful with the constraints. I will like to introduce about the constraints of list adapter with multiple view types.

 

(1) getItemViewType(int position) method

You must override getItemViewType. Let’s say you have two type of layouts, seperator and text layouts, you have to returned in this way.

@Override
public int getItemViewType(int position) {
    if(mList.get(position).type == TYPE_SEPERATOR){
        return 0; // seperator layout
    }
    return 1;  // text layout
} 

 

(2) getItemViewType index begin with 0

Continue reading

Setup egit for eclipse ADT by install new software

I spent almost half an hour to set it up. The whole setup process was spending less then 5 minutes and the rest of the time almost spent in googling and blogging.

I am going to guide you a straight forward way to setup it all up.

Install new software

  1. On menu bar, go to Help -> Install New Software…
  2. Type http://download.eclipse.org/egit/updates into Works with and press enter key. (Don’t need to press Add… button)
  3. Then, you will see Eclipse Git team provider. Check Eclipse Git.

Done ?!

Yes! It is done! You can check it by About ADT.

Show Git on menu bar (Optional)

You can setup git on your menu bar by a few steps

Continue reading

Login ssh to server without including username

Let’s say you want to login to ssh in very short command. For instance,

ssh myserver

How to do it?

No configuration on server, just do some configuration on client side.
On client side terminal, open ssh config file. If it doesn’t exists, create a new one.
nano ~/.ssh/config

Then, type in following. 
host myserver
hostname myserverdomain.com
user myuser

And save it. No restart is required, just try ssh myserver, and you are login as myuser@myserverdomain.com



LED Blinky with BGScript Programming

If you are not yet setup the development environment. Check the last post.

http://edisontus.blogspot.jp/2014/01/getting-started-with-development.html

I am going to guide you how to make LED blink (turn on and turn off) in every 1 seconds with BGScript.

Create 3 config files (gatt.xml, hardware.xml, project.xml)

Every file have it’s own function and contains the information needed when compile to binary file. These 3 files are config files that is needed and you must always remember to import these in every project. What you needs to do is copy following source code and paste it.

hardware.xml is configuration file that related to ble112 hardware configuration.

<?xml version="1.0" encoding="UTF-8" ?>
 
<hardware>
    <sleeposc enable="true" ppm="30" />
    <usb enable="false" endpoint="none" />
    <txpower power="15" bias="5" />
    <usart channel="1" alternate="1" baud="57600"  endpoint="api" />
    <wakeup_pin enable="true" port="0" pin="0" />
    <port index="0" tristatemask="0" pull="down" />
    <pmux regulator_pin="7" />
</hardware>

gatt.xml exposes the Bluetooth services and profiles.

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
 
    <service uuid="1800">
      <description>Generic Access Profile</description>
 
      <characteristic uuid="2a00">
        <properties read="true" const="true" />
        <value>BG Demo</value>
      </characteristic>
 
      <characteristic uuid="2a01">
        <properties read="true" const="true" />
        <value type="hex">4142</value>
      </characteristic>
    </service>
 
    <service type="primary" uuid="9000" id="manufacturer">
        <characteristic uuid="9100">
            <properties read="true" const="true" />
            <value type="hex">000780c0ffeef00d</value>
        </characteristic>
        <characteristic uuid="9101">
            <properties read="true" const="true" />
            <value>modelnumber</value>
        </characteristic>
        <characteristic uuid="9106">
            <properties read="true" const="true" />
            <value>Bluegiga</value>
        </characteristic>
    </service>
 
    <service uuid="e001">
       <description>Battery status</description>
       <include id="manufacturer" />
      <characteristic uuid="e101" id="xgatt_battery">
          <properties read="true" notify="true" />
          <value type="hex">ABCD</value>
      </characteristic>
    </service>
     
    <service uuid="00431c4a-a7a4-428b-a96d-d92d43c8c7cf">
        <description>Bluegiga demo service</description>
        <characteristic uuid="f1b41cde-dbf5-4acf-8679-ecb8b4dca6fe">
            <properties read="true" write="true"/>
            <value type="hex">coffee</value>
        </characteristic>
    </service>
</configuration></pre><br /><b>project.xml </b>tell bgbuild what roles played by every xml file.<br /><pre class="brush:xml"><project>
    <gatt in="gatt.xml" />
    <hardware in="hardware.xml" />    
    <script in="blink.bgs" />
    <image out="out.hex" />    
</project>

Create blink.bgs

I will explain detail on blink.bgs later. Copy following code and paste to blink.bgs
dim flag
dim interval
 
# Boot event listener
event system_boot(major ,minor ,patch ,build ,ll_version ,protocol_version ,hw)
 flag = 0
 interval = $8000
 
 # Configure the P0_0 as output
 call hardware_io_port_config_direction(0, 1)
 # Enable P0_0 pin
 call hardware_io_port_write(0, 1, 1)
 # Start a 5 second, one stop timer
 call hardware_set_soft_timer(interval, 0 ,1) 
end
 
# Timer event listener
event hardware_soft_timer(handle)
   
  #declare hardware_set_soft_timer to allow it work as forever loop as recursive
   
 if flag = 0 then
 # When timer expires disable P0_0 pin
 call hardware_io_port_write(0, 1, 0)
 call hardware_set_soft_timer(interval, 0 ,1)
 flag = 1
  else
 # When timer expires enable P0_0 pin
 call hardware_io_port_write(0, 1, 1)
 call hardware_set_soft_timer(interval, 0 ,1)
 flag = 0
 end if 
end

Debug with bgbuild.exe

bgbuild.exe can be found at {ble_directory} -> bin directory. 
Open command prompt and go to blink directory that created at beginning of this article, and run following command.
C:\Bluegiga\ble-1.2.1-91\bin\bgbuild.exe project.xml
Replace {ble_directory} to your own path. You should get the result look as below.
Then, binary file out.hex is generated. It is the file we needed to flash into ble112.

BLE SW update tool

Bluegiga prepared a flash tool called Bluegiga BLE SW Update tool. This tool can be found at BleUpdate directory, it is placed at different place with bgbuild.exe.
Click Refresh and Info to choose the debugger. Then click browse to the out.hex that generated at last section inside blink directory.
Then click update and it will write the binary file into ble112.

Last job

Connect LED to P0_0 pin. Then you will see LED blink at every 1 seconds.

Explaination on blink.bgs

event system_boot is something like int main() in c language. It is always the first part to be executed after global variables.
dim is used to declare variable. Usually, it means int or char in c language. 
$ mark in bgscript used to declared the following number is hexadecimal. In this case, interval = $8000 is same as interval = 0x8000 in c language. Following equation is used to calculate the time for timer. Based on the equation below, clock of ble112 is 32.768kHz, in order to set 1 seconds, interval needed to be set to 32768 ( 8000 in hexdecimal ).

You might reliased that there is not for or while loop in my script. How can I achieve forever loop? The answer is recursive between hardware_set_soft_timer and hardware_soft_timer. 
There is no built in delay event so recursive method is the only way to do forever loop.
hardware_set_soft_timer set the timer start and hardware_soft_timer is the handler event after the time specified in 1st parameter of hardware_set_soft_timer is passed.
By adding hardware_set_soft_timer into hardware_soft_timer, the timer will started again when timer is stop.

End

Thank you for reading.

Simple guide to ExecutorService Android

ExecutorService is almost same as ThreadPoolExecutor, it allows you to carry out multiple background thread in sequentially.

What can ExecutorService do? Do you know that powerful AsyncTask method is only allows to be executed one time in single activity. If you execute AsyncTask more then one time in single activity, you will get the errors.

So it is where ExecutorService comes, it help you handle multiple background task which AsyncTask cannot be done.

Try it out!!

It is always easy to understand if you get something work first. 
First, prepare server script. 
<?php  
 echo "hello! I am server.";
?>
Remember the url of your server. Then, copy following android code and replace the url to your own and give permission to internet.
package com.example.apps1;
 
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
 
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
 private Button mButton;
 private ExecutorService pool;
  
 public static final String URL = "http://path_to_server/";
  
 private static final String TAG = MainActivity.class.getName();
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                
        
        mButton = new Button(this);
        mButton.setText("Press");
         
        addContentView(mButton, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
          
        pool = Executors.newSingleThreadExecutor();
         
        mButton.setOnClickListener(mClickListener);
    }
     
    private View.OnClickListener mClickListener = new View.OnClickListener(){
 
  @Override
  public void onClick(View v) {
   pool.execute(new NetworkService());   
  }     
    };    
     
     
    private class NetworkService implements Runnable {
     private Handler mHandler;
     public NetworkService(){
      mHandler = new Handler(Looper.getMainLooper()){
        
       @Override
       public void handleMessage(Message inputMessage){
         
        String msg = (String) inputMessage.obj;        
        Toast.makeText(getApplicationContext(), ""+msg, Toast.LENGTH_SHORT).show();        
       }       
      };
     }
      
  @Override
  public void run() {
   String recv = HttpRequest(URL);
   sendMessage(1, recv);
  }
   
  public void sendMessage(int what, String msg){
   Message message = mHandler.obtainMessage(what , msg); 
   message.sendToTarget();
  }
      
    }
     
    // Doing all Networking task, if failed to get message from server, it will return null  
 // 
 public String HttpRequest(String url) {
       
   DefaultHttpClient client = new DefaultHttpClient();
   HttpResponse response = null;
      
   try{          
    HttpGet httpGet = new HttpGet(url);     
    response = client.execute(httpGet);     
            
    return EntityUtils.toString(response.getEntity());
 
   }catch(ClientProtocolException e){
    Log.e(TAG,"ClientProtocolException : "+e);
   }catch(IOException e){
    Log.e(TAG,"IOException : "+e);
   }      
 
   return null;
  }
}
Press the button and toast will show you the message from server.

Explanation

ExecutorService can be instanced in few different way.

  1. Executors.newSingleThreadExecutor();
  2. Executors.newFixedThreadPool(10); 
  3. Executors.newScheduledThreadPool(10);

Based on how ExecutorService is instanced, ExecutorService will be working in different way. For more detail please checking Executors API. In this guide, I am using newSingleThreadExecutor, it only allows one task in the same time.

NetworkService is implemented with Runnable. NetworkService is almost same as AsyncTask, contains UI thread callback method, doInBackground method.

In this case, same method of AsnycTask and NetworkService

  • doInBackground == run
  • onPostExecute == handleMessage
private class NetworkService implements Runnable {
 private Handler mHandler;
 public NetworkService(){
   
  // Handler looper constructor to declare this handler
  // is going to link to UI Thread 
  mHandler = new Handler(Looper.getMainLooper()){
    
   // handleMessage method is callback of background work.
   // All the tasks in handleMessage will be pass to UI thread
   //
   // This method is same as AsyncTask.onPostExecute        
   @Override
   public void handleMessage(Message inputMessage){
     
    String msg = (String) inputMessage.obj;        
    Toast.makeText(getApplicationContext(), ""+msg, Toast.LENGTH_SHORT).show();        
   }       
  };
 }
  
 // Runnable.run method doing all tasks in background
 // It is same as AsyncTask.doInBackground
 @Override
 public void run() {
  String recv = HttpRequest(URL);
   
  // Get the result from HttpRequest and past it to handler.
  sendMessage(1, recv);
 }
  
 public void sendMessage(int what, String msg){
  Message message = mHandler.obtainMessage(what , msg); 
  message.sendToTarget();
 }
  
}
Every time user press the button, NetworkService will be created and added to background’s pool. If there is no task queue in front the NetworkService task, it will be executed.
pool.execute(new NetworkService());   
Background task is not an easy task. There are much more work then the sample code on above such as shutdown or pause the ExecutorService. What I have explain in this article is to get you works on your apps quickly. 

End

Hope this article help you in coding. Thank you for reading.

Getting started with Developing Bluetooth 4.0 LE and Android with BLE112 Bluetooth module

If your objective is asking BLE112 to say “helloworld” to Android or any other smart phone in faster, quick and simple way. You are on the right way. I am going to guide you how to get BLE112 to connect to your Android, Iphone or any others smart phone.

Materials

What you need is

  1. Bluetooth module ( BLE112 )  USD$50
    http://www.inmojo.com/store/jeff-rowberg/item/ble112-bluetooth-low-energy-breakout/
  2. CC Debugger USD$ 49
    http://www.ti.com/tool/cc-debugger 
  3. Android which adaptable to Bluetooth 4.0

And the software you need to installed

  1. Bluetooth Smart Software and SDK ( Provided by bluegiga ) 
    http://www.bluegiga.com/en-US/products/bluetooth-4.0-modules/ble112-bluetooth–smart-module/documentation/
Bluegiga provide the SDK for free, but you have to register a new account to download it.

Reason why I choose BLE112 breakout board. BLE112 embed with antenna and bluetooth built in chip (Texas Instrument cc2540). It means you can begin your development with ble112 in a very cheap price around USD$12 to $16. However, bluegiga do not provide a nice pin leg and you need to soldering it to board in order to connect it to cc debugger. Here’s the reason why I choose jeff-rowberg breakout board. On jeff-rowberg site, it provide two type of board, one is ble112 embed and one is without embed. It save my time to design the breakout board and soldering ble112.

Preparation

Download the Bluetooth Smart software and SDK and install it by follow the instruction.

After you have successfully installed Bluetooth SDK, you are almost there. Connect cc debugger and ble112. To easy my developing, I soldering pin socket to ble112. It is optional for you either soldering pin socket or not.

There are three things needed to connect.

  1. usb to cc debugger
  2. cc debugger to ble112
  3. ble112 to 3.3V power supply
Pinout is written on board, so you should able to find GND and 3V3
Newbie usually think that debugger provide power to module, but it is WRONG.
Debugger do not provide power to module, you have to provide external power to module. Here’s the why number 3 comes.
After you have setup all the things, let’s begin to debug the ble112.

Debug

Go to Bluetooth Smart SDK directory -> example -> find_me directory. Run project.bgproj and you will see the following window.
Click Refresh button to detect debugger. Then, click Info to detect ble112. The you should see that cc-debugger led turn red to green and the message show in dialog. If led already turn green light, then it should be okay. Green light means that chip have been successfully detected.
If “No chip detected” messages is showed and LED is red, it means that cc debugger unable to detect the ble112. There are 3 things you needs to do.
  1. Make sure BLE112’s power is supplied by external power supply but not from debugger.
  2. Make sure CC debugger pin is correctly connected to ble112.
  3. Long press the cc debugger reset button.
Make sure that File point to correct directory “find_me” and “project.bgproj”.
Then, click Update to begin debug.
If you see the following messages, it means you have successfully debug the chip. 

Testing with Android

Go to bluetooth settings and enable Bluetooth. Click “Search for devices”.
If you see “Bluegiga Find Me”, it means your bluetooth have successfully connected to Android. If you can’t see it. Most probably your android device is not adaptable to Bluetooth 4.0, test it with another device which adaptable to Bluetooth 4.0

End

Here’s the end of the blog. Hope you are successfully to see the messages. On next section, I will begin to explain about more detail on what is going with “Bluegiga Find me” and how BLE112 interact with microcontroller.
Hope you will continue with it. Thank you for your reading.

How to inject javascript in android webview like chrome javascript console

If you used to inject javascript to test your website on chrome. You can do so on android webview.

To achieve it, you need to add internet permission on your AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Then, on your main_activity_layout.xml , add webview

<WebView android:id="@+id/web"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Next, on your MainActivity.java, instance webView and add following code.

final WebView webView = (WebView)findViewById(R.id.web);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
  
  public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {     
   Log.e("browser",description);
   dialog.dismiss();
   }
 
    @Override
    public void onPageFinished(WebView view, String url) {
        // do your javascript injection here, remember "javascript:" is needed to recognize this code is javascript
        webView.loadUrl("javascript:document.write('hello')"); 
    }
     
    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
     // this method is needed to ignore SSL certificate errors if you are visiting https website 
        handler.proceed(); 
    }
 
});
 
webView.loadUrl("https://your_sites.com");  

Javascript is disabled in default, you need to enable it by calling setJavascriptEnabled method.

Javascript needed to be added after the page is finished loaded, otherwise javascript will be debug before the page loaded.