const jcapi = uni.requireNativePlugin("JCSDK-JCApiModule");
|
|
let state = {
|
connectedDevice: null,
|
connectionStatus: "disconnected", // disconnected | connecting | connected
|
listeners: [],
|
};
|
|
/** 通知所有订阅页面 */
|
function notify() {
|
state.listeners.forEach(fn => fn({
|
connectedDevice: state.connectedDevice,
|
connectionStatus: state.connectionStatus,
|
}));
|
}
|
|
/** 页面订阅蓝牙状态 */
|
function onChange(fn) {
|
state.listeners.push(fn);
|
fn({
|
connectedDevice: state.connectedDevice,
|
connectionStatus: state.connectionStatus,
|
});
|
}
|
|
/** 初始化(全局只需一次) */
|
function init() {
|
jcapi.initSDK();
|
|
const saved = uni.getStorageSync("bluetoothConnection");
|
if (saved) {
|
state.connectedDevice = saved;
|
state.connectionStatus = "connected";
|
}
|
|
// 断开监听
|
jcapi.didReadPrintErrorInfo((r) => {
|
if (r.code === 23) {
|
state.connectedDevice = null;
|
state.connectionStatus = "disconnected";
|
uni.removeStorageSync("bluetoothConnection");
|
notify();
|
}
|
});
|
}
|
|
/** 搜索设备 */
|
function searchDevices() {
|
return new Promise((resolve, reject) => {
|
uni.openBluetoothAdapter({
|
success() {
|
jcapi.getBluetoothDevices(list => {
|
resolve(list || []);
|
});
|
},
|
fail: reject
|
});
|
});
|
}
|
|
/** 连接设备 */
|
function connect(device) {
|
return new Promise((resolve, reject) => {
|
state.connectionStatus = "connecting";
|
notify();
|
|
jcapi.openPrinterByDevice({
|
address: device.address,
|
name: device.name,
|
deviceType: 0,
|
}, (r) => {
|
if (r.code === 0) {
|
state.connectedDevice = device;
|
state.connectionStatus = "connected";
|
uni.setStorageSync("bluetoothConnection", device);
|
notify();
|
resolve(device);
|
} else {
|
state.connectionStatus = "disconnected";
|
notify();
|
reject(r);
|
}
|
});
|
});
|
}
|
|
function isConnected() {
|
return state.connectionStatus === "connected";
|
}
|
|
function getCurrentDevice() {
|
return state.connectedDevice;
|
}
|
|
export default {
|
init,
|
onChange,
|
searchDevices,
|
connect,
|
isConnected,
|
getCurrentDevice,
|
};
|