bluetooth_connect.js 10.6 KB
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
// 连接模式蓝牙
var util = require('util.js')
var data = {
bioland_device_uuid: '00001000-0000-1000-8000-00805f9b34fb', // 血压uuid
list:[],
deviceIdStr: ''
}


var characteristic_write_uuid = '00001001-0000-1000-8000-00805F9B34FB' // 数据写入接口特征值
var service_write_uuid = '00001000-0000-1000-8000-00805F9B34FB' // 数据写入接口服务服务值
var characteristic_notify_uuid = '00001002-0000-1000-8000-00805F9B34FB' // 数据读取接口特征值
var service_notify_uuid = '00001000-0000-1000-8000-00805F9B34FB' // 数据读取接口服务值

var responseData = {
code: '',
status: '',
data: {}
}
var notOpenBle = false
var callBack;
var notification;

// 401蓝牙设备中断连接 201连接设备 200蓝牙状态成功 402连接失败

function openBluetooth(data, callBackFun){
var self = this
callBack = callBackFun
var system = wx.getSystemInfoSync()
if (system.platform == 'android'){
toLower()
}
responseData = {
code: '',
status: '',
data: {}
}
getBLEData()
wx.onBluetoothAdapterStateChange(function (res) {
// callback
if (res.available == false) {
notOpenBle = true
responseData.status = '设备蓝牙未开启'
responseData.code = '404'
callBack(responseData)
} else {
if (notOpenBle) {
responseData.code = '200'
getBLEData()
}
}
})
}

function getBLEData() {
console.log('获取蓝牙适配器')
wx.openBluetoothAdapter({
success: function (res) {
// success
notOpenBle = false
wx.getBluetoothAdapterState({
success: function (res) {
console.log('蓝牙适配器状态', res)
if (res.discovering == true) {
console.log('正在搜索')
foundDevice()
} else {
console.log('开始获取连接设备')
getConnectedDevice()
}
},
fail: function (res) {
responseData.status = '未能成功获取到蓝牙信息'
callBack(responseData)
console.log(res)
}
})
},
fail: function (res) {
console.log(res)
if (res.errMsg.indexOf("already opened") != -1) {
notOpenBle = false
wx.getBluetoothAdapterState({
success: function (res) {
if (res.discovering == true) {
console.log('正在搜索')
foundDevice()
} else {
console.log('开始获取连接设备')
getConnectedDevice()
}
}
})
console.log('初始化蓝牙适配器')
return
}
notOpenBle = true
responseData.status = '请检查蓝牙是否打开'
callBack(responseData)
}
})
}

// 获取已经连接的设备
function getConnectedDevice() {
var self = this
responseData.code = '200'
wx.getConnectedBluetoothDevices({
services: [data.bioland_device_uuid],
success: function (res) {
// success
console.log('获取之前已经连接的蓝牙', res)
if (res.devices.length == 0) {
console.log('之前没有设备连接,开始搜索')
searchDevices()
} else {
var currentDev;
if (res.deviceId) { // android
currentDev = res
} else if (res.devices) { // ios
currentDev = res.devices[0]
}
wx.closeBLEConnection({
deviceId: res.devices[0].deviceId,
success: function (res) {
console.log('断开之前已经连接的设备,开始搜索')
searchDevices()
},
})
}
},
fail: function (res) {
// fail
console.log('获取已经连接蓝牙失败', res)
searchDevices()
},
complete: function (res) {
// complete
}
})
}

// 搜索设备
function searchDevices(){
var self = this
wx.startBluetoothDevicesDiscovery({
services: [data.bioland_device_uuid],
success: function (res) {
// success
console.log(`开始搜索设备`, res)
foundDevice()
},
fail: function (res) {
// fail
responseData.status = '未能搜索到设备'
callBack(responseData)
console.log('搜索失败', res)
}
})
}

// 找到设备
function foundDevice(){
var self = this
responseData.status = '搜索设备中...'
responseData.code = '200'
callBack(responseData)
wx.onBluetoothDeviceFound(function (res) {
console.log('搜索到',res)
var same = false
var currentDev;
if (res.deviceId) { // android
currentDev = res
} else if (res.devices) { // ios
currentDev = res.devices[0]
}
for (var i = 0; i < data.list.length; i++) {
var item = data.list[i]
if (item.deviceId == currentDev.deviceId) {
same = true
}
}
if (!same) {
// var list = data.list
// list.push(currentDev)
responseData.data.currentDev = currentDev
callBack(responseData)
}
})
}

function addNotification(notificationFun){
notification = notificationFun
}

// 选择设备
function connectionDevice(deviceId, callbackFun){
var self = this
data.deviceIdStr = deviceId
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
console.log('成功停止搜索')
},
fail: function (res) {
console.log('未能成功停止搜索')
}
})
responseData.status = '开始连接设备'
callbackFun(responseData)
wx.createBLEConnection({
deviceId: data.deviceIdStr,
success: function (res) {
// success
console.log('成功连接')
getDeviceService()
},
fail: function (res) {
// fail
console.log('连接失败',res)
responseData.status = '未能连接到设备'
responseData.code = '402'
callbackFun(responseData)
}
})
}

function getDeviceService(){
var self = this
wx.getBLEDeviceServices({
deviceId: data.deviceIdStr,
success: function (res) {
// success
console.log('成功获取服务')
res.services.map(function (item) {
if (item.uuid == service_write_uuid || item.uuid.toLowerCase() == service_write_uuid) {
// 如果是大写 就全部转换成大写
if (util.checkIsContainCapital(item.uuid)) {
toCapital()
} else {
toLower()
}
getDeviceServiceCharacteristics(item.uuid)
}
})
},
fail: function (res) {
responseData.status = '未能连接到设备'
callBack(responseData)
}
})
wx.onBLEConnectionStateChanged(function (res) {
// 该方法回调中可以用于处理连接意外断开等异常情况
if (res.connected == false){
responseData.status = '设备连接已断开'
responseData.code = '401'
callBack(responseData)
}
console.log(`device ${res.deviceId} state has changed, connected: ${res}`)
})
}

function getDeviceServiceCharacteristics(serviceId){
var self = this
wx.getBLEDeviceCharacteristics({
deviceId: data.deviceIdStr,
serviceId: serviceId,
success: function (res) {
// success
console.log('成功获取特征')
res.characteristics.map(function (item) {
if (item.uuid == characteristic_notify_uuid || item.uuid.toLowerCase() == characteristic_notify_uuid) {
console.log('打开监听',item)
openNotify()
}
responseData.code = '201'
responseData.status = '成功连接设备'
callBack(responseData)
})
}, fail: function (res) {
console.log('失败获取特征',res)
}
})
}
// 获取设备特征值信息
function getDeviceServiceCharacteristicsValue(serviceId, characteristicsUuid){
var self = this
wx.readBLECharacteristicValue({
deviceId: data.deviceIdStr,
serviceId: service_notify_uuid,
characteristicId: characteristic_notify_uuid,
success: function (res) {
// success
console.log('成功duqu特征')
},
fail: function (res) {
// fail
responseData.status = '未能获取到设备信息'
callBack(responseData)
}
})
wx.onBLECharacteristicValueChange(function (res) {
var dataStr = buf2hex(res.value)
if (dataStr) {
notification(dataStr)
}
// 55 0F 00 0A 00 01 00 00 64 00 00 00 00 00 D5
})
}

// 开启监听
function openNotify(){
var self = this
console.log(service_notify_uuid)
console.log(characteristic_notify_uuid)
wx.notifyBLECharacteristicValueChanged({
deviceId: data.deviceIdStr,
serviceId: service_notify_uuid,
characteristicId: characteristic_notify_uuid,
state: true,
success: function (res) {
},
fail: function (res) {
// fail
console.log('notifyBLECharacteristicValueChange fail --', res)
// responseData.status = '未能获取到设备信息'
callBack(responseData)
}
})
}

function writeDataWithStr(str){
var self = this
var typedArray = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
}))
var buffer = typedArray.buffer

wx.writeBLECharacteristicValue({
deviceId: data.deviceIdStr,
serviceId: service_write_uuid,
characteristicId: characteristic_write_uuid,
value: buffer,
success: function (res) {
// success
},
fail: function (res) {
// fail
},
complete: function (res) {
// complete
getDeviceServiceCharacteristicsValue()
}
})
}

function closeBLE() {
wx.stopBluetoothDevicesDiscovery({
complete: function (res) {
console.log('停止搜索', res)
},
})
wx.closeBLEConnection({
deviceId: data.deviceIdStr,
complete: function(res) {
console.log('断开该设备的蓝牙', res)
}
})
wx.closeBluetoothAdapter({
complete: function (res) {
console.log('关闭蓝牙', res)
},
})
}

function buf2hex(buffer) { // buffer is an ArrayBuffer
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}

function toCapital() {
characteristic_write_uuid = characteristic_write_uuid.toUpperCase()
service_write_uuid = service_write_uuid.toUpperCase()
characteristic_notify_uuid = characteristic_notify_uuid.toUpperCase()
service_notify_uuid = service_notify_uuid.toUpperCase()
}

function toLower() {
characteristic_write_uuid = characteristic_write_uuid.toLowerCase()
service_write_uuid = service_write_uuid.toLowerCase()
characteristic_notify_uuid = characteristic_notify_uuid.toLowerCase()
service_notify_uuid = service_notify_uuid.toLowerCase()
}


module.exports = {
writeDataWithStr: writeDataWithStr,
openBluetooth: openBluetooth,
connectionDevice: connectionDevice,
closeBLE: closeBLE,
addNotification: addNotification
}