android java 经典字符模式通信接收处理,标准modbus通讯协议接收处理提取数据

通信接收处理

一、字符

接收数据字符串格式:Te:xx Hu:xx GM:xxx CO:xxx \r\n

要提取上面这3个参数的值。

代码:

    	try {
			if (smsg.endsWith("\r\n") &&smsg.length()>20) {
				String s = "Te:";
				if (smsg.contains(s)) {
					int beginIndex = smsg.lastIndexOf(s);
					int endIndex = smsg.indexOf(' ',beginIndex + s.length());
					textView001.setText(smsg.substring(beginIndex + s.length(), endIndex));
					
				}
				s = "Hu:";
				if (smsg.contains(s)) {
					int beginIndex = smsg.lastIndexOf(s);// 761-754
					int endIndex = smsg.indexOf(' ',beginIndex + s.length());
					textView002.setText(smsg.substring(beginIndex + s.length(), endIndex));
				}
				s = "GM:";
				if (smsg.contains(s)) {
					int beginIndex = smsg.lastIndexOf(s);// 761-754
					int endIndex = smsg.indexOf(' ',
							beginIndex + s.length());
					textView003.setText(smsg.substring(beginIndex + s.length(), endIndex));
				}
				s = "CO:";
				if (smsg.contains(s)) {
					int beginIndex = smsg.lastIndexOf(s);// 761-754
					int endIndex = smsg.indexOf('\r',beginIndex + s.length());
					textView004.setText(smsg.substring(beginIndex + s.length(), endIndex).replaceAll(" ", ""));
				}
		
			}
		
		} catch (Exception e) {
		}

二、十六进制

临时

// 接收数据线程
	Thread ReadThread = new Thread() {
		public void run() {
			byte[] buffer = new byte[1];
			bRun = true;
			// 接收线程
			while (true) {
				try {
					while (is.available() == 0) {
						while (bRun == false) {

						}
					}
					while (true) {
						if (1 == is.read(buffer, 0, 1)) // 一个一个地接收,把需要的数据放在buffer_new中
						{
							if (num_new == 0) {
								if (buffer[0] == Wka.add) {
									buffer_new[num_new++] = buffer[0];
								}
							} else if (num_new == 1) {
								buffer_new[num_new++] = buffer[0];
							} else if (num_new < buffer_new[1]) {
								buffer_new[num_new++] = buffer[0];
							}
							// smsg+=String.format("%02X ",buffer[0]);
							// //转为十六进制格式 所有接收
						}
						// 接收处理最好放在线程中
						if (num_new == buffer_new[1]) {
							if ((buffer_new[num_new - 4] & 0xff) == 0xCC
									&& (buffer_new[num_new - 3] & 0xff) == 0x33
									&& (buffer_new[num_new - 2] & 0xff) == 0xC3
									&& (buffer_new[num_new - 1] & 0xff) == 0x3C) {
								Wka.jszt = buffer_new[3];
								if (Wka.jszt == 0x1f)
									Wka.ds++;

								if (Wka.jszt == 0) //
									Wka.pow_con = 0; // 更改状态
								else
									Wka.pow_con = 1;

								Wka.temsj = buffer_new[17] & 0xff;
								Wka.jserrno = buffer_new[16] & 0xff;
							}
							num_new = 0;
						}
						if (is.available() == 0)
							break; // 短时间没有数据才跳出进行显示
					}
					// 发送显示消息,进行显示刷新
					handler.sendMessage(handler.obtainMessage());
				} catch (IOException e) {
				}
			}
		}
	};

标准modbus通讯协议接收处理

之前写的代码,打不到放那了。

你可能感兴趣的:(Android复习)