BLE Lilypad simblee Android应用

时间:2016-04-06 15:18:34

标签: android bluetooth bluetooth-lowenergy

我对Android应用程序开发非常陌生,我试图编写蓝牙应用程序与BLE外围设备(Lilypad Simblee)进行通信。我希望应用程序在启动时与已配对的外围设备建立连接,一旦完成,我希望应用程序使用我在外围设备上配置的自定义128位uuid来查找特定的特征,并显示来自文本视图中的特征。

我查看了android的BluetoothLeGratt示例代码,这是我到目前为止所做的:

public class MainActivity extends AppCompatActivity {

private BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
private boolean mConnected = false;
//Textview to identify state as connected or disconnected
private TextView mConnectionState;
//Textview to display data from characteristic
private TextView mDataField;
String  mDeviceAddress;
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
public final static String EXTRA_DATA =
        "com.example.bluetooth.le.EXTRA_DATA";
public final static String ACTION_DATA_AVAILABLE =
        "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
private BluetoothGattCharacteristic mNotifyCharacteristic;
private BluetoothLeService mBluetoothLeService;
private BluetoothGatt mBluetoothGatt;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
        new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        String intentAction;
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            intentAction = "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
            //mConnectionState = STATE_CONNECTED;
             mConnectionState.setText("Connected");;
            broadcastUpdate(intentAction);

            // Attempts to discover services after successful connection.
            mBluetoothGatt.discoverServices();


        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            intentAction = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
            //mConnectionState = STATE_DISCONNECTED;
            mConnectionState.setText("Disconnected");

        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            mConnectionState.setText("Connected");
        } else {
            mConnectionState.setText("Disonnected");
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
             broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
    }
};

private final ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {
        mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
        if (!mBluetoothLeService.initialize()) {
            finish();
        }
        // Automatically connects to the device upon successful start-up initialization.
        mBluetoothLeService.connect("E8:FF:34:49:A9:5B");
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mBluetoothLeService = null;
    }
};

private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
            mConnected = true;
            updateConnectionState(R.string.connected);
            //invalidateOptionsMenu();
        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
            mConnected = false;
            updateConnectionState(R.string.disconnected);
            //invalidateOptionsMenu();
            //clearUI();
        } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
            // Show all the supported services and characteristics on the user interface.
            //displayGattServices(mBluetoothLeService.getSupportedGattServices());
        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mDataField = (TextView) findViewById(R.id.data);
    if(!BA.isEnabled()){
        Toast.makeText(getApplicationContext(), "Enable Bluetooth in phone settings.",
                Toast.LENGTH_LONG).show();
        //Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        //startActivityForResult(enableBtIntent, 0);
        }

    mConnectionState = (TextView) findViewById(R.id.connection_state);
    IntentFilter filter1 = new IntentFilter(BluetoothLeService.ACTION_GATT_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothLeService.ACTION_GATT_DISCONNECTED);
    registerReceiver(mGattUpdateReceiver, filter1);
    registerReceiver( mGattUpdateReceiver, filter2);
    final BluetoothDevice device = BA.getRemoteDevice("E8:FF:34:49:A9:5B");


    mBluetoothGatt = device.connectGatt(this, true, mGattCallback);
    final Intent intent = getIntent();
    Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
    bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);



    //mBluetoothLeService.readCharacteristic(characteristic);

}

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    if (mBluetoothLeService != null) {
        final boolean result = mBluetoothLeService.connect(mDeviceAddress);
    }
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mGattUpdateReceiver);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unbindService(mServiceConnection);
    mBluetoothLeService = null;
}


private void updateConnectionState(final int resourceId) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mConnectionState.setText(resourceId);
        }
    });
}


private void broadcastUpdate(final String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}

// For lilypad profile, writes data
private void broadcastUpdate(final String action,
                             final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);
    if ("c97433f0-be8f-4dc8-b6f0-5343e6100eb4".equals(characteristic.getUuid())) {

        long data = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 0);
        intent.putExtra(EXTRA_DATA, data);
    }

    sendBroadcast(intent);
}

private static IntentFilter makeGattUpdateIntentFilter() {
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
    intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
    intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
    intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
    return intentFilter;
}

private void displayData(String data) {
    if (data != null) {
        mDataField.setText(data);
    }
}

}

0 个答案:

没有答案