| | |
| | | const jcapi = uni.requireNativePlugin("JCSDK-JCApiModule"); |
| | | // 精臣打印机原生插件。插件由 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, |
| | |
| | | |
| | | /** 初始化(全局只需一次) */ |
| | | function init() { |
| | | jcapi.initSDK(); |
| | | const api = requirePlugin(); |
| | | if (!api) return; |
| | | |
| | | api.initSDK(); |
| | | |
| | | const saved = uni.getStorageSync("bluetoothConnection"); |
| | | if (saved) { |
| | |
| | | } |
| | | |
| | | // 断开监听 |
| | | jcapi.didReadPrintErrorInfo((r) => { |
| | | api.didReadPrintErrorInfo((r) => { |
| | | if (r.code === 23) { |
| | | state.connectedDevice = null; |
| | | state.connectionStatus = "disconnected"; |
| | |
| | | /** 搜索设备 */ |
| | | function searchDevices() { |
| | | return new Promise((resolve, reject) => { |
| | | const api = requirePlugin(); |
| | | if (!api) { |
| | | return reject(new Error(PLUGIN_MISSING_MSG)); |
| | | } |
| | | uni.openBluetoothAdapter({ |
| | | success() { |
| | | jcapi.getBluetoothDevices(list => { |
| | | api.getBluetoothDevices(list => { |
| | | resolve(list || []); |
| | | }); |
| | | }, |
| | |
| | | /** 连接设备 */ |
| | | function connect(device) { |
| | | return new Promise((resolve, reject) => { |
| | | const api = requirePlugin(); |
| | | if (!api) { |
| | | return reject(new Error(PLUGIN_MISSING_MSG)); |
| | | } |
| | | state.connectionStatus = "connecting"; |
| | | notify(); |
| | | |
| | | jcapi.openPrinterByDevice({ |
| | | api.openPrinterByDevice({ |
| | | address: device.address, |
| | | name: device.name, |
| | | deviceType: 0, |