- importjava.io.*;
- importjava.util.*;
- importjavax.comm.*;
- importjavax.swing.*;
- importjava.awt.*;
- importjava.awt.event.*;
- publicclassSimpleReadimplementsRunnable,SerialPortEventListener{
- staticCommPortIdentifierportId;
- staticEnumerationportList;
- InputStreaminputStream;
- SerialPortserialPort;
- ThreadreadThread;
- introadData=250;
- JFrameframe;
- classserialPaintextendsJPanelimplementsRunnable
- {
- publicvoidpaintComponent(GraphicsdrawPaint)
- {
- drawPaint.setColor(Color.blue);
- //drawPaint.fillRect(roadData,20,20,20);
- drawPaint.fillOval(roadData,250,10,10);
- }
- publicvoidrun()
- {
- go();
- }
- publicvoidgo()
- {
- while(true)
- {
- //roadData++;
- System.out.println(roadData);
- try{
- Thread.sleep(30);
- }catch(InterruptedExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }
- frame.repaint();
- }
- }
- }
- publicvoidui()
- {
- frame=newJFrame();
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- serialPaintserialpaint=newserialPaint();
- frame.add(serialpaint);
- frame.setSize(500,500);
- frame.setVisible(true);
- }
- publicvoidserialThread()
- {
- RunnableserialRunnable=newserialPaint();
- ThreadthreadS=newThread(serialRunnable);
- threadS.start();
- }
- publicstaticvoidmain(String[]args){
- //
- portList=CommPortIdentifier.getPortIdentifiers();
- //SimpleReadserialui=newSimpleRead();
- //serialui.ui();
- //serialui.serialThread();
- while(portList.hasMoreElements()){
- portId=(CommPortIdentifier)portList.nextElement();
- if(portId.getPortType()==CommPortIdentifier.PORT_SERIAL){
- if(portId.getName().equals("COM2")){
- //if(portId.getName().equals("/dev/term/a")){
- SimpleReadreader=newSimpleRead();
- reader.ui();
- reader.serialThread();
- }
- }
- }
- }
- publicSimpleRead(){
- try{
- serialPort=(SerialPort)portId.open("SimpleReadApp",2000);
- }catch(PortInUseExceptione){}
- try{
- inputStream=serialPort.getInputStream();
- }catch(IOExceptione){}
- try{
- serialPort.addEventListener(this);
- }catch(TooManyListenersExceptione){}
- serialPort.notifyOnDataAvailable(true);
- try{
- serialPort.setSerialPortParams(9600,
- SerialPort.DATABITS_8,
- SerialPort.STOPBITS_1,
- SerialPort.PARITY_NONE);
- }catch(UnsupportedCommOperationExceptione){}
- readThread=newThread(this);
- readThread.start();
- }
- publicvoidrun(){
- try{
- Thread.sleep(20000);
- }catch(InterruptedExceptione){}
- }
- publicvoidserialEvent(SerialPortEventevent){
- switch(event.getEventType()){
- caseSerialPortEvent.BI:
- caseSerialPortEvent.OE:
- caseSerialPortEvent.FE:
- caseSerialPortEvent.PE:
- caseSerialPortEvent.CD:
- caseSerialPortEvent.CTS:
- caseSerialPortEvent.DSR:
- caseSerialPortEvent.RI:
- caseSerialPortEvent.OUTPUT_BUFFER_EMPTY:
- break;
- caseSerialPortEvent.DATA_AVAILABLE:
- byte[]readBuffer=newbyte[1];
- try{
- while(inputStream.available()>0){
- intnumBytes=inputStream.read(readBuffer);
- }
- System.out.print(newString(readBuffer));
- roadData=readBuffer[0];
- }catch(IOExceptione){}
- break;
- }
- }
- }