1. Enable Bluetooth adapter (Wx. openBluetoothAdapter(Object Object))

2. Obtain the status of bluetooth adapter to determine whether bluetooth is available. (wx. GetBluetoothAdapterState (Object Object))

3, open the scan bluetooth devices (wx startBluetoothDevicesDiscovery Object (Object))

4, get bluetooth device list (wx.getbluetoothDevices (Object Object))

5. Connect a discovered device (wx.CreateBleconnection (Object Object))

6, to stop search the bluetooth devices (wx. StopBluetoothDevicesDiscovery (Object Object))

7. Get Bluetooth Device services (wx.GetBleDeviceservices (Object Object))

All the eigenvalues of 8, access to services (wx. GetBLEDeviceCharacteristics (Object Object))

9, enabling response characteristic value changes (wx notifyBLECharacteristicValueChange (Object Object))

10, receiving bluetooth returns information (wx onBLECharacteristicValueChange (function callback))

11, send information (wx. WriteBLECharacteristicValue (Object Object)))

12. Disconnect bluetooth device (wx.closeBLEConnection(Object Object))

For details of bluetooth related API functions, see wechat official development document: Official low power Bluetooth interface API functions;

Small program bluetooth automatic connection

1 Initialize bluetooth of the mobile phone

After initialization, add whether monitoring Bluetooth will be disconnected abnormally. Monitoring Bluetooth will be disconnected due to the distance, mobile phone Bluetooth shutdown and other circumstances. Only after the initialization is successful can the listening bluetooth be disconnected successfully

initBlue() { var that = this; Wx. openBluetoothAdapter({// call wechat apics to openBluetoothAdapter interface success: function (res) { that.countdown() that.getTheBlueDisConnectWithAccident(); FindBlue () that.setData({isBloothOpen:20}) that.monitortheblue (); }, fail: function (res) {if(thate.data.isfirestshow){wx.showtoast ({title: 'Please turn on Bluetooth ', icon: 'Fails ', duration: 3000,})} that.setdata ({remaiderString:' wait for connection ', connectionEquipment: }) console.log(res) console.log(" Bluetooth is enabled "); setTimeout(function () { that.initBlue(); }, 3000)}})}, copy codeCopy the code

2 Monitor the bluetooth switch of the mobile phone to determine whether the bluetooth of the mobile phone is enabled

Check whether bluetooth is turned on

// monitorTheBlue:function(){var that =this; wx.onBluetoothAdapterStateChange(function(res){ console.log(`adapterState changed, now is`, Res) if (res.available){that.setData({isBloothOpen: 20, connectionEquipment: 'Please open the device and close to the phone ',}) wx.showtoast ({title: 'Bluetooth enabled ', icon:' Fails ', duration: 3000,})}else{that.setdata ({remaiderString: 'Waiting for connection ', connectionEquipment: 'Please turn on your phone bluetooth first and wait to connect to the analyzer ', isBloothOpen: 10, isFirestShow: false,}) wx.showToast({title:' Bluetooth is off ', icon: 'Fails ', duration: 3000,})}})}, copy the codeCopy the code

3 Start to obtain a nearby Bluetooth device

Get the bluetooth device you want to connect to by using the Bluetooth specific name. Gets an array of nearby Bluetooth devices

findBlue() { var that = this wx.startBluetoothDevicesDiscovery({ allowDuplicatesKey: false, interval: 0, success: function (res) { if(that.data.isFirestShow){ wx.showLoading({ title: 'searching devices'})} that. GetBlue () / / 3.0 / / that stopFindBlue ()}, complete: function () {},}}), copy the codeCopy the code

4 Search for and obtain all Nearby Bluetooth devices Obtain information about all nearby Bluetooth devices Obtain the deviceID of the Bluetooth device to be connected

BluetoothDeviceName and localName to determine bluetooth. Generally according to the name of the equipment to connect the name of the equipment is set by the manufacturer

getBlue() { var that = this wx.getBluetoothDevices({ success: function (res) { wx.hideLoading(); console.log(res); var index = 10 for (var i = 0; i < res.devices.length; i++) { if(res.devices[i].name && res.devices[i].localName){ var arr = res.devices[i].name.split("-") var secArr = res.devices[i].localName.split("-") if (arr[0] == that.data.bluetoothDeviceName || secArr[0] == that.data.bluetoothDeviceName) { console.log(that.data.bluetoothDeviceName); index = 20 that.setData({ deviceId: res.devices[i].deviceId, devices: res.devices, connectionEquipment: 'Connected to device:' + res.devices[I]. LocalName + 'Please start measuring ', remaiderString: 'Measuring ',}) console.log(" device: "+ res.devices[I].deviceid + tha.data.deviceid); that.connetBlue(); //4.0}} if(index == 10){if(that.data.isfirestshow){that.showfailreminder (" No matching device ")} that. ConnectionEquipment: 'Please turn on the device and close to the phone ', remaiderString:' Wait for connection ',})}}, fail: Function () {if (that.data.isfirestShow) {that.showfailreminder (" no matching device ")} that.setData({connectionEquipment: RemaiderString: 'Wait for connection ',})}, complete:function(){that.setData({isFirestShow:false,})},})Copy the code

5 Connect a Bluetooth device

Connect to Bluetooth through deviceId

connetBlue(deviceId) { var that = this; Wx. createBLEConnection({// deviceId must already be connected to the device by createBLEConnection deviceId: Function (res) {that. SetData ({remaiderString: 'measuring ',}) wx.showtoast ({title: 'connected ', icon: 'success', duration: 1000}) var isConnect = that.data.isconnected; If (isConnect == 10){that.getServiceId()//5.0 that.setData({isConnected:20,})}, fail:function(res){},})}Copy the code

6 After the required Bluetooth device is connected, obtain the service UUID of the Bluetooth device

Obtain the UUID of the device

GetServiceId () {var that = this wx.getbleDeviceservices ({// deviceId must have been linked to the device through createBLEConnection deviceId: that.data.deviceId, success: function (res) { var model = res.services[1] console.log(res) that.setData({ servicesUUID: I should show the characteid () of the modelCopy the code

7 If a Bluetooth device needs to write and transmit data, it must have certain characteristic values. Therefore, you can view the characteristic values of the current Bluetooth device using the ID obtained in the preceding steps

Notify Write Read Only when the notify value is true, data can be received from the Bluetooth device. Only when the write value is true, data can be received. Only when the read value is true, data can be read from the device

GetCharacteId () {var that = this wx. GetBLEDeviceCharacteristics ({/ / deviceId need here has been through createBLEConnection establish links with the corresponding equipment DeviceId: that.data.deviceId, // The serviceId needs to be retrieved from the getBLEDeviceServices interface above: deviceId: that.data.deviceId, // The serviceId needs to be retrieved from the getBLEDeviceServices interface above: that.data.servicesUUID, success: function (res) { console.log(res); for (var i = 0; i < res.characteristics.length; If (typic.properties. Notify == true) {if (typic.properties. Notify == true) {if (typic.properties. Model.uuid // listen to the value}) that.startNotice(model.uuid)//7.0} if (model.properties. Read == true) {that.readdata (model.uuid)} If (model.properties.write == true) {that.setData({writeId: model.uuid// Write value})}}}})}, copy the codeCopy the code

8 If a Bluetooth device needs to write and transmit data, it must have some characteristic values. Therefore, you can view the characteristic values of the current Bluetooth device using the ID obtained in the preceding steps

Enable device data Listener To listen for data returned by bluetooth device

startNotice(uuid) { var that = this; Wx. NotifyBLECharacteristicValueChange ({state: true, / / enable deviceId notify function: that the data. The deviceId, serviceId: // The value of the notityID must contain a particular value, and the value of the notityID must contain a particular value. The function (res) {/ / equipment return method wx. OnBLECharacteristicValueChange (function (res) {the console. The log (res + "bluetooth test data returned by the" + res.value); var nonceId = that.ab2hex(res.value) } setTimeout(function () { that.setData({ isDeleteRepetition: 100, }) }, 20000) }) }, fail: function (res) { console.log(res); }})}, /** * convert ArrayBuffer to string */ ab2hex(buffer) {var hexArr = array.prototype.map. call(new Uint8Array(buffer), function (bit) { return ('00' + bit.toString(16)).slice(-2) } ) return hexArr.join(''); }, copy the codeCopy the code

10 The listener is interrupted abnormally

Start the timer again when the Bluetooth device is abnormally disconnected. Note that the return flag of android and iOS is not exactly the same. Use res.connected to return value to determine whether bluetooth is connected

/ / to monitor whether the bluetooth device will be abnormal disconnect getTheBlueDisConnectWithAccident: function (e) {var that = this; wx.onBLEConnectionStateChange(function (res) { console.log(res) if (! res.connected){ wx.closeBluetoothAdapter({ success: function(res) { wx.openBluetoothAdapter({ success: function(res) { }, }) }, }) that.setData({ showBacGroundImageView: '.. /.. /images/[email protected]',// background image remaiderString: "Waiting for connection ", ishindden: true, isSugarHidden: true, isConnected: 10, isFirestShow: false, testResultIndex: 0,}) that.countdown()// Enable timer}})}, duplicate codeCopy the code

11 Abnormal disconnection Starts again

I used to initialize Bluetooth again. The previous thought just continued to search for Bluetooth devices, but I found that the returned value was always the same. For example, the bluetooth of the device was turned off, but the original device still existed in the device array but could not be connected

// countdown: function() {var that = this; that.init(that); Var time = that.data.time; var time = that.data.time; Console. log(" start countdown ") var interval = setInterval(function () {time--; SetData ({time: time}) if (time == 0) {var countId = that.data.isconnected; if(countId == 10){ that.restartTap(); That.findblue ()} if(countId == 20){that.clearTimeInterval()}}, 1000) that.setData({interval: interval})}, copy codeCopy the code

Let’s go straight to the complete code

<template>
	<view class="">
		<view style="padding: 20rpx;font-size: 30rpx;">
			<view style="font-size: 34rpx;">测试结果:</view>
			<view>{{showtext}}</view>
		</view>
		<view>
			<view style="padding: 20rpx;font-size: 36rpx;">蓝牙设备列表:</view>
			<view v-for="(item,index) in infolist" :key="index" @tap="BLEConnect(item.deviceId)"
				style="padding: 20rpx;font-size: 36rpx;border-bottom: 1px solid #C0C0C0;">
				{{item.name}}
			</view>
		</view>
	</view>
</template>
<script>
        export default {
		data() {
			return {
				infolist: [],
				delayTimer: null,
				servicesUUID: '',
				deviceId: '',
				characteristicId: '',
				writeId: '',
				isDeleteRepetition: '',
				modeluuid: [],
				showtext: '',
				ACPC: ''
			}
		},
		onLoad() {},
		onShow() {
			this.BLEInit()
		},
		methods: {

			/****************1.蓝牙初始化***************/
			BLEInit(event) {
				var that = this;
				uni.openBluetoothAdapter({
					success: function(res) {
						wx.getBluetoothAdapterState({
							success: function(res) {
								// 初始化成功后调用搜索蓝牙方法
								that.Search()
								//打印相关信息
								console.log(JSON.stringify(res.errMsg) + "\n蓝牙是否可用:" + res
									.available);
							},

							fail: function(res) {
								//打印相关信息
								console.log(JSON.stringify(res.errMsg) + "\n蓝牙是否可用:" + res
									.available);
							}
						})
					},
					fail: function(res) {
						wx.showToast({
							title: '手机蓝牙未开启',
							icon: 'none',
							duration: 2000
						})
					}
				})
			},
			// 搜索蓝牙
			Search() {
				var that = this;
				wx.startBluetoothDevicesDiscovery({
					services: ['0000FFE0'], //限定蓝牙搜索类型  避免搜索到没有用的蓝牙 
					success(res) {
						wx.showLoading({
							title: '正在搜索设备',
						})
						//定时没两秒刷新一次搜索列表
						var delayTimer = setInterval(function() {
							that.findBlue();
						}, 2000);
						that.delayTimer = delayTimer
					},
					fail() {
						that.closeFindBlue();
					}
				})
			},
			// 搜索列表
			findBlue() {
				var that = this;
				wx.getBluetoothDevices({
					success: function(res) {
						var deviceNum = 0;
						if (res.devices && (deviceNum = res.devices.length) >= 1) {
							console.log("搜索设备数量:", res)
							that.infolist = res.devices
							// 这里我设置的是搜索到一个蓝牙时就调用关闭搜索蓝牙方法
							if (that.infolist.length > 0) {
								setTimeout(() => {
									that.closeFindBlue()
								}, 1500)
							}
						}
					}
				})
			},
			// 连接蓝牙 
			BLEConnect(deviceId) {
				var that = this;
				wx.setStorageSync('deviceId', that.deviceId)
				that.deviceId = deviceId
				that.closeFindBlue()
				wx.showLoading({
					title: '正在连接',
				})
				wx.createBLEConnection({
					timeout: 10000,
					deviceId: that.deviceId,
					success: function(res) {
						that.closeFindBlue()
						setTimeout(() => {
							wx.showToast({
								title: '连接成功'
							});
						}, 600)
						//获取设备的uuid
						that.getServiceId()
					},
					fail: function() {
						wx.hideLoading()
						wx.showToast({
							title: '无法连接此设备',
							icon: 'none',
							duration: 2000
						})
					},
				})
			},
			// 停止搜索
			closeFindBlue() {
				var that = this;
				clearInterval(that.delayTimer);
				wx.stopBluetoothDevicesDiscovery({
					success: function(res) {
						wx.hideLoading()
					}
				})
			},
			//获取设备的uuid
			getServiceId() {
				var that = this
				wx.getBLEDeviceServices({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: that.deviceId,
					success: function(res) {
						var model = res.services[0]
						that.servicesUUID = model.uuid
						console.log(that.servicesUUID, 'that.servicesUUID')
						that.getCharacteId() //6.0

					}
				})
			},
			getCharacteId() {
				var that = this
				wx.getBLEDeviceCharacteristics({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.servicesUUID,
					success: function(res) {
						console.log(res);
						for (var i = 0; i < res.characteristics.length; i++) { //2个值
							var model = res.characteristics[i]
							if (model.properties.notify == true) {
								that.characteristicId = model.uuid //监听的值
								that.startNotice(model.uuid)
							}
							if (model.properties.read == true) {
								that.modeluuid = model.uuid
							}
							if (model.properties.write == true) {
								that.writeId = model.uuid //用来写入的值
							}
						}
					}
				})
			},

			startNotice(uuid) {
				var that = this;
				that.BLEDataSend()
				wx.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: that.deviceId,
					serviceId: that.servicesUUID,
					characteristicId: uuid, //第一步 开启监听 notityid  第二步发送指令 write
					success: function(res) {
						// 蓝牙设备返回的数据
						wx.onBLECharacteristicValueChange(function(res) {
							var nonceId = that.ab2hex(res.value)
							console.log(nonceId, '蓝牙返回数据')
							if (nonceId == 'f5a05008b000009d') {
								wx.showToast({
									title: '插入试纸',
									icon: 'none'
								});
							}
							if (nonceId == 'f5a05008b2aa519a') {
								wx.showToast({
									title: '当前试纸已经使用过',
									icon: 'none'
								});
							}
							if (nonceId == 'f5a05008b40000a1') {
								wx.showToast({
									title: '请滴入血液',
									icon: 'none'
								});
							}
							if (nonceId == 'f5a05008ba0000a7') {
								wx.showToast({
									title: '机器已关闭'
								});
							}
							if (nonceId.length == 30) {
								//把字符串分割成每两个数字一个数组
								const arr = that.stringsplit(nonceId)
								let year = that.hex2int(arr[5])
								let mon = that.hex2int(arr[6])
								let date = that.hex2int(arr[7])
								let hour = that.hex2int(arr[8])
								let min = that.hex2int(arr[9])
								let sec = that.hex2int(arr[10])
								let mg = that.hex2int(arr[11] + arr[12])
								var nummg = parseInt(mg) / 18;
								let toFixedmg = nummg.toFixed(1)
								switch (arr[13]) {
									case '00':
										that.ACPC = 'GC'
										break
									case '01':
										that.ACPC = 'AC'
										break
									case '02':
										that.ACPC = 'PC'
										break
									case '03':
										that.ACPC = 'CTRL'
										break
								}
								that.showtext =
									`${'20' + year +'年'}${ mon +'月'}${ date +'日'}${ hour +'时'}${min +'分'}${sec +'秒'}${'测试血糖数据'+ toFixedmg + 'mg/' + that.ACPC }`
							}
						})
					},
					fail: function(res) {
						console.log(res);
					}
				})
			},

			BLEDataSend() {
				var that = this
				console.log('要发送的信息是:')
				var hex = 'F5 A0 50 08 B0 00 00 9D'
				var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				}))
				var buffer = typedArray.buffer
				console.log(that.deviceId, 'deviceId')
				console.log(that.servicesUUID, 'servicesUUID')
				console.log(that.characteristicId, 'characteristicId')
				console.log(buffer, 4444)

				wx.writeBLECharacteristicValue({
					deviceId: that.deviceId,
					serviceId: that.servicesUUID,
					characteristicId: that.characteristicId,
					// 这里的value是ArrayBuffer类型
					value: buffer,
					success: function(res) {
						console.log('写入成功', res.errMsg)
					},
					fail(res) {
						console.log('写入失败', res.errMsg)
					}
				})
			},
			/**
			 * 将ArrayBuffer转换成字符串
			 */
			ab2hex(buffer) {
				var hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('');
			},
			// 将字符串转为每两个字符一个数组
			stringsplit(nonceId) {
				var bbb = [...nonceId];
				var ccc = nonceId.split('');
				var a, b;
				var aIndex = 0;
				var bIndex = 1;
				var arr = [];
				bbb.forEach((str, index) => {
					if (index % 2 === 0) {
						a = str;
						aIndex += 1
					} else {
						b = str
						bIndex += 1
					}
					if (a && b && (bIndex - aIndex === 1)) {
						arr.push(a + b)
					}
				});
				return arr
			},
			// 16进制转10
			hex2int(hex) {
				var len = hex.length,
					a = new Array(len),
					code;
				for (var i = 0; i < len; i++) {
					code = hex.charCodeAt(i);
					if (48 <= code && code < 58) {
						code -= 48;
					} else {
						code = (code & 0xdf) - 65 + 10;
					}
					a[i] = code;
				}
				return a.reduce(function(acc, c) {
					acc = 16 * acc + c;
					return acc;
				}, 0);
			},
		}
	}
</script>

<style>

</style>
复制代码
Copy the code

You can also refer to the link below

Blog.csdn.net/weixin_4362…

  • Firstly, the bluetooth is initialized to detect whether the Bluetooth is available. When the Bluetooth is available, the search starts. When the Bluetooth is not available, the user is prompted that the Bluetooth is unavailable or to turn on the Bluetooth
  • If the UUID is used, only devices containing this UUID will be found. You are advised to leave this parameter blank at first
  • When our Bluetooth is searched, the stop search method will be called to end the search. // Connect bluetooth to get the deviceId of Bluetooth, and the connected device will be reminded that the connection is successful, and the UUID of the device will be obtained and saved
  • Obtain all characteristic values notify Write Read. Only when the notify value is true can data be received from the Bluetooth device. Only when the write value is true can data be transmitted to the device
  • The corresponding method in each feature, such as notify, receives data from bluetooth devices