Android Open Source - blue-tool-box Bluetooth Manager






From Project

Back to project page blue-tool-box.

License

The source code is released under:

Apache License

If you think the Android project blue-tool-box listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.eperu.bluemessenger;
/*from   w w  w . j av  a 2s.  c  om*/
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;

import android.app.Activity;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

public class BluetoothManager extends Service {

  private static final int REQUEST_ENABLE_BT = 1;

  static final int MSG_REGISTER = 1;

  static final int MSG_UNREGISTER = 2;

  // Unique UUID for this application, you may use different
  private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");

  public static final String TAG = "BluetoothManager";

  private static BluetoothManager instance;

  private final BluetoothAdapter mBluetoothAdapter;

  private final List<Messenger> mClients = new LinkedList<Messenger>();

  private final Messenger mMessenger;

  private BluetoothGatt bluetoothGatt;

  private static final byte[] ENABLE_SENSOR = { 0x01 };

  private static final Queue<Object> sWriteQueue = new ConcurrentLinkedQueue<Object>();

  private static boolean sIsWriting = false;

  private final Map<String, BluetoothDevice> mapBleFound = new HashMap<String, BluetoothDevice>();

  public static BluetoothManager getInstance(Activity activity) {
    if (instance == null) {
      instance = new BluetoothManager(activity);
    }
    return instance;
  }

  public BluetoothManager(final Activity activity) {
    this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    this.mMessenger = new Messenger(new IncomingHandler(this));
    if (this.mBluetoothAdapter == null) {
      // Device does not support Bluetooth
    }
    if (!this.mBluetoothAdapter.isEnabled()) {
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
    /*
     * Mthode appele lorsque le bluetooth scan un device en particulier.
     */
    this.mBluetoothAdapter.startLeScan(new LeScanCallback() {
      @Override
      public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        // Add the name and address to an array adapter to show in a ListView
        if (BluetoothManager.this.mapBleFound.put(device.getAddress(), device) == null) {
          Log.v("System.out", "startLeScan sur le device " + device.getName() + "-" + device.getAddress());
          // premire fois qu'on l'insre dans la map
          BluetoothManager.this.refreshListDevicesFound((MainActivity) activity, device);
        }
      }
    });

    this.mBluetoothAdapter.stopLeScan(new LeScanCallback() {
      @Override
      public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        Log.v("System.out", "StopLeScan sur le device " + device.getName());
      }
    });
  }

  public Set<BluetoothDevice> getDevicesAlreadyPaired() {

    return this.mBluetoothAdapter.getBondedDevices();
  }

  public BroadcastReceiver getReceiver(final MainActivity activity) {
    return new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.v("System.out", "On receive " + action);
        // 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);
          // Add the name and address to an array adapter to show in a ListView
          if (BluetoothManager.this.mapBleFound.put(device.getAddress(), device) == null) {
            // premire fois qu'on l'insre dans la map
            BluetoothManager.this.refreshListDevicesFound(activity, device);
            if (device.getName().contains("Emmanuel")) {
              Log.v("System.out", "On receive Emmanuel" + action);
              try {
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
                socket.connect();
                Log.i(TAG, "socket connected " + socket.isConnected());
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }

        }
      }
    };
  }

  protected void refreshListDevicesFound(MainActivity activity, BluetoothDevice device) {
    if (device != null) {
      activity.refreshDevicesFound(device);
      Log.v("System.out", "device " + device.getClass().getName() + '@' + Integer.toHexString(device.hashCode()));
      Log.v("System.out", "Device type " + device.getType());
    }
  }

  public void startDiscovery() {
    this.mBluetoothAdapter.startDiscovery();
  }

  @Override
  public IBinder onBind(Intent intent) {
    return this.mMessenger.getBinder();
  }

  public void connect(String macAdress) {
    final BluetoothDevice bd = this.mapBleFound.get(macAdress);
    this.bluetoothGatt = bd.connectGatt(this, true, new BluetoothGattCallback() {

      @Override
      public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);
        Log.v(TAG, "Connection State Changed: " + (newState == BluetoothProfile.STATE_CONNECTED ? "Connected" : "Disconnected"));
        if (newState == BluetoothProfile.STATE_CONNECTED) {
          Log.i(TAG, "connected to " + bd.getName());
          Log.i(TAG, "Discover services : " + BluetoothManager.this.bluetoothGatt.discoverServices());
          Log.i(TAG, "bd uuids" + bd.getUuids());
        } else {
          Log.i(TAG, "newState " + newState);
          // setState(State.IDLE);
        }
      }

      /*
       * (non-Javadoc)
       * 
       * @see android.bluetooth.BluetoothGattCallback#onServicesDiscovered(android.bluetooth.BluetoothGatt, int)
       */
      @Override
      public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
          Log.i(TAG, "onServicesDiscovered: " + status);
          List<BluetoothGattService> services = gatt.getServices();
          System.out.println(services);
          BluetoothGattService authService = gatt.getService(UUID.fromString("00001800-0000-1000-8000-00805f9b34fb"));
          System.out.println(authService.getCharacteristics());
          BluetoothGattCharacteristic charaPassword = authService.getCharacteristic(UUID.fromString("00002a00-0000-1000-8000-00805f9b34fb"));
          charaPassword.setValue("");

          for (BluetoothGattService service : services) {
            Log.i(TAG, "Service : " + service.getUuid().toString());

            List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
            for (BluetoothGattCharacteristic characteristic : characteristics) {
              Log.i(TAG, "Characteristic " + characteristic.getUuid().toString());
              if (characteristic.getUuid().toString().equals("00002221-0000-1000-8000-00805f9b34fb")) {
                Log.i(TAG, "Led Guitool");
                byte[] toto = new byte[1];
                toto[0] = (byte) 0;
                byte[] value = characteristic.getValue();
                System.out.println(value);
              }
            }
          }
        }
      }

      @Override
      public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        Log.v(TAG, "onCharacteristicWrite: " + status);
        sIsWriting = false;
        BluetoothManager.this.nextWrite();
      }

      @Override
      public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        Log.v(TAG, "onDescriptorWrite: " + status);
        sIsWriting = false;
        BluetoothManager.this.nextWrite();
      }

      @Override
      public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        Log.v(TAG, "onCharacteristicChanged: " + characteristic.getUuid());
        if (characteristic != null) {
          Log.i(TAG, "characteristics change on service : " + characteristic.getService().getUuid());
          if (characteristic.getUuid().equals(UUID.fromString("ed3a6985-8872-4bb7-b784-c59ef3589844"))) {
            Log.i(TAG, "proximity value : " + characteristic.getStringValue(8));
          }
          if (characteristic.getUuid().equals(UUID.fromString("180f"))) {
            Log.i(TAG, "Battery " + characteristic.getStringValue(8));
          }

        }
      }

    });
  }

  private synchronized void write(Object o) {
    if (sWriteQueue.isEmpty() && !sIsWriting) {
      this.doWrite(o);
    } else {
      sWriteQueue.add(o);
    }
  }

  private synchronized void nextWrite() {
    if (!sWriteQueue.isEmpty() && !sIsWriting) {
      this.doWrite(sWriteQueue.poll());
    }
  }

  private synchronized void doWrite(Object o) {
    if (o instanceof BluetoothGattCharacteristic) {
      sIsWriting = true;
      this.bluetoothGatt.writeCharacteristic((BluetoothGattCharacteristic) o);
    } else if (o instanceof BluetoothGattDescriptor) {
      sIsWriting = true;
      this.bluetoothGatt.writeDescriptor((BluetoothGattDescriptor) o);
    } else {
      this.nextWrite();
    }
  }

  private static Integer shortUnsignedAtOffset(BluetoothGattCharacteristic characteristic, int offset) {
    Integer lowerByte = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, offset);
    Integer upperByte = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, offset + 1);

    return (upperByte << 8) + lowerByte;
  }

  private static class IncomingHandler extends Handler {
    private final WeakReference<BluetoothManager> mService;

    public IncomingHandler(BluetoothManager service) {
      this.mService = new WeakReference<BluetoothManager>(service);
    }

    @Override
    public void handleMessage(Message msg) {
      BluetoothManager service = this.mService.get();
      if (service != null) {
        switch (msg.what) {
        case MSG_REGISTER:
          service.mClients.add(msg.replyTo);
          Log.d(TAG, "Registered");
          break;
        case MSG_UNREGISTER:
          service.mClients.remove(msg.replyTo);
          Log.d(TAG, "Unegistered");
          break;
        default:
          super.handleMessage(msg);
        }
      }
    }
  }

  public void stopScan() {
    this.mBluetoothAdapter.stopLeScan(new LeScanCallback() {

      @Override
      public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        Log.i(TAG, "Stop le scan");
      }
    });
  }
}




Java Source Code List

com.eperu.bluemessenger.BluetoothDeviceDetailsActivity.java
com.eperu.bluemessenger.BluetoothLEDeviceDetailsActivity.java
com.eperu.bluemessenger.BluetoothManager.java
com.eperu.bluemessenger.MainActivity.java