bluetoothTool.js
20.4 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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
/**
* 经典蓝牙工具(Android APP-PLUS)
* 兼容官方 UniApp SDK 经典蓝牙实现,并补充当前项目需要的简化调用:
* - getPairedDevices()
* - startClassicDiscovery(onDeviceFound, onDiscoveryFinished)
* - cancelClassicDiscovery()
* - connDevice(address, callback)
* - disConnDevice()
* - sendByteData(byteData)
*/
// #ifdef APP-PLUS
let BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter')
let Intent = plus.android.importClass('android.content.Intent')
let IntentFilter = plus.android.importClass('android.content.IntentFilter')
let BluetoothDevice = plus.android.importClass('android.bluetooth.BluetoothDevice')
let UUID = plus.android.importClass('java.util.UUID')
let Toast = plus.android.importClass('android.widget.Toast')
let Thread = plus.android.importClass('java.lang.Thread')
let MY_UUID = UUID.fromString('00001101-0000-1000-8000-00805F9B34FB')
let invoke = plus.android.invoke
let btAdapter = BluetoothAdapter.getDefaultAdapter()
let activity = plus.android.runtimeMainActivity()
let btSocket = null
let btInStream = null
let btOutStream = null
let setIntervalId = 0
let btFindReceiver = null
let btStatusReceiver = null
// #endif
function normalizeDeviceType (deviceType) {
if (deviceType === 1) return 'classic'
if (deviceType === 2) return 'ble'
if (deviceType === 3) return 'dual'
return 'unknown'
}
function fallbackRfcommSocket (device, insecure = false) {
try {
const cls = invoke(device, 'getClass')
const intClass = plus.android.importClass('java.lang.Integer').TYPE
const methodName = insecure ? 'createInsecureRfcommSocket' : 'createRfcommSocket'
const method = invoke(cls, 'getMethod', methodName, intClass)
return invoke(method, 'invoke', device, 1)
} catch (e) {
console.error('RFCOMM fallback failed:', e)
return null
}
}
function getErrorMessage (error) {
if (!error) return 'Unknown error'
if (typeof error === 'string') return error
return String(error.message || error.errMsg || error)
}
function normalizeWriteByte (value) {
const byte = Number(value) || 0
return byte & 0xff
}
function toSignedWriteByte (value) {
const byte = normalizeWriteByte(value)
return byte >= 128 ? byte - 256 : byte
}
function normalizeWriteChunk (byteData, start, end) {
const out = []
for (let i = start; i < end; i++) {
out.push(toSignedWriteByte(byteData[i]))
}
return out
}
function isConnectionStateConnected (state) {
return String(state || '').trim().toLowerCase() === 'connected'
}
function runOnUiThread (fn) {
// #ifdef APP-PLUS
try {
if (activity && typeof activity.runOnUiThread === 'function') {
const runnable = plus.android.implements('java.lang.Runnable', {
run: function () {
try {
fn && fn()
} catch (e) {
console.error('runOnUiThread callback failed:', e)
}
},
})
activity.runOnUiThread(runnable)
return
}
} catch (e) {
console.error('runOnUiThread failed:', e)
}
// #endif
try {
setTimeout(() => {
try {
fn && fn()
} catch (e) {
console.error('setTimeout callback failed:', e)
}
}, 0)
} catch (e) {
console.error('async callback fallback failed:', e)
}
}
function startBackgroundTask (task) {
// #ifdef APP-PLUS
const runnable = plus.android.implements('java.lang.Runnable', {
run: function () {
try {
task && task()
} catch (e) {
console.error('Background task failed:', e)
}
},
})
const thread = new Thread(runnable)
thread.start()
return
// #endif
try {
task && task()
} catch (e) {
console.error('Fallback task failed:', e)
}
}
function createSocketCandidates (device) {
return [
{
name: 'secure-service-record',
create: () => invoke(device, 'createRfcommSocketToServiceRecord', MY_UUID),
},
{
name: 'insecure-service-record',
create: () => invoke(device, 'createInsecureRfcommSocketToServiceRecord', MY_UUID),
},
{
name: 'secure-channel-1',
create: () => fallbackRfcommSocket(device, false),
},
{
name: 'insecure-channel-1',
create: () => fallbackRfcommSocket(device, true),
},
]
}
var blueToothTool = {
state: {
bluetoothEnable: false,
bluetoothState: '',
discoveryDeviceState: false,
readThreadState: false,
connectionState: 'idle',
lastAddress: '',
lastSocketStrategy: '',
lastError: '',
lastSendError: '',
outputReady: false,
lastSendMode: 'idle',
isSending: false,
},
options: {
listenBTStatusCallback: function (state) {},
discoveryDeviceCallback: function (newDevice) {},
discoveryFinishedCallback: function () {},
readDataCallback: function (dataByteArr) {},
connExceptionCallback: function (e) {},
},
init (setOptions) {
Object.assign(this.options, setOptions || {})
this.state.bluetoothEnable = this.getBluetoothStatus()
this.listenBluetoothStatus()
},
setErrorState (message, type = 'general') {
const text = String(message || '')
this.state.lastError = text
if (type === 'send') {
this.state.lastSendError = text
}
},
clearErrorState () {
this.state.lastError = ''
this.state.lastSendError = ''
},
shortToast (msg) {
// #ifdef APP-PLUS
try {
if (activity) Toast.makeText(activity, String(msg), Toast.LENGTH_SHORT).show()
} catch (_) {}
// #endif
},
isSupportBluetooth () {
// #ifdef APP-PLUS
return btAdapter != null
// #endif
return false
},
getBluetoothStatus () {
// #ifdef APP-PLUS
return btAdapter != null && btAdapter.isEnabled()
// #endif
return false
},
turnOnBluetooth () {
// #ifdef APP-PLUS
if (btAdapter == null) {
this.shortToast('Bluetooth not available')
return
}
if (!btAdapter.isEnabled()) {
if (activity == null) {
this.shortToast('Activity not available')
return
}
let intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
activity.startActivityForResult(intent, 1)
return
}
this.shortToast('Bluetooth already enabled')
// #endif
},
turnOffBluetooth () {
// #ifdef APP-PLUS
if (btAdapter != null && btAdapter.isEnabled()) {
btAdapter.disable()
}
if (btFindReceiver != null) {
try { activity.unregisterReceiver(btFindReceiver) } catch (_) {}
btFindReceiver = null
}
this.state.bluetoothEnable = false
this.cancelDiscovery()
this.closeBtSocket()
// #endif
},
getPairedDevices () {
// #ifdef APP-PLUS
let pairedDevices = []
try {
if (btAdapter == null || !btAdapter.isEnabled()) return pairedDevices
let pairedDevicesAndroid = btAdapter.getBondedDevices()
if (!pairedDevicesAndroid) return pairedDevices
let it = invoke(pairedDevicesAndroid, 'iterator')
while (invoke(it, 'hasNext')) {
let device = invoke(it, 'next')
let deviceType = invoke(device, 'getType')
let deviceId = invoke(device, 'getAddress')
let deviceName = invoke(device, 'getName')
pairedDevices.push({
name: deviceName != null ? String(deviceName).trim() || 'Unknown Device' : 'Unknown Device',
deviceId: String(deviceId || ''),
type: normalizeDeviceType(deviceType),
})
}
} catch (e) {
console.error('getPairedDevices error:', e)
}
return pairedDevices
// #endif
return []
},
discoveryNewDevice () {
// #ifdef APP-PLUS
if (btAdapter == null || !btAdapter.isEnabled() || activity == null) return
if (btFindReceiver != null) {
try { activity.unregisterReceiver(btFindReceiver) } catch (e) { console.error(e) }
btFindReceiver = null
this.cancelDiscovery()
}
let options = this.options
btFindReceiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
onReceive: function (context, intent) {
plus.android.importClass(context)
plus.android.importClass(intent)
let action = intent.getAction()
if (BluetoothDevice.ACTION_FOUND === action) {
let device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
if (!device) return
let deviceType = invoke(device, 'getType')
let deviceId = invoke(device, 'getAddress')
let deviceName = invoke(device, 'getName')
let newDevice = {
name: deviceName != null ? String(deviceName).trim() || 'Unknown Device' : 'Unknown Device',
deviceId: String(deviceId || ''),
type: normalizeDeviceType(deviceType),
}
options.discoveryDeviceCallback && options.discoveryDeviceCallback(newDevice)
}
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED === action) {
blueToothTool.cancelDiscovery()
options.discoveryFinishedCallback && options.discoveryFinishedCallback()
}
},
})
let filter = new IntentFilter()
filter.addAction(BluetoothDevice.ACTION_FOUND)
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
activity.registerReceiver(btFindReceiver, filter)
btAdapter.startDiscovery()
this.state.discoveryDeviceState = true
// #endif
},
startClassicDiscovery (onDeviceFound, onDiscoveryFinished) {
this.init({
discoveryDeviceCallback: onDeviceFound || function () {},
discoveryFinishedCallback: onDiscoveryFinished || function () {},
})
this.discoveryNewDevice()
},
listenBluetoothStatus () {
// #ifdef APP-PLUS
if (activity == null) return
if (btStatusReceiver != null) {
try { activity.unregisterReceiver(btStatusReceiver) } catch (e) { console.error(e) }
btStatusReceiver = null
}
btStatusReceiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
onReceive: (context, intent) => {
plus.android.importClass(context)
plus.android.importClass(intent)
let action = intent.getAction()
if (action === BluetoothAdapter.ACTION_STATE_CHANGED) {
let blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
let stateStr = ''
switch (blueState) {
case BluetoothAdapter.STATE_TURNING_ON:
stateStr = 'STATE_TURNING_ON'
break
case BluetoothAdapter.STATE_ON:
stateStr = 'STATE_ON'
this.state.bluetoothEnable = true
break
case BluetoothAdapter.STATE_TURNING_OFF:
stateStr = 'STATE_TURNING_OFF'
break
case BluetoothAdapter.STATE_OFF:
stateStr = 'STATE_OFF'
this.state.bluetoothEnable = false
break
}
this.state.bluetoothState = stateStr
this.options.listenBTStatusCallback && this.options.listenBTStatusCallback(stateStr)
}
},
})
let filter = new IntentFilter()
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
activity.registerReceiver(btStatusReceiver, filter)
if (this.state.bluetoothEnable) {
this.options.listenBTStatusCallback && this.options.listenBTStatusCallback('STATE_ON')
}
// #endif
},
connDevice (address, callback) {
// #ifdef APP-PLUS
this.cancelDiscovery()
if (btSocket != null) this.closeBtSocket()
this.state.readThreadState = false
this.state.connectionState = 'connecting'
this.state.lastAddress = String(address || '')
this.state.outputReady = false
this.clearErrorState()
if (btAdapter == null) {
this.shortToast('Bluetooth not available')
this.state.connectionState = 'error'
this.setErrorState('Bluetooth not available')
callback && callback(false)
return false
}
try {
let device = invoke(btAdapter, 'getRemoteDevice', address)
const candidates = createSocketCandidates(device)
let socket = null
let lastError = null
for (let i = 0; i < candidates.length; i++) {
const candidate = candidates[i]
try {
socket = candidate.create()
if (socket) {
this.state.lastSocketStrategy = candidate.name
break
}
} catch (e) {
lastError = e
console.warn('create socket failed:', candidate.name, e)
}
}
btSocket = socket
if (!btSocket) {
this.state.connectionState = 'error'
this.setErrorState(lastError ? getErrorMessage(lastError) : 'Unable to create Bluetooth socket')
callback && callback(false)
return false
}
} catch (e) {
console.error(e)
this.state.connectionState = 'error'
this.setErrorState(getErrorMessage(e))
callback && callback(false)
return false
}
try {
invoke(btSocket, 'connect')
const streamReady = this.readData()
if (!streamReady) {
throw new Error(this.state.lastError || 'Bluetooth output stream not ready')
}
this.state.connectionState = 'connected'
this.shortToast('Classic Bluetooth connected')
callback && callback(true)
} catch (e) {
console.error(e)
this.state.connectionState = 'error'
this.setErrorState(getErrorMessage(e))
callback && callback(false)
try {
btSocket.close()
btSocket = null
} catch (e1) {
console.error(e1)
}
btInStream = null
btOutStream = null
return false
}
return true
// #endif
callback && callback(false)
return false
},
disConnDevice () {
// #ifdef APP-PLUS
if (btSocket != null) this.closeBtSocket()
this.state.readThreadState = false
// #endif
},
closeBtSocket () {
// #ifdef APP-PLUS
this.state.readThreadState = false
this.state.outputReady = false
this.state.connectionState = 'idle'
clearInterval(setIntervalId)
setIntervalId = 0
if (!btSocket) return
try {
btSocket.close()
} catch (e) {
console.error(e)
}
btSocket = null
btInStream = null
btOutStream = null
// #endif
},
cancelDiscovery () {
// #ifdef APP-PLUS
if (btAdapter != null && btAdapter.isDiscovering()) {
btAdapter.cancelDiscovery()
}
if (btFindReceiver != null && activity != null) {
try { activity.unregisterReceiver(btFindReceiver) } catch (_) {}
btFindReceiver = null
}
this.state.discoveryDeviceState = false
// #endif
},
cancelClassicDiscovery () {
this.cancelDiscovery()
},
readData () {
// #ifdef APP-PLUS
if (!btSocket) {
this.shortToast('Please connect Bluetooth device first.')
this.state.connectionState = 'error'
this.setErrorState('Please connect Bluetooth device first.')
return false
}
try {
btInStream = invoke(btSocket, 'getInputStream')
btOutStream = invoke(btSocket, 'getOutputStream')
} catch (e) {
console.error(e)
this.setErrorState(getErrorMessage(e))
this.closeBtSocket()
return false
}
this.read()
this.state.readThreadState = true
this.state.outputReady = !!btOutStream
return true
// #endif
return false
},
read () {
// #ifdef APP-PLUS
clearInterval(setIntervalId)
setIntervalId = setInterval(() => {
if (this.state.readThreadState) {
let start = new Date().getTime()
let dataArr = []
try {
while (btInStream && invoke(btInStream, 'available') !== 0) {
let data = invoke(btInStream, 'read')
dataArr.push(data)
let current = new Date().getTime()
if (current - start > 20) break
}
} catch (e) {
this.state.readThreadState = false
this.state.connectionState = 'error'
this.setErrorState(getErrorMessage(e))
this.options.connExceptionCallback && this.options.connExceptionCallback(e)
}
if (dataArr.length > 0) {
this.options.readDataCallback && this.options.readDataCallback(dataArr)
}
}
}, 40)
// #endif
},
sendData (dataStr) {
// #ifdef APP-PLUS
if (!btOutStream) {
this.shortToast('Output stream not ready')
return false
}
let bytes = invoke(dataStr, 'getBytes', 'gb18030')
try {
this.sendByteData(bytes)
} catch (e) {
return false
}
return true
// #endif
return false
},
sendByteData (byteData) {
// #ifdef APP-PLUS
if (!btOutStream) {
this.state.outputReady = false
this.state.connectionState = 'error'
this.setErrorState('Classic Bluetooth output stream not ready', 'send')
this.shortToast('Not connected')
return false
}
const socketConnected = this.isSocketConnected()
const connectionUsable = socketConnected || isConnectionStateConnected(this.state.connectionState)
if (!connectionUsable) {
this.state.connectionState = 'error'
this.setErrorState('Classic Bluetooth connection is not ready', 'send')
this.shortToast('Not connected')
return false
}
try {
const CHUNK_SIZE = 4096
this.state.lastSendMode = 'chunk-write'
this.state.lastSendError = ''
for (let i = 0; i < byteData.length; i += CHUNK_SIZE) {
const chunk = byteData.slice(i, Math.min(i + CHUNK_SIZE, byteData.length))
try {
btOutStream.write(chunk)
} catch (writeChunkError) {
this.state.lastSendMode = 'byte-write-fallback'
const signedChunk = normalizeWriteChunk(byteData, i, Math.min(i + CHUNK_SIZE, byteData.length))
for (let j = 0; j < chunk.length; j++) {
invoke(btOutStream, 'write', normalizeWriteByte(signedChunk[j]))
}
}
}
return true
} catch (e) {
const message = getErrorMessage(e)
console.error('sendByteData failed:', e)
this.setErrorState(message, 'send')
this.state.connectionState = 'error'
return false
}
// #endif
return false
},
sendByteDataAsync (byteData, callback) {
// #ifdef APP-PLUS
if (!btOutStream) {
this.state.outputReady = false
this.state.connectionState = 'error'
this.setErrorState('Classic Bluetooth output stream not ready', 'send')
runOnUiThread(() => {
callback && callback(false, this.getLastError())
})
return false
}
const socketConnected = this.isSocketConnected()
const connectionUsable = socketConnected || isConnectionStateConnected(this.state.connectionState)
if (!connectionUsable) {
this.state.connectionState = 'error'
this.setErrorState('Classic Bluetooth connection is not ready', 'send')
runOnUiThread(() => {
callback && callback(false, this.getLastError())
})
return false
}
this.state.isSending = true
this.state.lastSendError = ''
startBackgroundTask(() => {
let ok = false
let errorMessage = ''
try {
ok = this.sendByteData(byteData)
if (!ok) {
errorMessage = this.getLastError() || 'Classic Bluetooth send failed'
}
} catch (e) {
errorMessage = getErrorMessage(e)
this.setErrorState(errorMessage, 'send')
this.state.connectionState = 'error'
} finally {
this.state.isSending = false
}
runOnUiThread(() => {
callback && callback(ok, errorMessage)
})
})
return true
// #endif
callback && callback(false, 'Classic Bluetooth is only available in the app.')
return false
},
isSocketConnected () {
// #ifdef APP-PLUS
if (!btSocket) return false
try {
return !!invoke(btSocket, 'isConnected')
} catch (_) {
return false
}
// #endif
return false
},
ensureConnection (address) {
// #ifdef APP-PLUS
const targetAddress = String(address || this.state.lastAddress || '')
if (targetAddress) {
this.state.lastAddress = targetAddress
}
if (btOutStream && (this.isSocketConnected() || isConnectionStateConnected(this.state.connectionState))) {
this.state.outputReady = true
return true
}
if (!targetAddress) {
this.setErrorState('Bluetooth address missing')
return false
}
let connected = false
this.connDevice(targetAddress, (ok) => {
connected = !!ok
})
return connected && !!btOutStream
// #endif
return false
},
getLastError () {
return this.state.lastSendError || this.state.lastError || ''
},
getDebugState () {
return {
...this.state,
socketConnected: this.isSocketConnected(),
outputReady: !!btOutStream,
inputReady: !!btInStream,
}
},
}
export default blueToothTool