yyb
5 小时以前 fc1a5059e586ab6d41fc3ec3bfacb727accc4765
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
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,
};