/* * Copyright 2009 Cedric Priscal * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android_serialport_api.print_tool; 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 android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Handler; import android.os.Message; import android.view.WindowManager; import android_serialport_api.SerialPort; import com.ectrip.cyt.callback.CloseCallback; 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.utils.LogUtil; import com.ectrip.cyt.utils.SharedPreferences2Obj; import com.hdx.lib.printer.SerialPrinter; import com.hdx.lib.serial.SerialParam; import com.hdx.lib.serial.SerialPortOperaion; import com.hdx.lib.serial.SerialPortOperaion.SerialReadData; /** * @author jigo pos机打印工具类 */ public class SerialPortTool implements CloseCallback{ private Context mContext; protected SerialPort mSerialPort=null; protected OutputStream mOutputStream; private InputStream mInputStream; protected ReadThread mReadThread; private static final String TAG = "SerialPortTool"; public SerialPrinter mSerialPrinter = null; private int n = 0; private ProgressDialog dialog; private Integer type; private int printNum=1; private int Select = 0; private String isStatistic; private String printinfo; private MyHandler handler; private final int CLOSE=5; private SerialDataHandler serialDataHandler; @SuppressLint("SimpleDateFormat") public void init(Context mContext, String printInfo) { this.mContext = mContext; this.printinfo = printInfo; this.serialDataHandler=new SerialDataHandler(); if(handler==null){ handler=new MyHandler(); } popUpDialog(); new Thread(new Runnable() { @Override public void run() { try { if (mSerialPort == null) { mSerialPort = getSerialPort(); } if (mSerialPrinter == null) { mSerialPrinter = SerialPrinter.GetSerialPrinter(); } try { mSerialPrinter.OpenPrinter(new SerialParam(115200, "/dev/ttyS2", 0),serialDataHandler,SerialPortTool.this); } catch (Exception e1) { e1.printStackTrace(); } if (mSerialPort != null) { mOutputStream = mSerialPort.getOutputStream(); mInputStream = mSerialPort.getInputStream(); sleep(200); mReadThread = new ReadThread(); mReadThread.start(); } else { } LogUtil.e(TAG, "print end"); for (int x = 0; x < printNum; x++) { if(x==1&&isStatistic.equals("1")){ close(); return; } try { if(isStatistic!=null&&isStatistic.equals("1")){ sendString(" 统计信息"+"\n",x); sendCommand(0x1b, 0x33, 0x14, 0x0a); }else{ sendString(" 订单信息"+"\n",x); sendCommand(0x1b, 0x33, 0x14, 0x0a); // 当时重打小票的时候,多打一段字符 if (Select==SelectAction.Reprint.getValue()) { sendString(" (重打小票)",x); sendCommand(0x1b, 0x33, 0x14, 0x0a); } } } catch (Exception e) { e.printStackTrace(); } try { mSerialPrinter.setLineSpace(5); // 间隔 } catch (Exception e) { e.printStackTrace(); } sendString(printinfo,x); 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");// 设置日期格式 sendString("检票时间:" + df.format(new Date()),x); sendCommand(0x1b, 0x33, 0x14, 0x0a); }else if (Select==SelectAction.Reprint.getValue()) {// 重打时间 SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");// 设置日期格式 //sendString("重打时间:" + df.format(new Date()),x); sendCommand(0x1b, 0x33, 0x14, 0x0a); } sendCommand(0x1b, 0x33, 0x14, 0x0a); sendString("取票人签名:",x); } sendCommand(0x1b, 0x33, 0x14, 0x0a); sendCommand(0x1b, 0x33, 0x14, 0x0a); if (constant.logoMark == LogoType.CYT.getValue()) { sendString("---畅游通—智慧旅游O2O平台---",x); sendCommand(0x1b, 0x33, 0x14, 0x0a); sendCommand(0x1b, 0x33, 0x14, 0x0a); sendString("--------www.jingqu.cn---------",x); } else if (constant.logoMark == LogoType.QNE.getValue()) { sendCommand(0x1b, 0x33, 0x14, 0x0a); sendCommand(0x1b, 0x33, 0x14, 0x0a); sendString("---欢迎使用去哪儿网O2O系统---",x); sendCommand(0x1b, 0x33, 0x14, 0x0a); sendCommand(0x1b, 0x33, 0x14, 0x0a); sendString("--------www.qunar.com--------",x); } sendCommand(0x1b, 0x33, 0x14, 0x0a); sendCommand(0x1b, 0x33, 0x14, 0x0a); sendCommand(0x1b, 0x33, 0x14, 0x0a); sendCommand(0x1b, 0x33, 0x14, 0x0a); sendCommand(0x1b, 0x33, 0x14, 0x0a); sendString("",x); } sleep(1000); mSerialPrinter.printString("printClose",1); LogUtil.e(TAG, "print end"); } catch (SecurityException e) { close(); // DisplayError(R.string.error_security); } catch (IOException e) { close(); // DisplayError(R.string.error_unknown); } catch (InvalidParameterException e) { close(); // DisplayError(R.string.error_configuration); }catch (Exception e) { close(); } } }).start(); } @SuppressLint("HandlerLeak") private class SerialDataHandler extends Handler { public void handleMessage(Message msg) { switch (msg.what) { case SerialPortOperaion.SERIAL_RECEIVED_DATA_MSG: SerialReadData data = (SerialReadData) msg.obj; StringBuilder sb = new StringBuilder(); for (int x = 0; x < data.size; x++) sb.append(String.format("%02x", data.data[x])); LogUtil.d(TAG, "data =" + sb); } } } private void popUpDialog(){ try { isStatistic=SharedPreferences2Obj.getInstance(mContext). setName("SelectAction").getObject("isStatistic",String.class); //非统计判断 type=SharedPreferences2Obj.getInstance(mContext). setName("MachineType").getObject("type", Integer.class); Select=SharedPreferences2Obj.getInstance(mContext). setName("SelectAction").getObject("Select",Integer.class); printNum = MyApp.getInstance().getPrintNum(); } catch (Exception e1) { e1.printStackTrace(); } if (dialog == null) { // 显示ProgressDialog dialog = new ProgressDialog(mContext); 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(); } } public SerialPort getSerialPort() throws SecurityException, IOException, InvalidParameterException { if (mSerialPort == null) { /* Read serial port parameters */ // SharedPreferences sp = mContext.getSharedPreferences( // "android_serialport_api.sample_preferences",0); String path = "/dev/ttyS2"; ;// 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); // (new File(path), baudrate, 0); } return mSerialPort; } class ReadThread extends Thread { @Override public void run() { super.run(); while (!isInterrupted()) { try { sleep(500); } catch (InterruptedException e1) { e1.printStackTrace(); } sendCommand(0x1d, 0x4f, 0x01, 0x0a, 0x1b, 0x21, 0x00); int size; LogUtil.e(TAG, "=============while(!isInterrupted())=========="); try { byte[] buffer = new byte[64]; LogUtil.e(TAG, "1.=============ReadThread"); if (mInputStream == null) return; LogUtil.e(TAG, "2.=============ReadThread"); LogUtil.i(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", buffer.toString()); size = mInputStream.read(buffer); LogUtil.e(TAG, "3.==============ReadThread,size : " + size); if (size > 0) { String tString = new String(buffer, 0, size); LogUtil.e(TAG, "4.==============ReadThread,size : " + size); LogUtil.e(TAG, "5.==============ReadThread,buffer : " + tString); for (int i = 0; i < tString.length(); i++) { LogUtil.e( TAG, "6. ===" + i + " : " + (tString.charAt(i))); LogUtil.e(TAG, "7.(int)===" + i + " : " + (int) (tString.charAt(i))); } LogUtil.e(TAG, "111==============n : " + n); n = ((n > 4) ? 0 : n); // onDataReceived(buffer, size, n); n++; } } catch (IOException e) { e.printStackTrace(); return; } } } } @SuppressWarnings("unused") private void DisplayError(int resourceId) { AlertDialog.Builder b = new AlertDialog.Builder(mContext); b.setTitle("Error"); b.setMessage(resourceId); b.setPositiveButton("OK", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); b.show(); } public void print(String printInfo) { } private void sendCommand(int... command) { synchronized ( SerialPrinter.GetSerialPrinter()) { try { if (mOutputStream != null) { for (int i = 0; i < command.length; i++) { mOutputStream.write(command[i]); LogUtil.e(TAG, "command[" + i + "] = " + Integer.toHexString(command[i])); } } } catch (IOException e) { e.printStackTrace(); } sleep(60); } } private void sendString(String tString, int num) { synchronized (SerialPrinter.GetSerialPrinter()) { String string = null; string = UnicodeToGBK(tString); if ("printClose".equals(string)) { closeback(); }else{ try { for (int i = 0; i < string.length(); i++) { LogUtil.e( TAG, "sendString," + i + " = " + Integer.toHexString(string.charAt(i))); if (mOutputStream != null) { mOutputStream.write(string.charAt(i)); } } } catch (IOException e) { e.printStackTrace(); } sleep(50); } } } public static String UnicodeToGBK(String s) { try { String newstring = null; newstring = new String(s.getBytes("GBK"), "ISO-8859-1"); return newstring; } catch (UnsupportedEncodingException e) { return s; } } public void sleep(int ms) { try { java.lang.Thread.sleep(ms); } catch (Exception e) { e.printStackTrace(); } } @SuppressLint("HandlerLeak") class MyHandler extends Handler{ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case CLOSE: if(dialog!=null&&dialog.isShowing()){ try { dialog.dismiss(); } catch (Exception e) { e.printStackTrace(); } } break; default: break; } } } public void close() { new Thread(new Runnable() { @Override public void run() { if (mReadThread != null) mReadThread.interrupt(); if (mSerialPrinter != null) { try { mSerialPrinter.ClosePrinter(); } catch (Exception e) { e.printStackTrace(); } } if (mSerialPort != null) { try { mSerialPort.close(); mSerialPort = null; } catch (Exception e) { e.printStackTrace(); } } try { if (mOutputStream != null) { mOutputStream.close(); } if (mInputStream != null) { mInputStream.close(); } } catch (IOException e) { } handler.sendMessage(handler.obtainMessage(CLOSE)); } }).start(); } @Override public void closeback() { close(); } }