java 串口通信 代码

下面是我自己实现的串口接收的类,串口发送比较简单,就直接发送就可以了。下面的这个类可以直接使用。

package com.boomdts.weather_monitor.util;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.comm.*;
import com.boomdts.weather_monitor.biz.RecvCommand;
import com.boomdts.weather_monitor.util.SysLog;
/*
串口通信类
*/
public class SerialComm {
private int ibaudRate;
private String scomPort;
private CommPortIdentifier portId = null;
//从外设获取数据
private InputStream inStream ;
//发送命令到外设
private OutputStream outStream ;
private SerialPort serialPort;
public SerialComm(int ibaudRate, String scomPort) {
this.ibaudRate = ibaudRate;
this.scomPort = scomPort;
try {
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements())
{
portId = (CommPortIdentifier) portList.nextElement();
//如果端口类型是串口则判断名称
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
//如果是COM1端口则退出循环
System.out.println("portId = " + portId.getName());
if(portId.getName().equals(scomPort)){
break;
}else{
portId=null;
}
}
}
//打开串口的超时时间为1000ms
SerialPort serialPort = (SerialPort)portId.open("Serial_Communication", 1000);
//设置串口速率为38400,数据位8位,停止位1们,奇偶校验无
serialPort.setSerialPortParams(ibaudRate,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
//建立好监听类以后要在port上添加。
//其中port是上文打开的串口端口,commListener是上文的监听器实例
serialPort.addEventListener(new CommListener(serialPort));
//设置监听模式为当有数据到达时唤醒监听线程。
serialPort.notifyOnDataAvailable(true);
// Set notifyOnBreakInterrup to allow event driven break handling.
serialPort.notifyOnBreakInterrupt(true);
// Set receive timeout to allow breaking out of polling loop during input handling.
serialPort.enableReceiveTimeout(30);
//发送命令到外设
OutputStream outStream = new BufferedOutputStream(serialPort.getOutputStream());
//new ReceiveThread(inStream).start();
//new SendThread(outStream).start();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
} catch (PortInUseException e) {
e.printStackTrace();
} catch (TooManyListenersException e) {
e.printStackTrace();
}
SysLog.logger.info("串口打开成功!");
}
}
//建立监听类,继承自javax.comm.SerialPortEventListener;
class CommListener implements SerialPortEventListener {
private StringBuffer linkWgt ;//存放获取的数据
private String sCommand ;//上传的命令
private SerialPort serialPort ;
private InputStream inStream ;
private RecvCommand recvCommand;
public CommListener(SerialPort serialPort){
recvCommand = new RecvCommand();
linkWgt = new StringBuffer();
sCommand = new String();
this.serialPort = serialPort;
try {
//从外设获取数据
this.inStream = new BufferedInputStream(serialPort.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
//实现监听方法
public void serialEvent(SerialPortEvent e){
int newData = 0;
byte bRead[] = {0};
String sSubStr = "";
// Determine type of event.
switch (e.getEventType()) {
// Read data until -1 is returned. If \r is received substitute
// \n for correct newline handling.
case SerialPortEvent.DATA_AVAILABLE:
while (newData != -1) {
try {
//inStream = serialPort.getInputStream();
newData = inStream.read();
if (newData == -1) {
break;
}
if ('\r' == (char)newData) {
} else {
//把0~255的int转换成两位的16进制字符串
sSubStr = Integer.toHexString((newData & 0x000000FF) | 0xFFFFFF00).substring(6);
//System.out.println(sSubStr);
linkWgt.append(sSubStr);
}
} catch (IOException ex) {
System.err.println(ex);
return;
}
}
try{
System.out.println("linkWgt 提取命令前----start-----" + linkWgt.toString() + "----end-----");
while(linkWgt.indexOf("a55a") != -1) {
linkWgt.delete(0,linkWgt.indexOf("a55a"));
if(linkWgt.indexOf("9191910000") == -1)
{
System.out.println("该命令内容错误!" + linkWgt);
} else {
sCommand =linkWgt.substring(0, linkWgt.indexOf("9191910000"));
linkWgt.delete(0,linkWgt.indexOf("9191910000"));
System.out.println("sCommand ----start-----" + sCommand + "----end-----");
recvCommand.analyze(sCommand);
}
}
}catch(Exception ew){
ew.printStackTrace();
}finally{
}
break;
// If break event append BREAK RECEIVED message.
case SerialPortEvent.BI:
System.out.println("\n--- BREAK RECEIVED ---\n");
}
}
}
上一篇:无法使用以下搜索标准找到 X.509 证书: StoreName“My”、StoreLocation“LocalMachine”、FindType“FindBySubjectName”、FindValue“MyWebSite”。


下一篇:s21day13 python笔记