// 精臣打印机原生插件。插件由 DCloud 账号绑定,账号未购买/未打入基座时不能抛错,
|
// 否则页面一加载就白屏,所以这里做容错加载,缺失时打印功能给出提示而不是崩溃。
|
let jcapi = null;
|
let pluginMissing = false;
|
try {
|
jcapi = uni.requireNativePlugin("JCSDK-JCApiModule");
|
if (!jcapi) {
|
pluginMissing = true;
|
}
|
} catch (e) {
|
pluginMissing = true;
|
}
|
|
const PLUGIN_MISSING_MSG = "未检测到精臣打印插件,请确认打包时已购买并勾选该原生插件";
|
|
function requirePlugin() {
|
if (pluginMissing || !jcapi) {
|
uni.showToast({ title: PLUGIN_MISSING_MSG, icon: "none", duration: 3000 });
|
return null;
|
}
|
return jcapi;
|
}
|
|
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() {
|
const api = requirePlugin();
|
if (!api) return;
|
|
api.initSDK();
|
|
const saved = uni.getStorageSync("bluetoothConnection");
|
if (saved) {
|
state.connectedDevice = saved;
|
state.connectionStatus = "connected";
|
}
|
|
// 断开监听
|
api.didReadPrintErrorInfo((r) => {
|
if (r.code === 23) {
|
state.connectedDevice = null;
|
state.connectionStatus = "disconnected";
|
uni.removeStorageSync("bluetoothConnection");
|
notify();
|
}
|
});
|
}
|
|
/** 搜索设备 */
|
function searchDevices() {
|
return new Promise((resolve, reject) => {
|
const api = requirePlugin();
|
if (!api) {
|
return reject(new Error(PLUGIN_MISSING_MSG));
|
}
|
uni.openBluetoothAdapter({
|
success() {
|
api.getBluetoothDevices(list => {
|
resolve(list || []);
|
});
|
},
|
fail: reject
|
});
|
});
|
}
|
|
/** 连接设备 */
|
function connect(device) {
|
return new Promise((resolve, reject) => {
|
const api = requirePlugin();
|
if (!api) {
|
return reject(new Error(PLUGIN_MISSING_MSG));
|
}
|
state.connectionStatus = "connecting";
|
notify();
|
|
api.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,
|
};
|