From fc1a5059e586ab6d41fc3ec3bfacb727accc4765 Mon Sep 17 00:00:00 2001
From: yyb <995253665@qq.com>
Date: 星期一, 15 十二月 2025 14:52:02 +0800
Subject: [PATCH] 核磅录入打印装箱单

---
 common/bluetoothPrinter.js |  102 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 102 insertions(+), 0 deletions(-)

diff --git a/common/bluetoothPrinter.js b/common/bluetoothPrinter.js
new file mode 100644
index 0000000..dc018e0
--- /dev/null
+++ b/common/bluetoothPrinter.js
@@ -0,0 +1,102 @@
+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,
+};

--
Gitblit v1.9.3