1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java rxtx_Java使用开源Rxtx实现串口通讯(串口开发) | 学步园

java rxtx_Java使用开源Rxtx实现串口通讯(串口开发) | 学步园

时间:2022-11-15 19:45:46

相关推荐

java  rxtx_Java使用开源Rxtx实现串口通讯(串口开发) | 学步园

importgnu.io.*;

importjava.io.*;

importjava.util.*;

importcom.call.dao.*;

publicclassSerialReaderextendsObservableimplementsRunnable,SerialPortEventListener

{

staticCommPortIdentifierportId;

intdelayRead=100;

intnumBytes;//buffer中的实际数据字节数

privatestaticbyte[]readBuffer=newbyte[1024];//4k的buffer空间,缓存串口读入的数据

staticEnumerationportList;

InputStreaminputStream;

OutputStreamoutputStream;

staticSerialPortserialPort;

HashMapserialParams;

ThreadreadThread;//本来是static类型的

//端口是否打开了

booleanisOpen=false;

//端口读入数据事件触发后,等待n毫秒后再读取,以便让数据一次性读完

publicstaticfinalStringPARAMS_DELAY="delayread";//延时等待端口数据准备的时间

publicstaticfinalStringPARAMS_TIMEOUT="timeout";//超时时间

publicstaticfinalStringPARAMS_PORT="portname";//端口名称

publicstaticfinalStringPARAMS_DATABITS="databits";//数据位

publicstaticfinalStringPARAMS_STOPBITS="stopbits";//停止位

publicstaticfinalStringPARAMS_PARITY="parity";//奇偶校验

publicstaticfinalStringPARAMS_RATE="rate";//波特率

publicbooleanisOpen(){

returnisOpen;

}

/**

*初始化端口操作的参数.

*@throwsSerialPortException

*

*@see

*/

publicSerialReader()

{

isOpen=false;

}

publicvoidopen(HashMapparams)

{

serialParams=params;

if(isOpen){

close();

}

try

{

//参数初始化

inttimeout=Integer.parseInt(serialParams.get(PARAMS_TIMEOUT)

.toString());

intrate=Integer.parseInt(serialParams.get(PARAMS_RATE)

.toString());

intdataBits=Integer.parseInt(serialParams.get(PARAMS_DATABITS)

.toString());

intstopBits=Integer.parseInt(serialParams.get(PARAMS_STOPBITS)

.toString());

intparity=Integer.parseInt(serialParams.get(PARAMS_PARITY)

.toString());

delayRead=Integer.parseInt(serialParams.get(PARAMS_DELAY)

.toString());

Stringport=serialParams.get(PARAMS_PORT).toString();

//打开端口

portId=CommPortIdentifier.getPortIdentifier(port);

serialPort=(SerialPort)portId.open("SerialReader",timeout);

inputStream=serialPort.getInputStream();

serialPort.addEventListener(this);

serialPort.notifyOnDataAvailable(true);

serialPort.setSerialPortParams(rate,dataBits,stopBits,parity);

isOpen=true;

}

catch(PortInUseExceptione)

{

//端口"+serialParams.get(PARAMS_PORT).toString()+"已经被占用";

}

catch(TooManyListenersExceptione)

{

//"端口"+serialParams.get(PARAMS_PORT).toString()+"监听者过多";

}

catch(UnsupportedCommOperationExceptione)

{

//"端口操作命令不支持";

}

catch(NoSuchPortExceptione)

{

//"端口"+serialParams.get(PARAMS_PORT).toString()+"不存在";

}

catch(IOExceptione)

{

//"打开端口"+serialParams.get(PARAMS_PORT).toString()+"失败";

}

serialParams.clear();

ThreadreadThread=newThread(this);

readThread.start();

}

publicvoidrun()

{

try

{

Thread.sleep(50);

}

catch(InterruptedExceptione)

{

}

}

publicvoidstart(){

try{

outputStream=serialPort.getOutputStream();

}

catch(IOExceptione){}

try{

readThread=newThread(this);

readThread.start();

}

catch(Exceptione){}

}//start()end

publicvoidrun(Stringmessage){

try{

Thread.sleep(4);

}

catch(InterruptedExceptione){}

try{

if(message!=null&&message.length()!=0)

{

System.out.println("runmessage:"+message);

outputStream.write(message.getBytes());

}

}catch(IOExceptione){}

}

publicvoidclose()

{

if(isOpen)

{

try

{

serialPort.notifyOnDataAvailable(false);

serialPort.removeEventListener();

inputStream.close();

serialPort.close();

isOpen=false;

}catch(IOExceptionex)

{

//"关闭串口失败";

}

}

}

publicvoidserialEvent(SerialPortEventevent)

{

try

{

Thread.sleep(delayRead);

}

catch(InterruptedExceptione)

{

e.printStackTrace();

}

switch(event.getEventType())

{

caseSerialPortEvent.BI://10

caseSerialPortEvent.OE://7

caseSerialPortEvent.FE://9

caseSerialPortEvent.PE://8

caseSerialPortEvent.CD://6

caseSerialPortEvent.CTS://3

caseSerialPortEvent.DSR://4

caseSerialPortEvent.RI://5

caseSerialPortEvent.OUTPUT_BUFFER_EMPTY://2

break;

caseSerialPortEvent.DATA_AVAILABLE://1

try

{

//多次读取,将所有数据读入

while(inputStream.available()>0){

numBytes=inputStream.read(readBuffer);

}

//打印接收到的字节数据的ASCII码

for(inti=0;i

//System.out.println("msg["+numBytes+"]:["+readBuffer[i]+"]:"+(char)readBuffer[i]);

}

//numBytes=inputStream.read(readBuffer);

changeMessage(readBuffer,numBytes);

}

catch(IOExceptione)

{

e.printStackTrace();

}

break;

}

}

//通过observerpattern将收到的数据发送给observer

//将buffer中的空字节删除后再发送更新消息,通知观察者

publicvoidchangeMessage(byte[]message,intlength)

{

setChanged();

byte[]temp=newbyte[length];

System.arraycopy(message,0,temp,0,length);

notifyObservers(temp);

}

staticvoidlistPorts()

{

EnumerationportEnum=CommPortIdentifier.getPortIdentifiers();

while(portEnum.hasMoreElements())

{

CommPortIdentifierportIdentifier=(CommPortIdentifier)portEnum

.nextElement();

}

}

publicvoidopenSerialPort(Stringmessage)

{

HashMapparams=newHashMap();

otherDAOodao=newotherDAO();

Stringport=odao.selectNumberById(15);

Stringrate="9600";

StringdataBit=""+SerialPort.DATABITS_8;

StringstopBit=""+SerialPort.STOPBITS_1;

Stringparity=""+SerialPort.PARITY_NONE;

intparityInt=SerialPort.PARITY_NONE;

params.put(SerialReader.PARAMS_PORT,port);//端口名称

params.put(SerialReader.PARAMS_RATE,rate);//波特率

params.put(SerialReader.PARAMS_DATABITS,dataBit);//数据位

params.put(SerialReader.PARAMS_STOPBITS,stopBit);//停止位

params.put(SerialReader.PARAMS_PARITY,parityInt);//无奇偶校验

params.put(SerialReader.PARAMS_TIMEOUT,100);//设备超时时间1秒

params.put(SerialReader.PARAMS_DELAY,100);//端口数据准备时间1秒

try{

open(params);//打开串口

LoginFramecf=newLoginFrame();

addObserver(cf);

if(message!=null&&message.length()!=0)

{

Stringstr="";

for(inti=0;i<10;i++)

{

str+=message;

}

start();

run(str);

}

}catch(Exceptione){

}

}

staticStringgetPortTypeName(intportType)

{

switch(portType)

{

caseCommPortIdentifier.PORT_I2C:

return"I2C";

caseCommPortIdentifier.PORT_PARALLEL:

return"Parallel";

caseCommPortIdentifier.PORT_RAW:

return"Raw";

caseCommPortIdentifier.PORT_RS485:

return"RS485";

caseCommPortIdentifier.PORT_SERIAL:

return"Serial";

default:

return"unknowntype";

}

}

publicHashSetgetAvailableSerialPorts()//本来static

{

HashSeth=newHashSet();

EnumerationthePorts=CommPortIdentifier.getPortIdentifiers();

while(thePorts.hasMoreElements())

{

CommPortIdentifiercom=(CommPortIdentifier)thePorts

.nextElement();

switch(com.getPortType())

{

caseCommPortIdentifier.PORT_SERIAL:

try

{

CommPortthePort=com.open("CommUtil",50);

thePort.close();

h.add(com);

}

catch(PortInUseExceptione)

{

System.out.println("Port,"+com.getName()

+",isinuse.");

}

catch(Exceptione)

{

System.out.println("Failedtoopenport"

+com.getName()+e);

}

}

}

returnh;

}

}

//ASCII表

//-------------------------------------------------------------

//ASCIICharacters

//

//DecHexCharCodeDecHexChar

//

//00NUL6440@

//11SOH6541A

//22STX6642B

//33ETX6743C

//44EOT6844D

//55ENQ6945E

//66ACK7046F

//77BEL7147G

//88BS7248H

//99HT7349I

//100ALF744AJ

//110BVT754BK

//120CFF764CL

//130DCR774DM

//140ESO784EN

//150FSI794FO

//1610SLE8050P

//1711CS18151Q

//1812DC28252R

//1913DC38353S

//DC48454T

//2115NAK8555U

//2216SYN8656V

//2317ETB8757W

//2418CAN8858X

//2519EM8959Y

//261ASIB905AZ

//271BESC915B[

//925C\

//281CFS935D]

//291DGS945E^

//301ERS955F_

//311FUS9660`

//3220(space)9761a

//3321!9862b

//3422"

//9963c

//3523#10064d

//3624$

//3725%10165e

//3826&10266f

//3927'10367g

//4028(10468h

//4129)10569i

//422A*1066Aj

//432B+1076Bk

//442C,1086Cl

//452D-1096Dm

//462E.1106En

//472F/1116Fo

//4830011270p

//4931111372q

//5032211472r

//5133311573s

//5234411674t

//5335511775u

//5436611876v

//5537711977w

//5638812078x

//5739912179y

//583A:1227Az

//593B;1237B{

//603C

//613D=1257D}

//623E>1267E~

//633F?1277F

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。