微信小程式藍芽連線2.0說明:
1、本版本區分了ANDROID和IOS系統下藍芽連線的不同方式。
2、相容了更多情況下的連結包括:
(1)未開啟裝置藍芽,當監聽到開啟了藍芽後自動開始連線。
(2)初始化藍芽失敗後每3000ms自動重新初始化藍芽介面卡。
(3)安卓端開啟藍芽介面卡掃描失敗,每3000ms自動重新開啟。
(4)IOS端獲取已連線藍芽裝置為空,每3000ms自動重新獲取。
(5)安卓端藍芽開始連結後中斷掃描,連線失敗了,重新開始掃描。
(6)IOS端開始連線裝置後,停止獲取已連線裝置,連線失敗自動重新開啟獲取。
(7)連線成功後,關閉系統藍芽,藍芽介面卡重置。
(8)連線成功後,關閉系統藍芽,再次開啟藍芽,自動重新開始連線。
(9)連線成功後,關閉目標藍芽裝置,自動重新開始掃描(獲取)。
(10)連線成功後,最小化小程式(連線未中斷),開啟小程式顯示已連線。
(11)連線成功後,殺掉小程式程式,連線關閉,自動重新開始掃描(獲取)。
3、想起來了再來更新....。
4、流程圖,明天或後天或...誰有空幫我畫一下也行。
我的連線是在App.js中做的。
在App.js中的onLaunch觸發是呼叫 init()方法。
init程式碼:
init: function (n) {
this.list = [];
this.serviceId = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E";
this.serviceId_2 = "00001803-0000-1000-8000-00805F9B34FB";
this.serviceId_3 = "00001814-0000-1000-8000-00805F9B34FB";
this.serviceId_4 = "00001802-0000-1000-8000-00805F9B34FB";
this.serviceId_5 = "00001804-0000-1000-8000-00805F9B34FB";
this.serviceId_6 = "00001535-1212-EFDE-1523-785FEABCD123";
this.characterId_write = "6E400042-B5A3-F393-E0A9-E50E24DCCA9E";
this.characterId_read = "6E400012-B5A3-F393-E0A9-E50E24DCCA9E";
this.connectDeviceIndex = 0;
this.isGettingConnected = false;
this.isDiscovering = false;
this.isConnecting = false;
this.connectedDevice = {};
console.log('init state', this.connectedDevice.state);
if (!this.connectedDevice.state || n == 200) {
this.connectedDevice.state = false;
this.connectedDevice.deviceId = '';
this.adapterHasInit = false
}
this.startConnect();
}複製程式碼
說明:
1、 serviceId_2~6 是我已知的想要連線的藍芽裝置的serviceId可以只寫一個。
2、characterId_write 是我已知的想要連線的藍芽裝置寫入資料的特徵值。
3、characterId_read是我已知的想要連線的藍芽裝置讀取資料的特徵值。
(以上3個都是為了做比對,真實的操作按照獲取到的sericeid, characterid為準)。
4、connectedDevice 是已連線了的裝置資訊物件。
init完成後開始呼叫連線 startConnect();
startConnect程式碼:
startConnect: function () {
var that = this;
if (that.connectedDevice.state) return;
that.connectedDevice.deviceId = "";
that.connectedDevice.state = false;
// 如果介面卡已經初始化不在呼叫初始化(重複初始化會報錯)
if (this.adapterHasInit == undefined || this.adapterHasInit) return;
wx.showLoading({
title: '初始化藍芽',
duration: 2000
});
// 開啟藍芽介面卡狀態監聽
this.listenAdapterStateChange();
// 初始化藍芽介面卡狀態(必須步驟,否則無法進行後續的任何操作)
wx.openBluetoothAdapter({
success: function (res) {
console.log("初始化藍芽介面卡成功");
that.getBluetoothAdapterState();
that.adapterHasInit = true;
},
fail: function (err) {
console.log(err);
wx.showLoading({
title: '請開藍芽',
icon: 'loading',
duration: 2000
})
}
});
}複製程式碼
說明:這段有註釋,就不多說了,比較簡單。
在初始化藍芽介面卡狀態成功後呼叫getBluetoothAdapterState()方法。
getBluetoothAdapterState程式碼:
getBluetoothAdapterState: function () {
var that = this;
wx.getBluetoothAdapterState({
success: function (res) {
console.log(res);
var available = res.available;
that.isDiscovering = res.discovering;
if (!available) {
wx.showLoading({
title: '請開藍芽',
icon: 'loading',
duration: 2000
})
} else {
if (!that.connectedDevice['state']) {
that.judegIfDiscovering(res.discovering);
}
}
},
fail: function (err) {
console.log(err);
}
})
}複製程式碼
說明:此方法是用來獲取當前藍芽狀態。
當檢測到藍芽可用時呼叫judegIfDiscovering方法。
judegIfDiscovering程式碼:
judegIfDiscovering: function (discovering) {
var that = this;
if (this.isConnectinng) return;
wx.getConnectedBluetoothDevices({
services: [that.serviceId],
success: function (res) {
console.log("獲取處於連線狀態的裝置", res);
var devices = res['devices'];
if (devices[0]) {
if (that.isAndroidPlatform) {
wx.showToast({
title: '藍芽連線成功',
icon: 'success',
duration: 2000
});
} else {
that.getConnectedBluetoothDevices(256);
}
} else {
if (discovering) {
wx.showLoading({
title: '藍芽搜尋中'
})
} else {
if (that.isAndroidPlatform) {
that.startBluetoothDevicesDiscovery();
} else {
that.getConnectedBluetoothDevices(267);
}
}
}
},
fail: function (err) {
console.log('getConnectedBluetoothDevices err 264', err);
if (that.isAndroidPlatform) {
that.startBluetoothDevicesDiscovery();
} else {
that.getConnectedBluetoothDevices(277);
}
}
});
}複製程式碼
說明:
1、此方法是用來判斷是否正在掃描。
2、isAndroidPlatform 是通過小程式的getSystemInfo獲取到的判斷是安卓裝置還是IOS裝置。
如果是安卓裝置呼叫startBluetoothDevicesDiscovery()開啟掃描,如果是IOS裝置呼叫getConnectedBluetoothDevices() 開啟獲取已配對的藍芽裝置。
startBluetoothDevicesDiscovery程式碼:
startBluetoothDevicesDiscovery: function () {
var that = this;
if (!this.isAndroidPlatform) return;
if (!this.connectedDevice['state']) {
wx.getBluetoothAdapterState({
success: function (res) {
console.log(res);
var available = res.available;
that.isDiscovering = res.discovering;
if (!available) {
wx.showLoading({
title: '請開藍芽',
icon: 'loading',
duration: 2000
})
} else {
if (res.discovering) {
wx.showLoading({
title: '藍芽搜尋中'
})
} else {
wx.startBluetoothDevicesDiscovery({
services: [],
allowDuplicatesKey: true,
success: function (res) {
that.onBluetoothDeviceFound();
wx.showLoading({
title: '藍芽搜尋中'
})
},
fail: function (err) {
if (err.isDiscovering) {
wx.showLoading({
title: '藍芽搜尋中'
})
} else {
that.startDiscoveryTimer = setTimeout(function () {
if (!that.connectedDevice.state) {
that.startBluetoothDevicesDiscovery();
}
}, 5000)
}
}
});
}
}
},
fail: function (err) {
console.log(err);
}
})
}複製程式碼
說明:
1、僅在安卓端裝置上開啟掃描附近藍芽裝置。
2、在開啟成功的回撥中開啟發現新藍芽裝置的事件監聽onBluetoothDeviceFound()。
onBluetoothDeviceFound程式碼:
[mw_shl_code=javascript,true]onBluetoothDeviceFound: function () {
var that = this;
wx.onBluetoothDeviceFound(function (res) {
console.log('new device list has founded');
if (res.devices[0]) {
var name = res.devices[0]['name'];
if (name.indexOf('FeiZhi') != -1) {
var deviceId = res.devices[0]['deviceId'];
console.log(deviceId);
that.deviceId = deviceId;
if (!that.isConnecting) {
that.startConnectDevices();
}
}
}
})
}複製程式碼
說明:
1、此處對已發現的藍芽裝置根據name屬性進行了過濾。
2、當篩選出含有需要連線的裝置的name屬性的裝置是獲取到deviceId,開始連線呼叫startConnectDevices()方法。
startConnectDevices程式碼:
startConnectDevices: function (ltype, array) {
var that = this;
clearTimeout(this.getConnectedTimer);
clearTimeout(this.startDiscoveryTimer);
this.getConnectedTimer = null;
this.startDiscoveryTimer = null;
this.isConnectinng = true;
wx.showLoading({
title: '正在連線'
});
that.stopBluetoothDevicesDiscovery();
wx.createBLEConnection({
deviceId: that.deviceId,
success: function (res) {
console.log('連線成功', res);
wx.showLoading({
title: '正在連線'
});
that.connectedDevice.state = true;
that.connectedDevice.deviceId = that.deviceId;
if (res.errCode == 0) {
setTimeout(function () {
that.getService(that.deviceId);
}, 5000)
}
wx.onBLEConnectionStateChange(function (res) {
console.log('連線變化', res);
that.connectedDevice.state = res.connected;
that.connectedDevice.deviceId = res.deviceId;
if (!res.connected) {
that.init('200');
}
});
},
fail: function (err) {
console.log('連線失敗:', err);
wx.hideLoading();
if (ltype == 'loop') {
array = array.splice(0, 1);
console.log(array);
that.loopConnect(array);
} else {
if (that.isAndroidPlatform) {
that.startBluetoothDevicesDiscovery();
} else {
that.getConnectedBluetoothDevices(488);
}
}
},
complete: function () {
that.isConnectinng = false;
}
});
}複製程式碼
說明:
1、開啟連線後終止掃描(獲取已配對)方法。
2、根據deviceId建立低功耗藍芽連線。如果連線成功,就繼續做後續讀寫操作。
3、如果連線失敗根據裝置系統分別呼叫startBluetoothDevicesDiscovery() 或 getConnectedBluetoothDevices();
getConnectedBluetoothDevices程式碼:
getConnectedBluetoothDevices: function (n) {
var that = this;
that.isGettingConnected = true;
wx.showLoading({
title: '藍芽搜尋中'
});
wx.getConnectedBluetoothDevices({
services: [that.serviceId],
success: function (res) {
console.log("獲取處於連線狀態的裝置", res);
var devices = res['devices'],
flag = false,
index = 0,
conDevList = [];
devices.forEach(function (value, index, array) {
if (value['name'].indexOf('FeiZhi') != -1) {
// 如果存在包含FeiZhi欄位的裝置
flag = true;
index += 1;
conDevList.push(value['deviceId']);
that.deviceId = value['deviceId'];
}
});
if (flag) {
that.connectDeviceIndex = 0;
that.loopConnect(conDevList);
} else {
that.failToGetConnected();
}
},
fail: function (err) {
that.failToGetConnected();
},
complete: function () {
that.isGettingConnected = false;
}
});
}複製程式碼
說明:如果獲取藍芽已配對的藍芽裝置失敗了,或獲取到的列表為空呼叫failToGetConnected();
failToGetConnected程式碼:
failToGetConnected: function () {
var that = this;
if (!that.getConnectedTimer) {
clearTimeout(that.getConnectedTimer);
that.getConnectedTimer = null;
}
that.getConnectedTimer = setTimeout(function () {
wx.getBluetoothAdapterState({
success: function (res) {
console.log(res);
var available = res.available;
if (!available) {
wx.showLoading({
title: '請開藍芽',
icon: 'loading',
duration: 2000
})
} else {
if (!that.connectedDevice['state']) {
that.getConnectedBluetoothDevices();
}
}
},
fail: function (err) {
console.log(err);
}
})
}, 5000);
}複製程式碼
說明:
1、該方法呼叫成功後返回的devices是一個陣列包含多個已經系統配對的藍芽裝置。
2、如果devices列表獲取到呼叫loopConnect()方法開始遞迴呼叫連線藍芽裝置。
loopConnect程式碼:
loopConnect: function (array) {
var that = this;
var listLen = array.length;
if (array[0]) {
that.deviceId = array[0];
if (!that.isConnecting) {
that.startConnectDevices('loop', array);
}
} else {
console.log('已配對的裝置小程式藍芽連線失敗');
if (!that.isAndroidPlatform) {
that.getConnectedBluetoothDevices(431);
}
}
}複製程式碼
說明:looConnect在建立連線的方法連線失敗後會操作刪除陣列的第一個值,然後繼續呼叫該方法,直到其中所有的裝置都連線過。
差點漏了:在app.js的onShow裡呼叫init()方法。
特別說明:
1、安卓和IOS的藍芽連線在當前版本中推薦採用不同方式。安卓裝置直接使用小程式的藍芽連線,取消系統配對。IOS裝置先系統配對在開啟小程式可以時效秒連線成功。
2、此版本的連線仍然有待完善,連線不會自動終止(需要的可以自己加),會無限掃描重連,直到成功。
3、連結成功後的操作如果寫入資料和開啟notify需要同時進行,建議先寫入,後開啟notify。(原因未知,否則必然出現10008錯誤)。
本文由 博主熊晨灃 原創釋出於小程式社群(www.wxapp-union.com/portal.php)
轉載請註明出處