论坛首页 Java企业应用论坛

最近基于rxtx包做了一些串口开发

浏览 3986 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-06-16   最后修改:2011-06-23

    * 官方demo版只有一个线程实现和一个监听实现,所以都是main方法。知道需要连接的串口号,对于实际开发中不太实用,因为咱们一般都是自动获取的多嘛。。所以这文章就算是总结吧。

 

 

    先说一下连接思路,由于串口设备需要热拨插,所以我必须写一个线程一直监控着端口的状态是否正常,所以可以按以下几个步骤进行解决。

 

    1.  列出可用的串口列表;(如果某串口被占用证明是被打开通讯后的,此时不会在这个列表中,还有一般的串口号不会是什么 COM1 、COM2、COM3之类的,所以我会做一些过滤)

 

 

public static List<String> getAvailableSerialPortsName() {
	List<String> result = new ArrayList<String>();
		Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
                     while (thePorts.hasMoreElements()) {
			CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement();
			switch (com.getPortType()) {
			case CommPortIdentifier.PORT_SERIAL:
				CommPort thePort = null;
				try {//过滤COM1-3
					thePort = com.open("CommUtil", 50);
					if (!Pattern.compile("COM[1-3]\\b").matcher(com.getName()).matches()) {
						result.add(com.getName());
					}
				} catch (PortInUseException e) {
					// log.debug("Port, " + com.getName() + ", is in use.");
				} catch (Exception e) {
					log.error("Failed to open port " + com.getName());
				} finally {
					if (thePort != null) {
						thePort.close();
					}
				}
			}
		}
		return result;
	}
 

 

 

    2.  如果系统未正常连接时,会把串口列表中的端口放入队列中,然后每个串口都去打开连接测试,确保哪个串口可用;(连接串口时成功后发送串口指令,只有返回OK的才是我需要用的端口,并记录下串口名,而这里使用了SWT的UI线程,所以主线程是每3秒跑一次,里面等待设备返回状态的是2秒,所以基本上也能满足到测试连接的效果)

 

 

public static boolean connectTest(final String portName) {
		CommPortIdentifier portIdentifier;
		try {
			portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
			if (portIdentifier.isCurrentlyOwned()) {
				log.error("错误:串口被占用");
				return false;
			} else {
				commPort = portIdentifier.open(TDUtil.class.getName(), 2000);
				if (commPort instanceof SerialPort) {
					SerialPort serialPort = (SerialPort) commPort;
					serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
					final InputStream in = serialPort.getInputStream();
					OutputStream out = serialPort.getOutputStream();
					out.write("AT+CLIP=1\r".getBytes());
					// 停顿2秒,为了话机返回数据给予时间
					Display.getCurrent().timerExec(1000, new Runnable() {
						public void run() {
							try {
								byte[] readBuffer = new byte[20];
								in.read(readBuffer);
								String result = new String(readBuffer, "GBK").trim();
								if (result != null && result.indexOf("OK") != -1) {
									log.debug(portName + "可用");
									setProtName(portName);
								} else {
									log.debug(portName + "不可用");
									setProtName(null);
								}
							} catch (IOException e) {
								e.printStackTrace();
							} finally {
								if (commPort != null) {
									log.debug(portName + "串口关闭");
									commPort.close();
								}
							}
						}
					});
				} else {
					log.error("Error: Only serial ports are handled by this example.");
					return false;
				}
			}
		} catch (NoSuchPortException e) {
			log.error("不支持的串口异常!" + e.getMessage());
			e.printStackTrace();
		} catch (PortInUseException e) {
			log.error("串口被战用异常!" + e.getMessage());
			e.printStackTrace();
		} catch (UnsupportedCommOperationException e) {
			log.error("不支持的串口操作异常!" + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			log.error("IO异常!" + e.getMessage());
			e.printStackTrace();
		}
		return false;
	}
 

 

 

    3.  把可用的端口记录到系统中,这样标识连接状态是正常的。如果非法拨出设备,线程会监控到没有可用的端口,此时再把状态置为不可用。等待着下次设备正常连接后重复上面的1、2操作,然后把原来的端口关闭即可。

 

 

 

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics