comm

package Serial2;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.comm.*;
class R_Frame extends Frame implements Runnable,ActionListener,SerialPortEventListener{
 static CommPortIdentifier  portId;  //檢測系統中可用的通信端口
 static Enumeration   portList;      //Enumeration爲枚舉型類,在java.util.*中
 InputStream  inputStream;
 SerialPort serialPort;   //聲明RS-232串口的成員變量
 Thread readThread;
 String str="";
 String str1="";
 TextField  out_message = new TextField("上面文本框顯示接受到的數據");
 TextArea   in_message  = new TextArea();
 Button     btnOpen = new Button("打開串口");
 
 //建立窗體
 R_Frame(){
  super("串口接收數據");
  setSize(200,200);
  setVisible(true);
  btnOpen.addActionListener(this);
  add(out_message,"South");
  add(in_message,"Center");
  add(btnOpen,"North");
 }
 
 //偵聽到串口有數據,觸發串口事件
 public void actionPerformed(ActionEvent event){
  portList = CommPortIdentifier.getPortIdentifiers();
  // 測試此枚舉是否包含更多的元素。
  while(portList.hasMoreElements()){
   portId = (CommPortIdentifier)portList.nextElement();   //如果此枚舉對象至少還有一個可提供的元素,則返回此枚舉的下一個元素。
   if(portId.getPortType()==CommPortIdentifier.PORT_SERIAL){
    if(portId.getName().equals("COM1")){
     try{
      serialPort = (SerialPort)portId.open("ReadComm",2000);
      out_message.setText("已打開端口COM1,正在接收數據.......");
     }
     catch(PortInUseException e){
      e.printStackTrace();
     }
     
     try{
      serialPort.addEventListener(this);
      
     }
     catch(TooManyListenersException e){
      
     }
     serialPort.notifyOnDataAvailable(true);
    }
   }
  }
  readThread = new Thread(this);
  readThread.start();     //線程負責每接受一次數據休眠20秒
 }
 
 //接收數據後休眠20秒
 public void run(){
  try{
   Thread.sleep(20000);
  }
  catch(InterruptedException e){
   
  }
 }
 
 //串口監聽器觸發的事件,設置串口通信參數,讀取數據並寫到文本區中
 public void serialEvent(SerialPortEvent event){
  try{
   //設置串口通信參數:波特率、數據位、停止位、奇偶校驗
   serialPort.setSerialPortParams(9600,
           SerialPort.DATABITS_8,
           SerialPort.STOPBITS_1,
           SerialPort.PARITY_NONE);
   
  }
  catch(UnsupportedCommOperationException e){
   
  }
  /*switch(event.getEventType()){
  case SerialPortEvent.BI:
  case SerialPortEvent.OE:
  case SerialPortEvent.FE:
  case SerialPortEvent.PE:
  case SerialPortEvent.CD:
  case SerialPortEvent.CTS:
  case SerialPortEvent.DSR:
  case SerialPortEvent.RI:
  case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
   break;
  case SerialPortEvent.DATA_AVAILABLE:*/
  
   byte[] readBuffer = new byte[5120];
   
   try{
    inputStream = serialPort.getInputStream();
   }
   catch(IOException e){
   
   }
   try{
    //從線路上讀取數據流
    while(inputStream.available()>0){
     int numBytes = inputStream.read(readBuffer);
    }
    str = new String(readBuffer);
    //System.out.print(str);
    
    //str = new String("");
    //接收到的數據存放到文本區中
    str1 =in_message.getText();
    System.out.print(str1);
    //in_message.append(str+"\n");
    //接收到的數據存放到文件中
    
     try{
      FileOutputStream fos = new FileOutputStream("1.txt");
      //PrintWriter fos = new PrintWriter(new BufferedWriter( new FileWriter("1.txt")));
      OutputStreamWriter osw = new OutputStreamWriter(fos);
       BufferedWriter bw = new BufferedWriter(osw);
      
      //fos.write(str.getBytes("GBK"));
      //for(int i =0;i<readBuffer.length;i++){
        //fos.write(String.valueOf(readBuffer[i]).getBytes("UTF-8"));
       bw.write(str);
       bw.flush();
       bw.close();
       //fos.write("G".getBytes());
      // System.out.println(readBuffer[i]);
       // bw.write(String.valueOf(readBuffer[i]));
       //dos.writeByte(b);
       
       //}
      //bw.write(str);
      //bw.flush();
      //bw.close();
      //str = str;
      // fos.write(str.getBytes());
   
    
      //fos.close();
    }
    catch(IOException e){}
    
    
   }
   catch(IOException e){
   
   }
  //break;
  //}
 }
}
public class ReadComm {
   public static void main(String args[]){
    R_Frame R_Win = new R_Frame();   //實例化接收串口數據的窗體類
 
    //定義窗體適配器的關閉按鈕功能
    R_Win.addWindowListener(new WindowAdapter(){
     public void windowClosing(WindowEvent e){
      System.exit(0);
     }
    });
    R_Win.pack();
   }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章