问题描述
最初写入蓝牙设备后,它将在BLE设备上正确执行命令。但是,当我尝试向BLE设备发送另一个命令时,它会调用onCharacteristicWrite,但是与我连接的BLE设备却没有任何作用。但是,如果我断开连接并重新连接,它将让我先发送一次写操作,然后再不响应。我很困惑,我能够在Swift / IOS中完成所有这些工作而没有很多问题。任何帮助表示赞赏。
公共类IntellidropperActivity扩展了AppCompatActivity,实现了BluetoothAdapter.LeScanCallback {
//bluetooth values
private Integer REQUEST_ENABLE_BT = 1;
//bluetooth manager
BluetoothManager bluetoothManager = null;
//bluetooth adapter
BluetoothAdapter bluetoothAdapter = null;
//bluetooth gatt
BluetoothGatt bluetoothGatt = null;
//bluetooth device
BluetoothDevice bluetoothDevice = null;
// Stops scanning after 10 seconds.
private static final String TAG = "BluetoothGattActivity";
//outlets
private Button trickleButton;
private Button cancelButton;
private Button calibrateButton;
private Button zeroButton;
//services
private static final UUID CUSTOM_SERVICE = UUID.fromString("49535343-FE7D-4AE5-8FA9-9FAFD205E455");
//chars
private static final UUID WRITE_WITHOUT_RESPONSE = UUID.fromString("49535343-8841-43F4-A8D4-ECBE34729BB3");
private static final UUID writeReadCharacteristicUUID = UUID.fromString("49535343-6DAA-4D02-ABF6-19569ACA69FE");
private static final UUID writeNotifySecondCharacteristicUUID = UUID.fromString("49535343-026E-3A9B-954C-97DAEF17E26E");
private static final UUID writeReadNotifyWithoutResponseSecondCharacteristicUUID = UUID.fromString("49535343-1E4D-4BD9-BA61-23C647249616");
@Override
public void onStart() {
super.onStart();
//fires when this scene is started
}
@Override
protected void onStop() {
super.onStop();
//disconnect from any active tag connection
if (bluetoothGatt != null) {
bluetoothGatt.disconnect();
bluetoothGatt = null;
}
}
@Override
protected void onResume() {
super.onResume();
//check to see if bluetooth is enabled
/*
* We need to enforce that Bluetooth is first enabled,and take the
* user to settings to enable it if they have not done so.
*/
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
//Bluetooth is disabled
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBtIntent);
finish();
return;
}
/*
* Check for Bluetooth LE Support. In production,our manifest entry will keep this
* from installing on these devices,but this will allow test devices or other
* sideloads to report whether or not the feature exists.
*/
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUetoOTH_LE)) {
Toast.makeText(this,"No LE Support.",Toast.LENGTH_SHORT).show();
finish();
return;
}
}
@Override
public void onPause() {
super.onPause();
overridePendingTransition(0,0);
//Cancel any scans in progress
//mHandler.removeCallbacks(mStopRunnable);
//mHandler.removeCallbacks(mStartRunnable);
//stop any scans currently going
bluetoothAdapter.stopLeScan(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the content view to the scene
setContentView(R.layout.activity_intellidropper);
//set title and settings for the current activity
getSupportActionBar().setdisplayHomeAsUpEnabled(false);
getSupportActionBar().setTitle("Intellidropper");
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
trickleButton = findViewById(R.id.trickleButton);
cancelButton = findViewById(R.id.cancelButton);
calibrateButton = findViewById(R.id.calibrateButton);
zeroButton = findViewById(R.id.zeroButton);
//set the bluetooth manager
bluetoothManager = (BluetoothManager)getSystemService(BLUetoOTH_SERVICE);
//set the bluetooth adaptor
bluetoothAdapter = bluetoothManager.getAdapter();
// Use this check to determine whether BLE is supported on the device. Then
// you can selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUetoOTH_LE)) {
Toast.makeText(this,"Bluetooth LE not supported",Toast.LENGTH_SHORT).show();
finish();
}
//Now we cans start scanning
startScan();
//These arent working
//readUnits(bluetoothGatt);
//THESE WORK
//zero scale command
//zeroScale(bluetoothGatt);
//start trickle
//startTrickle(bluetoothGatt);
//start calibration
//startCalibration(bluetoothGatt);
//start load dispense
//startLoaddispense(bluetoothGatt);
//stop the load
//cancelLoad(bluetoothGatt);
//sitch device
//switchUnit(bluetoothGatt);
//readUnits(bluetoothGatt);
//ACTIONS
zeroButton.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
zeroScale(bluetoothGatt);
}
});
cancelButton.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelLoad(bluetoothGatt);
}
});
calibrateButton.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startCalibration(bluetoothGatt);
}
});
trickleButton.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startTrickle(bluetoothGatt);
}
});
// Ensures Bluetooth is available on the device and it is enabled. If not,// displays a dialog requesting user permission to enable Bluetooth.
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
}
navigation.setSelectedItemId(R.id.navigation_intellidropper);
navigation.setonNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_arsenal:
item.setChecked(true);
Intent a = new Intent(IntellidropperActivity.this,ArsenalActivity.class);
startActivity(a);
break;
case R.id.navigation_intellidropper:
item.setChecked(true);
break;
case R.id.navigation_components:
item.setChecked(true);
Intent b = new Intent(IntellidropperActivity.this,ComponentActivity.class);
startActivity(b);
break;
case R.id.navigation_loads:
item.setChecked(true);
Intent c = new Intent(IntellidropperActivity.this,LoadsActivity.class);
startActivity(c);
break;
case R.id.navigation_settings:
item.setChecked(true);
Intent d = new Intent(IntellidropperActivity.this,SettingsActivity.class);
startActivity(d);
break;
}
return false;
}
});
}
private Runnable mStopRunnable = new Runnable() {
@Override
public void run() {
stopScan();
}
};
private Runnable mStartRunnable = new Runnable() {
@Override
public void run() {
startScan();
}
};
private void startScan() {
bluetoothAdapter.startLeScan(this);
//mHandler.postDelayed(mStopRunnable,2500);
}
private void stopScan() {
bluetoothAdapter.stopLeScan(this);
}
@Override
public void onLeScan(BluetoothDevice device,int RSSi,byte[] scanRecord) {
//print the results of the device here
if (device.getName() != null){
Log.d(TAG,"Found Device namend: "+ device.getName());
//check to see if its the device we want
if (device.getName().equals("FA Dropper") || device.getName().equals("Dual-SPP")){
Log.d(TAG,"Starting to connect to:: "+ device.getName());
Log.d(TAG,"Device Type: "+ device.getType());
//stop scanning
stopScan();
//set the device
bluetoothDevice = device;
//create the bond
bluetoothDevice.createBond();
//this means we have the correct device
bluetoothGatt = bluetoothDevice.connectGatt(this,true,mGattCallback,BluetoothDevice.TRANSPORT_LE);
//connect Now
bluetoothGatt.connect();
}
}
}
//gatt callback
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt,int status,int newState) {
//once the device has connected
if(newState == STATE_CONNECTED && status == GATT_SUCCESS) {
Log.d(TAG,"Device connected");
//start discovering servives
gatt.discoverServices();
//if the device doesnt connect
} else if (newState == STATE_disCONNECTED) {
Log.i(TAG,"disconnected from GATT server.");
gatt.disconnect();
}
}
@Override
public void onServicesdiscovered(BluetoothGatt gatt,int status) {
Log.d(TAG,"Services discovered: "+status);
//once services have been found lets use them
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,"Character Read: "+status);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,int status) {
//check to make sure the write happened succesfully
if (GATT_SUCCESS == status){
Log.d(TAG,"Write Success");
Log.d(TAG,"Character Write: "+status);
Log.d(TAG,"Character Write UUId: "+characteristic.getUuid());
Log.d(TAG,"Character Write Value: "+characteristic.getValue());
byte[] bytes = characteristic.getValue();
Log.d("nveo","Byte data is: " + Hex.bytesToStringUppercase(bytes));
}else {
//if the write Failed
Log.d(TAG,"Write Failed");
//disconnect
gatt.disconnect();
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {
/*
* After notifications are enabled,all updates from the device on characteristic
* value changes will be posted here. Similar to read,we hand these up to the
* UI thread to update the display.
*/
Log.d(TAG,"Character changed: "+characteristic);
}
@Override
public void onReliableWriteCompleted(BluetoothGatt gatt,int status) {
Log.d(TAG,"Reliable write completed: ");
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt,BluetoothGattDescriptor descriptor,int status) {
//Once notifications are enabled,we move to the next sensor and start over with enable
Log.d(TAG,"Descriptor write: "+descriptor);
}
@Override
public void onReadRemoteRSSi(BluetoothGatt gatt,"Remote RSSI: "+RSSi);
}
private String connectionState(int status) {
switch (status) {
case BluetoothProfile.STATE_CONNECTED:
return "Connected";
case BluetoothProfile.STATE_disCONNECTED:
return "disconnected";
case BluetoothProfile.STATE_CONNECTING:
return "Connecting";
case BluetoothProfile.STATE_disCONNECTING:
return "disconnecting";
default:
return String.valueOf(status);
}
}
};
//function used to switch units
private void switchUnit(BluetoothGatt gatt) {
//char to be created
BluetoothGattCharacteristic characteristic;
Log.d(TAG,"Sending Switch Unit");
//set the char
characteristic = gatt.getService(CUSTOM_SERVICE).getCharacteristic(WRITE_WITHOUT_RESPONSE);
List<BluetoothGattCharacteristic> list = gatt.getService(CUSTOM_SERVICE).getcharacteristics();
//loop thru all characterstics
for (int i = 0; i < list.size(); i++) {
//get each characterstic for the service
System.out.println(list.get(i));
//set new char
characteristic = list.get(i);
//setup notifications
gatt.setCharacteristicNotification(characteristic,true);
//set the value
characteristic.setValue(new byte[]{0x16,0x38,0x14,0x00,0x1A,0x01,(byte)0xF0,(byte)0xE1,0x01});
//write it to the server
gatt.writeCharacteristic(characteristic);
gatt.readCharacteristic(characteristic);
}
}
//function used to zero the scale
private void zeroScale(BluetoothGatt gatt) {
//char to be created
BluetoothGattCharacteristic characteristic;
//zero command
byte[] zeroCommand = {0x16,0x1B,(byte) 0xFF,(byte) 0xFF};
//get the chara
characteristic = gatt.getService(CUSTOM_SERVICE).getCharacteristic(WRITE_WITHOUT_RESPONSE);
//set the value
characteristic.setValue(zeroCommand);
//send Now
gatt.writeCharacteristic(characteristic);
}
//function used to start calibration
private void startCalibration(BluetoothGatt gatt){
//char to be created
BluetoothGattCharacteristic characteristic;
//calibration command
byte[] startCalibrationCommand = {0x16,0x15,(byte) 0xFF};
//send the command to dispense
//get the chara
characteristic = gatt.getService(CUSTOM_SERVICE).getCharacteristic(WRITE_WITHOUT_RESPONSE);
//set the value
characteristic.setValue(startCalibrationCommand);
//send Now
gatt.writeCharacteristic(characteristic);
}
//function used to stop load dispense
private void stopLoaddispense(BluetoothGatt gatt){
//char to be created
BluetoothGattCharacteristic characteristic;
//calibration command
byte[] stopLoaddispenseCommand = {0x16,0x18,(byte) 0xFF};
//get the chara
characteristic = gatt.getService(CUSTOM_SERVICE).getCharacteristic(WRITE_WITHOUT_RESPONSE);
//set the value
characteristic.setValue(stopLoaddispenseCommand);
//send Now
gatt.writeCharacteristic(characteristic);
}
//function used to start the load dispense
private void startLoaddispense(BluetoothGatt gatt){
//char to be created
BluetoothGattCharacteristic characteristic;
//calibration command
byte[] startLoaddispenseCommand = {0x16,0x17,(byte) 0xFF};
//get the chara
characteristic = gatt.getService(CUSTOM_SERVICE).getCharacteristic(WRITE_WITHOUT_RESPONSE);
//set the value
characteristic.setValue(startLoaddispenseCommand);
//send Now
gatt.writeCharacteristic(characteristic);
}
//function used to cancel a load
private void cancelLoad(BluetoothGatt gatt){
//char to be created
BluetoothGattCharacteristic characteristic;
//calibration command
byte[] cancelCommand = {0x16,0x1C,(byte) 0xFF};
//get the chara
characteristic = gatt.getService(CUSTOM_SERVICE).getCharacteristic(WRITE_WITHOUT_RESPONSE);
//set the value
characteristic.setValue(cancelCommand);
//send Now
gatt.writeCharacteristic(characteristic);
}
//function used to start trickle
private void startTrickle(BluetoothGatt gatt){
//char to be created
BluetoothGattCharacteristic characteristic;
//calibration command
byte[] startTrickleCommand = {0x16,0x1D,(byte)0xFF};
//get the chara
characteristic = gatt.getService(CUSTOM_SERVICE).getCharacteristic(WRITE_WITHOUT_RESPONSE);
//set the value
characteristic.setValue(startTrickleCommand);
//send Now
gatt.writeCharacteristic(characteristic);
}
//function used to powder calc
private void powderCal(BluetoothGatt gatt){
//char to be created
BluetoothGattCharacteristic characteristic;
//calibration command
byte[] powderCalCommand = {0x16,0x19,(byte) 0xFF};
//get the chara
characteristic = gatt.getService(CUSTOM_SERVICE).getCharacteristic(WRITE_WITHOUT_RESPONSE);
//set the value
characteristic.setValue(powderCalCommand);
//send Now
gatt.writeCharacteristic(characteristic);
}
private void readUnits(BluetoothGatt gatt) {
BluetoothGattCharacteristic characteristic = gatt.getService(CUSTOM_SERVICE).getCharacteristic(WRITE_WITHOUT_RESPONSE);
//set value ff the read
gatt.readCharacteristic(characteristic);
}
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
//chara that will be returned
BluetoothGattCharacteristic characteristic;
Log.w(TAG,"Error obtaining humidity value" + msg.what);
}
};
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)