Blame view

打印机安卓基座/native-fast-printer/android-src/src/com/foodlabel/nativeprinter/NativeFastPrinterModule.java 21.8 KB
a6f5c1af   “wangming”   开发了安卓基座
1
2
3
4
5
6
7
8
9
  package com.foodlabel.nativeprinter;
  
  import com.alibaba.fastjson.JSONObject;
  import com.foodlabel.nativeprinter.debug.NativePrintDebugState;
  import com.foodlabel.nativeprinter.support.PluginResult;
  import com.foodlabel.nativeprinter.support.SafeJson;
  import com.foodlabel.nativeprinter.support.ThrowableUtils;
  import com.foodlabel.nativeprinter.template.NativeTemplateCommandBuilder;
  import com.foodlabel.nativeprinter.transport.GprinterBluetoothTransport;
3ead62fc   杨鑫   优化
10
11
  import com.foodlabel.nativeprinter.transport.UposBuiltinPrinterTransport;
  import com.foodlabel.nativeprinter.transport.UposSerialPortTransport;
a6f5c1af   “wangming”   开发了安卓基座
12
13
14
15
16
17
  import com.taobao.weex.annotation.JSMethod;
  import com.taobao.weex.bridge.JSCallback;
  
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  
58d2e61c   杨鑫   最新代码
18
19
  import android.util.Base64;
  
a6f5c1af   “wangming”   开发了安卓基座
20
21
22
23
  import io.dcloud.feature.uniapp.common.UniModule;
  
  public class NativeFastPrinterModule extends UniModule {
      private static final String BACKEND = "gprinter-sdk";
699ea6e8   杨鑫   完善打印逻辑
24
25
      private static final String PLUGIN_VERSION = "1.2.8";
      private static final String BUILD_TIME = String.valueOf(System.currentTimeMillis());
a6f5c1af   “wangming”   开发了安卓基座
26
27
28
29
      private static final Object LOCK = new Object();
      private static final ExecutorService PRINT_EXECUTOR = Executors.newSingleThreadExecutor();
      private static final NativePrintDebugState DEBUG_STATE = new NativePrintDebugState(BACKEND, PLUGIN_VERSION);
      private static final GprinterBluetoothTransport BLUETOOTH_TRANSPORT = new GprinterBluetoothTransport();
3ead62fc   杨鑫   优化
30
31
      private static final UposBuiltinPrinterTransport UPOS_BUILTIN_TRANSPORT = new UposBuiltinPrinterTransport();
      private static final UposSerialPortTransport UPOS_SERIAL_TRANSPORT = new UposSerialPortTransport();
699ea6e8   杨鑫   完善打印逻辑
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
      /**
       * Some builds of NativePrintDebugState.attachTo() do not expose stage/lastError in JSON.
       * Keep an explicit copy here so JS can always read it for diagnosis.
       */
      private static volatile String LAST_STAGE = "";
      private static volatile String LAST_ERROR = "";
      private static volatile int LAST_COMMAND_BYTES = 0;
      private static volatile long LAST_WRITE_MS = 0L;
  
      private static void setStage(String stage) {
          LAST_STAGE = stage == null ? "" : stage;
          DEBUG_STATE.setStage(LAST_STAGE);
      }
  
      private static void setError(String error) {
          LAST_ERROR = error == null ? "" : error;
          DEBUG_STATE.setError(LAST_ERROR);
      }
  
      private static void clearError() {
          LAST_ERROR = "";
          DEBUG_STATE.clearError();
      }
  
      private static void setCommandBytes(int n) {
          LAST_COMMAND_BYTES = Math.max(0, n);
      }
  
      private static void setWriteMs(long ms) {
          LAST_WRITE_MS = Math.max(0L, ms);
      }
3ead62fc   杨鑫   优化
63
64
65
66
67
68
69
70
71
  
      private static final String[] SERIAL_PORT_CANDIDATES = new String[]{
              "/dev/ttyS1",
              "/dev/ttyS0",
              "/dev/ttyMSM0",
              "/dev/ttyMSM1",
              "/dev/ttyUSB0",
              "/dev/ttyACM0"
      };
a6f5c1af   “wangming”   开发了安卓基座
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
  
      @JSMethod(uiThread = false)
      public void connect(JSONObject params, JSCallback callback) {
          String deviceId = SafeJson.getString(params, "deviceId", "");
          String deviceName = SafeJson.getString(params, "deviceName", "");
          PluginResult result = ensureConnected(deviceId, deviceName);
          if (callback != null) {
              callback.invoke(result.toJsonString());
          }
      }
  
      @JSMethod(uiThread = false)
      public void disconnect(JSCallback callback) {
          synchronized (LOCK) {
              BLUETOOTH_TRANSPORT.disconnect();
              DEBUG_STATE.clearCurrentDevice();
699ea6e8   杨鑫   完善打印逻辑
88
89
              setStage("disconnect:ok");
              clearError();
a6f5c1af   “wangming”   开发了安卓基座
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
          }
          if (callback != null) {
              callback.invoke(debugResult(PluginResult.ok(false, "", "", "disconnect:ok")).toJsonString());
          }
      }
  
      @JSMethod(uiThread = false)
      public void isConnected(JSCallback callback) {
          boolean connected;
          synchronized (LOCK) {
              connected = BLUETOOTH_TRANSPORT.isConnected();
          }
          if (callback != null) {
              callback.invoke(debugResult(PluginResult.ok(connected, DEBUG_STATE.getCurrentDeviceId(), DEBUG_STATE.getCurrentDeviceName(), "isConnected:ok")).toJsonString());
          }
      }
  
      @JSMethod(uiThread = false)
      public void getDebugInfo(JSCallback callback) {
          boolean connected;
          synchronized (LOCK) {
              connected = BLUETOOTH_TRANSPORT.isConnected();
          }
          if (callback != null) {
              callback.invoke(debugResult(PluginResult.ok(connected, DEBUG_STATE.getCurrentDeviceId(), DEBUG_STATE.getCurrentDeviceName(), "debug:ok")).toJsonString());
          }
      }
  
      @JSMethod(uiThread = false)
      public void printTemplate(JSONObject params, JSCallback callback) {
          String deviceId = SafeJson.getString(params, "deviceId", "");
          String deviceName = SafeJson.getString(params, "deviceName", "");
          String templateJson = SafeJson.getString(params, "templateJson", "");
          String dataJson = SafeJson.getString(params, "dataJson", "{}");
          int dpi = SafeJson.getInt(params, "dpi", 203);
          int printQty = Math.max(1, SafeJson.getInt(params, "printQty", 1));
699ea6e8   杨鑫   完善打印逻辑
126
127
128
129
130
          String outputTransport = SafeJson.getString(params, "outputTransport", "bluetooth");
          final String uposPrefer = SafeJson.getString(params, "uposPrefer", "builtin");
          final String uposSerialPath = SafeJson.getString(params, "uposSerialPath", "");
          final int uposBaudrate = Math.max(1200, SafeJson.getInt(params, "uposBaudrate", 9600));
          final boolean useUpos = "upos".equalsIgnoreCase(outputTransport);
a6f5c1af   “wangming”   开发了安卓基座
131
132
133
134
135
136
137
138
  
          if (templateJson == null || templateJson.trim().isEmpty()) {
              if (callback != null) {
                  callback.invoke(errorResult(9011006, "Template json is empty.").toJsonString());
              }
              return;
          }
  
699ea6e8   杨鑫   完善打印逻辑
139
140
141
142
143
144
          if (!useUpos) {
              PluginResult connectResult = ensureConnected(deviceId, deviceName);
              if (!connectResult.success) {
                  if (callback != null) callback.invoke(connectResult.toJsonString());
                  return;
              }
a6f5c1af   “wangming”   开发了安卓基座
145
146
          }
  
699ea6e8   杨鑫   完善打印逻辑
147
          setStage("printTemplate:queued");
a6f5c1af   “wangming”   开发了安卓基座
148
          if (callback != null) {
699ea6e8   杨鑫   完善打印逻辑
149
150
151
              String did = useUpos ? "builtin-upos" : DEBUG_STATE.getCurrentDeviceId();
              String dname = useUpos ? "Built-in UPOS" : DEBUG_STATE.getCurrentDeviceName();
              callback.invoke(debugResult(PluginResult.ok(true, did, dname, "printTemplate:queued")).toJsonString());
a6f5c1af   “wangming”   开发了安卓基座
152
153
154
155
156
157
158
          }
  
          PRINT_EXECUTOR.execute(new Runnable() {
              @Override
              public void run() {
                  try {
                      DEBUG_STATE.resetBuildMetrics();
699ea6e8   杨鑫   完善打印逻辑
159
                      setStage("build-command");
a6f5c1af   “wangming”   开发了安卓基座
160
161
162
163
164
165
                      long buildStarted = System.currentTimeMillis();
                      NativeTemplateCommandBuilder.BuildResult buildResult =
                              NativeTemplateCommandBuilder.buildWithStats(templateJson, dataJson, dpi, printQty);
                      DEBUG_STATE.setBuildMs(Math.max(0L, System.currentTimeMillis() - buildStarted));
                      DEBUG_STATE.setBuildResult(buildResult);
  
699ea6e8   杨鑫   完善打印逻辑
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
                      if (buildResult.bytes == null || buildResult.bytes.length == 0) {
                          setError("built command bytes empty");
                          setStage("printTemplate:error");
                          return;
                      }
  
                      if (useUpos) {
                          setCommandBytes(buildResult.bytes.length);
                          setStage("write-upos-command");
                          boolean ok = dispatchUposPrint(buildResult.bytes, uposPrefer, uposSerialPath, uposBaudrate);
                          if (!ok) {
                              setStage("printTemplate:error");
                              if (DEBUG_STATE.getLastError() == null || DEBUG_STATE.getLastError().isEmpty()) {
                                  setError("upos write failed");
                              }
                              return;
                          }
                          DEBUG_STATE.markPrinted(System.currentTimeMillis());
                          setStage("printTemplate:ok");
                          clearError();
                          return;
                      }
  
a6f5c1af   “wangming”   开发了安卓基座
189
190
191
192
193
194
                      long writeStarted = System.currentTimeMillis();
                      synchronized (LOCK) {
                          if (!BLUETOOTH_TRANSPORT.isConnected()) {
                              errorResult(9011005, "Bluetooth printer transport is not ready.");
                              return;
                          }
699ea6e8   杨鑫   完善打印逻辑
195
                          setStage("write-command");
a6f5c1af   “wangming”   开发了安卓基座
196
197
198
199
200
201
                          boolean ok = BLUETOOTH_TRANSPORT.write(buildResult.bytes);
                          if (!ok) {
                              errorResult(9011011, "Printer writeDataImmediately returned false.");
                              return;
                          }
                      }
699ea6e8   杨鑫   完善打印逻辑
202
                      setCommandBytes(buildResult.bytes.length);
a6f5c1af   “wangming”   开发了安卓基座
203
204
                      DEBUG_STATE.setWriteMs(Math.max(0L, System.currentTimeMillis() - writeStarted));
                      DEBUG_STATE.markPrinted(System.currentTimeMillis());
699ea6e8   杨鑫   完善打印逻辑
205
206
                      setStage("printTemplate:ok");
                      clearError();
a6f5c1af   “wangming”   开发了安卓基座
207
                  } catch (Throwable e) {
699ea6e8   杨鑫   完善打印逻辑
208
209
                      setError(ThrowableUtils.unwrap(e));
                      setStage("printTemplate:error");
a6f5c1af   “wangming”   开发了安卓基座
210
211
212
213
214
                  }
              }
          });
      }
  
58d2e61c   杨鑫   最新代码
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
      /**
       *  JS 侧已生成的 TSC/指令字节(Base64)经佳博 SDK 写出。
       * 用于整页光栅等路径,避免再走 JS 经典蓝牙 socket(慢、易超时)。
       */
      @JSMethod(uiThread = false)
      public void printCommandBytes(JSONObject params, JSCallback callback) {
          String deviceId = SafeJson.getString(params, "deviceId", "");
          String deviceName = SafeJson.getString(params, "deviceName", "");
          String base64 = SafeJson.getString(params, "base64", "");
  
          if (base64 == null || base64.trim().isEmpty()) {
              if (callback != null) {
                  callback.invoke(errorResult(9011012, "base64 is empty.").toJsonString());
              }
              return;
          }
  
          PluginResult connectResult = ensureConnected(deviceId, deviceName);
          if (!connectResult.success) {
              if (callback != null) {
                  callback.invoke(connectResult.toJsonString());
              }
              return;
          }
  
699ea6e8   杨鑫   完善打印逻辑
240
          setStage("printCommandBytes:queued");
58d2e61c   杨鑫   最新代码
241
242
243
244
245
246
247
248
249
250
          if (callback != null) {
              callback.invoke(debugResult(PluginResult.ok(true, DEBUG_STATE.getCurrentDeviceId(), DEBUG_STATE.getCurrentDeviceName(), "printCommandBytes:queued")).toJsonString());
          }
  
          PRINT_EXECUTOR.execute(new Runnable() {
              @Override
              public void run() {
                  try {
                      byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
                      if (bytes == null || bytes.length == 0) {
699ea6e8   杨鑫   完善打印逻辑
251
252
                          setError("decoded bytes empty");
                          setStage("printCommandBytes:error");
58d2e61c   杨鑫   最新代码
253
254
255
256
257
258
259
260
                          return;
                      }
                      long writeStarted = System.currentTimeMillis();
                      synchronized (LOCK) {
                          if (!BLUETOOTH_TRANSPORT.isConnected()) {
                              errorResult(9011005, "Bluetooth printer transport is not ready.");
                              return;
                          }
699ea6e8   杨鑫   完善打印逻辑
261
                          setStage("write-raw-command");
58d2e61c   杨鑫   最新代码
262
263
264
265
266
267
268
269
                          boolean ok = BLUETOOTH_TRANSPORT.write(bytes);
                          if (!ok) {
                              errorResult(9011011, "Printer writeDataImmediately returned false.");
                              return;
                          }
                      }
                      DEBUG_STATE.setWriteMs(Math.max(0L, System.currentTimeMillis() - writeStarted));
                      DEBUG_STATE.markPrinted(System.currentTimeMillis());
699ea6e8   杨鑫   完善打印逻辑
270
271
                      setStage("printCommandBytes:ok");
                      clearError();
58d2e61c   杨鑫   最新代码
272
                  } catch (Throwable e) {
699ea6e8   杨鑫   完善打印逻辑
273
274
                      setError(ThrowableUtils.unwrap(e));
                      setStage("printCommandBytes:error");
58d2e61c   杨鑫   最新代码
275
276
277
278
279
                  }
              }
          });
      }
  
3ead62fc   杨鑫   优化
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
      /**
       * UnifiedPOS SDK: built-in printer / serial port printing (no Bluetooth pairing).
       *
       * Params:
       * - base64: required, raw command bytes
       * - prefer: optional, "builtin" | "serial" (default builtin)
       * - serialPath: optional, e.g. "/dev/ttyS1"
       * - baudrate: optional, default 9600
       */
      @JSMethod(uiThread = false)
      public void printUposCommandBytes(JSONObject params, JSCallback callback) {
          String base64 = SafeJson.getString(params, "base64", "");
          String prefer = SafeJson.getString(params, "prefer", "builtin");
          String serialPath = SafeJson.getString(params, "serialPath", "");
          int baudrate = Math.max(1200, SafeJson.getInt(params, "baudrate", 9600));
  
          if (base64 == null || base64.trim().isEmpty()) {
              if (callback != null) {
                  callback.invoke(errorResult(9011012, "base64 is empty.").toJsonString());
              }
              return;
          }
  
699ea6e8   杨鑫   完善打印逻辑
303
          setStage("printUposCommandBytes:queued");
3ead62fc   杨鑫   优化
304
305
306
307
308
309
310
  
          PRINT_EXECUTOR.execute(new Runnable() {
              @Override
              public void run() {
                  try {
                      byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
                      if (bytes == null || bytes.length == 0) {
699ea6e8   杨鑫   完善打印逻辑
311
312
                          setError("decoded bytes empty");
                          setStage("printUposCommandBytes:error");
3ead62fc   杨鑫   优化
313
314
                          return;
                      }
699ea6e8   杨鑫   完善打印逻辑
315
316
                      setCommandBytes(bytes.length);
                      boolean ok = dispatchUposPrint(bytes, prefer, serialPath, baudrate);
3ead62fc   杨鑫   优化
317
318
                      DEBUG_STATE.markPrinted(System.currentTimeMillis());
                      if (ok) {
699ea6e8   杨鑫   完善打印逻辑
319
320
                          setStage("printUposCommandBytes:ok");
                          clearError();
3ead62fc   杨鑫   优化
321
322
323
324
                          if (callback != null) {
                              callback.invoke(debugResult(PluginResult.ok(true, "", "", "printUposCommandBytes:ok")).toJsonString());
                          }
                      } else {
699ea6e8   杨鑫   完善打印逻辑
325
                          setStage("printUposCommandBytes:error");
3ead62fc   杨鑫   优化
326
                          if (DEBUG_STATE.getLastError() == null || DEBUG_STATE.getLastError().isEmpty()) {
699ea6e8   杨鑫   完善打印逻辑
327
                              setError("upos write failed");
3ead62fc   杨鑫   优化
328
329
330
331
332
333
                          }
                          if (callback != null) {
                              callback.invoke(errorResult(9011020, "UPOS print failed: " + DEBUG_STATE.getLastError()).toJsonString());
                          }
                      }
                  } catch (Throwable e) {
699ea6e8   杨鑫   完善打印逻辑
334
335
                      setError(ThrowableUtils.unwrap(e));
                      setStage("printUposCommandBytes:error");
3ead62fc   杨鑫   优化
336
337
338
339
340
341
342
343
                      if (callback != null) {
                          callback.invoke(errorResult(9011021, "UPOS print exception: " + DEBUG_STATE.getLastError()).toJsonString());
                      }
                  }
              }
          });
      }
  
699ea6e8   杨鑫   完善打印逻辑
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
      /**
       * 内置/串口 UPOS 写出(与 printUposCommandBytes 同源逻辑)。
       */
      private static boolean dispatchUposPrint(byte[] bytes, String prefer, String serialPath, int baudrate) {
          if (bytes == null || bytes.length == 0) {
              setError("bytes empty");
              return false;
          }
          long writeStarted = System.currentTimeMillis();
          boolean ok;
          if ("serial".equalsIgnoreCase(prefer)) {
              ok = writeBySerial(bytes, serialPath, baudrate);
          } else {
              ok = writeByBuiltinPrinter(bytes);
              if (!ok) {
                  ok = writeBySerial(bytes, serialPath, baudrate);
              }
          }
          setWriteMs(Math.max(0L, System.currentTimeMillis() - writeStarted));
          return ok;
      }
  
3ead62fc   杨鑫   优化
366
367
      private static boolean writeByBuiltinPrinter(byte[] bytes) {
          try {
699ea6e8   杨鑫   完善打印逻辑
368
369
370
371
372
373
374
              setStage("upos:builtin:write");
              boolean ok = runUposWriteWithTimeout(new UposWriteOp() {
                  @Override
                  public boolean run() {
                      return UPOS_BUILTIN_TRANSPORT.write(bytes);
                  }
              }, estimateUposWriteTimeoutMs(bytes == null ? 0 : bytes.length), "upos:builtin:write:timeout");
3ead62fc   杨鑫   优化
375
              if (!ok) {
699ea6e8   杨鑫   完善打印逻辑
376
                  setError("upos builtin failed: " + UPOS_BUILTIN_TRANSPORT.getLastError());
3ead62fc   杨鑫   优化
377
378
379
              }
              return ok;
          } catch (Throwable e) {
699ea6e8   杨鑫   完善打印逻辑
380
              setError(ThrowableUtils.unwrap(e));
3ead62fc   杨鑫   优化
381
382
383
384
385
386
387
388
              return false;
          }
      }
  
      private static boolean writeBySerial(byte[] bytes, String path, int baudrate) {
          try {
              String usePath = (path != null && !path.trim().isEmpty()) ? path.trim() : null;
              if (usePath != null) {
699ea6e8   杨鑫   完善打印逻辑
389
                  setStage("upos:serial:open:" + usePath);
3ead62fc   杨鑫   优化
390
391
                  UPOS_SERIAL_TRANSPORT.close();
                  if (!UPOS_SERIAL_TRANSPORT.open(usePath, baudrate)) {
699ea6e8   杨鑫   完善打印逻辑
392
                      setError("upos serial open failed: " + UPOS_SERIAL_TRANSPORT.getLastError());
3ead62fc   杨鑫   优化
393
394
                      return false;
                  }
699ea6e8   杨鑫   完善打印逻辑
395
396
397
398
399
400
401
402
                  setStage("upos:serial:write");
                  boolean ok = runUposWriteWithTimeout(new UposWriteOp() {
                      @Override
                      public boolean run() {
                          return UPOS_SERIAL_TRANSPORT.write(bytes);
                      }
                  }, estimateUposWriteTimeoutMs(bytes == null ? 0 : bytes.length), "upos:serial:write:timeout");
                  if (!ok) setError("upos serial write failed: " + UPOS_SERIAL_TRANSPORT.getLastError());
3ead62fc   杨鑫   优化
403
404
405
406
407
                  UPOS_SERIAL_TRANSPORT.close();
                  return ok;
              }
  
              for (String candidate : SERIAL_PORT_CANDIDATES) {
699ea6e8   杨鑫   完善打印逻辑
408
                  setStage("upos:serial:open:" + candidate);
3ead62fc   杨鑫   优化
409
410
411
412
                  UPOS_SERIAL_TRANSPORT.close();
                  if (!UPOS_SERIAL_TRANSPORT.open(candidate, baudrate)) {
                      continue;
                  }
699ea6e8   杨鑫   完善打印逻辑
413
414
415
416
417
418
419
                  setStage("upos:serial:write");
                  boolean ok = runUposWriteWithTimeout(new UposWriteOp() {
                      @Override
                      public boolean run() {
                          return UPOS_SERIAL_TRANSPORT.write(bytes);
                      }
                  }, estimateUposWriteTimeoutMs(bytes == null ? 0 : bytes.length), "upos:serial:write:timeout");
3ead62fc   杨鑫   优化
420
421
422
423
424
425
426
                  if (!ok) {
                      UPOS_SERIAL_TRANSPORT.close();
                      continue;
                  }
                  UPOS_SERIAL_TRANSPORT.close();
                  return true;
              }
699ea6e8   杨鑫   完善打印逻辑
427
              setError("upos serial open failed: no candidate ports worked");
3ead62fc   杨鑫   优化
428
429
              return false;
          } catch (Throwable e) {
699ea6e8   杨鑫   完善打印逻辑
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
              setError(ThrowableUtils.unwrap(e));
              return false;
          }
      }
  
      /**
       * UnifiedPOS/Serial 写入在部分机型/驱动上可能“卡死不返回且无异常”。
       * 为避免 JS Promise 长时间悬挂,增加超时保护:超时则尝试 close,并返回 false(上层会回调错误)。
       */
      private interface UposWriteOp {
          boolean run();
      }
  
      private static long estimateUposWriteTimeoutMs(int byteLen) {
          int n = Math.max(0, byteLen);
          // 基础 15s + 按体量加成(整页光栅可达数百 KB);上限 3min,与 JS printUposCommandBytes 300s 对齐。
          long base = 15000L;
          long extra = (long) Math.min(150000L, (n / 1024L) * 900L);
          long ms = base + extra;
          if (ms < 15000L) ms = 15000L;
          if (ms > 180000L) ms = 180000L;
          return ms;
      }
  
      private static boolean runUposWriteWithTimeout(UposWriteOp op, long timeoutMs, String timeoutStage) {
          if (op == null) return false;
          final boolean[] done = new boolean[]{false};
          final boolean[] ok = new boolean[]{false};
          Thread t = new Thread(new Runnable() {
              @Override
              public void run() {
                  try {
                      ok[0] = op.run();
                  } catch (Throwable e) {
                      ok[0] = false;
                      setError(ThrowableUtils.unwrap(e));
                  } finally {
                      done[0] = true;
                  }
              }
          }, "upos-write");
          t.setDaemon(true);
          t.start();
          try {
              t.join(Math.max(1000L, timeoutMs));
          } catch (InterruptedException ignored) {
              // keep going
          }
          if (!done[0]) {
              setStage(timeoutStage);
              setError("upos write timeout");
              try {
                  UPOS_SERIAL_TRANSPORT.close();
              } catch (Throwable ignored) {
              }
              try {
                  UPOS_BUILTIN_TRANSPORT.close();
              } catch (Throwable ignored) {
              }
3ead62fc   杨鑫   优化
489
490
              return false;
          }
699ea6e8   杨鑫   完善打印逻辑
491
          return ok[0];
3ead62fc   杨鑫   优化
492
493
      }
  
a6f5c1af   “wangming”   开发了安卓基座
494
495
496
497
498
499
500
501
502
503
504
      private PluginResult ensureConnected(String deviceId, String deviceName) {
          synchronized (LOCK) {
              PluginResult result = BLUETOOTH_TRANSPORT.ensureConnected(deviceId, deviceName, DEBUG_STATE);
              if (!result.success) {
                  return debugResult(result);
              }
              return debugResult(PluginResult.ok(true, DEBUG_STATE.getCurrentDeviceId(), DEBUG_STATE.getCurrentDeviceName(), "connect:ok"));
          }
      }
  
      private static PluginResult errorResult(int code, String message) {
699ea6e8   杨鑫   完善打印逻辑
505
          setError(message == null ? "" : message);
a6f5c1af   “wangming”   开发了安卓基座
506
507
508
509
          return debugResult(PluginResult.error(code, message));
      }
  
      private static PluginResult debugResult(PluginResult result) {
699ea6e8   杨鑫   完善打印逻辑
510
511
512
513
514
515
516
517
518
519
          PluginResult r = DEBUG_STATE.attachTo(result);
          // Always expose minimal diagnostics for JS (even if attachTo omits some fields).
          r.withMeta("backend", BACKEND)
                  .withMeta("pluginVersion", PLUGIN_VERSION)
                  .withMeta("buildTime", BUILD_TIME)
                  .withMeta("stage", LAST_STAGE)
                  .withMeta("lastError", LAST_ERROR)
                  .withMeta("commandBytes", LAST_COMMAND_BYTES)
                  .withMeta("writeMs", LAST_WRITE_MS);
          return r;
a6f5c1af   “wangming”   开发了安卓基座
520
521
      }
  }