我正在尝试开发一个与BLE设备通信的android应用程序。我能够读取和写入BLE设备的特征。现在,我想通过我的应用程序对设备执行ble OTA更新。我不知道该怎么办?如果我有OTA更新文件,如何将其安装在ble设备上以及如何进行OTA升级?
答案 0 :(得分:0)
使用
从文件中读取数据protected byte[] readFile(File file) {
BufferedInputStream buf;
int size = (int) file.length();
byte[] mDataFile = new byte[size];
//mDataFile = new byte[size];
try {
buf = new BufferedInputStream(new FileInputStream(file));
buf.read(mDataFile, 0, size);
} catch (IOException e) {
e.printStackTrace();
}
return mDataFile;
}
然后,开始设备扫描。使用特定的macAddress连接设备后 调用方法connectToDevice
public static BluetoothGatt connectToDevice(Context context,
BluetoothDevice device,
BluetoothGattCallback mGattCallBack){
BluetoothGatt connectedGatt = null;
if (device != null) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
connectedGatt = device.connectGatt(context, false,
mGattCallBack,
BluetoothDevice.DEVICE_TYPE_LE,
BluetoothDevice.PHY_LE_2M|BluetoothDevice.PHY_LE_1M);
}else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
connectedGatt = device.connectGatt(context, false, mGattCallBack, BluetoothDevice.DEVICE_TYPE_LE);
} else if (android.os.Build.VERSION.SDK_INT >= 21) {
connectedGatt = connectGattApi21(context, device, mGattCallBack);
} else {
connectedGatt = device.connectGatt(context, false,
mGattCallBack);
}
} else {
//WiSeSdkFileWritter.writeToFile(fileName, TAG + " FAILED could not find remote device/ remote device is null >>" + macAddress);
}
return connectedGatt;
}
然后处理BluetoothGattCallback回调方法-onServicesDiscovered,onCharacteristicWrite,onConnectionStateChange
在onServicesDiscovered方法中,您将获得BluetoothGattService。从gattService提取特征。最后将特征写入ble设备。
BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
BluetoothGattService mService = gatt.getService(service);
mCharacteristics = mService.getCharacteristic(characteristics);
mCharacteristics.setValue(bytes);
Logger.v(TAG, "data write count ::" + writeCounter++);
Timer t = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
gatt.writeCharacteristic(mCharacteristics);
}
};
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
}
};