Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulties while connecting to remote device. Needs more than one try

I working with a project where I need to connect my tablet (android 4.2.2) to Bluetooth-to-UART converter (RN42 by microchip). I am using BluetoothChat example to manage bluetooth connection, but its difficult to connect. Sometimes program fails at method mmSocket.connect(); - it throws IOException. Sometimes i need three or more tries to connect to my remote device. After connection is made, it is very stable. I tried to change UUID, tried to change rn42 module (i also tried to use HC-05 module). I tried secure and insecure rfcomm connection, still no luck. here is my code: In the MainActivity:

  @Override
public void onButtonPressed(View view, Device device){
    switch (view.getId()){
    case R.id.buttonRedaguotiIrengini:
        // Edit button is pressed
        Intent i = new Intent(this, DeviceActivity.class);
        i.putExtra("device", device);
        i.putExtra("requestCode", REQUEST_EDIT_DEVICE);
        startActivityForResult(i, REQUEST_EDIT_DEVICE);
        break;
    case R.id.buttonPrisijungti:
        if (mBtService.getState()==BluetoothService.STATE_CONNECTED){
            mBtService.stop();
        } else {
            BluetoothDevice btDevice = mBluetoothAdapter.getRemoteDevice(device.getMac());
            mBtService.connect(btDevice, false);
        }
        break;
    }
}

in the BluetoothService Class:

   // Name for the SDP record when creating server socket
private static final String NAME_SECURE = "BluetoothChatSecure";
private static final String NAME_INSECURE = "BluetoothChatInsecure";

// Unique UUID for this application
private static final UUID MY_UUID_SECURE =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final UUID MY_UUID_INSECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");


// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mSecureAcceptThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;

// Constants that indicate the current connection state
public static final int STATE_NONE = 0;       // we're doing nothing
public static final int STATE_LISTEN = 1;     // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3;  // now connected to a remote device

   public synchronized void connect(BluetoothDevice device, boolean secure) {
    if (D) Log.d(TAG, "connect to: " + device);

    // Cancel any thread attempting to make a connection
    if (mState == STATE_CONNECTING) {
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
    }

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

    // Start the thread to connect with the given device
    mConnectThread = new ConnectThread(device, secure);
    mConnectThread.start();
    setState(STATE_CONNECTING);
}

   private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    private String mSocketType;

    public ConnectThread(BluetoothDevice device, boolean secure) {
        mmDevice = device;
        BluetoothSocket tmp = null;
        mSocketType = secure ? "Secure" : "Insecure";

        // Get a BluetoothSocket for a connection with the
        // given BluetoothDevice
        try {
            if (secure) {
                tmp = device.createRfcommSocketToServiceRecord(
                        MY_UUID_SECURE);
            } else {
                tmp = device.createInsecureRfcommSocketToServiceRecord(
                        MY_UUID_INSECURE);
            }
        } catch (IOException e) {
            Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
        }
        mmSocket = tmp;
    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
        setName("ConnectThread" + mSocketType);

        // Always cancel discovery because it will slow down a connection
        mAdapter.cancelDiscovery();

        // Make a connection to the BluetoothSocket
        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            if (D) {Log.d(TAG,  "will try to connect to socket");};
            mmSocket.connect();
        } catch (IOException e) {
            // Close the socket
            if (D) {Log.d(TAG, "failed to connect to socket");};
            e.printStackTrace();
            try {
                mmSocket.close();
            } catch (IOException e2) {
                Log.e(TAG, "unable to close() " + mSocketType +
                        " socket during connection failure", e2);
            }
            connectionFailed();
            return;
        }
        if (D){Log.d(TAG,  "Success");};
        // Reset the ConnectThread because we're done
        synchronized (BluetoothService.this) {
            mConnectThread = null;
        }

        // Start the connected thread
        connected(mmSocket, mmDevice, mSocketType);
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
        }
    }
}

    private void connectionFailed() {
    // Send a failure message back to the Activity
    Message msg = mHandler.obtainMessage(MainActivity.MESSAGE_TOAST);
    Bundle bundle = new Bundle();
    bundle.putString(MainActivity.TOAST, "Unable to connect device");
    msg.setData(bundle);
    mHandler.sendMessage(msg);
    if (D){Log.d(TAG,  "Failed, unable to connect device");};
    setState(STATE_NONE);
}

Here are the LogCat output

  03-12 16:01:38.992: D/mBT(9947): connect to: 00:06:66:67:44:3E
  03-12 16:01:38.992: I/BluetoothSocket_MTK(9947): [JSR82] Bluetooth Socket Constructor
  03-12 16:01:38.992: I/BluetoothSocket_MTK(9947): [JSR82] type=1 fd=-1 auth=false encrypt=false port=-1
  03-12 16:01:38.993: D/BTSocketService(452): [JSR82][Service] initSocket
  03-12 16:01:38.993: I/BluetoothSocketService.cpp(452): [JSR82][JNI] initSocketNative +++.
  03-12 16:01:38.993: I/BluetoothSocketService.cpp(452): [JSR82][JNI] initSocketNative: start to initialize socket.
  03-12 16:01:38.993: I/BluetoothSocketService.cpp(452): [JSR82][JNI] type=1, auth=0, encrypt=0, port=-1
  03-12 16:01:38.993: I/BluetoothSocketService.cpp(452): [JSR82][JNI] initSocketNative: Initialize socket done.
  03-12 16:01:38.993: E/BluetoothSocketService.cpp(452): [JSR82] alloc context : index=2
  03-12 16:01:38.993: E/BluetoothSocketService.cpp(452): [JSR82] Clear context : index=2, ctx.index=0, ctx.fd=0
  03-12 16:01:38.993: I/BluetoothSocketService.cpp(452): [JSR82][JNI] jsr82ConnectCond (2) initialization success 
  03-12 16:01:38.993: I/BluetoothSocketService.cpp(452): [JSR82][JNI] jsr82ReadCond (2) initialization success <READ> 
  03-12 16:01:38.993: I/BluetoothSocketService.cpp(452): [JSR82][JNI] jsr82WriteCond (2) initialization success <WRITE> 
  03-12 16:01:38.993: I/BluetoothSocketService.cpp(452): [JSR82][JNI] jsr82RegisterCond (2) initialization success <REGISTER> 
  03-12 16:01:38.993: I/BluetoothSocketService.cpp(452): [JSR82][JNI] initSocketNative ---. fdHandle=32770
  03-12 16:01:38.995: D/mBT(9947): setState() 1 -> 2
  03-12 16:01:38.998: I/mBT(9947): BEGIN mConnectThread SocketType:Insecure
  03-12 16:01:39.001: D/BluetoothService(452): [API] cancelDiscovery()
  03-12 16:01:39.001: I/BluetoothService.cpp(452): [GAP][API] stopDiscoveryNative
  03-12 16:01:39.001: I/BluetoothService.cpp(452): [GAP] btmtk_gap_discovery_cancel
  03-12 16:01:39.001: I/BluetoothService.cpp(452): [GAP] btmtk_gap_discovery_cancel already cancelled
  03-12 16:01:39.001: I/BluetoothService.cpp(452): [GAP] btmtk_gap_send_discovery_stop_event
  03-12 16:01:39.001: I/BluetoothService.cpp(452): [JNI] bt_sendind(ptr=0x5C6AEA50, len=28)
  03-12 16:01:39.001: I/BluetoothService.cpp(452): [JNI] send ind=3528
  03-12 16:01:39.001: I/BluetoothEventLoop.cpp(452): [MSG] Polling returned
  03-12 16:01:39.001: I/BluetoothEventLoop.cpp(452): [MSG] Start retrieve data
  03-12 16:01:39.002: I/BluetoothEventLoop.cpp(452): [MSG] fd 1 data ready
  03-12 16:01:39.002: I/BluetoothEventLoop.cpp(452): [MSG] nat->pollData[i].fd data ready : revents = 0x1
  03-12 16:01:39.002: I/BluetoothEventLoop.cpp(452): [MSG] msg 3528 received : size=28
  03-12 16:01:39.002: I/BluetoothEventLoop.cpp(452): [GAP] receive event=3528
  03-12 16:01:39.002: I/BluetoothEventLoop.cpp(452): [GAP] btmtk_util_update_adapter_property_discovering: is_discovering = 0
  03-12 16:01:39.002: D/BluetoothEventLoop(452): Property Changed: Discovering : false
  03-12 16:01:39.006: I/BluetoothService.cpp(452): [JNI] send ind success : 28
  03-12 16:01:39.007: I/BluetoothEventLoop.cpp(452): [MSG] Start polling
  03-12 16:01:39.008: V/BluetoothEventManager(1562): Received android.bluetooth.adapter.action.DISCOVERY_FINISHED
  03-12 16:01:39.011: D/mBT(9947): will try to connect to socket
  03-12 16:01:39.011: I/BluetoothSocket_MTK(9947): [JSR82] connect: do SDP
  03-12 16:01:39.012: D/BluetoothService(452): [API] fetchRemoteUuids(00:06:66:67:44:3E)
  03-12 16:01:39.012: V/BluetoothAdapterProperties(452): getObjectPath():MTKBT/dev_
  03-12 16:01:39.012: I/BluetoothService.cpp(452): [GAP][API] discoverServicesNative : addr=MTKBT/dev_00_06_66_67_44_3E, pattern=00001101-0000-1000-8000-00805f9b34fb
  03-12 16:01:39.013: I/BluetoothService.cpp(452): [GAP] btmtk_gap_service_search_raw_request addr=67443E:66:6, size=19
  03-12 16:01:39.013: D/[BT](142): mtk_bt_write: buffer bebcbcc8, len 5
  03-12 16:01:39.013: I/BluetoothService.cpp(452): [GAP] btmtk_gap_send_sdp_discover_event
  03-12 16:01:39.013: I/BluetoothService.cpp(452): [JNI] bt_sendind(ptr=0x54B921A0, len=60)
  03-12 16:01:39.013: I/BluetoothService.cpp(452): [JNI] send ind=3535
  03-12 16:01:39.013: I/BluetoothService.cpp(452): [JNI] send ind success : 60
  03-12 16:01:39.013: I/BluetoothEventLoop.cpp(452): [MSG] Polling returned
  03-12 16:01:39.013: I/BluetoothEventLoop.cpp(452): [MSG] Start retrieve data
  03-12 16:01:39.013: I/BluetoothEventLoop.cpp(452): [MSG] fd 1 data ready
  03-12 16:01:39.014: I/BluetoothEventLoop.cpp(452): [MSG] nat->pollData[i].fd data ready : revents = 0x1
  03-12 16:01:39.014: I/BluetoothEventLoop.cpp(452): [MSG] msg 3535 received : size=60
  03-12 16:01:39.014: I/BluetoothEventLoop.cpp(452): [GAP] receive event=3535
  03-12 16:01:39.014: I/BluetoothEventLoop.cpp(452): [GAP] receive event ANDROID_EV_SDP_DEVICE_CREATE 0x67443E:0x66:0x6
  03-12 16:01:39.014: I/BluetoothEventLoop.cpp(452): [GAP] pattern (16)  0: 0:11: 1
  03-12 16:01:39.014: I/BluetoothEventLoop.cpp(452): [MSG] Start polling
  03-12 16:01:39.015: V/BluetoothDiscoveryReceiver(1562): Received: android.bluetooth.adapter.action.DISCOVERY_FINISHED
  03-12 16:01:39.018: D/[BT](142): mtk_bt_read: buffer 401c901c, len 1
  03-12 16:01:39.018: D/[BT](142): mtk_bt_read: buffer 401c9024, len 2
  03-12 16:01:39.018: D/[BT](142): mtk_bt_read: buffer 401980e6, len 4
  03-12 16:01:39.018: D/[BT](142): mtk_bt_read: buffer 401c901c, len 1
  03-12 16:01:39.019: D/[BT](142): mtk_bt_write: buffer bebcbcc8, len 5
  03-12 16:01:39.026: D/[BT](142): mtk_bt_read: buffer 401c901c, len 1
  03-12 16:01:39.026: D/[BT](142): mtk_bt_read: buffer 401c9024, len 2
  03-12 16:01:39.026: D/[BT](142): mtk_bt_read: buffer 401981e7, len 4
  03-12 16:01:39.026: D/[BT](142): mtk_bt_read: buffer 401c901c, len 1
  03-12 16:01:39.026: D/[BT](142): mtk_bt_write: buffer bebcbcc8, len 17
  03-12 16:01:39.032: D/[BT](142): mtk_bt_read: buffer 401c901c, len 1
  03-12 16:01:39.032: D/[BT](142): mtk_bt_read: buffer 401c9024, len 2
  03-12 16:01:39.032: D/[BT](142): mtk_bt_read: buffer 401982e8, len 4
  03-12 16:01:39.033: D/[BT](142): mtk_bt_read: buffer 401c901c, len 1
  03-12 16:01:40.017: D/[BT](142): mtk_bt_read: buffer 401c901c, len 1
  03-12 16:01:40.017: D/[BT](142): mtk_bt_read: buffer 401c9024, len 2
  03-12 16:01:40.017: D/[BT](142): mtk_bt_read: buffer 401983e9, len 4
  03-12 16:01:40.017: D/[BT](142): mtk_bt_read: buffer 401c901c, len 1
  03-12 16:01:44.775: D/Bluetooth HS/HF(692): [BT][HFG] [API] mStateReceiver.onReceive(android.intent.action.BATTERY_CHANGED)
  03-12 16:01:44.776: D/Bluetooth HS/HF(692): [BT][HFG] [API] mHandler.handleMessage(9)
  03-12 16:01:44.776: D/Bluetooth HS/HF(692): [BT][HFG] [API] updateBatteryState
  03-12 16:01:45.014: D/BluetoothService(452): [API] getUuidFromCache(00:06:66:67:44:3E)
  03-12 16:01:45.015: D/BluetoothService(452): [API] getUuidFromCache=00001101-0000-1000-8000-00805f9b34fb)
  03-12 16:01:45.016: D/BluetoothService(452): [API] getUuidFromCache=00001101-0000-1000-8000-00805f9b34fb)
  03-12 16:01:45.016: D/BluetoothService(452): [API] sendUuidIntent(00:06:66:67:44:3E)
  03-12 16:01:45.020: D/Bluetooth HSHFP(692): [BT][HFG][Intent] action=android.bluetooth.device.action.UUID, state=0
  03-12 16:01:45.022: D/BluetoothService(452): [API] makeServiceChannelCallbacks(00:06:66:67:44:3E)
  03-12 16:01:45.022: D/BluetoothService(452): Cleaning up failed UUID channel lookup: 00:06:66:67:44:3E 00001101-0000-1000-8000-00805f9b34fb
  03-12 16:01:45.022: I/BluetoothSocket_MTK(9947): [JSR82] SdpHelper::onRfcommChannelFound: channel=-1
  03-12 16:01:45.023: D/mBT(9947): failed to connect to socket
  03-12 16:01:45.023: W/System.err(9947): java.io.IOException: Service discovery failed
  03-12 16:01:45.024: W/System.err(9947):   at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:813)
  03-12 16:01:45.024: W/System.err(9947):   at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:382)
  03-12 16:01:45.024: W/System.err(9947):   at p.demoui.BluetoothService$ConnectThread.run(BluetoothService.java:389)
  03-12 16:01:45.024: I/BluetoothSocket_MTK(9947): [JSR82] close
  03-12 16:01:45.024: I/BluetoothSocket_MTK(9947): [JSR82] readLock got.
  03-12 16:01:45.025: D/BTSocketService(452): [JSR82][Service] abort
  03-12 16:01:45.025: I/BluetoothSocketService.cpp(452): [JSR82][JNI] abortNative +++. fd=32770.
  03-12 16:01:45.025: I/BluetoothSocketService.cpp(452): [JSR82][JNI] abortNative ---.
  03-12 16:01:45.025: I/BluetoothSocket_MTK(9947): [JSR82] Start to aquire writeLock.
  03-12 16:01:45.026: I/BluetoothSocket_MTK(9947): [JSR82] writeLock got.
  03-12 16:01:45.026: D/BTSocketService(452): [JSR82][Service] destroy
  03-12 16:01:45.026: I/BluetoothSocketService.cpp(452): [JSR82][JNI] destroyNative: fd=32770.
  03-12 16:01:45.026: E/BluetoothSocketService.cpp(452): [JSR82] Clear context : index=2, ctx.index=-1, ctx.fd=32770
  03-12 16:01:45.030: D/mBT(9947): Failed, unable to connect device
  03-12 16:01:45.030: D/mBT(9947): setState() 2 -> 0

Where is mistake? how can I improve this code? Why is the IOException is thrown in this case?

Thanks for your help.

like image 983
PauliusM Avatar asked Nov 10 '22 11:11

PauliusM


1 Answers

Here is how I had done similar Bluetooth connection and sending commands.I am posting complete demo code please give it a try.

BluetoothService.java ( same class from BluetoothChat example)
can be found here http://stanford.edu/~tpurtell/BluetoothChatService.java

In My case MacID was already pre given to me.

MainActivity.java

    public class MainActivity extends Activity implements OnClickListener {


        // Layout Views
        private Button bt_on_off;
        private TextView statuses;
        private Button connectIt;

        private Button click;

        //Timer timer;
        private boolean isBTOnOrOff = false;

        // Debugging
        private static final String TAG = "BluetoothChat";
        private static final boolean D = true;

        // Message types sent from the BluetoothChatService Handler
        public static final int MESSAGE_STATE_CHANGE = 1;
        public static final int MESSAGE_READ = 2;
        public static final int MESSAGE_WRITE = 3;
        public static final int MESSAGE_DEVICE_NAME = 4;
        public static final int MESSAGE_TOAST = 5;

        // Key names received from the BluetoothChatService Handler
        public static final String DEVICE_NAME = "device_name";
        public static final String TOAST = "toast";

        // Intent request codes
        private static final int REQUEST_CONNECT_DEVICE = 1;
        private static final int REQUEST_ENABLE_BT = 2;

        // Name of the connected device
        private String mConnectedDeviceName = null;
        // Array adapter for the conversation thread
        //private ArrayAdapter<String> mConversationArrayAdapter;
        // String buffer for outgoing messages
        private StringBuffer mOutStringBuffer;
        // Local Bluetooth adapter
        private BluetoothAdapter mBluetoothAdapter = null;
        // Member object for the chat services
        private BluetoothService mChatService = null;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            initViews();
            enableDissableViews(false);
            listeners();

            preBTConfigCheck();
        }

        private void initViews() {

            bt_on_off = (Button) findViewById(R.id.bt_on_off);
            connectIt= (Button) findViewById(R.id.connect);
            statuses= (TextView) findViewById(R.id.statuses);

            click= (Button) findViewById(R.id.click);

        }

        private void listeners() {
            bt_on_off.setOnClickListener(this);
            connectIt.setOnClickListener(this);
            click.setOnClickListener(this);
        }

        // Broadcast reciever for BT
        private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                final String action = intent.getAction();

                if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                    final int state = intent.getIntExtra(
                            BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                    switch (state) {
                    case BluetoothAdapter.STATE_OFF:
                        enableDissableViews(false);
                        isBTOnOrOff=false;
                        bt_on_off.setText(getResources().getString(
                                R.string.on_off_status)
                                + "OFF");
                        if (D)
                            Log.d(TAG, "STATE OFF");
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        enableDissableViews(false);
                        bt_on_off.setText(getResources().getString(
                                R.string.on_off_status)
                                + "Turning off...");
                        if (D)
                            Log.d(TAG, "STATE Turning off...");
                        break;
                    case BluetoothAdapter.STATE_ON:
                        bt_on_off.setText(getResources().getString(
                                R.string.on_off_status)
                                + "ON");
                        if (D)
                            Log.d(TAG, "STATE ON");
                        enableDissableViews(true);
                        isBTOnOrOff=true;
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        bt_on_off.setText(getResources().getString(
                                R.string.on_off_status)
                                + "Turning on...");
                        if (D)
                            Log.d(TAG, "STATE Turning on...");
                        break;
                    }
                }
            }
        };

        private void preBTConfigCheck() {

            // Register for broadcasts on BluetoothAdapter state change
            IntentFilter filter = new IntentFilter(
                    BluetoothAdapter.ACTION_STATE_CHANGED);
            this.registerReceiver(mReceiver, filter);

            // Get local Bluetooth adapter
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

              // If the adapter is null, then Bluetooth is not supported
            if (mBluetoothAdapter == null) {
                // Device does not support Bluetooth
                Toast.makeText(MainActivity.this,
                        "BlueTooth Not supported on your device!", 0).show();
                bt_on_off.setText(getResources().getString(R.string.on_off_status)
                        + "NOT SUPPORTED");
                enableDissableViews(false);
            } else {
                // status of BT
                isBTOnOrOff = mBluetoothAdapter.isEnabled();
                if (D)
                    Log.d(TAG, "BT status @ preBTConfigCheck() ->" + isBTOnOrOff);
                if (isBTOnOrOff) {
                    // Bluetooth is enable,
                    bt_on_off.setText(getResources().getString(
                            R.string.on_off_status)
                            + "ON");
                    enableDissableViews(isBTOnOrOff);
                } else {
                    bt_on_off.setText(getResources().getString(
                            R.string.on_off_status)
                            + "OFF");
                    // User did not enable Bluetooth or an error occurred
                    if (D)
                        Log.d(TAG, "BT not enabled");
                    enableDissableViews(isBTOnOrOff);
                }
            }
        }


         @Override
            public void onStart() {
                super.onStart();
                if(D) Log.e(TAG, "++ ON START ++");

                // If BT is not on, request that it be enabled.
                // setupChat() will then be called during onActivityResult
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                // Otherwise, setup the chat session
                } else {
                    if (mChatService == null) setupCommand();
                }
            }
         @Override
            public synchronized void onResume() {
                super.onResume();
                if(D) Log.e(TAG, "+ ON RESUME +");

                // Performing this check in onResume() covers the case in which BT was
                // not enabled during onStart(), so we were paused to enable it...
                // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
                if (mChatService != null) {
                    // Only if the state is STATE_NONE, do we know that we haven't started already
                    if (mChatService.getState() == BluetoothService.STATE_NONE) {
                      // Start the Bluetooth chat services
                      mChatService.start();
                    }
                }
            }


         @Override
            public synchronized void onPause() {
                super.onPause();
                if(D) Log.e(TAG, "- ON PAUSE -");
            }

            @Override
            public void onStop() {
                super.onStop();
                if(D) Log.e(TAG, "-- ON STOP --");
            }

            @Override
            public void onDestroy() {
                super.onDestroy();
                // Stop the Bluetooth chat services
                if (mChatService != null) mChatService.stop();
                this.unregisterReceiver(mReceiver);
                if(D) Log.e(TAG, "--- ON DESTROY ---");
            }

         private void setupCommand() {
                Log.d(TAG, "setupChat()");

                // Initialize the BluetoothService to perform bluetooth connections
                mChatService = new BluetoothService(this, mHandler);

                // Initialize the buffer for outgoing messages
                mOutStringBuffer = new StringBuffer("");
            }
        private void resultMacId(String address) {


              // Performing this check in onResume() covers the case in which BT was
            // not enabled during onStart(), so we were paused to enable it...
            // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
            if (mChatService != null) {
                // Only if the state is STATE_NONE, do we know that we haven't started already
                if (mChatService.getState() == BluetoothService.STATE_NONE) {
                  // Start the Bluetooth chat services
                  mChatService.start();
                }
            }
            // Get the BLuetoothDevice object
            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

            // Attempt to connect to the device
            mChatService.connect(device, false);
        }
          @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                MenuInflater inflater = getMenuInflater();
                inflater.inflate(R.menu.main, menu);
                return true;
            }
         @Override
            public boolean onOptionsItemSelected(MenuItem item) 
            {
                switch (item.getItemId()) 
                {
                case R.id.action_settings:
                    // Launch the DeviceListActivity to see devices and do scan

                    return true;
                }
                return false;
            }
        // The Handler that gets information back from the BluetoothChatService
        private final Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);



                    switch (msg.arg1) {
                    case BluetoothService.STATE_CONNECTED:
                        statuses.setText("connected to :"+mConnectedDeviceName);
                       // mTitle.setText(R.string.title_connected_to);
                        //mTitle.append(mConnectedDeviceName);
                        //mConversationArrayAdapter.clear();

                        break;
                    case BluetoothService.STATE_CONNECTING:
                        statuses.setText("connecting ... ");

                       // mTitle.setText(R.string.title_connecting);

                        break;
                    case BluetoothService.STATE_LISTEN:
                    case BluetoothService.STATE_NONE:
                        statuses.setText("Not Connected");
                       // mTitle.setText(R.string.title_not_connected);
                        break;
                    }
                    break;
                case MESSAGE_WRITE:
                    byte[] writeBuf = (byte[]) msg.obj;
                    // construct a string from the buffer
                    String writeMessage = new String(writeBuf);
                    Log.d(TAG, "MESSAGE_WRITE++++++++"+writeMessage);
                    //mConversationArrayAdapter.add("Me:  " + writeMessage);
                    break;
                case MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    // construct a string from the valid bytes in the buffer
                    String readMessage = new String(readBuf, 0, msg.arg1);
                    Log.d(TAG, "MESSAGE_READ++++++++"+readMessage);

                   // mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                    break;
                case MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);

                    statuses.setText("Connected to "+ mConnectedDeviceName);

                    Toast.makeText(getApplicationContext(), "Connected to "
                                   + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                    connectIt.setText("Connected to "+ mConnectedDeviceName);
                    connectIt.setEnabled(false);
                    break;
                case MESSAGE_TOAST:
                    statuses.setText(msg.getData().getString(TOAST));

                    Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                                   Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        };


        /**
         * Sends a message.
         * @param message  A string of text to send.
         */
        private void sendMessage(byte[] message) {
            // Check that we're actually connected before trying anything
             if (mChatService.getState() != BluetoothService.STATE_CONNECTED) {
                 Toast.makeText(this, "not_connected", Toast.LENGTH_SHORT).show();
                return;
            } 

            // Check that there's actually something to send
            if (message.length > 0) {
                // Get the message bytes and tell the BluetoothChatService to write

                mChatService.write(message);

                // Reset out string buffer to zero and clear the edit text field
                //mOutStringBuffer.setLength(0);
                 //mOutEditText.setText(mOutStringBuffer);
            }
        }
        private void btOnOffClick() {

            if (D)
                Log.d(TAG, "BT status @ btOnOffClick() ->" + isBTOnOrOff);
            if (isBTOnOrOff) {
                // make BT off & set isBTOnOrOff to false
                btOFF();
                isBTOnOrOff = false;

            } else if (!isBTOnOrOff) {
                // make BT on & set isBTOnOrOff to true

                btON(REQUEST_ENABLE_BT);
                isBTOnOrOff = true;
            }

        }

        private void btOFF() {
            enableDissableViews(false);
            if (D)
                Log.d(TAG, "BT status @ btOFF() -> OFF");

            mBluetoothAdapter.disable();
            bt_on_off.setText(getResources().getString(R.string.on_off_status)
                    + "OFF");
        }

        private void btON(int requestType) {
            if (D)
                Log.d(TAG, "BT status @ btON() -> Turning on dialog");

            Intent enableBtIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, requestType);

        }
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (D)
                Log.d(TAG, "onActivityResult " + resultCode);
            switch (requestCode) {
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled,
                    isBTOnOrOff=true;
                    enableDissableViews(true);
                    bt_on_off.setText(getResources().getString(
                            R.string.on_off_status)
                            + "ON");
                    if (D)
                        Log.d(TAG, "onActivityResult - status ON ");
                } else {
                    isBTOnOrOff=false;
                    enableDissableViews(false);
                    bt_on_off.setText(getResources().getString(
                            R.string.on_off_status)
                            + "OFF");
                    if (D)
                        Log.d(TAG, "onActivityResult - BT not enabled");
                    // User did not enable Bluetooth or an error occurred
                }
            }
        }


        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.bt_on_off:
                if (D)
                    Log.d(TAG, "...........ON OFF button clicked ........ ");
                // check for BT adaptor available then check its on or off
                try {
                    if (D)
                        Log.d(TAG, "Before sleep");
                    // Thread.sleep(SLEEP_THREAD_FOR_ACTION);
                    if (D)
                        Log.d(TAG, "after sleep");
                    btOnOffClick();
                    if (D)
                        Log.d(TAG, "after btn click completed");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                break;
            case R.id.connect:
                resultMacId("00:08:F4:00:12:A4");
                break;
            case R.id.click:
                sendMessage("commands in bytes".getBytes());
                break;
            default:
                break;
            }

        }


        private void disconnectIt() {
             if (mChatService != null) mChatService.stop();
             connectIt.setEnabled(true);
        }


        void enableDissableViews(boolean state)
        {   
            if (!state) {
                connectIt.setText("Not Connected");
            }
              connectIt.setEnabled(state);
        }

    }

activity_main.xml

<LinearLayout
    android:id="@+id/top"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="#bababa"
    android:gravity="center" >

    <Button
        android:id="@+id/bt_on_off"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_weight="1"
        android:text="@string/on_off_status" />

    <TextView
        android:id="@+id/statuses"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:text="@string/all_status"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#FF0000" />

    <Button
        android:id="@+id/connect"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_weight="1"
        android:text="@string/socket_connected_status" />
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/top"
    android:layout_weight="1" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" >
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" >
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" >
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/TextView01"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="GPS"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:visibility="gone" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/click"
            android:layout_width="317dp"
            android:layout_height="match_parent"
            android:text="Send" />
    </LinearLayout>
</LinearLayout>
like image 149
ravz Avatar answered Nov 14 '22 23:11

ravz