├── .idea └── vcs.xml └── blueDevice.md /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /blueDevice.md: -------------------------------------------------------------------------------- 1 | #使用mpvue 开发小程序过程中 简单介绍一下微信小程序蓝牙连接过程 2 | #在蓝牙连接的过程中部分api需要加定时器延时1秒到2秒左右再执行,原因为何不知道,小程序有这样的要求 3 | #1.首先是要初始化蓝牙:openBluetoothAdapter() 4 | ```js 5 | if (wx.openBluetoothAdapter) { 6 | wx.openBluetoothAdapter({ 7 | success: function(res) { 8 | /* 获取本机的蓝牙状态 */ 9 | setTimeout(() => { 10 | getBluetoothAdapterState() 11 | }, 1000) 12 | }, 13 | fail: function(err) { 14 | // 初始化失败 15 | } 16 | }) 17 | } else { 18 | 19 | } 20 | ``` 21 | 22 | #2.检测本机蓝牙是否可用: 23 | # 要在上述的初始化蓝牙成功之后回调里调用 24 | ```js 25 | getBluetoothAdapterState() { 26 | var that = this; 27 | that.toastTitle = '检查蓝牙状态' 28 | wx.getBluetoothAdapterState({ 29 | success: function(res) { 30 | startBluetoothDevicesDiscovery() 31 | }, 32 | fail(res) { 33 | console.log(res) 34 | } 35 | }) 36 | } 37 | ``` 38 | 39 | #3. 开始搜索蓝牙设备: 40 | ```js 41 | startBluetoothDevicesDiscovery() { 42 | var that = this; 43 | setTimeout(() => { 44 | wx.startBluetoothDevicesDiscovery({ 45 | success: function(res) { 46 | /* 获取蓝牙设备列表 */ 47 | that.getBluetoothDevices() 48 | }, 49 | fail(res) { 50 | } 51 | }) 52 | }, 1000) 53 | } 54 | ``` 55 | 56 | #4. 获取搜索到的蓝牙设备列表 57 | # /* that.deviceName 是获取到的蓝牙设备的名称, 因为蓝牙设备在安卓和苹果手机上搜到的蓝牙地址显示是不一样的,所以根据设备名称匹配蓝牙*/ 58 | ```js 59 | getBluetoothDevices() { 60 | var that = this; 61 | setTimeout(() => { 62 | wx.getBluetoothDevices({ 63 | services: [], 64 | allowDuplicatesKey: false, 65 | interval: 0, 66 | success: function(res) { 67 | if (res.devices.length > 0) { 68 | if (JSON.stringify(res.devices).indexOf(that.deviceName) !== -1) { 69 | for (let i = 0; i < res.devices.length; i++) { 70 | if (that.deviceName === res.devices[i].name) { 71 | /* 根据指定的蓝牙设备名称匹配到deviceId */ 72 | that.deviceId = that.devices[i].deviceId; 73 | setTimeout(() => { 74 | that.connectTO(); 75 | }, 2000); 76 | }; 77 | }; 78 | } else { 79 | } 80 | } else { 81 | } 82 | }, 83 | fail(res) { 84 | console.log(res, '获取蓝牙设备列表失败=====') 85 | } 86 | }) 87 | }, 2000) 88 | }, 89 | ``` 90 | #5.连接蓝牙 91 | # 匹配到的蓝牙设备ID 发送连接蓝牙的请求, 连接成功之后 应该断开蓝牙搜索的api,然后去获取所连接蓝牙设备的service服务 92 | ```js 93 | connectTO() { 94 | wx.createBLEConnection({ 95 | deviceId: deviceId, 96 | success: function(res) { 97 | that.connectedDeviceId = deviceId; 98 | /* 4.获取连接设备的service服务 */ 99 | that.getBLEDeviceServices(); 100 | wx.stopBluetoothDevicesDiscovery({ 101 | success: function(res) { 102 | console.log(res, '停止搜索') 103 | }, 104 | fail(res) { 105 | } 106 | }) 107 | }, 108 | fail: function(res) { 109 | } 110 | }) 111 | } 112 | ``` 113 | #6. 获取蓝牙设备的service服务,获取的serviceId有多个要试着连接最终确定哪个是稳定版本的service 获取服务完后获取设备特征值 114 | ```js 115 | getBLEDeviceServices() { 116 | setTimeout(() => { 117 | wx.getBLEDeviceServices({ 118 | deviceId: that.connectedDeviceId, 119 | success: function(res) { 120 | that.services = res.services 121 | /* 获取连接设备的所有特征值 */ 122 | that.getBLEDeviceCharacteristics() 123 | }, 124 | fail: (res) => { 125 | } 126 | }) 127 | }, 2000) 128 | }, 129 | ``` 130 | #7.获取蓝牙设备特征值 131 | # 获取到的特征值有多个,最后要用的事能读,能写,能监听的那个值的uuid作为特征值id, 132 | ```js 133 | getBLEDeviceCharacteristics() { 134 | setTimeout(() => { 135 | wx.getBLEDeviceCharacteristics({ 136 | deviceId: connectedDeviceId, 137 | serviceId: services[2].uuid, 138 | success: function(res) { 139 | for (var i = 0; i < res.characteristics.length; i++) { 140 | if ((res.characteristics[i].properties.notify || res.characteristics[i].properties.indicate) && 141 | (res.characteristics[i].properties.read && res.characteristics[i].properties.write)) { 142 | console.log(res.characteristics[i].uuid, '蓝牙特征值 ==========') 143 | /* 获取蓝牙特征值 */ 144 | that.notifyCharacteristicsId = res.characteristics[i].uuid 145 | // 启用低功耗蓝牙设备特征值变化时的 notify 功能 146 | that.notifyBLECharacteristicValueChange() 147 | } 148 | } 149 | }, 150 | fail: function(res) { 151 | } 152 | }) 153 | }, 1000) 154 | }, 155 | ``` 156 | #8.启动notify 蓝牙监听功能 然后使用 wx.onBLECharacteristicValueChange用来监听蓝牙设备传递数据 157 | #接收到的数据和发送的数据必须是二级制数据, 页面展示的时候需要进行转换 158 | ```js 159 | notifyBLECharacteristicValueChange() { // 启用低功耗蓝牙设备特征值变化时的 notify 功能 160 | var that = this; 161 | console.log('6.启用低功耗蓝牙设备特征值变化时的 notify 功能') 162 | wx.notifyBLECharacteristicValueChange({ 163 | state: true, 164 | deviceId: that.connectedDeviceId, 165 | serviceId: that.notifyServicweId, 166 | characteristicId: that.notifyCharacteristicsId, 167 | complete(res) { 168 | /*用来监听手机蓝牙设备的数据变化*/ 169 | wx.onBLECharacteristicValueChange(function(res) { 170 | /**/ 171 | that.balanceData += that.buf2string(res.value) 172 | that.hexstr += that.receiveData(res.value) 173 | }) 174 | }, 175 | fail(res) { 176 | console.log(res, '启用低功耗蓝牙设备监听失败') 177 | that.measuringTip(res) 178 | } 179 | }) 180 | }, 181 | 182 | /*转换成需要的格式*/ 183 | buf2string(buffer) { 184 | var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x) 185 | return arr.map((char, i) => { 186 | return String.fromCharCode(char); 187 | }).join(''); 188 | }, 189 | receiveData(buf) { 190 | return this.hexCharCodeToStr(this.ab2hex(buf)) 191 | }, 192 | /*转成二进制*/ 193 | ab2hex (buffer) { 194 | var hexArr = Array.prototype.map.call( 195 | new Uint8Array(buffer), function (bit) { 196 | return ('00' + bit.toString(16)).slice(-2) 197 | } 198 | ) 199 | return hexArr.join('') 200 | }, 201 | /*转成可展会的文字*/ 202 | hexCharCodeToStr(hexCharCodeStr) { 203 | var trimedStr = hexCharCodeStr.trim(); 204 | var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr; 205 | var len = rawStr.length; 206 | var curCharCode; 207 | var resultStr = []; 208 | for (var i = 0; i < len; i = i + 2) { 209 | curCharCode = parseInt(rawStr.substr(i, 2), 16); 210 | resultStr.push(String.fromCharCode(curCharCode)); 211 | } 212 | return resultStr.join(''); 213 | }, 214 | ``` 215 | # 向蓝牙设备发送数据 216 | ```js 217 | sendData(str) { 218 | let that = this; 219 | let dataBuffer = new ArrayBuffer(str.length) 220 | let dataView = new DataView(dataBuffer) 221 | for (var i = 0; i < str.length; i++) { 222 | dataView.setUint8(i, str.charAt(i).charCodeAt()) 223 | } 224 | let dataHex = that.ab2hex(dataBuffer); 225 | this.writeDatas = that.hexCharCodeToStr(dataHex); 226 | wx.writeBLECharacteristicValue({ 227 | deviceId: that.connectedDeviceId, 228 | serviceId: that.notifyServicweId, 229 | characteristicId: that.notifyCharacteristicsId, 230 | value: dataBuffer, 231 | success: function (res) { 232 | console.log('发送的数据:' + that.writeDatas) 233 | console.log('message发送成功') 234 | }, 235 | fail: function (res) { 236 | }, 237 | complete: function (res) { 238 | } 239 | }) 240 | }, 241 | ``` 242 | # 当不需要连接蓝牙了后就要关闭蓝牙,并关闭蓝牙模块 243 | ```js 244 | // 断开设备连接 245 | closeConnect() { 246 | if (that.connectedDeviceId) { 247 | wx.closeBLEConnection({ 248 | deviceId: that.connectedDeviceId, 249 | success: function(res) { 250 | that.closeBluetoothAdapter() 251 | }, 252 | fail(res) { 253 | } 254 | }) 255 | } else { 256 | that.closeBluetoothAdapter() 257 | } 258 | }, 259 | // 关闭蓝牙模块 260 | closeBluetoothAdapter() { 261 | wx.closeBluetoothAdapter({ 262 | success: function(res) { 263 | }, 264 | fail: function(err) { 265 | } 266 | }) 267 | }, 268 | ``` 269 | #在向蓝牙设备传递数据和接收数据的过程中,并未使用到read的API 不知道有没有潜在的问题,目前线上运行为发现任何的问题 270 | #今天的蓝牙使用心得到此结束,谢谢 271 | --------------------------------------------------------------------------------