2.0藍芽裝置的韌體升級
阿新 • • 發佈:2018-11-07
首先針對2.0的藍芽裝置對於資料的傳送很有侷限,每次只能傳輸20個位元組,如果傳輸大資料還會特別不穩定,所以關於韌體升級,能不通過藍芽升級就不要通過藍芽升級,但是有時候必須實現這種需求,就沒辦法,一定得入坑去研究了,最近在做的一個專案,裝置需要兩個空中升級的功能,一個是給CPU晶片軟體升級,一個是給藍芽晶片軟體升級,但是升級方式是相同的,下面是一些示例程式碼:
首先還是得讀懂文件看明白如何通訊
1有關藍芽的配對連線請參考藍芽配對githubDemo 這個庫對於藍芽連線配對描述的很詳細,也很好用。首先是藍芽連線:
private void connectDevice() {
BleConnectOptions options = new BleConnectOptions.Builder().setConnectRetry(3).setConnectTimeout(10000).setServiceDiscoverRetry(3)
.setServiceDiscoverTimeout(10000).build();
ClientManager.getClient().connect(mBluetoothDevice.getAddress(), options, new BleConnectResponse() {
@Override
public void onResponse(int code, BleGattProfile profile) {
hideConnectDialog();
if (code ==REQUEST_SUCCESS) {
mBluetoothDetailInfo =null;
//mCustomToast.ShowToast(R.string.connect_success);
if(mHandler !=null && profile !=null){
Listservices = profile.getServices();
for (BleGattService service : services) {
if(Constant.BULETOOTH_SERVICE_UUID.equalsIgnoreCase(service.getUUID().toString())) {
Listcharacters =service.getCharacters();
for (BleGattCharacter character :characters) {
if(Constant.BULETOOTH_CHARACTER_UUID.equalsIgnoreCase(character.getUuid().toString())) {
mBluetoothDetailInfo =new BluetoothDetailInfo();
mBluetoothDetailInfo.setBlueName(mBluetoothDevice.getName());
mBluetoothDetailInfo.setBlueMac(mBluetoothDevice.getAddress());
mBluetoothDetailInfo.setType(BluetoothDetailInfo.TYPE_CHARACTER);
mBluetoothDetailInfo.setCharacterUuid(character.getUuid());
mBluetoothDetailInfo.setServiceUuid(service.getUUID());
break;
}
}
break;
}
}
mHandler.sendEmptyMessage(ENTER_SATELLITE_ACTIVITY);
}
}else{
mCustomToast.ShowToast(R.string.connect_failed);
}
}
});
}
2,連線成功之後開始升級,
第一步:獲取bin檔案的長度,從伺服器下載下來一般都存在sd卡中
public static int getCpuBinLength(String name) {
int length = 0;
try {
File file = new File(Constant.FILE_PATH,name);
FileInputStream is = new FileInputStream(file);
length = is.available();
is.close();
}catch (IOException e) {
e.printStackTrace();
}
return length;
}
第二步,開始組裝資料,我的專案通訊協議是吧資料轉成byte進行傳輸,
//下面方法是讀取指定長度的byte資料
public static byte[]getBleBinToByte(String name, long start, int len,int allLength ) {
try {
File file =new File(Constant.FILE_PATH,name);
if (file.exists()&&len>0){
//拿出bin檔案
FileInputStream inputStream =new FileInputStream(file);
//讀到指定長度
long curPos =inputStream.skip(start);
//判斷最後一個數據是否滿足指定的len,不夠的話不用0補齊,剩下多少使用多少
if ((curPos+len)>allLength){
len= (int) (allLength-curPos);
}
byte[]bytes =new byte[len];
//從流中獨處檔案,轉成byte
inputStream.read(bytes);
inputStream.close();
if (start ==curPos)
{
return bytes;
}
}
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
第三步:拿出指定長度的bin檔案並轉化成byte陣列之後就可以進行傳送了,在傳送過程中對傳輸失敗,以及超時未返回都要做相應的重發處理,但是不能無限制的重發,一般重發十次就可以了。
自己的一點小經驗,謝謝大家瀏覽,歡迎指教