Browse Source

1.先连接蓝牙,app可以检测。
2.增加了app连接蓝牙成功,手机没匹配框的问题(仅是引导到首页蓝牙页面,需要蓝牙页面自处理)

slambb 5 years ago
parent
commit
6060ba66e6

+ 1 - 1
common/config.js

@@ -136,7 +136,7 @@ const URL = {
 
 //设置游戏列表的更新时间,超过这个时间,不显示出来
 //"2020-07-14"
-const endTime = "2021-01-19"
+const endTime = "2021-01-21"
 
 export default {
 	URL,

+ 2 - 2
manifest.json

@@ -2,8 +2,8 @@
     "name" : "哔蹦",
     "appid" : "__UNI__2635DF5",
     "description" : "",
-    "versionName" : "2.0.9",
-    "versionCode" : 21012001,
+    "versionName" : "2.1.0",
+    "versionCode" : 21012101,
     "transformPx" : false,
     /* 5+App特有相关 */
     "app-plus" : {

+ 110 - 67
pages/personal-page/devices-hardware/devices-hardware.vue

@@ -68,8 +68,10 @@
 				getServicesTimeout: null,
 				writeMacTimeout: null,
 				//限制关闭连接
-				bLimitClose: false
-
+				bLimitClose: false,
+				
+				//是否需要检测发起的连接蓝牙是否匹配上
+				bTestBondConnect:true
 			}
 		},
 		onLoad(op) {
@@ -93,7 +95,6 @@
 			uni.$on('callbackCloseBLE', this.hardCallbackCloseBLE);
 			uni.$on('listenerBLE', this.onListenerBLE);
 
-			// this.getBondedDevices();
 		},
 		onUnload() {
 			uni.$off('callbackCloseBLE', this.hardCallbackCloseBLE);
@@ -105,7 +106,7 @@
 		onShow() {
 
 			this.bLimitClose = false;
-			// console.log(this.cIndex, this.BLEDeviceShowList, this.BLEConnectDevice,this.devicesList);
+			console.log(this.cIndex, this.BLEDeviceShowList, this.BLEConnectDevice,this.devicesList);
 			//this.bConnection &&
 			if (this.bVerifiedConnection && this.BLEConnectDevice) {
 				for (let i = 0; i < this.devicesList.length; i++) {
@@ -116,6 +117,8 @@
 						(eq.ename.indexOf("BLEHandle") > -1 && this.BLEConnectDevice.id == 2)) {
 						eq.bRatio = true;
 						this.currentItem = eq;
+						
+						this.onCheckBondDevice();
 					}
 				}
 			} else {
@@ -133,7 +136,7 @@
 		methods: {
 			...mapMutations(['initAdapter', 'onCreateBLESuccess', 'onGetBLEDeviceServices', 'onOnlyCloseBLEConnection',
 				'onGetRSSITransDistance',
-				'addBLEDevice', 'onWriteBLEConnectionValue', 'deleteBLEDevice'
+				'addBLEDevice', 'onWriteBLEConnectionValue', 'deleteBLEDevice' ,'B_GetBondedDevices','B_OpenBLESetting'
 			]),
 			//
 			onClearTimeout() {
@@ -258,9 +261,43 @@
 						 * 已验证的连接设置true
 						 */
 						this.$store.state.bVerifiedConnection = true;
+						
+						this.onCheckBondDevice();
 					}
 				}
 			},
+			onCheckBondDevice(){
+				if(this.bTestBondConnect){
+					/**
+					 * 假如手机没有匹配,断开连接
+					 */
+					this.B_GetBondedDevices({success:(bondedDevice)=>{
+						if(bondedDevice == null ){
+							//此问题 华为手机容易出现
+							//android手机已配对的设备 不存在,但是app 又直接连接成功了。提示,并且断开app连接
+							//1.关闭当前连接
+							this.onOnlyCloseBLEConnection({
+								getSuccess: () => {
+									this.currentItem.bRatio = false;
+									this.currentItem = null;
+									this.saveObj = null;
+								}
+							});
+							//2.跳转蓝牙设置
+							uni.showModal({
+								title:'蓝牙提示',
+								content:'请在弹出框点击确定匹配蓝牙。\r\n如没有提示框,重新刷新手机蓝牙,是否跳转手机蓝牙页面?',
+								success: (res) => {
+									if(res.confirm){
+										this.B_OpenBLESetting();
+									}
+								}
+							})
+						}
+					}});
+					this.bTestBondConnect = false;
+				}
+			},
 			hardCallbackCloseBLE() {
 				//如果限制不走重连
 				if (this.bLimitClose) return;
@@ -278,6 +315,8 @@
 						this.currentItem.bRatio = false;
 						this.oldItem = null;
 						this.currentItem = null;
+						//断开连接
+						this.$store.state.bVerifiedConnection = false;
 					}
 				} else if (this.bConnection && this.BLEConnectDevice) {
 					//假如匹配过程中断开连接
@@ -294,7 +333,8 @@
 				//在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功,则开始查找设备
 				let _self = this;
 				if (_self.bOpenBluetooth) {
-
+					
+					
 					//先查询最近使用的硬件,如果最近使用的和当前需要连接的item id一样,则认为是
 					if (_self.finallyUseDevice !== null) {
 						if (_self.finallyUseDevice.id == _self.currentItem.id) {
@@ -314,7 +354,7 @@
 
 							uni.showModal({
 								title: '连接提示!',
-								content: "是否使用旧设备连接,取消则搜索'蓝灯闪烁'的新设备。",
+								content: "确定则连接最近使用的设备。\r\n取消则重新搜索设备。",
 								success: (res) => {
 									if (res.confirm) {
 										//currentItem 是mode 页面选中的item
@@ -333,22 +373,72 @@
 										// 先直连,然后判断版本
 										_self._onConnectDevice(obj);
 									} else if (res.cancel) {
-										_self.onCanStart();
+										_self.onBondedDeviceConnect();
 									}
 								}
 							})
 
 						}
-
-						return;
+					}else{
+						_self.onBondedDeviceConnect();
 					}
-					_self.onCanStart();
+					
 				} else {
 					_self.initAdapter(() => {
 						_self.startBluetoothDeviceDiscovery();
 					});
 				}
 			},
+			/**
+			 * 通过检测手机连接的设备进行连接,null 的话进行搜索操作
+			 */
+			onBondedDeviceConnect(){
+				let _self = this;
+				// _self.onCanStart();
+				
+				//获取手机本身已连接的硬件,
+				//示例
+				// {
+				// 	"deviceId": "C5:5C:19:04:00:30",
+				// 	"name": "BGBox_202012",
+				// 	"RSSI": -74,
+				// 	"localName": "BGBox_20201",
+				// 	"advertisServiceUUIDs": ["00001812-0000-1000-8000-00805F9B34FB", "0000FFF0-0000-1000-8000-00805F9B34FB"]
+				// }
+				_self.B_GetBondedDevices({success:(bondedDevice)=>{
+					//获取已和蓝牙连接的设备
+					if(bondedDevice != null){
+						//如果用户匹配了对应的设备,直接用对应的设备来连接
+						let setDevice = {
+							"deviceId": bondedDevice.address,
+							"name": bondedDevice.name,
+							"RSSI": -74,
+							"localName": "",
+							"advertisServiceUUIDs": ["00001812-0000-1000-8000-00805F9B34FB", "0000FFF0-0000-1000-8000-00805F9B34FB"]
+						}
+						
+						let obj = Object.assign({}, setDevice, _self.currentItem);
+						//finallyUserDevice 就是最后一次使用搜索到的设备信息
+						_self.saveObj = Object.assign({}, setDevice, {
+							id: _self.currentItem.id
+						});
+						uni.showToast({
+							title: '设备连接中...',
+							icon: 'loading',
+							duration: 10000,
+							mask: true
+						})
+						console.log("B_GetBondedDevices:::===", obj);
+						// 先直连,然后判断版本
+						_self._onConnectDevice(obj);
+						
+						//getBond后发起的连接,不需要检测了
+						_self.bTestBondConnect = false;
+					}else{
+						_self.onCanStart();
+					}
+				}});
+			},
 			//开始搜索
 			onCanStart() {
 				let _self = this;
@@ -382,7 +472,7 @@
 					_self.stopBluetoothDevicesDiscovery();
 					uni.showModal({
 						title: '搜索失败',
-						content: '请开启设备或断开手机匹配,直到设备灯闪,再重新搜索连接。'
+						content: '1.请开启设备。\r\n2.或者断开手机蓝牙页面连接的手柄。\r\n待蓝色设备灯闪烁,再重新搜索连接。'
 					})
 				}, 10000)
 			},
@@ -425,12 +515,12 @@
 							}
 							//currentItem 是mode 页面选中的item
 							let obj = Object.assign({}, device, _self.currentItem);
-
+							
 							_self.saveObj = Object.assign({}, {
 								id: _self.currentItem.id
 							}, device);
 
-							console.log("****", obj, _self.saveObj, _self.currentItem)
+							console.log(device,"****", obj, _self.saveObj, _self.currentItem)
 							// 先直连,然后判断版本
 							_self._onConnectDevice(obj);
 							_self.stopBluetoothDevicesDiscovery();
@@ -540,7 +630,7 @@
 
 								}
 							});
-						}, 2000);
+						}, 2500);
 					}
 				})
 			},
@@ -548,11 +638,15 @@
 			_onRadio(item, event) {
 
 				if (!item.bRatio) {
+					//设置默认值
+					this.bTestBondConnect = true;
 					console.log("this.currentItem ==:", this.currentItem, this.bOpenBluetooth, this.BLEConnectDevice);
 					if (this.BLEConnectDevice) {
 						this.onOnlyCloseBLEConnection({
 							getSuccess: () => {
-								this.currentItem.bRatio = false;
+								if(this.currentItem)
+									this.currentItem.bRatio = false;
+									
 								this.currentItem = null;
 								this.currentItem = item;
 								this.startBluetoothDeviceDiscovery();
@@ -596,57 +690,6 @@
 				uni.navigateTo({
 					url: "../devices-update/devices-update?deviceType=" + this.option.deviceType
 				})
-			},
-
-			//获取手机已连接的设备
-			getBondedDevices() {
-				console.log("getBondedDevices ====>");
-				// 	uni.getBluetoothDevices({
-				// 		success(res) {
-				// 			console.log("getBluetoothDevices:", res)
-				// 		}
-				// 	})
-
-				// 	uni.getConnectedBluetoothDevices({
-				// 		success(res) {
-				// 			console.log("getConnectedBluetoothDevices:", res)
-				// 		}
-				// 	})
-
-				function bluetooth_list() {
-					var main = plus.android.runtimeMainActivity();
-					var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
-					var BAdapter = BluetoothAdapter.getDefaultAdapter();
-					var Context = plus.android.importClass("android.content.Context");
-					var lists = BAdapter.getBondedDevices();
-					plus.android.importClass(lists);
-					var len = lists.size();
-					console.log(len);
-					var iterator = lists.iterator();
-					plus.android.importClass(iterator);
-					while (iterator.hasNext()) {
-						var d = iterator.next();
-						plus.android.importClass(d);
-						console.log(d.getName());
-						console.log(d.getAddress());
-					}
-
-				}
-
-				switch (plus.os.name) {
-					case "Android":
-						// Android平台: plus.android.*  
-						bluetooth_list();
-						break;
-					case "iOS":
-						// iOS平台: plus.ios.*  
-						break;
-					default:
-						// 其它平台  
-						break;
-				}
-
-
 			}
 		}
 

+ 80 - 58
pages/personal-page/personal/personal.vue

@@ -302,7 +302,6 @@
 						<!-- <button class="margin" @click="openGyro">开启手机加速计和方向传感器</button> -->
 						<!-- <button class="margin" @click="stopGyro">关闭手机加速计和方向传感器</button> -->
 						<!-- <keyboard-listener @keydown="onKeyDown"></keyboard-listener> -->
-						<!-- <button class="margin" @click="getDevice">getDevice</button> -->
 						<!-- 视频推荐 -->
 						<view class="card-view" v-if="videoList.length !== 0">
 							<view class="text-left padding margin-xs flex justify-between">
@@ -493,7 +492,9 @@
 			'bGuidePages',
 			'globalAcc', 'globalOri', 'DeviceBindingList', 'ConnectBindingDevice', 'cIndex', 'bNewGuide', 'localSportTime',
 			'currentModeIndex', 'oldArcbarProCalorie', 'oldArcbarAllCalorie', 'bOpenBluetooth', 'bOpenSuccess',
-			'bListenAdapterStateChange', 'bConnection', 'bVerifiedConnection', 'currentInstruction', 'instructionState', 'LocationGameUrl'
+			'bListenAdapterStateChange', 'bConnection', 'bVerifiedConnection', 'currentInstruction', 'instructionState',
+			'LocationGameUrl',
+			'bPhoneMatched'
 		]),
 		components: {
 			uniNavBar,
@@ -753,7 +754,13 @@
 
 				bAiHitShake: false,
 				//限制重连,比如去了对应硬件连接页面,限制这个页面的重连操作
-				bLimitReconnection:false,
+				bLimitReconnection: false,
+				
+				/**
+				 * 首页这里连接了蓝牙,然后选择框回来后show会触发,触发时候检测一下是否有对应的
+				 * 匹配蓝牙
+				 */
+				bGetBondTesting:false,
 
 			};
 		},
@@ -882,11 +889,23 @@
 			if (this.bVerifiedConnection && this.BLEConnectDevice) {
 				// console.log('this.BLEConnectDevice:',this.BLEConnectDevice);
 				this.updateBLECIndex();
+				
+				setTimeout(()=>{
+					/**
+					 * 如果是首页连接,则检测
+					 */
+					if(this.bGetBondTesting){
+						this.onGetBondDevice();
+						this.bGetBondTesting = false;
+					}
+				},2000)
+				
 			}
-			
+
 			console.log('personal show');
-			
+
 			this.bLimitReconnection = false;
+		
 		},
 		onReady() {
 			// 计算屏幕剩余高度  填补剩余高度
@@ -945,8 +964,9 @@
 		methods: {
 			...mapMutations(['accountLogin', 'getPlanData', 'addlocalCalorie', 'setLocalCalorie', 'setShowCalorie',
 				'syncLocalDataToServer', 'syncRequestEvent', 'setLocalSportTime',
-				'initAdapter', 'onCreateBLEConnection', 'onUnloadCreateBLEConnectionTimeout', 'onCloseBLEConnection', 'gOnAddClientInfo', 'onWriteBLEConnectionValue',
-				'gCreateFilterObj', 'gUpdateFilter'
+				'initAdapter', 'onCreateBLEConnection', 'onUnloadCreateBLEConnectionTimeout', 'onCloseBLEConnection',
+				'gOnAddClientInfo', 'onWriteBLEConnectionValue',
+				'gCreateFilterObj', 'gUpdateFilter', 'B_GetBondedDevices','B_OpenBLESetting'
 			]),
 			onKeyDown(e) {
 				console.log(e);
@@ -1339,6 +1359,7 @@
 
 						eq.bRatio = true;
 						this.$store.state.cIndex = i;
+
 					}
 				}
 			},
@@ -1348,18 +1369,27 @@
 				this.$store.state.cIndex = -1;
 				//蓝牙断开连接后,直接关闭
 				this.$refs.boxingPostRef.onCloseDevices();
+
 				if (!this.BLEConnectDevice) {
 					console.log('连接蓝牙对象为空,不进行重连!');
 					return;
 				}
 				//如果限制不走重连
-				if(this.bLimitReconnection)return;
+				if (this.bLimitReconnection) return;
 				//连接蓝牙
 				this.onCreateBLEConnection({
 					item: this.BLEConnectDevice,
 					initItem: false,
 					getSuccess: () => {
 						this.updateBLECIndex();
+						
+						if(this.bHide){
+							//弹出框时候,是隐藏状态
+							this.bGetBondTesting = true;
+						}else{
+							//没有弹出框时候,直接检测
+							this.onGetBondDevice();
+						}
 					},
 					getinitAdapter: () => {
 						// this.onDevice(item, e);
@@ -1467,8 +1497,50 @@
 					initItem: true,
 					getinitAdapter: () => {
 						this.onDevice(item, e);
+					},
+					getSuccess: () => {
+						if(this.bHide){
+							//弹出框时候,是隐藏状态
+							this.bGetBondTesting = true;
+						}else{
+							//没有弹出框时候,直接检测
+							this.onGetBondDevice();
+						}
+					}
+				});
+			},
+			/**
+			 * 检测获取匹配的设备
+			 */
+			onGetBondDevice() {
+				/**
+				 * 假如手机没有匹配,断开连接
+				 */
+				this.B_GetBondedDevices({
+					success:(bondedDevice)=>{
+						console.error("===========",bondedDevice);
+						if (bondedDevice == null) {
+							//此问题 华为手机容易出现
+							//android手机已配对的设备 不存在,但是app 又直接连接成功了。提示,并且断开app连接
+							//1.关闭当前连接
+							this.onCloseBLEConnection({
+								getSuccess: () => {}
+							});
+							uni.hideToast();
+							//2.跳转蓝牙设置
+							uni.showModal({
+								title: '蓝牙配对失败',
+								content: '1.请在蓝牙匹配框点击配对蓝牙。\r\n2.如果没有蓝牙配对提示框,去蓝牙页面重新刷新手机蓝牙。是否跳转手机蓝牙页面?',
+								success: (res) => {
+									if (res.confirm) {
+										this.B_OpenBLESetting();
+									}
+								}
+							})
+						}
 					}
 				});
+				
 			},
 
 			openDeviceList(e) {
@@ -2351,56 +2423,6 @@
 				})
 			},
 
-			getDevice() {
-				console.log("getDevice");
-				uni.getBluetoothDevices({
-					success(res) {
-						console.log("getBluetoothDevices:", res)
-					}
-				})
-
-				uni.getConnectedBluetoothDevices({
-					success(res) {
-						console.log("getConnectedBluetoothDevices:", res)
-					}
-				})
-
-				function bluetooth_list() {
-					var main = plus.android.runtimeMainActivity();
-					var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
-					var BAdapter = BluetoothAdapter.getDefaultAdapter();
-					var Context = plus.android.importClass("android.content.Context");
-					var lists = BAdapter.getBondedDevices();
-					plus.android.importClass(lists);
-					var len = lists.size();
-					console.log(len);
-					var iterator = lists.iterator();
-					plus.android.importClass(iterator);
-					while (iterator.hasNext()) {
-						var d = iterator.next();
-						plus.android.importClass(d);
-						console.log(d.getName());
-						console.log(d.getAddress());
-					}
-
-				}
-
-				switch (plus.os.name) {
-					case "Android":
-						// Android平台: plus.android.*  
-						bluetooth_list();
-						break;
-					case "iOS":
-						// iOS平台: plus.ios.*  
-						break;
-					default:
-						// 其它平台  
-						break;
-				}
-
-
-			},
-
 			onNavAppInfo() {
 				uni.navigateTo({
 					url: '../../info-page/app-info/app-info'

+ 1 - 553
util/util-js/BLE.js

@@ -1,382 +1,4 @@
 // 灵敏度
-const BLEDIS = 0.9;
-
-
-// 设备Id
-var deviceId = "";
-// 服务Id
-var serviceId = "";
-
-var notifyCharacteristicId = "";
-
-var writeCharacteristicId = "";
-
-var currentInstruction = "";
-
-var showToast = false;
-
-var bListenerUpdate = false;
-
-var bListenerJson = false;
-
-var bListenerMac = false;
-
-function initData() {
-	// 设备Id
-	this.deviceId = "";
-	// 服务Id
-	this.serviceId = "";
-
-	this.notifyCharacteristicId = "";
-
-	this.writeCharacteristicId = "";
-
-	this.currentInstruction = "";
-
-	this.showToast = false;
-
-	this.bListenerUpdate = false;
-
-	this.bListenerJson = false;
-
-	this.bListenerMac = false;
-
-}
-
-
-function openBluetoothAdapter(context) {
-
-	let {
-		success,
-		fail,
-		complete
-	} = context;
-
-	//#ifdef H5
-	console.warn('h5不加载蓝牙模块');
-	return;
-	//#endif
-
-	let self = this;
-	// 初始化蓝牙适配器
-	uni.openBluetoothAdapter({
-		success: res => {
-			// console.log("初始化蓝牙成功:", res);
-			if (success)
-				success(res);
-		},
-		fail: res => {
-			// console.error("openBluetoothAdapter == ", res);
-			if (fail)
-				fail(res);
-		},
-		complete: res => {
-			// console.warn("************openBluetoothAdapter complete == ", res);
-			if (complete)
-				complete(res);
-		}
-	})
-}
-
-function onBLEConnectionStateChange() {
-	//#ifdef H5
-	console.warn('h5不加载蓝牙模块');
-	return;
-	//#endif
-
-	uni.onBLEConnectionStateChange(res => {
-		// 该方法回调中可以用于处理连接意外断开等异常情况
-		console.log(`蓝牙连接状态 -------------------------->`, JSON.stringify(res));
-		if (!res.connected) {
-			// if (this.isStop) return;
-			// console.log('断开低功耗蓝牙成功:');
-			uni.$emit('callbackCloseBLE');
-			//todo 在这里尝试重连
-			//关闭连接
-			// this.closeBluetoothAdapter();
-		}
-	});
-}
-
-/**
- * 连接低功耗蓝牙设备。
- * 若APP在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。
- */
-function createBLEConnection(item, success, fail) {
-	let self = this;
-	self.initData();
-	self.deviceId = item.deviceId;
-	let timeout = 10000;
-	uni.createBLEConnection({
-		// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
-		deviceId: self.deviceId,
-		timeout,
-		success: res => {
-			if (success) {
-				success(res);
-			}
-		},
-		fail: res => {
-			if (fail)
-				fail(res);
-		}
-	});
-
-
-}
-
-/**
- * 获取设备的服务ID
- */
-function getBLEDeviceServices(item, callback,getServiceList) {
-	let serviceList = [];
-	let self = this;
-	// console.log("getBLEDeviceServices");
-	uni.getBLEDeviceServices({
-		deviceId: item.deviceId,
-		success: res => {
-			console.log("getBLEDeviceServices==", JSON.stringify(res), item);
-			serviceList = res.services;
-			// serviceList = [];
-			if(serviceList.length == 0){
-				uni.hideToast();
-				uni.showModal({
-					title:'失败',
-					content:'获取服务失败,请尝试重新连接对应的模式。'
-				})
-			}
-			if(getServiceList){
-				getServiceList(serviceList);
-			}
-			for (let i = 0; i < serviceList.length; i++) {
-				let service = serviceList[i];
-				//比对service是否是F393服务
-				// if (item.primaryUUID && service.uuid.indexOf(item.primaryUUID) != -1) 
-				if (service.uuid.toLocaleLowerCase() === item.PRIMARY_SERVICE.toLocaleLowerCase()) {
-					self.serviceId = service.uuid;
-					// console.log("设备的serviceId: " + self.serviceId);
-					//开始获取指定服务的特征值
-					self.getBLEDeviceCharacteristics(item, callback);
-					break;
-				}
-			}
-		},
-		fail: failRes => {
-			console.log('device services:', failRes.services)
-			uni.showModal({
-				title:'连接失败',
-				content:'未获取到相应服务,请继续尝试连接设备。'
-			})
-		}
-	});
-}
-/**
- * 获取指定服务的特征值
- */
-function getBLEDeviceCharacteristics(item, callback) {
-	let deviceId = this.deviceId;
-	let serviceId = this.serviceId;
-	let characteristicsList = [];
-	let self = this;
-	uni.getBLEDeviceCharacteristics({
-		deviceId,
-		serviceId,
-		success: res => {
-			// console.log(JSON.stringify(res));
-			// console.log("获取的" + serviceId + "服务的特征值:" + JSON.stringify(res.characteristics)+JSON.stringify(item));
-			// console.log(res.characteristics);
-			// console.log(item);
-			// characteristicsList = res.characteristics;
-			// for (let i = 0; i < characteristicsList.length; i++) {
-			// 	let characteristic = characteristicsList[i];
-			// 	//该特征值是否支持 notify或indicate 操作
-			// 	if (characteristic.properties.notify || characteristic.properties.indicate) {
-			// 		console.log("该特征值支持 notify 操作:" + characteristic.uuid);
-			// 		self.notifyCharacteristicId = characteristic.uuid;
-			// 		self.notifyBLECharacteristicValueChange(deviceId, serviceId);
-			// 	}
-			// 	if (characteristic.properties.write) {
-			// 		console.log("该特征值支持 write 操作:" + characteristic.uuid);
-			// 		self.writeCharacteristicId = characteristic.uuid;
-			// 		// break;
-			// 	}
-			// }
-			if (item.PRIMARY_NOTIFY != '') {
-				self.notifyCharacteristicId = item.PRIMARY_NOTIFY;
-				self.notifyBLECharacteristicValueChange(callback);
-			}
-			if (item.PRIMARY_WRITE != '') {
-				self.writeCharacteristicId = item.PRIMARY_WRITE;
-			}
-		},
-		fail: res => {
-			console.log('device getBLEDeviceCharacteristics failed:', JSON.stringify(res))
-		}
-	})
-}
-
-//启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。
-//注意:必须设备的特征值支持notify或者indicate才可以成功调用,具体参照 characteristic 的 properties 属性
-function notifyBLECharacteristicValueChange(callback) {
-	var _self = this;
-	// 启用notify功能
-	// console.log("启用notify功能");
-	uni.notifyBLECharacteristicValueChange({
-		state: true,
-		deviceId: _self.deviceId,
-		serviceId: _self.serviceId,
-		characteristicId: _self.notifyCharacteristicId,
-		success: function(res) {
-			_self.onBLECharacteristicValueChange(callback); //监听特征值变化
-		},
-		fail: function(res) {
-			uni.showToast({
-				title: 'notify启动失败',
-				icon: "none",
-				mask: true
-			});
-
-		}
-	})
-}
-//监听低功耗蓝牙设备的特征值变化。必须先启用notify接口才能接收到设备推送的notification。
-function onBLECharacteristicValueChange(callback) {
-	var self = this;
-	console.log("onBLECharacteristicValueChange success");
-	if (callback) {
-		callback({
-			notifyCharacteristicId: self.notifyCharacteristicId,
-			writeCharacteristicId: self.writeCharacteristicId
-		})
-	}
-	uni.onBLECharacteristicValueChange(function(res) {
-		let box = {};
-		var resValue = ab2hext(res.value); //16进制字符串
-		// console.log(self.currentInstruction +","+ self.bListenerUpdate+","+self.bListenerJson);
-
-		if (self.currentInstruction == "V" && self.showToast) {
-			var resValueStr = hexToString(resValue);
-			// console.log("v resValueStr:" + resValueStr);
-			// uni.showToast({
-			// 	title: resValueStr.replace(/\{|}/g,'').trim(),
-			// 	icon: 'none',
-			// 	duration: 5000
-			// })
-			let _info = {
-				type: 'version',
-				instruction: 'V',
-				value: resValueStr.replace(/\{|}/g, '').trim()
-			}
-			uni.$emit('listenerBLE', _info);
-			self.currentInstruction = "";
-			self.showToast = false;
-			return;
-		} else if (self.currentInstruction == 'M' && self.bListenerMac) {
-			var resValueStr = hexToString(resValue);
-			// console.log(resValue);
-			// console.log("m:", resValueStr.replace(/\{|}/g,''));
-			// uni.showToast({
-			// 	title: resValueStr.replace(/\{|}/g,'').trim(),
-			// 	icon: 'none',
-			// 	duration: 5000
-			// })
-			let _info = {
-				type: 'mac',
-				instruction: 'M',
-				value: resValueStr.replace(/\{|}/g, '').trim()
-			}
-			uni.$emit('listenerBLE', _info);
-			self.currentInstruction = "";
-			self.bListenerMac = false;
-			return;
-		}
-		//步数数据解析
-		if (self.bListenerJson) {
-			var resValueStr = hexToString(resValue);
-			// let _info = {
-			// 	type: 'mac',
-			// 	instruction: 'M',
-			// 	value: resValueStr.replace(/\{|}/g, '').trim()
-			// }
-			console.log(resValueStr);
-			box["Json"] = resValueStr;
-			uni.$emit('updateBLEDeviceJson', box);
-		}
-		//原始数据解析
-		if (self.bListenerUpdate) {
-			// console.log("min:" + min+",s:"+s+",ms:"+ms);
-
-			//R/L 左手还是右手
-			let handle = resValue.substr(6, 2);
-
-			let axStr = resValue.substr(8, 4);
-			let ayStr = resValue.substr(12, 4);
-			let azStr = resValue.substr(16, 4);
-			// console.log("accStr:" + axStr+","+ayStr+","+azStr);
-			// console.log("hex2int:" + hexToSignedInt(axStr)+","+hexToSignedInt(ayStr)+","+hexToSignedInt(azStr));
-			//一个字节最大只能表示265  2个字节可以表示65536  然后你这边做一下转换 例如00 3E   3*16+14=62 ----->0.03  g 
-			//(真实值= AD值 /32768  * 16)
-			//0.003 = 62 / 2768  * 16
-			let ax = hexToSignedInt(axStr) / 32768 * 16;
-			let ay = hexToSignedInt(ayStr) / 32768 * 16;
-			let az = hexToSignedInt(azStr) / 32768 * 16;
-
-			let gxStr = resValue.substr(20, 4);
-			let gyStr = resValue.substr(24, 4);
-			let gzStr = resValue.substr(28, 4);
-
-			//角速度(AD值/32768 * 2000) 角速度单位是 °/s  范围是 正负2000
-			let gx = hexToSignedInt(gxStr) / 32768 * 2000;
-			let gy = hexToSignedInt(gyStr) / 32768 * 2000;
-			let gz = hexToSignedInt(gzStr) / 32768 * 2000;
-
-			//毫秒
-			let ms = hex2int(resValue.substr(2, 4));
-			//分
-			let min = hex2int(resValue.substr(32, 2));
-			//秒
-			let s = hex2int(resValue.substr(34, 2));
-
-			box["handle"] = hexToString(handle);
-			box["acc"] = {
-				ax,
-				ay,
-				az
-			};
-			box["gyro"] = {
-				gx,
-				gy,
-				gz
-			};
-
-			box["min"] = min;
-			box["s"] = s;
-			box["ms"] = ms;
-
-
-			// console.log("box:" + JSON.stringify(box));
-
-			// if (typeof obj !== 'object' && obj) {
-			// 	// console.log("连接错误")
-			// 	//-1为错误
-			// 	uni.$emit("callbackBLEState", {
-			// 		state: -1,
-			// 		msg: "设备数据错误"
-			// 	});
-			// 	return;
-			// }
-			// if (obj.hasOwnProperty("H")) {
-			// 	console.log("HHHH:", obj.H);
-			// }
-			//更新数据给webview,在game-play-web||game-play-sub绑定
-			//后面更新数据都用此接口
-			uni.$emit('updateBLEDeviceData', box);
-		}
-
-
-	});
-}
-
 // ArrayBuffer转16进制字符串示例
 function ab2hext(buffer) {
 	var hexArr = Array.prototype.map.call(
@@ -497,189 +119,15 @@ function hexToString(str) {
 }
 
 
-/**
- * 断开蓝牙模块连接
- */
-function closeBluetoothAdapter() {
-	//#ifdef H5
-	console.warn('h5不加载蓝牙模块');
-	return;
-	//#endif
-
-	uni.closeBluetoothAdapter({
-		success: res => {
-			console.log('断开蓝牙模块成功');
-
-			uni.showToast({
-				icon: "none",
-				title: "蓝牙已经断开!",
-				mask: false,
-				duration: 3000
-			});
-		}
-	});
-}
-
-
-//向低功耗蓝牙设备特征值中写入二进制数据。注意:必须设备的特征值支持 write 才可以成功调用。
-function writeBLECharacteristicValue(value, retryCount, success, getFail) {
-	var self = this;
-	if (!value && value === '') {
-		uni.showToast({
-			title: "指令为空"
-		})
-		return;
-	}
-	//记录一下指令
-	self.currentInstruction = value;
-	//V 获取版本,M 获取mac 地址
-	if (value == "V")
-		self.showToast = true;
-
-	if (value == "M") {
-		self.showToast = true;
-		self.bListenerMac = true;
-	}
-	if (value == "4") {
-		self.bListenerUpdate = false;
-	}
-	if (value == "3") {
-		if (self.bListenerUpdate) {
-			uni.showToast({
-				title: "原始数据已开启"
-			})
-			return;
-		}
-		self.bListenerUpdate = true;
-	}
-
-	if (value == "6") {
-		self.bListenerJson = false;
-	}
-	if (value == "5") {
-		if (self.bListenerJson) {
-			uni.showToast({
-				title: "步数数据已开启"
-			})
-			return;
-		}
-		self.bListenerJson = true;
-	}
-
-
-	console.log("currentInstruction:", self.currentInstruction, value, self.bListenerUpdate, self.bListenerMac);
-	console.log("self.deviceId:", self.deviceId, self.serviceId, self.writeCharacteristicId);
-	uni.writeBLECharacteristicValue({
-		deviceId: self.deviceId,
-		serviceId: self.serviceId,
-		// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
-		characteristicId: self.writeCharacteristicId,
-		// 这里的value是ArrayBuffer类型
-		value: str2ab(value),
-		success:(res)=> {
-			console.log('writeBLECharacteristicValue success', res.errMsg, value,retryCount);
-			if (success) {
-				success(res);
-			}
-		},
-		fail: (fail) => {
-			console.log(fail)
-			//重新写入
-			// uni.showModal({
-			// 	title:"提示",
-			// 	content:"蓝牙通信失败,是否重新执行此操作。",
-			// 	success: (resValue) => {
-			// 		if(resValue.confirm){
-			// 			self.writeBLECharacteristicValue(value, success);
-			// 		}
-			// 	}
-			// })
-			if(retryCount>0){
-				console.log("writeBLECharacteristicValue Rewrite ===================>"+value+" == "+retryCount);
-				retryCount--;
-				setTimeout(()=>{
-					self.writeBLECharacteristicValue(value,retryCount,success,getFail);
-				},300);
-			}
-			if(getFail){
-				getFail(fail);
-			}
-		}
-		// ,
-		// complete: (completeRes) => {
-		// 	console.log(completeRes)
-		// }
-	})
-	
-	// uni.readBLECharacteristicValue({
-	// 	deviceId:self.deviceId,
-	// 	serviceId:self.serviceId,
-	// 	characteristicId:self.notifyCharacteristicId,
-	// 	success: (resValue) => {
-	// 		console.log('read success!');
-	// 	}
-	// })
-}
-
-/**
- * 断开蓝牙连接
- */
-function closeBLEConnection(deviceId, success) {
-	uni.closeBLEConnection({
-		deviceId,
-		success: res => {
-			if (success)
-				success();
-		},
-		fail: (fail) => {
-			console.log("关闭蓝牙失败",fail);
-		}
-	});
-}
 
 function getRSSITransDistance(rssi) {
 	return Math.pow(Math.E, (Math.abs(rssi) - 66.78) / 16.56);
 }
 
-/**
- * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
- */
-function getBluetoothDevices() {
-	uni.getBluetoothDevices({
-		success(res) {
-			console.log("getBluetoothDevices:", res)
-		}
-	})
-}
-
-export default {
-	deviceId,
-	serviceId,
-	//蓝牙模块
-	openBluetoothAdapter,
-	closeBluetoothAdapter,
-
-	onBLEConnectionStateChange,
-	getBLEDeviceCharacteristics,
-	notifyBLECharacteristicValueChange,
-	onBLECharacteristicValueChange,
 
-	//建立连接模块
-	createBLEConnection,
-	closeBLEConnection,
 
-	getBLEDeviceServices,
+export default {
 	getRSSITransDistance,
-
-	BLEDIS,
-
-	//写入模块数据
-	writeBLECharacteristicValue,
-
-	//获取已经匹配的蓝牙
-	getBluetoothDevices,
-	//初始化this变量
-	initData,
 	
 	ab2hext,
 	str2ab,

+ 202 - 37
util/util-js/store.js

@@ -162,6 +162,13 @@ const store = new Vuex.Store({
 		 * 通过验证的连接,比如通过mac验证,或者说是首页直连,都设置这个参数,确保已经连上
 		 */
 		bVerifiedConnection: false,
+
+		/**
+		 * Android 出现不匹配的情况下,判断
+		 * ios 暂时没有此类问题
+		 */
+		bPhoneMatched: false,
+
 		//最近连接过的设备
 		finallyUseDevice: null,
 
@@ -1295,7 +1302,9 @@ const store = new Vuex.Store({
 						}
 
 						setTimeout(() => {
-							this.commit("B_CloseBLEConnection",{deviceId:deviceId})
+							this.commit("B_CloseBLEConnection", {
+								deviceId: deviceId
+							})
 							state.cIndex = -1;
 							state.bConnection = false;
 							state.bVerifiedConnection = false;
@@ -1323,27 +1332,27 @@ const store = new Vuex.Store({
 				state.getBLEDeviceServicesTimeout = null;
 			}
 		},
-		
+
 		initBLEData(state) {
 			// 设备Id
 			state.deviceId = "";
 			// 服务Id
 			state.serviceId = "";
-		
+
 			state.notifyCharacteristicId = "";
-		
+
 			state.writeCharacteristicId = "";
-		
+
 			state.currentInstruction = "";
-		
+
 			state.showToast = false;
-		
+
 			state.bListenerUpdate = false;
-		
+
 			state.bListenerJson = false;
-		
+
 			state.bListenerMac = false;
-		
+
 		},
 		//连接蓝牙
 		onCreateBLEConnection(state, context) {
@@ -1356,8 +1365,22 @@ const store = new Vuex.Store({
 			} = context;
 
 			let params = {
-				item:item,
-				success:(success) => {
+				item: item,
+				success: (success) => {
+
+					// 	uni.getBluetoothDevices({
+					// 		success(res) {
+					// 			console.log("getBluetoothDevices:", res)
+					// 		}
+					// 	})
+
+					// 	uni.getConnectedBluetoothDevices({
+					// 		success(res) {
+					// 			console.log("getConnectedBluetoothDevices:", res)
+					// 		}
+					// 	})
+
+
 					state.bConnection = true;
 					if (state.getBLEDeviceServicesTimeout) {
 						clearTimeout(state.getBLEDeviceServicesTimeout);
@@ -1366,8 +1389,8 @@ const store = new Vuex.Store({
 
 					state.getBLEDeviceServicesTimeout = setTimeout(() => {
 						this.commit("B_GetBLEDeviceServices", {
-							item:item,
-							callback:() => {
+							item: item,
+							callback: () => {
 								uni.showToast({
 									title: '连接成功',
 									icon: 'loading',
@@ -1380,14 +1403,17 @@ const store = new Vuex.Store({
 									state.BLEConnectDevice = item;
 								}
 
+
+								if (getSuccess)
+									getSuccess();
+
 								/**
 								 * 直接连接过成功
 								 */
 								state.bVerifiedConnection = true;
-								if (getSuccess)
-									getSuccess();
+
 							},
-							getServiceList:(serviceList) => {
+							getServiceList: (serviceList) => {
 								//搜索服务失败后
 								state.BLEGetServices = serviceList;
 							}
@@ -1396,14 +1422,14 @@ const store = new Vuex.Store({
 					}, 2000);
 
 				},
-				fail:(fail) => {
+				fail: (fail) => {
 					console.log("***fail:", fail);
 					if (fail.errCode === 10012) {
 						console.log("连接超时,请重试!");
 						uni.showToast({
-							title: '连接失败,请重试',
+							title: '连接失败,设备无响应,请重试。',
 							icon: 'none',
-							duration: 2000,
+							duration: 3000,
 							mask: true
 						})
 					} else if (fail.errCode === 10013) {
@@ -1452,15 +1478,15 @@ const store = new Vuex.Store({
 				getSuccess = null
 			} = context;
 			this.commit("B_CreateBLEConnection", {
-				item:item,
-				success:success => {
+				item: item,
+				success: success => {
 					state.BLEConnectDevice = item;
 					state.bConnection = true;
 					if (getSuccess) {
 						getSuccess();
 					}
 				},
-				fail:fail => {
+				fail: fail => {
 					if (fail.errCode === 10012) {
 						console.log("连接超时,请重试!");
 						uni.showToast({
@@ -1508,9 +1534,9 @@ const store = new Vuex.Store({
 				success = null,
 			} = context;
 			this.commit("B_GetBLEDeviceServices", {
-				item:item,
-				callback:success,
-				getServiceList:(serviceList) => {
+				item: item,
+				callback: success,
+				getServiceList: (serviceList) => {
 					state.BLEGetServices = serviceList;
 				}
 			})
@@ -1527,8 +1553,8 @@ const store = new Vuex.Store({
 				state.BLERSSIInterval = null;
 			}
 			this.commit("B_CloseBLEConnection", {
-				deviceId:state.BLEConnectDevice.deviceId,
-				success:() => {
+				deviceId: state.BLEConnectDevice.deviceId,
+				success: () => {
 					state.cIndex = -1;
 					state.BLEConnectDevice = null;
 					//蓝牙服务
@@ -1564,7 +1590,7 @@ const store = new Vuex.Store({
 
 			this.commit("B_CloseBLEConnection", {
 				deviceId: state.BLEConnectDevice.deviceId,
-				success:() => {
+				success: () => {
 					state.cIndex = -1;
 					state.BLEConnectDevice = null;
 					//蓝牙服务
@@ -1609,7 +1635,12 @@ const store = new Vuex.Store({
 				state.instructionState.bSteps = false;
 			}
 			let retryCount = 4;
-			this.commit("B_WriteBLECharacteristicValue",{value, retryCount, getSuccess, getFail});
+			this.commit("B_WriteBLECharacteristicValue", {
+				value,
+				retryCount,
+				getSuccess,
+				getFail
+			});
 		},
 		//获取距离
 		onGetRSSITransDistance(state, context) {
@@ -1871,10 +1902,11 @@ const store = new Vuex.Store({
 			this.commit('initBLEData');
 			state.deviceId = item.deviceId;
 			let timeout = 10000;
+			console.log("B_CreateBLEConnection deviceId ==", state.deviceId)
 			uni.createBLEConnection({
 				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
 				deviceId: state.deviceId,
-				timeout,
+				timeout: timeout,
 				success: res => {
 					if (success) {
 						success(res);
@@ -1908,8 +1940,8 @@ const store = new Vuex.Store({
 					if (serviceList.length == 0) {
 						uni.hideToast();
 						uni.showModal({
-							title: '失败',
-							content: '获取服务失败,请尝试重新连接对应的模式。'
+							title: '提示',
+							content: '获取服务失败,请尝试重新连接。'
 						})
 					}
 					if (getServiceList) {
@@ -1921,8 +1953,8 @@ const store = new Vuex.Store({
 							state.serviceId = service.uuid;
 							//开始获取指定服务的特征值
 							_self.commit('B_GetBLEDeviceCharacteristics', {
-								item:item,
-								callback:callback
+								item: item,
+								callback: callback
 							});
 							break;
 						}
@@ -1955,7 +1987,7 @@ const store = new Vuex.Store({
 					if (item.PRIMARY_NOTIFY != '') {
 						state.notifyCharacteristicId = item.PRIMARY_NOTIFY;
 						this.commit('B_NotifyBLECharacteristicValueChange', {
-							callback:callback
+							callback: callback
 						});
 					}
 					if (item.PRIMARY_WRITE != '') {
@@ -1983,7 +2015,7 @@ const store = new Vuex.Store({
 				characteristicId: state.notifyCharacteristicId,
 				success: (res) => {
 					this.commit('B_OnBLECharacteristicValueChange', {
-						callback:callback
+						callback: callback
 					});
 					// _self.onBLECharacteristicValueChange(callback); //监听特征值变化
 				},
@@ -2202,6 +2234,139 @@ const store = new Vuex.Store({
 					console.log("关闭蓝牙失败", fail);
 				}
 			});
+		},
+
+
+		//获取手机中蓝牙已匹配的设备
+		B_GetBondedDevices(state, context) {
+			// console.log("getBondedDevices ====>");
+			// 	uni.getBluetoothDevices({
+			// 		success(res) {
+			// 			console.log("getBluetoothDevices:", res)
+			// 		}
+			// 	})
+
+			// 	uni.getConnectedBluetoothDevices({
+			// 		success(res) {
+			// 			console.log("getConnectedBluetoothDevices:", res)
+			// 		}
+			// 	})
+			let {
+				success = null
+			} = context;
+
+			function bluetooth_list(deviceName) {
+				var main = plus.android.runtimeMainActivity();
+				var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
+				var BAdapter = BluetoothAdapter.getDefaultAdapter();
+				var Context = plus.android.importClass("android.content.Context");
+				var lists = BAdapter.getBondedDevices();
+				plus.android.importClass(lists);
+				var len = lists.size();
+				// console.log("getBondedDevices.len=" + len);
+				if (len == 0) {
+					//如果没有配对的设备
+					return null;
+				} else {
+					var iterator = lists.iterator();
+					plus.android.importClass(iterator);
+					while (iterator.hasNext()) {
+						var d = iterator.next();
+						plus.android.importClass(d);
+						let temp = null;
+						//
+						if (d.getName().indexOf(deviceName) > -1) {
+							// console.log(d.getName());
+							// console.log(d.getAddress());
+							// Classic	1	
+							// Dual	3	
+							// Le	2	
+							// Unknown	0
+							// console.log(d.getType());
+							// Bonded	12
+							// Bonding	11	Indicates bonding (pairing) is in progress with the remote device.
+							// None	10
+							// console.log(d.getBondState());
+							let typeEnum = {
+								0: 'Unknown',
+								1: 'Classic',
+								2: 'Le',
+								3: 'Dual'
+							};
+							let bondStateEnum = {
+								10: 'None',
+								11: 'Bonding',
+								12: 'Bonded'
+							};
+							temp = {
+								name: d.getName(),
+								address: d.getAddress(),
+								type: {
+									'value': d.getType(),
+									'name': typeEnum[d.getType()]
+								},
+								bondState: {
+									'value': d.getBondState(),
+									'name': bondStateEnum[d.getBondState()]
+								}
+							}
+
+						}
+						return temp;
+					}
+				}
+
+
+			}
+			let device = null;
+
+			switch (plus.os.name) {
+				case "Android":
+					// Android平台: plus.android.*  
+					device = bluetooth_list("BGBox");
+					console.log("getBondedDevices 匹配的对象======>", device)
+					if (device != null) {
+						state.bPhoneMatched = true;
+					} else {
+						state.bPhoneMatched = false;
+					}
+
+					break;
+				case "iOS":
+					// iOS平台: plus.ios.*  
+					break;
+				default:
+					// 其它平台  
+					break;
+			}
+			if (success) {
+				success(device);
+			}
+		},
+
+		B_OpenBLESetting() {
+			function bluetooth_setting() {
+				var main = plus.android.runtimeMainActivity(); //获取activity  
+				var Intent = plus.android.importClass('android.content.Intent');
+				var Settings = plus.android.importClass('android.provider.Settings');
+				var intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); //可设置表中所有Action字段  
+				main.startActivity(intent);
+			}
+			let device = null;
+
+			switch (plus.os.name) {
+				case "Android":
+					// Android平台: plus.android.*  
+					bluetooth_setting();
+					break;
+				case "iOS":
+					// iOS平台: plus.ios.*  
+					break;
+				default:
+					// 其它平台  
+					break;
+			}
+
 		}
 	}
 })