Blame view

src/android_serialport_api/print_tool/SerialNewPortTool.java 17.7 KB
3c2353cd   杜方   1、畅游通核销app源码提交;
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
  package android_serialport_api.print_tool;
  
  import hdx.HdxUtil;
  
  import java.io.File;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.io.UnsupportedEncodingException;
  import java.security.InvalidParameterException;
  import java.text.SimpleDateFormat;
  import java.util.Date;
  import java.util.concurrent.ConcurrentLinkedQueue;
  import java.util.concurrent.atomic.AtomicBoolean;
  
  import android.annotation.SuppressLint;
  import android.app.Activity;
  import android.app.ProgressDialog;
  import android.content.Context;
  import android.content.Intent;
  import android.os.AsyncTask;
  import android.os.Handler;
  import android.os.Message;
  import android.os.PowerManager;
  import android.os.PowerManager.WakeLock;
  import android.text.format.Time;
  import android.util.Log;
  import android.view.WindowManager;
  import android.widget.Toast;
  
  import android_serialport_api.SerialPort;
  
  import com.ectrip.cyt.config.MyApp;
  import com.ectrip.cyt.constant.DeviceType;
  import com.ectrip.cyt.constant.LogoType;
  import com.ectrip.cyt.constant.SelectAction;
  import com.ectrip.cyt.constant.constant;
  import com.ectrip.cyt.ui.PhomeScanerOrderActivity;
  import com.ectrip.cyt.utils.LogUtil;
  import com.ectrip.cyt.utils.SharedPreferences2Obj;
  import com.ectrip.trips.check.R;
  
  /**
   * @author jigo 新款pos
   */
  public class SerialNewPortTool {
      private WakeLock lock;
      private static final String TAG = "SerialNewPortTool";
  
      private Context context;
  
      private final int ENABLE_BUTTON = 2;
  
      private SerialPort mSerialPort = null;
      protected OutputStream mOutputStream;
      private InputStream mInputStream;
      protected ReadThread mReadThread;
      private int n = 0;
      private int printer_status = 0;
  
      private MyHandler handler;
  
      private int printNum = 1;
      // 打印信息
      private ConcurrentLinkedQueue<String> queue;
  
      // 初始化
      @SuppressWarnings("deprecation")
      public void init(Context context, String contentStr) {
          this.context = context;
          if (queue == null) {
              queue = new ConcurrentLinkedQueue<String>();
          }
          if (handler == null) {
              handler = new MyHandler();
          }
c05c7a9b   黄灿宏   标准版本 1.扩展设备8 2....
77
  
3c2353cd   杜方   1、畅游通核销app源码提交;
78
79
80
81
          try {
              HdxUtil.SwitchSerialFunction(HdxUtil.SERIAL_FUNCTION_PRINTER);
          } catch (Throwable e) {
              e.printStackTrace();
8094643a   黄灿宏   畅游通核销app: 1.适配之前机...
82
              Toast.makeText(context, "不支持", Toast.LENGTH_SHORT).show();
3c2353cd   杜方   1、畅游通核销app源码提交;
83
84
              return;
          }
c05c7a9b   黄灿宏   标准版本 1.扩展设备8 2....
85
          popUpDialog();
3c2353cd   杜方   1、畅游通核销app源码提交;
86
87
88
89
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
          PowerManager pm = (PowerManager) context
                  .getSystemService(Context.POWER_SERVICE);
          lock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
  
          new WriteThread(contentStr).start();
      }
  
      @SuppressLint("SimpleDateFormat")
      private class WriteThread extends Thread {
          private String arr;
  
          public WriteThread(String str) {
              arr = str;
          }
  
          public void run() {
              super.run();
              try {
                  mSerialPort = getSerialPort();
                  mOutputStream = mSerialPort.getOutputStream();
                  mInputStream = mSerialPort.getInputStream();
  
  				/* Create a receiving thread */
                  mReadThread = new ReadThread();
                  mReadThread.start();
              } catch (SecurityException e) {
                  // DisplayError(R.string.error_security);
              } catch (IOException e) {
                  // DisplayError(R.string.error_unknown);
              } catch (InvalidParameterException e) {
                  // DisplayError(R.string.error_configuration);
              }
              HdxUtil.SetPrinterPower(1);
              lock.acquire();
              try {
                  try {
                      sleep(500);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  sendCommand(0x1B, 0x23, 0x23, 0x53, 0x4C, 0x41, 0x4E, 0x0f); // china
  
  
                  for (int x = 0; x < printNum; x++) {
  
                      if (x == 1 && isStatistic.equals("1")) {
                          break;
                      }
  
                      try {
                          sendCommand(0x1D, 0x21, 0x11); //double height
                          if (isStatistic != null && isStatistic.equals("1")) {
                              mOutputStream.write("   统计信息\n".getBytes("cp936"));
                              sendCommand(0x1D, 0x21, 0x00); //cancel double height
                              sendCommand(0x1B, 0x32); //设置行间距
                             // queue.offer("            统计信息\n");
                          } else {
                              mOutputStream.write("   订单信息\n".getBytes("cp936"));
                              sendCommand(0x1D, 0x21, 0x00); //cancel double height
                              sendCommand(0x1B, 0x32); //设置行间距
                             // queue.offer("            订单信息\n");
                              if (Select == SelectAction.Reprint.getValue()) {
                                  mOutputStream.write("\n          (重打小票)\n\n".getBytes("cp936"));
                                  //queue.offer("           (重打小票)\n\n");
                              }
                          }
  
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                     // queue.offer(arr);
                      try {
                          String [] arrs =arr.split("\n");
                          for (int i=0;i<arrs.length;i++){
                              //sendCommand(0x1B, 0x33, 0x200); //设置行间距
                              mOutputStream.write((arrs[i]+"\n").getBytes("cp936"));
                          }
                      }catch (Exception e){
  
                      }
  
                      sendCommand(0x0a);
                      sendCommand(0x1b, 0x33, 0x14, 0x0a);
  
                      if (isStatistic != null && isStatistic.equals("1")) {
  
                      } else {
                          // 重打时间
                          if (Select == SelectAction.Query.getValue()) { // 打印时间
                              SimpleDateFormat df = new SimpleDateFormat(
                                      "yyyy-MM-dd HH:mm:ss");// 设置日期格式
                              printWrint("检票时间:" + df.format(new Date()) + "\n");
                             // queue.offer("检票时间:" + df.format(new Date()) + "\n");
                          } else if (Select == SelectAction.Reprint.getValue()) {// 重打时间
                              SimpleDateFormat df = new SimpleDateFormat(
                                      "yyyy-MM-dd HH:mm:ss");// 设置日期格式
                              //queue.offer("重打时间:" + df.format(new Date())+"\n");
                          }
                          printWrint("取票人签名:\n\n");
                         // queue.offer("取票人签名:\n\n");
                      }
  
                      if (constant.logoMark == LogoType.CYT.getValue()) {
                          printWrint("---畅游通—智慧旅游O2O平台---\n");
                          printWrint("--------www.jingqu.cn---------\n");
                         // queue.offer("---畅游通—智慧旅游O2O平台---\n");
                         // queue.offer("--------www.jingqu.cn---------\n");
                      } else if (constant.logoMark == LogoType.QNE.getValue()) {
                          printWrint("---欢迎使用去哪儿网O2O系统---\n");
                          printWrint("--------www.qunar.com--------\n");
                          //queue.offer("---欢迎使用去哪儿网O2O系统---\n");
                         // queue.offer("--------www.qunar.com--------\n");
                      }
                      printWrint("\n\n");
                    //  queue.offer("\n\n\n\n");
                  }
                  queue.offer("\n\n\n\n");
                  Wait_Printer_Ready(queue);
              } finally {
                  lock.release();
              }
          }
      }
      private void printWrint(String string){
          try {
              mOutputStream.write(stringGetByte(string));
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      private byte[] stringGetByte(String string){
          try {
              return string.getBytes("cp936");
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
              return null;
          }
      }
  
      @SuppressLint("HandlerLeak")
      private class MyHandler extends Handler {
          public void handleMessage(Message msg) {
              switch (msg.what) {
                  case ENABLE_BUTTON:
                      try {
                          if (dialog != null) {
                              dialog.dismiss();
                          }
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
  
                      Boolean scanBack = SharedPreferences2Obj.getInstance(context).setName("config").getObject("scanBack", Boolean.class);
                      if (scanBack != null && scanBack) {
                          checkScan();
                      }
  
                      break;
                  default:
                      break;
              }
          }
      }
  
      class ReadThread extends Thread {
  
          @Override
          public void run() {
              super.run();
              while (!isInterrupted()) {
                  int size;
                  try {
                      byte[] buffer = new byte[64];
  
                      if (mInputStream == null)
                          return;
                      size = mInputStream.read(buffer);
                      if (size > 0) {
                          onDataReceived(buffer, size, n);
                      }
                  } catch (IOException e) {
                      e.printStackTrace();
                      return;
                  }
              }
          }
      }
  
      protected void onDataReceived(final byte[] buffer, final int size,
                                    final int n) {
          printer_status = buffer[0];
          LogUtil.e(TAG, "onDataReceived= " + printer_status);
      }
  
      private void sendCommand(int... command) {
          try {
              for (int i = 0; i < command.length; i++) {
                  mOutputStream.write(command[i]);
                  // Log.e(TAG,"command["+i+"] = "+Integer.toHexString(command[i]));
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  
      public void sleep(int ms) {
  
          try {
              java.lang.Thread.sleep(ms);
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  
      public SerialPort getSerialPort() throws SecurityException, IOException,
              InvalidParameterException {
          if (mSerialPort == null) {
              /* Read serial port parameters */
              // SharedPreferences sp = context.getSharedPreferences(
              // "android_serialport_api.sample_preferences",0);
              String path = "/dev/ttyS3";
              ;// sp.getString("DEVICE", "");
              int baudrate = 115200;// Integer.decode(sp.getString("BAUDRATE",
              // "-1"));
  
  			/* Check parameters */
              if ((path.length() == 0) || (baudrate == -1)) {
                  // throw new InvalidParameterException();
  				/* use default value. Nirvana 0710 */
                  path = "/dev/ttyS2";
                  baudrate = 115200;
              }
  
  			/* Open the serial port */
              mSerialPort = new SerialPort(new File(path), baudrate, 0);
          }
          return mSerialPort;
      }
  
      public void closeSerialPort() {
          if (mSerialPort != null) {
              mSerialPort.close();
              mSerialPort = null;
          }
      }
  
      /************************
       * 关闭处理
       **********************************/
      public void close() {
          try {
              if (mReadThread != null)
                  mReadThread.interrupt();
          } catch (Exception e1) {
              e1.printStackTrace();
          }
          try {
              mSerialPort = null;
          } catch (Exception e1) {
              e1.printStackTrace();
          }
          try {
              mOutputStream.close();
              mInputStream.close();
          } catch (IOException e) {
          } catch (Exception e) {
          }
          if (dialog != null) {
              dialog.dismiss();
          }
          HdxUtil.SetPrinterPower(0);
      }
  
      /***************************
       * 打印状态
       ***********************************/
      byte[] Status_Buffer = new byte[300];
      boolean Status_Start_Falg = false;
      int Status_Buffer_Index = 0;
      Time time = new Time();
      int TimeSecond;
      private final byte HDX_ST_WORK = (byte) (1 << 5);// 1 打印机在工作状态
  
      void setStatus_Buffer_Index(int v) {
          Status_Buffer_Index = v;
      }
  
      int getStatus_Buffer_Index() {
          return Status_Buffer_Index;
  
      }
  
      boolean TimeIsOver(int second) {
  
          time.setToNow();
          int t = time.second;
          if (t < TimeSecond) {
              t += 60;
          }
  
          if (t - TimeSecond > second) {
              return true;
          }
          return false;
      }
  
      byte Get_Printer_Status() {
          Status_Buffer[0] = 0;
          Status_Buffer[1] = 0;
          Status_Start_Falg = true;
          setStatus_Buffer_Index(0);
          sendCommand(0x1b, 0x76);
          LogUtil.i(TAG, "Get_Printer_Status->0x1b,0x76");
          Time_Check_Start();
          while (true) {
              if (getStatus_Buffer_Index() > 0) {
                  Status_Start_Falg = false;
                  LogUtil.e(TAG, "Get_Printer_Status :" + Status_Buffer[0]);
                  return Status_Buffer[0];
              }
              if (TimeIsOver(5)) {
                  Status_Start_Falg = false;
                  LogUtil.e(TAG, "Get_Printer_Status->TIME OVER:"
                          + Status_Buffer[0]);
                  return (byte) 0xff;
              }
              sleep(50);
          }
      }
  
      void Time_Check_Start() {
          time.setToNow();
          TimeSecond = time.second;
      }
  
      AtomicBoolean isStop = new AtomicBoolean();
  
      void Wait_Printer_Ready(final ConcurrentLinkedQueue<String> queue) {
  
          new AsyncTask() {
              @Override
              protected Object doInBackground(Object[] objects) {
  
                  while (!isStop.get()) {
                      if (!queue.isEmpty()) {
                          try {
                              mOutputStream.write(queue.poll().getBytes("gbk"));
                          } catch (IOException e) {
                              e.printStackTrace();
                          }
  
                      } else {
  
                          isStop.set(true);
                          sleep(500);
  
                      }
  
                      sleep(40);
                  }
                  if (MyApp.getInstance().getCheckType() == 0) {
                      sleep(1000);
                  }
  
                  return null;
              }
  
              @Override
              protected void onPostExecute(Object o) {
                  super.onPostExecute(o);
                  handler.sendMessage(handler.obtainMessage(
                          ENABLE_BUTTON, 1, 0, null));
  
  
              }
          }.execute();
  
      }
  
  
      private void checkScan() {
          if (MyApp.getInstance().getCheckType() == 0) {
              Integer Select = SharedPreferences2Obj
                      .getInstance(context)
                      .setName("SelectAction").getObject("Select", Integer.class);
              Intent intent = new Intent(context,
                      PhomeScanerOrderActivity.class);
              if (Select != null) {
                  if (Select == SelectAction.Check.getValue()) {
                      intent.putExtra("titleName",
                              context.getString(R.string.check_scan_code));
                  } else if (Select == SelectAction.Reprint.getValue()) {
                      intent.putExtra("titleName",
                              context.getString(R.string.repriint_scan_code));
                  } else if (Select == SelectAction.Query.getValue()) {
                      intent.putExtra("titleName",
                              context.getString(R.string.query_scan_code));
                  }
              } else {
                  intent.putExtra("titleName",
                          context.getString(R.string.scan_qr_code));
              }
              context.startActivity(intent);
              Activity activity = (Activity) context;
              activity.finish();
          }
      }
  
      /***************************
       * 弹框处理
       ********************************/
      private ProgressDialog dialog;
      private String isStatistic;
      private Integer type;
      private int Select = 0;
  
      private void popUpDialog() {
          try {
              isStatistic = SharedPreferences2Obj.getInstance(context)
                      .setName("SelectAction")
                      .getObject("isStatistic", String.class); // 非统计判断
              type = SharedPreferences2Obj.getInstance(context)
                      .setName("MachineType").getObject("type", Integer.class);
              Select = SharedPreferences2Obj.getInstance(context)
                      .setName("SelectAction").getObject("Select", Integer.class);
              printNum = MyApp.getInstance().getPrintNum();
          } catch (Exception e1) {
              e1.printStackTrace();
          }
          if (dialog == null) {
              // 显示ProgressDialog
              dialog = new ProgressDialog(context);
              dialog.setMessage("打印中...");
              dialog.setCanceledOnTouchOutside(true);
              dialog.setCancelable(false);
              if (type == DeviceType.HANDSET.getValue()) {
                  dialog.getWindow().setType(
                          WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
              }
              try {
                  dialog.show();
              } catch (Exception e) {
                  e.printStackTrace();
              }
          } else {
              dialog.setMessage("打印中...");
              dialog.show();
          }
      }
  }