@mpxjs/api-proxy 2.10.16-beta.9 → 2.10.17-beta.1

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