bluetoothTool.js
7.99 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
/**
* 经典蓝牙工具(仅 Android APP-PLUS)
* 用于佳博 D320FAX 等一体机的 Virtual BT Printer 连接
* 支持 RFCOMM 回退连接(部分设备需要)
*/
// #ifdef APP-PLUS
function getAdapter () {
if (typeof plus === 'undefined' || !plus.android) return null
const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter')
return BluetoothAdapter.getDefaultAdapter()
}
function getActivity () {
return typeof plus !== 'undefined' ? plus.android.runtimeMainActivity() : null
}
function showToast (msg) {
try {
const activity = getActivity()
if (activity) {
const Toast = plus.android.importClass('android.widget.Toast')
Toast.makeText(activity, String(msg), Toast.LENGTH_SHORT).show()
}
} catch (_) {}
}
function getInvoke () {
return typeof plus !== 'undefined' && plus.android ? plus.android.invoke : null
}
function getMyUuid () {
if (typeof plus === 'undefined' || !plus.android) return null
return plus.android.importClass('java.util.UUID').fromString('00001101-0000-1000-8000-00805F9B34FB')
}
let btSocket = null
let btInStream = null
let btOutStream = null
let btFindReceiver = null
// #endif
var blueToothTool = {
state: { bluetoothEnable: false, readThreadState: false },
shortToast (msg) {
// #ifdef APP-PLUS
showToast(msg)
// #endif
},
getBluetoothStatus () {
// #ifdef APP-PLUS
const btAdapter = getAdapter()
return btAdapter != null && btAdapter.isEnabled()
// #endif
return false
},
/** 获取已配对设备(含 Virtual BT Printer / D320FAX) */
getPairedDevices () {
// #ifdef APP-PLUS
const pairedDevices = []
try {
const btAdapter = getAdapter()
if (!btAdapter || !btAdapter.isEnabled()) {
this.shortToast('Bluetooth is off')
return pairedDevices
}
const bonded = btAdapter.getBondedDevices()
if (!bonded) return pairedDevices
const inv = getInvoke()
if (!inv) return pairedDevices
const it = inv(bonded, 'iterator')
while (inv(it, 'hasNext')) {
const device = inv(it, 'next')
const deviceType = inv(device, 'getType')
const deviceId = inv(device, 'getAddress')
let deviceName = inv(device, 'getName')
if (deviceName == null) deviceName = ''
deviceName = String(deviceName).trim() || 'Unknown Device'
let typeStr = 'unknown'
if (deviceType === 1) typeStr = 'classic'
else if (deviceType === 2) typeStr = 'ble'
else if (deviceType === 3) typeStr = 'dual'
pairedDevices.push({ name: deviceName, deviceId: String(deviceId), type: typeStr })
}
} catch (e) {
console.error('getPairedDevices error:', e)
}
return pairedDevices
// #endif
return []
},
/** 经典蓝牙扫描(发现未配对设备,如 d320fax_295c)— 不过滤任何设备 */
startClassicDiscovery (onDeviceFound, onDiscoveryFinished) {
// #ifdef APP-PLUS
const btAdapter = getAdapter()
const activity = getActivity()
if (!btAdapter || !btAdapter.isEnabled() || !activity) return
if (btFindReceiver) {
try { activity.unregisterReceiver(btFindReceiver) } catch (_) {}
btFindReceiver = null
}
if (btAdapter.isDiscovering()) btAdapter.cancelDiscovery()
const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter')
const BluetoothDevice = plus.android.importClass('android.bluetooth.BluetoothDevice')
const IntentFilter = plus.android.importClass('android.content.IntentFilter')
const inv = getInvoke()
btFindReceiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
onReceive (context, intent) {
const action = intent.getAction()
if (BluetoothDevice.ACTION_FOUND === action) {
const device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
if (!device) return
const deviceType = inv(device, 'getType')
const deviceId = String(inv(device, 'getAddress') || '')
let deviceName = inv(device, 'getName')
if (deviceName == null) deviceName = ''
deviceName = String(deviceName).trim() || 'Unknown Device'
let typeStr = 'unknown'
if (deviceType === 1) typeStr = 'classic'
else if (deviceType === 2) typeStr = 'ble'
else if (deviceType === 3) typeStr = 'dual'
if (onDeviceFound) onDeviceFound({ name: deviceName, deviceId, type: typeStr })
}
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED === action) {
try { activity.unregisterReceiver(btFindReceiver) } catch (_) {}
btFindReceiver = null
if (onDiscoveryFinished) onDiscoveryFinished()
}
},
})
const filter = new IntentFilter()
filter.addAction(BluetoothDevice.ACTION_FOUND)
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
activity.registerReceiver(btFindReceiver, filter)
btAdapter.startDiscovery()
// #endif
},
/** 停止经典蓝牙扫描 */
cancelClassicDiscovery () {
// #ifdef APP-PLUS
const btAdapter = getAdapter()
const activity = getActivity()
if (btAdapter && btAdapter.isDiscovering()) btAdapter.cancelDiscovery()
if (btFindReceiver && activity) {
try { activity.unregisterReceiver(btFindReceiver) } catch (_) {}
btFindReceiver = null
}
// #endif
},
/** 连接经典蓝牙设备(含 D320FAX Virtual BT Printer,支持 RFCOMM 回退) */
connDevice (address, callback) {
// #ifdef APP-PLUS
if (btSocket != null) this.closeBtSocket()
this.state.readThreadState = false
const btAdapter = getAdapter()
if (!btAdapter) {
this.shortToast('Bluetooth not available')
if (callback) callback(false)
return false
}
const inv = getInvoke()
const uuid = getMyUuid()
if (!inv || !uuid) {
this.shortToast('Bluetooth not ready')
if (callback) callback(false)
return false
}
try {
const device = inv(btAdapter, 'getRemoteDevice', address)
btSocket = inv(device, 'createRfcommSocketToServiceRecord', uuid)
} catch (e) {
console.warn('createRfcommSocketToServiceRecord failed, try fallback:', e)
try {
const device = inv(btAdapter, 'getRemoteDevice', address)
const cls = inv(device, 'getClass')
const intClass = plus.android.importClass('java.lang.Integer').TYPE
const m = inv(cls, 'getMethod', 'createRfcommSocket', intClass)
btSocket = inv(m, 'invoke', device, 1)
} catch (e2) {
console.error('RFCOMM fallback failed:', e2)
this.shortToast('Connect failed')
if (callback) callback(false)
return false
}
}
try {
inv(btSocket, 'connect')
btInStream = inv(btSocket, 'getInputStream')
btOutStream = inv(btSocket, 'getOutputStream')
this.state.readThreadState = true
this.shortToast('Connected')
if (callback) callback(true)
} catch (e) {
try { btSocket.close() } catch (_) {}
btSocket = null
this.shortToast('Connect failed')
if (callback) callback(false)
return false
}
return true
// #endif
if (callback) callback(false)
return false
},
disConnDevice () {
// #ifdef APP-PLUS
this.closeBtSocket()
this.state.readThreadState = false
this.shortToast('Disconnected')
// #endif
},
closeBtSocket () {
// #ifdef APP-PLUS
this.state.readThreadState = false
if (btSocket) {
try { btSocket.close() } catch (_) {}
btSocket = null
btInStream = null
btOutStream = null
}
// #endif
},
sendByteData (byteData) {
// #ifdef APP-PLUS
if (!btOutStream) {
this.shortToast('Not connected')
return false
}
try {
const CHUNK_SIZE = 4096
for (let i = 0; i < byteData.length; i += CHUNK_SIZE) {
const chunk = byteData.slice(i, i + CHUNK_SIZE)
btOutStream.write(chunk)
}
return true
} catch (e) {
return false
}
// #endif
return false
}
}
export default blueToothTool