12 Replies Latest reply on Oct 6, 2016 12:14 PM by Intel Corporation

    Bluetooth Problem

    Iosif

      Hi,
      I was trying to connect from an android app to Edison via bluetooth, just like Arduino and send some text. But when i am trying to connect edison disconnects me right away (android says connection lost).

       

      bluetoothctl output:

       

      1. [CHG] Device C0:EE:FB:43:9D:73 Connected: yes 
      2. [CHG] Device C0:EE:FB:43:9D:73 Connected: no

       

       

      Android BT Service:

       

      package com.itbstudios.indoorscale.bluetooth;
      
      
      import android.app.Service;
      import android.bluetooth.BluetoothAdapter;
      import android.bluetooth.BluetoothDevice;
      import android.bluetooth.BluetoothSocket;
      import android.content.Intent;
      import android.os.Binder;
      import android.os.Bundle;
      import android.os.Handler;
      import android.os.IBinder;
      import android.os.Message;
      import android.util.Log;
      import android.widget.Toast;
      
      
      import com.itbstudios.indoorscale.GlobalActivity;
      
      
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.OutputStream;
      import java.util.ArrayList;
      import java.util.UUID;
      
      
      /**
       * Created by iosif on 10/14/2015.
       */
      public class BluetoothService extends Service {
      
      
          public static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
          public static int mState = GlobalActivity.STATE_NONE;
          public static String deviceName;
          public static BluetoothDevice device = null;
          private static ConnectedThread mConnectedThread;
          private static Handler mHandler = null;
          private static Object obj = new Object();
          private final IBinder mBinder = new LocalBinder();
          private BluetoothAdapter mBluetoothAdapter;
          private ConnectThread mConnectThread;
          private Handler handler = new Handler() {
              @Override
              public void handleMessage(Message msg) {//
                  if (!Thread.currentThread().isInterrupted()) {
                      switch (msg.what) {
                          case 3:
      
      
                              break;
      
      
                          case 4:
      
      
                              break;
                          case 5:
                              break;
      
      
                          case -1:
                              break;
                      }
                  }
                  super.handleMessage(msg);
              }
      
      
          };
      
      
          public static void write(byte[] out) {
              // Create temporary object
              ConnectedThread r;
              // Synchronize a copy of the ConnectedThread
              synchronized (obj) {
                  if (mState != GlobalActivity.STATE_CONNECTED)
                      return;
                  r = mConnectedThread;
              }
              // Perform the write unsynchronized
              r.write(out);
      
      
          }
      
      
          @Override
          public void onCreate() {
              Log.d("BluetoothService", "Service started");
              super.onCreate();
          }
      
      
          @Override
          public IBinder onBind(Intent intent) {
              mHandler = ((BluetoothApplication) getApplication()).getHandler();
              return mBinder;
          }
      
      
          @Override
          public int onStartCommand(Intent intent, int flags, int startId) {
              Log.d("BluetoothService", "Onstart Command");
              mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
              if (mBluetoothAdapter != null) {
                  device = intent.getParcelableExtra(GlobalActivity.BT_DEVICE);
                  deviceName = device.getName();
                  String macAddress = device.getAddress();
                  if (macAddress != null && macAddress.length() > 0) {
                      connectToDevice(macAddress);
                  } else {
                      stopSelf();
                      return 0;
                  }
              }
              String stopservice = intent.getStringExtra("stopservice");
              if (stopservice != null && stopservice.length() > 0) {
                  stop();
              }
              return START_STICKY;
          }
      
      
          private synchronized void connectToDevice(String macAddress) {
              BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAddress);
              if (mState == GlobalActivity.STATE_CONNECTING) {
                  if (mConnectThread != null) {
                      mConnectThread.cancel();
                      mConnectThread = null;
                  }
              }
      
      
              // Cancel any thread currently running a connection
              if (mConnectedThread != null) {
                  mConnectedThread.cancel();
                  mConnectedThread = null;
              }
              mConnectThread = new ConnectThread(device);
              mConnectThread.start();
              setState(GlobalActivity.STATE_CONNECTING);
      
      
              GlobalActivity.BluetoothConnectionStatus = GlobalActivity.STATE_CONNECTING;
      
      
          }
      
      
          private void setState(int state) {
              BluetoothService.mState = state;
              if (mHandler != null) {
                  mHandler.obtainMessage(GlobalActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
              }
          }
      
      
          public synchronized void stop() {
              setState(GlobalActivity.STATE_NONE);
              GlobalActivity.BluetoothConnected = false;
              if (mConnectThread != null) {
                  mConnectThread.cancel();
                  mConnectThread = null;
              }
      
      
              if (mConnectedThread != null) {
                  mConnectedThread.cancel();
                  mConnectedThread = null;
              }
              if (mBluetoothAdapter != null) {
                  mBluetoothAdapter.cancelDiscovery();
              }
              stopSelf();
      
      
              GlobalActivity.BluetoothConnectionStatus = GlobalActivity.STATE_NONE;
      
      
          }
      
      
          @Override
          public boolean stopService(Intent name) {
              setState(GlobalActivity.STATE_NONE);
              if (mConnectThread != null) {
                  mConnectThread.cancel();
                  mConnectThread = null;
              }
      
      
              if (mConnectedThread != null) {
                  mConnectedThread.cancel();
                  mConnectedThread = null;
              }
              mBluetoothAdapter.cancelDiscovery();
      
      
      
      
              GlobalActivity.BluetoothConnectionStatus = GlobalActivity.STATE_NONE;
      
      
              return super.stopService(name);
          }
      
      
          private void connectionFailed() {
              GlobalActivity.BluetoothConnectionStatus = GlobalActivity.STATE_NONE;
      
      
              BluetoothService.this.stop();
              Message msg = mHandler.obtainMessage(GlobalActivity.MESSAGE_TOAST);
              Bundle bundle = new Bundle();
              bundle.putString(GlobalActivity.TOAST, "Connection Failed");
              GlobalActivity.BluetoothConnected = false;
              msg.setData(bundle);
              mHandler.sendMessage(msg);
      
      
      
      
          }
      
      
          private void connectionLost() {
              GlobalActivity.BluetoothConnected = false;
              GlobalActivity.BluetoothConnectionStatus = GlobalActivity.STATE_NONE;
              setState(GlobalActivity.STATE_NONE);
      
      
              BluetoothService.this.stop();
              Message msg = null;
              msg = mHandler.obtainMessage(GlobalActivity.MESSAGE_TOAST);
              Bundle bundle = new Bundle();
              bundle.putString(GlobalActivity.TOAST, "Connection Lost");
              msg.setData(bundle);
              mHandler.sendMessage(msg);
      
      
      
      
          }
      
      
          private synchronized void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
              // Cancel the thread that completed the connection
              if (mConnectThread != null) {
                  mConnectThread.cancel();
                  mConnectThread = null;
              }
      
      
              // Cancel any thread currently running a connection
              if (mConnectedThread != null) {
                  mConnectedThread.cancel();
                  mConnectedThread = null;
              }
      
      
              mConnectedThread = new ConnectedThread(mmSocket);
              mConnectedThread.start();
      
      
              // Message msg =
              // mHandler.obtainMessage(_AbstractActivity.MESSAGE_DEVICE_NAME);
              // Bundle bundle = new Bundle();
              // bundle.putString(_AbstractActivity.DEVICE_NAME, "p25");
              // msg.setData(bundle);
              // mHandler.sendMessage(msg);
              setState(GlobalActivity.STATE_CONNECTED);
      
      
              GlobalActivity.BluetoothConnectionStatus = GlobalActivity.STATE_CONNECTED;
      
      
          }
      
      
          public void trace(String msg) {
              Log.d("_AbstractActivity", msg);
              toast(msg);
          }
      
      
          public void toast(String msg) {
              Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
          }
      
      
          @Override
          public void onDestroy() {
              stop();
              Log.d("Service", "Destroyed");
              super.onDestroy();
          }
      
      
          private void sendMsg(int flag) {
              Message msg = new Message();
              msg.what = flag;
              handler.sendMessage(msg);
          }
      
      
          public class LocalBinder extends Binder {
              public BluetoothService getService() {
                  return BluetoothService.this;
              }
          }
      
      
          private class ConnectThread extends Thread {
              private final BluetoothSocket mmSocket;
              private final BluetoothDevice mmDevice;
      
      
              public ConnectThread(BluetoothDevice device) {
                  this.mmDevice = device;
                  BluetoothSocket tmp = null;
                  try {
                      tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(SPP_UUID));
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
                  mmSocket = tmp;
              }
      
      
              @Override
              public void run() {
                  setName("ConnectThread");
                  mBluetoothAdapter.cancelDiscovery();
                  try {
                      mmSocket.connect();
                  } catch (IOException e) {
                      try {
                          mmSocket.close();
                      } catch (IOException e1) {
                          e1.printStackTrace();
                      }
                      connectionFailed();
                      return;
      
      
                  }
                  synchronized (BluetoothService.this) {
                      mConnectThread = null;
                  }
                  connected(mmSocket, mmDevice);
              }
      
      
              public void cancel() {
                  try {
                      mmSocket.close();
                  } catch (IOException e) {
                      Log.e("BluetoothService", "close() of connect socket failed", e);
                  }
              }
          }
      
      
          private class ConnectedThread extends Thread {
              private final BluetoothSocket mmSocket;
              private final InputStream mmInStream;
              private final OutputStream mmOutStream;
              private byte[] btBuff;
      
      
      
      
              public ConnectedThread(BluetoothSocket socket) {
                  mmSocket = socket;
                  InputStream tmpIn = null;
                  OutputStream tmpOut = null;
                  GlobalActivity.BluetoothConnected = true;
                  try {
                      tmpIn = socket.getInputStream();
                      tmpOut = socket.getOutputStream();
                  } catch (IOException e) {
                      Log.e("Printer Service", "temp sockets not created", e);
                  }
                  mmInStream = tmpIn;
                  mmOutStream = tmpOut;
              }
      
      
              @Override
              public void run() {
                  byte[] buffer = new byte[1024];
                  String ReceivedMessage = "";
                  while (true) {
      
      
                      try {
                          int bytes;
                          // Read from the InputStream
                          bytes = mmInStream.read(buffer);
                          String TempString = new String(buffer, 0, bytes);
                          ReceivedMessage = ReceivedMessage + TempString;
      
      
      
      
                          // Send the obtained bytes to the UI Activity
                          if (ReceivedMessage.endsWith("\n")) {
                              if(ReceivedMessage.contains("\r"))
                                  ReceivedMessage = ReceivedMessage.replace("\r", ""); //// TODO: 11/12/2015
                              ReceivedMessage = ReceivedMessage.replace("\n", "");
                              String VectorString[] = ReceivedMessage.split(" ");
                              ArrayList<String> Tokens = new ArrayList<String>();
                              for(int i = 0; i < VectorString.length; i++)
                                  Tokens.add(VectorString[i]);
      
      
                              Message msg = mHandler.obtainMessage(GlobalActivity.MESSAGE_READ);
                              Bundle bundle = new Bundle();
                              bundle.putStringArrayList(GlobalActivity.TOAST, Tokens);
                              msg.setData(bundle);
                              ReceivedMessage = "";
                              mHandler.sendMessage(msg);
                          }
                      } catch (IOException e) {
                          e.printStackTrace();
                          connectionLost();
                          BluetoothService.this.stop();
                          break;
                      }
      
      
                  }
      
      
      
      
              }
      
      
              public void write(byte[] buffer) {
                  try {
                      mmOutStream.write(buffer);
                      mmOutStream.flush();
      
      
                  } catch (IOException e) {
                      Log.e("BluetoothService", "Exception during write", e);
                  }
              }
      
      
              public void cancel() {
                  try {
                      mmSocket.close();
                      GlobalActivity.BluetoothConnected = false;
      
      
                  } catch (IOException e) {
                      Log.e("BluetoothService", "close() of connect socket failed", e);
                  }
              }
      
      
          }
      
      
      }
      

       

       

       

      I use YOCTO latest version.... I really don't know hot to fix the problem and i have to deliver a project within 1 week - this is the last part of it sending text via bluetooth to android.

       

       

      Thank You!