项目总结:一种Java串口自定义协议解析方法

2016年6月28日 由 Creater 留言 »
	class ReceiveThread extends Thread {
		private InputStream mInputStream;
		@Override  
		public void run() {  
			super.run();  
			mInputStream = serialPort.getInputStream();
			int maxLength = 2048;  //2016-06-26
			byte[] buffer = new byte[maxLength];  
			int available = 0;  
			int currentLength = 0;   
			int factPackLen = 6;  

			while (!serialPort.isOpen) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			//while (!isInterrupted()) {  
			while (true) {  
				try {  
					available = mInputStream.available();  
					if (available > 0) {  
						// 防止超出数组最大长度导致溢出  
						//System.out.println("available+++++++++++++++++++++++++:"+available);  
						if (available > maxLength - currentLength) {  
							available = maxLength - currentLength;  
						}  
						mInputStream.read(buffer, currentLength, available);  
						currentLength += available;  
					}else{
						Thread.sleep(10);
					}
				}  
				catch (Exception e) {  
					e.printStackTrace();  
				}  
				int cursor = 0;  
				while (currentLength >= factPackLen) {  
					if (buffer[cursor] != (byte)0xFB) {  
						//System.out.println("未发现头部");
						--currentLength;  
						++cursor;  
						continue;  
					}  
					if (currentLength < factPackLen) {  
						break;  
					} 
					if(buffer[cursor + factPackLen - 1] != (byte)0xFE){

						--currentLength;  
						++cursor; 
						continue;
					}
					// System.out.println("发现完整帧");
					onDataReceived(buffer, cursor, factPackLen);  
					currentLength -= factPackLen;  
					cursor += factPackLen;   
				}  
				if (currentLength > 0 && cursor > 0) {  
					System.arraycopy(buffer, cursor, buffer, 0, currentLength);  
				}  
			}  
		}  
	}  
	protected void onDataReceived(final byte[] buffer, final int index, final int packlen) {  
		byte[] buf = new byte[packlen];  
		System.arraycopy(buffer, index, buf, 0, packlen);  
		getUploadData(buf);
	} 
广告位

发表评论

你必须 登陆 方可发表评论.