Android Serial Bluetooth Plugin on Unity

Hi,

I am trying to make a Bluetooh Android plugin for unity. I want to able to communicate from my android to Arduino with HC-05 module. I’ve managed to find the module, but cant connect to it. Here are my codes:

My Android Code:

package ivan.setiawan.plugin_bt;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText; 
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;


public class bt {
    TextView myLabel;
    EditText myTextbox;
    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
    OutputStream mmOutputStream;
    InputStream mmInputStream;
    Thread workerThread;
    byte[] readBuffer;
    int readBufferPosition;
    int counter;
    volatile boolean stopWorker;
   
    public String findBT()
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null)
        {
           return "Turn On Bluetooh";
        }

        if(!mBluetoothAdapter.isEnabled())
        {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if(pairedDevices.size() > 0)
        {
            for(BluetoothDevice device : pairedDevices)
            {
                if(device.getName().equals("HC-05"))
                {
                    mmDevice = device;
                    return "Bluetooth Device Found";
                   
                }
            }
        }
        return "Error";
       
    }
   
    private void startActivityForResult(Intent enableBluetooth, int i) {
        // TODO Auto-generated method stub
       
    }

    public String openBT() throws IOException
    {
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);       
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();

       beginListenForData();
       
        return "Bluetooth Opened";
       
    }
   
    public void beginListenForData()
    {
        final Handler handler = new Handler();
        final byte delimiter = 10; //This is the ASCII code for a newline character

        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1024];
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {               
               while(!Thread.currentThread().isInterrupted() && !stopWorker)
               {
                    try
                    {
                        int bytesAvailable = mmInputStream.available();                       
                        if(bytesAvailable > 0)
                        {
                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);
                            for(int i=0;i<bytesAvailable;i++)
                            {
                                byte b = packetBytes[i];
                                if(b == delimiter)
                                {
         byte[] encodedBytes = new byte[readBufferPosition];
         System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
         final String data = new String(encodedBytes, "US-ASCII");
         readBufferPosition = 0;

                                    handler.post(new Runnable()
                                    {
                                        public void run()
                                        {
                                            myLabel.setText(data);
                                        }
                                    });
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    }
                    catch (IOException ex)
                    {
                        stopWorker = true;
                    }
               }
            }
        });

        workerThread.start();
    }
   
    public void sendData() throws IOException
    {
        String msg = "1";
       msg += "\n";
       mmOutputStream.write(msg.getBytes());
        myLabel.setText(msg);
    }

    public void closeBT() throws IOException
    {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        myLabel.setText("Bluetooth Closed");
    }
}

Here is my Bridge Code in Unity:

using UnityEngine;
using System.Collections;

public class BTBridge : MonoBehaviour {

#if UNITY_ANDROID && !UNITY_EDITOR

    public string findBT(){
        AndroidJavaObject ajc = new AndroidJavaObject ("ivan.setiawan.plugin_bt.bt");
        return ajc.Call<string>("findBT");
    }

    public string openBT(){
        AndroidJavaObject ajc = new AndroidJavaObject ("ivan.setiawan.plugin_bt.bt");
        return ajc.Call<string>("openBT");
    }

    public void sendOn(){
        AndroidJavaObject ajc = new AndroidJavaObject ("ivan.setiawan.plugin_bt.bt");
        ajc.Call("sendOn");
    }

    public void sendOff(){
        AndroidJavaObject ajc = new AndroidJavaObject ("ivan.setiawan.plugin_bt.bt");
        ajc.Call("sendOff");
    }
#endif
}

And here is the controller code:

using UnityEngine;
using System.Collections;

public class BT_Controller : MonoBehaviour {
    public BTBridge bt;
    public GUIText status;

    // Use this for initialization
    void Start () {
#if UNITY_ANDROID && !UNITY_EDITOR


#endif
    }
   
    // Update is called once per frame
    void Update () {
   
    }

    void OnGUI(){
#if UNITY_ANDROID && !UNITY_EDITOR
        if (GUI.Button (new Rect (200, 10, 100, 50), "OPEN")) {
           
            status.text = bt.findBT();
        }

        if (GUI.Button (new Rect (400, 10, 100, 50), "Connect")) {

            status.text = bt.openBT();
        }

        if (GUI.Button (new Rect (10, 10, 100, 50), "ON")) {

            bt.sendOn();
        }

        else if (GUI.Button (new Rect (10, 200, 100, 50), "OFF")) {
           
            bt.sendOff();
           
        }
#endif

    }
}

I am guessing the problem is in the “openBT” method… Any help will be appreciated.
Thanks

you can fix the problem yet?

I am also trying to write the plugin for Unity but I cant even get the function “findBT” work. It doesnt return anything. I seems like no code is executed after this function. Any ideas?

You create ajc object in all method calls. It’s no saving device and connection, try create class level field.
This C# code working for me:

public class BTController : MonoBehaviour
{
    private const string CLASS_PATH = "com.bttemp.btplugin.BTLink";

    public Button findBtn;
    public Button connectBtn;
    public Button sendBtn;

    private AndroidJavaObject ajc;

    void Start ()
    {
        ajc = new AndroidJavaObject(CLASS_PATH);

        if (ajc==null)
        {
            Console.Log("Error Java class creation!");
            return;
        }

        findBtn.onClick.AddListener(()=> {
            string s = findBT();
            Console.Log(s);
        });

        connectBtn.onClick.AddListener(() => {
            string s = connectBT();
            Console.Log(s);
        });

        sendBtn.onClick.AddListener(() => {
            sendData();
        });
    }
  
    public string findBT()
    {
        return ajc.Call<string>("findBT");
    }

    public string connectBT()
    {
        return ajc.Call<string>("connectBT");
    }

    public void sendData()
    {
        ajc.Call("sendData");
    }
}

hello. I’ve been scanning for a few hours for a bit of advice on this. if this code sends data to the arduino bluetooth device from unity how does the arduino code read the sent data? any help would be great.