@mpxjs/api-proxy 2.10.16-beta.7 → 2.10.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,815 +0,0 @@
1
- import BleManager from 'react-native-ble-manager'
2
- import { noop } from '@mpxjs/utils'
3
- import mpx from '@mpxjs/core'
4
- import { Platform, PermissionsAndroid } from 'react-native'
5
- import { base64ToArrayBuffer } from '../base/index'
6
-
7
- // BleManager 相关
8
- // 全局状态管理
9
- let bleManagerInitialized = false
10
- let DiscoverPeripheralSubscription = null
11
- let updateStateSubscription = null
12
- let discovering = false
13
- let getDevices = [] // 记录已扫描的设备列表
14
- const deviceFoundCallbacks = []
15
- const onStateChangeCallbacks = []
16
- const characteristicCallbacks = []
17
- const onBLEConnectionStateCallbacks = []
18
- let characteristicSubscriptions = {}
19
- const connectedDevices = new Set()
20
- let createBLEConnectionTimeout = null
21
- const BLEDeviceCharacteristics = {} // 记录已连接设备的特征值
22
- const connectedDeviceId = []
23
-
24
- // 请求蓝牙权限
25
- const requestBluetoothPermission = async () => {
26
- if (__mpx_mode__ === 'android') {
27
- const permissions = []
28
- if (Platform.Version >= 23 && Platform.Version < 31) {
29
- permissions.push(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION)
30
- } else if (Platform.Version >= 31) {
31
- permissions.push(
32
- PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
33
- PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT
34
- )
35
- }
36
-
37
- if (permissions.length === 0) {
38
- return true
39
- }
40
- const granted = await PermissionsAndroid.requestMultiple(permissions)
41
- return Object.values(granted).every(
42
- result => result === PermissionsAndroid.RESULTS.GRANTED
43
- )
44
- }
45
- return true
46
- }
47
-
48
- const removeBluetoothDevicesDiscovery = function () {
49
- if (DiscoverPeripheralSubscription) {
50
- DiscoverPeripheralSubscription.remove()
51
- DiscoverPeripheralSubscription = null
52
- }
53
- }
54
- const removeUpdateStateSubscription = function () {
55
- if (updateStateSubscription && onStateChangeCallbacks.length === 0 && onBLEConnectionStateCallbacks.length === 0) {
56
- updateStateSubscription.remove()
57
- updateStateSubscription = null
58
- }
59
- }
60
- const commonFailHandler = function (errMsg, fail, complete) {
61
- const result = {
62
- errMsg
63
- }
64
- if (!bleManagerInitialized) {
65
- Object.assign(result, {
66
- errCode: 10000,
67
- errno: 1500101
68
- })
69
- }
70
- fail(result)
71
- complete(result)
72
- }
73
-
74
- function openBluetoothAdapter (options = {}) {
75
- const { success = noop, fail = noop, complete = noop } = options
76
- let bluetoothPermission = requestBluetoothPermission
77
- if (__mpx_env__ === 'android' && mpx.rnConfig?.bluetoothPermission) { // 安卓需要验证权限,开放给用户可以自定义验证权限的方法
78
- bluetoothPermission = mpx.rnConfig.bluetoothPermission
79
- }
80
- // 先请求权限,再初始化蓝牙管理器
81
- bluetoothPermission().then((hasPermissions) => {
82
- if (!hasPermissions) {
83
- commonFailHandler('openBluetoothAdapter:fail no permission', fail, complete)
84
- return
85
- }
86
-
87
- if (bleManagerInitialized) {
88
- commonFailHandler('openBluetoothAdapter:fail already opened', fail, complete)
89
- return
90
- }
91
-
92
- BleManager.start({ showAlert: false }).then(() => {
93
- bleManagerInitialized = true
94
-
95
- // 检查蓝牙状态
96
- setTimeout(() => {
97
- BleManager.checkState().then((state) => {
98
- if (state === 'on') {
99
- const result = {
100
- errno: 0,
101
- errMsg: 'openBluetoothAdapter:ok'
102
- }
103
- success(result)
104
- complete(result)
105
- } else {
106
- commonFailHandler('openBluetoothAdapter:fail bluetooth not enabled', fail, complete)
107
- }
108
- }).catch((error) => {
109
- commonFailHandler('openBluetoothAdapter:fail ' + (typeof error === 'string' ? error : ''), fail, complete)
110
- })
111
- }, 1000)
112
- }).catch((error) => {
113
- commonFailHandler('openBluetoothAdapter:fail ' + (typeof error === 'string' ? error : ''), fail, complete)
114
- })
115
- }).catch(() => {
116
- commonFailHandler('openBluetoothAdapter:fail no permission', fail, complete)
117
- })
118
- }
119
-
120
- function closeBluetoothAdapter (options = {}) {
121
- const { success = noop, fail = noop, complete = noop } = options
122
- if (!bleManagerInitialized) {
123
- const result = {
124
- errMsg: 'closeBluetoothAdapter:fail 请先调用 wx.openBluetoothAdapter 接口进行初始化操作'
125
- }
126
- fail(result)
127
- complete(result)
128
- return
129
- }
130
- try {
131
- // 停止扫描
132
- if (discovering) {
133
- BleManager.stopScan()
134
- discovering = false
135
- }
136
-
137
- if (createBLEConnectionTimeout) { // 清除掉正在连接的蓝牙设备
138
- clearTimeout(createBLEConnectionTimeout)
139
- createBLEConnectionTimeout = null
140
- }
141
-
142
- removeUpdateStateSubscription()
143
- // 清理状态
144
- bleManagerInitialized = false
145
- discovering = false
146
- getDevices = []
147
- connectedDeviceId.length = 0
148
- connectedDevices.forEach((id) => {
149
- BleManager.disconnect(id).catch(() => {})
150
- })
151
- connectedDevices.clear()
152
- deviceFoundCallbacks.length = 0
153
- onStateChangeCallbacks.length = 0
154
- characteristicCallbacks.length = 0
155
- onBLEConnectionStateCallbacks.length = 0
156
- if (valueForCharacteristicSubscriptions) {
157
- valueForCharacteristicSubscriptions.remove()
158
- valueForCharacteristicSubscriptions = null
159
- }
160
-
161
- removeBluetoothDevicesDiscovery()
162
-
163
- // 清理订阅
164
- Object.keys(characteristicSubscriptions).forEach(key => {
165
- if (characteristicSubscriptions[key]) {
166
- characteristicSubscriptions[key].remove()
167
- }
168
- })
169
- characteristicSubscriptions = {}
170
-
171
- const result = {
172
- errMsg: 'closeBluetoothAdapter:ok'
173
- }
174
- success(result)
175
- complete(result)
176
- } catch (error) {
177
- const result = {
178
- errMsg: 'closeBluetoothAdapter:fail ' + error.message
179
- }
180
- fail(result)
181
- complete(result)
182
- }
183
- }
184
-
185
- function startBluetoothDevicesDiscovery (options = {}) {
186
- const {
187
- services = [],
188
- allowDuplicatesKey = false,
189
- success = noop,
190
- fail = noop,
191
- complete = noop
192
- } = options
193
-
194
- if (!bleManagerInitialized) {
195
- commonFailHandler('startBluetoothDevicesDiscovery:fail ble adapter hans\'t been opened or ble is unavailable.', fail, complete)
196
- return
197
- }
198
- DiscoverPeripheralSubscription = BleManager.onDiscoverPeripheral((device) => {
199
- const advertising = device.advertising || {}
200
- const advertisData = advertising.manufacturerData?.data || null
201
- const deviceInfo = {
202
- deviceId: device.id,
203
- name: device.name || advertising.localName || '未知设备',
204
- RSSI: device.rssi || 0,
205
- advertisData: advertisData ? base64ToArrayBuffer(advertisData) : advertisData, // todo需要转换
206
- advertisServiceUUIDs: advertising.serviceUUIDs || [],
207
- localName: advertising.localName || '',
208
- serviceData: advertising.serviceData || {},
209
- connectable: advertising.isConnectable || false
210
- }
211
- if (allowDuplicatesKey === false) {
212
- const existingDeviceIndex = getDevices.findIndex(existingDevice => existingDevice.deviceId === deviceInfo.deviceId)
213
- if (existingDeviceIndex > -1) {
214
- return
215
- }
216
- }
217
- deviceFoundCallbacks.forEach(cb => {
218
- cb({
219
- devices: [deviceInfo]
220
- })
221
- })
222
- getDevices.push(deviceInfo)
223
- // 处理设备发现逻辑
224
- })
225
- BleManager.scan(services, 0, allowDuplicatesKey).then((res) => { // 必须,没有开启扫描,onDiscoverPeripheral回调不会触发
226
- onStateChangeCallbacks.forEach(cb => {
227
- cb({
228
- available: true,
229
- discovering: true
230
- })
231
- })
232
- discovering = true
233
- getDevices = [] // 清空之前的发现设备列表
234
- const result = {
235
- errMsg: 'startBluetoothDevicesDiscovery:ok',
236
- isDiscovering: true
237
- }
238
- success(result)
239
- complete(result)
240
- }).catch((error) => {
241
- commonFailHandler('startBluetoothDevicesDiscovery:fail ' + (typeof error === 'string' ? error : ''), fail, complete)
242
- })
243
- }
244
-
245
- function stopBluetoothDevicesDiscovery (options = {}) {
246
- const { success = noop, fail = noop, complete = noop } = options
247
-
248
- if (!bleManagerInitialized) {
249
- commonFailHandler('stopBluetoothDevicesDiscovery:fail ble adapter hans\'t been opened or ble is unavailable.', fail, complete)
250
- return
251
- }
252
- removeBluetoothDevicesDiscovery()
253
- BleManager.stopScan().then(() => {
254
- discovering = false
255
- onStateChangeCallbacks.forEach(cb => {
256
- cb({
257
- available: true,
258
- discovering: false
259
- })
260
- })
261
- const result = {
262
- errMsg: 'stopBluetoothDevicesDiscovery:ok'
263
- }
264
- success(result)
265
- complete(result)
266
- }).catch((error) => {
267
- commonFailHandler('stopBluetoothDevicesDiscovery:fail ' + (typeof error === 'string' ? error : ''), fail, complete)
268
- })
269
- }
270
-
271
- function onBluetoothDeviceFound (callback) {
272
- if (deviceFoundCallbacks.indexOf(callback) === -1) {
273
- deviceFoundCallbacks.push(callback)
274
- }
275
- }
276
-
277
- function offBluetoothDeviceFound (callback) {
278
- const index = deviceFoundCallbacks.indexOf(callback)
279
- if (index > -1) {
280
- deviceFoundCallbacks.splice(index, 1)
281
- }
282
- }
283
-
284
- function getConnectedBluetoothDevices (options = {}) {
285
- const { services = [], success = noop, fail = noop, complete = noop } = options
286
-
287
- if (!bleManagerInitialized) {
288
- commonFailHandler('getConnectedBluetoothDevices:fail 请先调用 wx.openBluetoothAdapter 接口进行初始化操作', fail, complete)
289
- return
290
- }
291
-
292
- BleManager.getConnectedPeripherals(services).then((peripherals) => {
293
- const devices = peripherals.map(peripheral => ({
294
- deviceId: peripheral.id,
295
- name: peripheral.name || '未知设备'
296
- }))
297
- const result = {
298
- errMsg: 'getConnectedBluetoothDevices:ok',
299
- devices: devices
300
- }
301
- success(result)
302
- complete(result)
303
- }).catch((error) => {
304
- commonFailHandler('getConnectedBluetoothDevices:fail ' + (typeof error === 'string' ? error : ''), fail, complete)
305
- })
306
- }
307
-
308
- function getBluetoothAdapterState (options = {}) {
309
- const { success = noop, fail = noop, complete = noop } = options
310
-
311
- if (!bleManagerInitialized) {
312
- commonFailHandler('getBluetoothAdapterState:fail ble adapter need open first.', fail, complete)
313
- return
314
- }
315
-
316
- BleManager.checkState().then((state) => {
317
- const result = {
318
- errMsg: 'getBluetoothAdapterState:ok',
319
- discovering,
320
- available: state === 'on'
321
- }
322
- success(result)
323
- complete(result)
324
- }).catch((error) => {
325
- commonFailHandler('getBluetoothAdapterState:fail ' + (typeof error === 'string' ? error : ''), fail, complete)
326
- })
327
- }
328
- function onDidUpdateState () {
329
- updateStateSubscription = BleManager.onDidUpdateState((state) => {
330
- onStateChangeCallbacks.forEach(cb => {
331
- cb({
332
- available: state.state === 'on',
333
- discovering: state.state === 'on' ? discovering : false
334
- })
335
- })
336
- if (onBLEConnectionStateCallbacks.length && connectedDeviceId.length && state.state !== 'on') {
337
- connectedDeviceId.forEach((id) => {
338
- onBLEConnectionStateCallbacks.forEach(cb => {
339
- cb({
340
- deviceId: id,
341
- connected: false
342
- })
343
- })
344
- })
345
- }
346
- })
347
- }
348
-
349
- function onBluetoothAdapterStateChange (callback) {
350
- if (!updateStateSubscription) {
351
- onDidUpdateState()
352
- }
353
- if (onStateChangeCallbacks.indexOf(callback) === -1) {
354
- onStateChangeCallbacks.push(callback)
355
- }
356
- }
357
-
358
- function offBluetoothAdapterStateChange (callback) {
359
- const index = onStateChangeCallbacks.indexOf(callback)
360
- if (index > -1) {
361
- onStateChangeCallbacks.splice(index, 1)
362
- }
363
- if (deviceFoundCallbacks.length === 0) {
364
- removeUpdateStateSubscription()
365
- }
366
- }
367
-
368
- function getBluetoothDevices (options = {}) { // 该能力只是获取应用级别已连接设备列表,非手机级别的已连接设备列表
369
- const { success = noop, fail = noop, complete = noop } = options
370
- if (!bleManagerInitialized) {
371
- const result = {
372
- errMsg: 'getBluetoothDevices:fail ble adapter hans\'t been opened or ble is unavailable.'
373
- }
374
- fail(result)
375
- complete(result)
376
- return
377
- }
378
- const result = {
379
- errMsg: 'getBluetoothDevices:ok',
380
- devices: getDevices // 返回已扫描的设备列表
381
- }
382
- success(result)
383
- complete(result)
384
- }
385
-
386
- function writeBLECharacteristicValue (options = {}) {
387
- const { deviceId, serviceId, characteristicId, value, success = noop, fail = noop, complete = noop } = options
388
- if (!deviceId || !serviceId || !characteristicId || !value) {
389
- const result = {
390
- errMsg: 'writeBLECharacteristicValue:ok',
391
- errno: 1509000
392
- }
393
- success(result)
394
- complete(result)
395
- return
396
- }
397
-
398
- // 将ArrayBuffer转换为byte array
399
- const bytes = Array.from(new Uint8Array(value))
400
- BleManager.write(deviceId, serviceId, characteristicId, bytes).then(() => {
401
- const result = {
402
- errMsg: 'writeBLECharacteristicValue:ok'
403
- }
404
- success(result)
405
- complete(result)
406
- }).catch((error) => {
407
- const result = {
408
- errMsg: 'writeBLECharacteristicValue:fail ' + (typeof error === 'string' ? error : '')
409
- }
410
- fail(result)
411
- complete(result)
412
- })
413
- }
414
-
415
- function readBLECharacteristicValue (options = {}) {
416
- const { deviceId, serviceId, characteristicId, success = noop, fail = noop, complete = noop } = options
417
-
418
- if (!deviceId || !serviceId || !characteristicId) {
419
- const result = {
420
- errMsg: 'readBLECharacteristicValue:ok',
421
- errno: 1509000
422
- }
423
- success(result)
424
- complete(result)
425
- return
426
- }
427
-
428
- BleManager.read(deviceId, serviceId, characteristicId).then((data) => {
429
- // 将byte array转换为ArrayBuffer
430
- const buffer = new ArrayBuffer(data.length)
431
- const view = new Uint8Array(buffer)
432
- data.forEach((byte, index) => {
433
- view[index] = byte
434
- })
435
-
436
- const result = {
437
- errMsg: 'readBLECharacteristicValue:ok',
438
- value: buffer
439
- }
440
- success(result)
441
- complete(result)
442
- }).catch((error) => {
443
- const result = {
444
- errMsg: 'readBLECharacteristicValue:fail ' + (typeof error === 'string' ? error : '')
445
- }
446
- fail(result)
447
- complete(result)
448
- })
449
- }
450
-
451
- function notifyBLECharacteristicValueChange (options = {}) {
452
- const { deviceId, serviceId, characteristicId, state = true, success = noop, fail = noop, complete = noop } = options
453
-
454
- if (!deviceId || !serviceId || !characteristicId) {
455
- const result = {
456
- errMsg: 'notifyBLECharacteristicValueChange:ok',
457
- errno: 1509000
458
- }
459
- success(result)
460
- complete(result)
461
- return
462
- }
463
-
464
- const subscriptionKey = `${deviceId}_${serviceId}_${characteristicId}`
465
-
466
- if (state) {
467
- // 启用监听
468
- BleManager.startNotification(deviceId, serviceId, characteristicId).then(() => {
469
- characteristicSubscriptions[subscriptionKey] = true
470
-
471
- const result = {
472
- errMsg: 'notifyBLECharacteristicValueChange:ok'
473
- }
474
- success(result)
475
- complete(result)
476
- }).catch((error) => {
477
- const result = {
478
- errMsg: 'notifyBLECharacteristicValueChange:fail ' + (typeof error === 'string' ? error : '')
479
- }
480
- fail(result)
481
- complete(result)
482
- })
483
- } else {
484
- // 停止监听
485
- BleManager.stopNotification(deviceId, serviceId, characteristicId).then(() => {
486
- delete characteristicSubscriptions[subscriptionKey]
487
-
488
- const result = {
489
- errMsg: 'notifyBLECharacteristicValueChange:ok'
490
- }
491
- success(result)
492
- complete(result)
493
- }).catch((error) => {
494
- const result = {
495
- errMsg: 'notifyBLECharacteristicValueChange:fail ' + (typeof error === 'string' ? error : '')
496
- }
497
- fail(result)
498
- complete(result)
499
- })
500
- }
501
- }
502
-
503
- let valueForCharacteristicSubscriptions = null
504
- function onBLECharacteristicValueChange (callback) {
505
- if (characteristicCallbacks.length === 0) {
506
- valueForCharacteristicSubscriptions = BleManager.onDidUpdateValueForCharacteristic((data) => {
507
- // 将byte array转换为ArrayBuffer
508
- const buffer = new ArrayBuffer(data.value.length)
509
- const view = new Uint8Array(buffer)
510
- data.value.forEach((byte, index) => {
511
- view[index] = byte
512
- })
513
- const result = {
514
- deviceId: data.peripheral,
515
- serviceId: data.service,
516
- characteristicId: data.characteristic,
517
- value: buffer
518
- }
519
- characteristicCallbacks.forEach(cb => {
520
- cb(result)
521
- })
522
- })
523
- }
524
- if (characteristicCallbacks.indexOf(callback) === -1) {
525
- characteristicCallbacks.push(callback)
526
- }
527
- }
528
-
529
- function offBLECharacteristicValueChange (callback) {
530
- const index = characteristicCallbacks.indexOf(callback)
531
- if (index > -1) {
532
- characteristicCallbacks.splice(index, 1)
533
- }
534
- if (characteristicCallbacks.length === 0 && valueForCharacteristicSubscriptions) {
535
- valueForCharacteristicSubscriptions.remove()
536
- valueForCharacteristicSubscriptions = null
537
- }
538
- }
539
-
540
- function setBLEMTU (options = {}) {
541
- const { deviceId, mtu, success = noop, fail = noop, complete = noop } = options
542
- if (!mtu) {
543
- commonFailHandler('setBLEMTU:fail parameter error: parameter.mtu should be Number instead of Undefined;', fail, complete)
544
- return
545
- }
546
- if (!deviceId) {
547
- commonFailHandler('setBLEMTU:fail parameter error: parameter.deviceId should be String instead of Undefined;', fail, complete)
548
- return
549
- }
550
- if (!deviceId && !mtu) {
551
- commonFailHandler('setBLEMTU:fail parameter error: parameter.deviceId should be String instead of Undefined;parameter.mtu should be Number instead of Undefined;', fail, complete)
552
- return
553
- }
554
-
555
- BleManager.requestMTU(deviceId, mtu).then((actualMtu) => {
556
- const result = {
557
- errMsg: 'setBLEMTU:ok',
558
- mtu: actualMtu
559
- }
560
- success(result)
561
- complete(result)
562
- }).catch((error) => {
563
- const result = {
564
- errMsg: 'setBLEMTU:fail ' + (typeof error === 'string' ? error : '')
565
- }
566
- fail(result)
567
- complete(result)
568
- })
569
- }
570
-
571
- function getBLEDeviceRSSI (options = {}) {
572
- const { deviceId, success = noop, fail = noop, complete = noop } = options
573
-
574
- if (!deviceId) {
575
- const result = {
576
- errMsg: 'getBLEDeviceRSSI:ok',
577
- errno: 1509000
578
- }
579
- success(result)
580
- complete(result)
581
- return
582
- }
583
-
584
- BleManager.readRSSI(deviceId).then((rssi) => {
585
- const result = {
586
- errMsg: 'getBLEDeviceRSSI:ok',
587
- RSSI: rssi
588
- }
589
- success(result)
590
- complete(result)
591
- }).catch((error) => {
592
- const errmsg = typeof error === 'string' ? error : (typeof error === 'string' ? error : '')
593
- const result = {
594
- errMsg: 'getBLEDeviceRSSI:fail ' + errmsg
595
- }
596
- fail(result)
597
- complete(result)
598
- })
599
- }
600
-
601
- function getBLEDeviceServices (options = {}) {
602
- const { deviceId, success = noop, fail = noop, complete = noop } = options
603
-
604
- if (!deviceId) {
605
- const result = {
606
- errMsg: 'getBLEDeviceServices:ok',
607
- errno: 1509000,
608
- services: []
609
- }
610
- fail(result)
611
- complete(result)
612
- return
613
- }
614
- BleManager.retrieveServices(deviceId).then((peripheralInfo) => {
615
- const services = peripheralInfo.services.map(service => ({
616
- uuid: service.uuid,
617
- isPrimary: true
618
- }))
619
-
620
- // 存储服务信息
621
- BLEDeviceCharacteristics[deviceId] = peripheralInfo
622
-
623
- const result = {
624
- errMsg: 'getBLEDeviceServices:ok',
625
- services: services
626
- }
627
- success(result)
628
- complete(result)
629
- }).catch((error) => {
630
- const errmsg = typeof error === 'string' ? error : (typeof error === 'string' ? error : '')
631
- const result = {
632
- errMsg: 'getBLEDeviceServices:fail ' + errmsg
633
- }
634
- fail(result)
635
- complete(result)
636
- })
637
- }
638
-
639
- function getBLEDeviceCharacteristics (options = {}) {
640
- const { deviceId, serviceId, success = noop, fail = noop, complete = noop } = options
641
-
642
- if (!deviceId || !serviceId) {
643
- const result = {
644
- errMsg: 'getBLEDeviceCharacteristics:ok',
645
- errno: 1509000,
646
- characteristics: []
647
- }
648
- success(result)
649
- complete(result)
650
- return
651
- }
652
-
653
- const peripheralInfo = BLEDeviceCharacteristics[deviceId]
654
- if (!peripheralInfo) {
655
- const result = {
656
- errMsg: 'getBLEDeviceCharacteristics:fail device services not retrieved'
657
- }
658
- fail(result)
659
- complete(result)
660
- return
661
- }
662
- const characteristicsList = peripheralInfo.characteristics || []
663
- const service = characteristicsList.find(c => c.service.toLowerCase() === serviceId.toLowerCase())
664
- if (!service && !characteristicsList.length) {
665
- const result = {
666
- errMsg: 'getBLEDeviceCharacteristics:fail service not found'
667
- }
668
- fail(result)
669
- complete(result)
670
- return
671
- }
672
- const characteristics = characteristicsList.map(char => ({
673
- uuid: char.characteristic,
674
- properties: char.properties
675
- }))
676
-
677
- const result = {
678
- errMsg: 'getBLEDeviceCharacteristics:ok',
679
- characteristics
680
- }
681
- success(result)
682
- complete(result)
683
- }
684
-
685
- function createBLEConnection (options = {}) {
686
- const { deviceId, timeout, success = noop, fail = noop, complete = noop } = options
687
-
688
- if (!deviceId) {
689
- const result = {
690
- errMsg: 'createBLEConnection:ok',
691
- errno: 1509000
692
- }
693
- fail(result)
694
- complete(result)
695
- return
696
- }
697
-
698
- BleManager.connect(deviceId, {
699
- autoconnect: true
700
- }).then(() => {
701
- if (connectedDeviceId.indexOf(deviceId) === -1) {
702
- connectedDeviceId.push(deviceId) // 记录一下已连接的设备id
703
- }
704
- clearTimeout(createBLEConnectionTimeout)
705
- onBLEConnectionStateCallbacks.forEach(cb => {
706
- cb({
707
- deviceId,
708
- connected: true
709
- })
710
- })
711
- connectedDevices.add(deviceId)
712
- const result = {
713
- errMsg: 'createBLEConnection:ok'
714
- }
715
- success(result)
716
- complete(result)
717
- }).catch((error) => {
718
- clearTimeout(createBLEConnectionTimeout)
719
- const result = {
720
- errMsg: 'createBLEConnection:fail ' + (typeof error === 'string' ? error : '')
721
- }
722
- fail(result)
723
- complete(result)
724
- })
725
- if (timeout) {
726
- createBLEConnectionTimeout = setTimeout(() => { // 超时处理,仅ios会一直连接,android不会
727
- BleManager.disconnect(deviceId).catch(() => {})
728
- }, timeout)
729
- }
730
- }
731
-
732
- function closeBLEConnection (options = {}) {
733
- const { deviceId, success = noop, fail = noop, complete = noop } = options
734
-
735
- if (!deviceId) {
736
- const result = {
737
- errMsg: 'closeBLEConnection:ok',
738
- errno: 1509000
739
- }
740
- success(result)
741
- complete(result)
742
- return
743
- }
744
-
745
- BleManager.disconnect(deviceId).then(() => {
746
- const index = connectedDeviceId.indexOf(deviceId)
747
- if (index !== -1) {
748
- connectedDeviceId.splice(index, 1) // 记录一下已连接的设备id
749
- }
750
- onBLEConnectionStateCallbacks.forEach(cb => {
751
- cb({
752
- deviceId,
753
- connected: false
754
- })
755
- })
756
- connectedDevices.delete(deviceId)
757
- const result = {
758
- errMsg: 'closeBLEConnection:ok'
759
- }
760
- success(result)
761
- complete(result)
762
- }).catch((error) => {
763
- const result = {
764
- errMsg: 'closeBLEConnection:fail ' + (typeof error === 'string' ? error : '')
765
- }
766
- fail(result)
767
- complete(result)
768
- })
769
- }
770
-
771
- function onBLEConnectionStateChange (callback) {
772
- if (!updateStateSubscription) {
773
- onDidUpdateState()
774
- }
775
- if (onBLEConnectionStateCallbacks.indexOf(callback) === -1) {
776
- onBLEConnectionStateCallbacks.push(callback)
777
- }
778
- }
779
-
780
- function offBLEConnectionStateChange (callback) {
781
- const index = onBLEConnectionStateCallbacks.indexOf(callback)
782
- if (index !== -1) {
783
- onBLEConnectionStateCallbacks.splice(index, 1)
784
- }
785
- if (onBLEConnectionStateCallbacks.length === 0) {
786
- removeUpdateStateSubscription()
787
- }
788
- }
789
-
790
- export {
791
- openBluetoothAdapter,
792
- closeBluetoothAdapter,
793
- startBluetoothDevicesDiscovery,
794
- stopBluetoothDevicesDiscovery,
795
- onBluetoothDeviceFound,
796
- offBluetoothDeviceFound,
797
- getConnectedBluetoothDevices,
798
- getBluetoothAdapterState,
799
- onBluetoothAdapterStateChange,
800
- offBluetoothAdapterStateChange,
801
- getBluetoothDevices,
802
- writeBLECharacteristicValue,
803
- readBLECharacteristicValue,
804
- notifyBLECharacteristicValueChange,
805
- onBLECharacteristicValueChange,
806
- offBLECharacteristicValueChange,
807
- setBLEMTU,
808
- getBLEDeviceRSSI,
809
- getBLEDeviceServices,
810
- getBLEDeviceCharacteristics,
811
- createBLEConnection,
812
- closeBLEConnection,
813
- onBLEConnectionStateChange,
814
- offBLEConnectionStateChange
815
- }