SerialIDPortTool.java 11.8 KB
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 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
package android_serialport_api.print_tool;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.WindowManager;

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.ui.ScanerOrderActivity;
import com.ectrip.cyt.utils.LogUtil;
import com.ectrip.cyt.utils.SharedPreferences2Obj;
import com.ectrip.trips.check.R;
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;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidParameterException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android_serialport_api.SerialPort;
import hdx.HdxUtil;

public class SerialIDPortTool implements CloseCallback {
	private String TAG = "SerialIDPortTool";
	private Context mcontext;
	private MyIdPosHandler idPosHandler;
	private WakeLock lock;
	private final int PRINTIT = 1;
	private final int CLOSE = 2;
	protected SerialPort mSerialPort = null;
	protected OutputStream mOutputStream;
	public SerialPrinter mSerialPrinter = null;
	private InputStream mInputStream;
	private ProgressDialog dialog;
	private Integer type;
	private int printNum = 1;
	private int Select = 0;
	private String isStatistic = "0";
	private String printinfo;
	private SerialDataHandler serialDataHandler;

	@SuppressLint("Wakelock")
	public void init(Context mContext, String printInfo) {
		this.printinfo = printInfo;
		this.mcontext = mContext;
		if (idPosHandler == null) {
			idPosHandler = new MyIdPosHandler();
		}
		if (serialDataHandler == null) {
			serialDataHandler = new SerialDataHandler();
		}
		popUpDialog();
		new Thread(new Runnable() {
			@SuppressWarnings("deprecation")
			@Override
			public void run() {
				try {
					try {
						if (mSerialPort == null) {
							mSerialPort = getSerialPort();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (mSerialPrinter == null) {
						mSerialPrinter = SerialPrinter.GetSerialPrinter();
					}
					if (mSerialPort != null) {
						mOutputStream = mSerialPort.getOutputStream();
						mInputStream = mSerialPort.getInputStream();
					} else {

					}
					HdxUtil.SwitchSerialFunction(HdxUtil.SERIAL_FUNCTION_PRINTER);
					sleep(500);
					try {
						mSerialPrinter.OpenPrinter(new SerialParam(115200,
										"/dev/ttyS1", 0), serialDataHandler,
								SerialIDPortTool.this);
					} catch (Exception e1) {
						e1.printStackTrace();
					}

					PowerManager pm = (PowerManager) mcontext
							.getSystemService(Context.POWER_SERVICE);
					lock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
					lock.acquire();
					try {
						HdxUtil.SetPrinterPower(1);
						try {
							sleep(200);
						} catch (Exception e) {
							e.printStackTrace();
						}
						List<String> info = new ArrayList<String>();
						if (printinfo != null) {
							String[] str = printinfo.split("\n");
							for (int i = 0; i < str.length; i++) {
								info.add(str[i]);
							}
						}
						try {
							HdxUtil.SetPrinterPower(1);
							sleep(200);
							sendCharacterDemo(info);
							sleep(500);
							//打印完成发送消息关闭dialog。
							idPosHandler.sendMessage(idPosHandler.obtainMessage(CLOSE, 1,
									0, null));
							mSerialPrinter.printString("printClose", 1);
						} catch (Exception e) {
							close();
							e.printStackTrace();
						}
					} finally {
						try {
							lock.release();
						} catch (Exception e) {
							e.printStackTrace();
						}
						HdxUtil.SetPrinterPower(0);
					}

				} catch (SecurityException e) {
					close();
					// DisplayError(R.string.error_security);
				} catch (InvalidParameterException e) {
					close();
					// DisplayError(R.string.error_configuration);
				} catch (Exception e) {
					close();
					// TODO: handle exception
				}
			}
		}).start();
	}

	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) {
			String path = "/dev/ttyS1";
			int baudrate = 115200;

			if ((path.length() == 0) || (baudrate == -1)) {
				path = "/dev/ttyS1";
				baudrate = 115200;
			}
			mSerialPort = new SerialPort(new File(path), baudrate, 0);
		}
		return mSerialPort;
	}

	@SuppressLint("HandlerLeak")
	private class MyIdPosHandler extends Handler {
		public MyIdPosHandler() {
		}

		public void handleMessage(Message msg) {
			switch (msg.what) {
				case CLOSE:
					if (dialog != null) {
						dialog.dismiss();
					}

					Boolean scanBack = SharedPreferences2Obj.getInstance(mcontext).setName("config").getObject("scanBack", Boolean.class);
					if (MyApp.getInstance().getCheckType()==0&&scanBack != null && scanBack) {
						checkScan();
					}
					break;
				default:
					break;
			}
		}
	}

	private void checkScan() {
		if (MyApp.getInstance().getCheckType() == 0) {
			Integer Select = SharedPreferences2Obj
					.getInstance(mcontext)
					.setName("SelectAction").getObject("Select", Integer.class);
			Intent intent = new Intent(mcontext,
					ScanerOrderActivity.class);
			if (Select != null) {
				if (Select == SelectAction.Check.getValue()) {
					intent.putExtra("titleName",
							mcontext.getString(R.string.check_scan_code));
				} else if (Select == SelectAction.Reprint.getValue()) {
					intent.putExtra("titleName",
							mcontext.getString(R.string.repriint_scan_code));
				} else if (Select == SelectAction.Query.getValue()) {
					intent.putExtra("titleName",
							mcontext.getString(R.string.query_scan_code));
				}
			} else {
				intent.putExtra("titleName",
						mcontext.getString(R.string.scan_qr_code));
			}
			mcontext.startActivity(intent);
			Activity activity = (Activity) mcontext;
			activity.finish();
		}
	}

	@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);
			}
		}
	}

	@SuppressLint("SimpleDateFormat")
	private void sendCharacterDemo(List<String> arr) {

		LogUtil.e(TAG, "#########sendCharacterDemo##########");

		for (int x = 0; x < printNum; x++) {
			if (x == 1 && isStatistic.equals("1")) {
				close();
				return;
			}

			try {
				if (isStatistic != null && isStatistic.equals("1")) {
					mSerialPrinter.enlargeFontSize(2, 2);//
					mSerialPrinter.printString("    统计信息", x);
					sleep(100);
				} else {
					mSerialPrinter.enlargeFontSize(2, 2);//
					mSerialPrinter.printString("    订单信息", x);
					sleep(100);
					// 当时重打小票的时候,多打一段字符

					if (Select == SelectAction.Reprint.getValue()) {
						mSerialPrinter.enlargeFontSize(1, 1);
						mSerialPrinter.printString("           (重打小票)", x);
						sleep(100);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				mSerialPrinter.setLineSpace(5); // 间隔
				sleep(100);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (arr == null) {
				return;
			}
			// 打印信息
			try {
				mSerialPrinter.enlargeFontSize(1, 1);
				for (int i = 0; i < arr.size(); i++) {
					mSerialPrinter.printString(arr.get(i), x);
					mSerialPrinter.sendLineFeed();
					sleep(100);
				}
				if (isStatistic != null && isStatistic.equals("1")) {

				} else {
					if (Select == SelectAction.Query.getValue()) { // 打印时间
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");// 设置日期格式
						mSerialPrinter.printString(
								"检票时间:" + df.format(new Date()), x);// new
						sleep(100);
						// Date()为获取当前系统时间
						mSerialPrinter.sendLineFeed();
					} else if(Select == SelectAction.Reprint.getValue()) {// 重打时间
						SimpleDateFormat df = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");// 设置日期格式
						mSerialPrinter.printString(
								"重打时间:" + df.format(new Date()), x);// new
						sleep(100);
						// Date()为获取当前系统时间
						mSerialPrinter.sendLineFeed();
					}
					mSerialPrinter.setLineSpace(10);
					mSerialPrinter.sendLineFeed();
					mSerialPrinter.printString("取票人签名:", x);
					sleep(100);
					mSerialPrinter.setLineSpace(10);
				}

				mSerialPrinter.sendLineFeed();

				if (constant.logoMark == LogoType.CYT.getValue()) {
					mSerialPrinter.printString("---畅游通—智慧旅游O2O平台---", x);
					sleep(100);
					mSerialPrinter.sendLineFeed();
					mSerialPrinter.printString(
							"--------www.jingqu.cn---------", x);
				} else if (constant.logoMark == LogoType.QNE.getValue()) {
					mSerialPrinter.printString("---欢迎使用去哪儿网O2O系统---", x);
					sleep(100);
					mSerialPrinter.sendLineFeed();
					sleep(100);
					mSerialPrinter.printString("--------www.qunar.com--------",
							x);
					sleep(100);
				}
				mSerialPrinter.sendLineFeed();
				sleep(100);
			} catch (Exception e) {
				e.printStackTrace();
			}

			// 信息完打印的空格行数
			try {
				mSerialPrinter.setLineSpace(30); //
				sleep(100);
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				mSerialPrinter.walkPaper(60);//
				sleep(100);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//sleep(1500);
		LogUtil.e(TAG, "print end");
	}

	public void sleep(int ms) {

		try {
			Thread.sleep(ms);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void close() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				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) {
				} catch (Exception e) {
				}
				idPosHandler.sendMessage(idPosHandler.obtainMessage(CLOSE, 1,
						0, null));
			}
		}).start();
	}

	@Override
	public void closeback() {
		close();
	}

}