2013-05-28 129 views
0

當我嘗試從串行COM使用RXTX讀取字符串緩衝區時,出現了奇怪的結果。 向COM寫入字符串後,我必須將該字符串存儲爲回覆。這是在一個循環內。在控制檯中打印的字符串有時不會對最後的寫入命令作出響應,但屬於前一個寫入命令。JAVA:使用RXTX從串行寫入和讀取緩衝區

 while (running) { 
      char campioni = (char) start; 
      hexStart = Integer.toHexString(campioni).toUpperCase(); 
      String stringa = ">eL#" + hexStart + "??!\r\n" + "\n"; 
      output.write((">eL" + "L#" + hexStart + "??!\r\n").getBytes()); 
      output.flush(); 

      byte[] buffer = new byte[10000]; 

      n=0; 
     try { 
      n = input.read(buffer); 
     } catch (IOException e1) { 
     e1.printStackTrace(); 
     } 

      if(n>0){ 
        String data = new String (buffer,0,n); 
        System.out.println(new String(buffer)); 
        start=start+5; 
        Thread.sleep(2000); 
       } 
      } 
+0

請重新格式化您的代碼 – Beryllium

回答

0

我找到了兩件事情,你可以檢查

  • 是它造成的睡眠?
  • System.out可能被緩衝;您正在使用打印(與println不同),所以如果您的緩衝區不包含CR/LF,它可能不會立即顯示。
+0

我認爲這是一個監督。現在我糾正它。我把睡眠緩衝整個字符串的大小。 –

0

下面的例子是用戶讀取由RFID閱讀器掃描的RFID值

1) Reader Form Build in netbeans 

    /* 
    * To change this license header, choose License Headers in Project Properties. 
    * To change this template file, choose Tools | Templates 
    * and open the template in the editor. 
    */ 
    package rfid_thumb; 

    import com.data.access.AbstractDao; 
    import gnu.io.SerialPort; 

    /** 
    * 
    * @author ANGEL 
    */ 
    public class ReaderForm extends javax.swing.JFrame { 

     /** 
     * Creates new form ReaderForm 
     */ 
     public AbstractDao abstractDao=new AbstractDao(); 
     SerialPort serialPort, serialPort1; 
     //Communicator object 
     Communicator communicator = null; 
     //KeybindingController object 


     @Override 
     public void list() { 
      super.list(); //To change body of generated methods, choose Tools | Templates. 
     } 


     public ReaderForm() { 
      initComponents(); 
      createObjects(); 
      communicator.searchForPorts(); 
     } 

     private void createObjects() 
     { 
      communicator = new Communicator(this); 
     } 

     /** 
     * This method is called from within the constructor to initialize the form. 
     * WARNING: Do NOT modify this code. The content of this method is always 
     * regenerated by the Form Editor. 
     */ 
     @SuppressWarnings("unchecked") 
     // <editor-fold defaultstate="collapsed" desc="Generated Code">       
     private void initComponents() { 

      jPanel1 = new javax.swing.JPanel(); 
      thumbCobBox = new javax.swing.JComboBox(); 
      jLabel6 = new javax.swing.JLabel(); 
      jLabel7 = new javax.swing.JLabel(); 
      jScrollPane1 = new javax.swing.JScrollPane(); 
      txtLog = new javax.swing.JTextArea(); 
      jButton1 = new javax.swing.JButton(); 
      Scan = new javax.swing.JButton(); 
      jButton3 = new javax.swing.JButton(); 

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

      jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "RFID and Thumb Scanning", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 14))); // NOI18N 

      jLabel6.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N 
      jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); 
      jLabel6.setText("Thumb Scanning Port"); 
      jLabel6.setOpaque(true); 

      jLabel7.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N 
      jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); 
      jLabel7.setText("Logs"); 
      jLabel7.setOpaque(true); 

      txtLog.setColumns(20); 
      txtLog.setRows(5); 
      jScrollPane1.setViewportView(txtLog); 

      jButton1.setText("Connect"); 
      jButton1.addActionListener(new java.awt.event.ActionListener() { 
       public void actionPerformed(java.awt.event.ActionEvent evt) { 
        jButton1ActionPerformed(evt); 
       } 
      }); 

      Scan.setText("Scan"); 
      Scan.addActionListener(new java.awt.event.ActionListener() { 
       public void actionPerformed(java.awt.event.ActionEvent evt) { 
        ScanActionPerformed(evt); 
       } 
      }); 

      jButton3.setText("Enroll"); 
      jButton3.addActionListener(new java.awt.event.ActionListener() { 
       public void actionPerformed(java.awt.event.ActionEvent evt) { 
        jButton3ActionPerformed(evt); 
       } 
      }); 

      javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); 
      jPanel1.setLayout(jPanel1Layout); 
      jPanel1Layout.setHorizontalGroup(
       jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(jPanel1Layout.createSequentialGroup() 
        .addContainerGap(24, Short.MAX_VALUE) 
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
         .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
          .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE) 
          .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)) 
         .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
          .addGroup(jPanel1Layout.createSequentialGroup() 
           .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE) 
           .addGap(18, 18, 18) 
           .addComponent(thumbCobBox, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)) 
          .addGroup(jPanel1Layout.createSequentialGroup() 
           .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE) 
           .addGap(29, 29, 29) 
           .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE) 
           .addGap(18, 18, 18) 
           .addComponent(Scan, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)))) 
        .addGap(34, 34, 34)) 
      ); 
      jPanel1Layout.setVerticalGroup(
       jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(jPanel1Layout.createSequentialGroup() 
        .addContainerGap(37, Short.MAX_VALUE) 
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
         .addComponent(thumbCobBox, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) 
         .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)) 
        .addGap(18, 18, 18) 
        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
         .addGroup(jPanel1Layout.createSequentialGroup() 
          .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) 
          .addGap(13, 13, 13)) 
         .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() 
          .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
           .addComponent(Scan, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) 
           .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) 
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))) 
        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) 
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE) 
        .addContainerGap()) 
      ); 

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
      getContentPane().setLayout(layout); 
      layout.setHorizontalGroup(
       layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(layout.createSequentialGroup() 
        .addContainerGap() 
        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
        .addContainerGap(31, Short.MAX_VALUE)) 
      ); 
      layout.setVerticalGroup(
       layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(layout.createSequentialGroup() 
        .addContainerGap() 
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
        .addContainerGap()) 
      ); 

      pack(); 
     }// </editor-fold>       

     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
      // TODO add your handling code here: 
      communicator.connect(); 
      if (communicator.getConnected() == true) 
      { 
       if (communicator.initIOStream() == true) 
       { 
        communicator.initListener(); 
       } 
      } 
     }           

     private void ScanActionPerformed(java.awt.event.ActionEvent evt) {          
      // TODO add your handling code here: 
     }          

     private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {           
      // TODO add your handling code here: 
     }           

     /** 
     * @param args the command line arguments 
     */ 
     public static void main(String args[]) { 
      /* Set the Nimbus look and feel */ 
      //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
      /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
      * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
      */ 
      try { 
       for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
        if ("Nimbus".equals(info.getName())) { 
         javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
         break; 
        } 
       } 
      } catch (ClassNotFoundException ex) { 
       java.util.logging.Logger.getLogger(ReaderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
      } catch (InstantiationException ex) { 
       java.util.logging.Logger.getLogger(ReaderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
      } catch (IllegalAccessException ex) { 
       java.util.logging.Logger.getLogger(ReaderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
      } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
       java.util.logging.Logger.getLogger(ReaderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
      } 
      //</editor-fold> 

      /* Create and display the form */ 
      java.awt.EventQueue.invokeLater(new Runnable() { 
       public void run() { 
        new ReaderForm().setVisible(true); 
       } 
      }); 
     } 

     // Variables declaration - do not modify      
     private javax.swing.JButton Scan; 
     private javax.swing.JButton jButton1; 
     private javax.swing.JButton jButton3; 
     private javax.swing.JLabel jLabel6; 
     private javax.swing.JLabel jLabel7; 
     private javax.swing.JPanel jPanel1; 
     private javax.swing.JScrollPane jScrollPane1; 
     public javax.swing.JComboBox thumbCobBox; 
     public javax.swing.JTextArea txtLog; 
     // End of variables declaration     
    } 

2)通訊類用於讀取串口值

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 

package rfid_thumb; 

import com.data.model.ThumbTemp; 
import gnu.io.*; 
import java.awt.Color; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.Enumeration; 
import java.util.HashMap; 
import java.util.TooManyListenersException; 
import java.util.Vector; 

public class Communicator implements SerialPortEventListener 
{ 
    //passed from main GUI 
    ReaderForm window = null; 
    public Vector<String> inDataVector; 
    //for containing the ports that will be found 
    private Enumeration ports = null; 
    //map the port names to CommPortIdentifiers 
    private final HashMap portMap = new HashMap(); 
    public int inData = 0, outData = 0, outData1 = 0; 
    //this is the object that contains the opened port 

    private final CommPortIdentifier selectedPortIdentifierT = null; 
    private SerialPort serialPort = null; 
    private SerialPort serialPortT = null; 

    String rfid=""; 
    String thumb=""; 



    private InputStream inputT = null; 
    private OutputStream outputT = null; 

    //just a boolean flag that i use for enabling 
    //and disabling buttons depending on whether the program 
    //is connected to a serial port or not 
    private boolean bConnected = false; 

    //the timeout value for connecting with the port 
    final static int TIMEOUT = 2000; 

    //some ascii values for for certain things 
    final static int SPACE_ASCII = 32; 
    final static int DASH_ASCII = 45; 
    final static int NEW_LINE_ASCII = 10; 

    public boolean dataReady=false, dataReady1=false, receivedPin=false; 

    //a string for recording what goes on in the program 
    //this string is written to the GUI 
    String logText = ""; 

    public Communicator(ReaderForm window) 
    { 
     this.window = window; 
     inDataVector = new Vector<String>(); 
     dataReady = false; 
     dataReady1 = false; 
    } 

    //search for all the serial ports 
    //pre: none 
    //post: adds all the found ports to a combo box on the GUI 
    public void searchForPorts() 
    { 
     ports = CommPortIdentifier.getPortIdentifiers(); 

     while (ports.hasMoreElements()) 
     { 
      CommPortIdentifier curPort = (CommPortIdentifier)ports.nextElement(); 

      //get only serial ports 
      if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL) 
      { 
       //window.rfidComBox.addItem(curPort.getName()); 
       window.thumbCobBox.addItem(curPort.getName()); 
       portMap.put(curPort.getName(), curPort); 
      } 
     } 
    } 

    //connect to the selected port in the combo box 
    //pre: ports are already found by using the searchForPorts method 
    //post: the connected comm port is stored in commPort, otherwise, 
    //an exception is generated 
    public void connect() 
    { 

      //String selectedPort = (String)window.rfidComBox.getSelectedItem(); 
      String selectedPortT = (String)window.thumbCobBox.getSelectedItem(); 

      //selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort); 
      //selectedPortIdentifierT = (CommPortIdentifier)portMap.get(selectedPortT); 
      CommPort commPort = null; 
      CommPort commPortT = null; 
      try 
      { 
       //the method below returns an object of type CommPort 
       // commPort = selectedPortIdentifier.open("TigerControlPanel", TIMEOUT); 
       commPortT = selectedPortIdentifierT.open("TigerControlPanel1", TIMEOUT); 
       //the CommPort object can be casted to a SerialPort object 
       serialPort = (SerialPort)commPort; 
       serialPortT = (SerialPort)commPortT; 

       //for controlling GUI elements 
       setConnected(true); 

       //logging 
       logText = selectedPortT + " opened successfully."; 
       window.txtLog.setForeground(Color.black); 
       window.txtLog.append(logText + "\n"); 

       //CODE ON SETTING BAUD RATE ETC OMITTED 
       //XBEE PAIR ASSUMED TO HAVE SAME SETTINGS ALREADY 

       //enables the controls on the GUI if a successful connection is made 
       //window.keybindingController.toggleControls(); 
      } 
      catch (PortInUseException e) 
      { 
       logText = selectedPortT + " is in use. (" + e.toString() + ")"; 
       window.txtLog.setForeground(Color.RED); 
       window.txtLog.append(logText + "\n"); 
      } 
      catch (Exception e) 
      { 
       logText = "Failed to open " + selectedPortT + "(" + e.toString() + ")"; 
       window.txtLog.append(logText + "\n"); 
       window.txtLog.setForeground(Color.RED); 
      } 
    } 

    //open the input and output streams 
    //pre: an open port 
    //post: initialized intput and output streams for use to communicate data 
    public boolean initIOStream() 
    { 
     //return value for whather opening the streams is successful or not 
     boolean successful = false; 

     try { 
      // 
      //input = serialPort.getInputStream(); 
      //output = serialPort.getOutputStream(); 

      inputT = serialPortT.getInputStream(); 
      outputT = serialPortT.getOutputStream(); 

      //writeData(0, 0); 

      successful = true; 
      return successful; 
     } 
     catch (IOException e) { 
      logText = "I/O Streams failed to open. (" + e.toString() + ")"; 
      window.txtLog.setForeground(Color.red); 
      window.txtLog.append(logText + "\n"); 
      return successful; 
     } 
    } 

    //starts the event listener that knows whenever data is available to be read 
    //pre: an open serial port 
    //post: an event listener for the serial port that knows when data is recieved 
    public void initListener() 
    { 
     try 
     { 
      //serialPort.addEventListener(this); 
      //serialPort.notifyOnDataAvailable(true); 

      serialPortT.addEventListener(this); 
      serialPortT.notifyOnDataAvailable(true); 

     } 
     catch (TooManyListenersException e) 
     { 
      logText = "Too many listeners. (" + e.toString() + ")"; 
      window.txtLog.setForeground(Color.red); 
      window.txtLog.append(logText + "\n"); 
     } 
    } 

    //disconnect the serial port 
    //pre: an open serial port 
    //post: clsoed serial port 
    public void disconnect() 
    { 
     //close the serial port 
     try 
     { 


      serialPort.removeEventListener(); 
      serialPort.close(); 

      serialPortT.removeEventListener(); 
      serialPortT.close(); 

      //input.close(); 
      //output.close(); 

      inputT.close(); 
      outputT.close(); 
      setConnected(false); 
      //window.keybindingController.toggleControls(); 

      logText = "Disconnected."; 
      window.txtLog.setForeground(Color.red); 
      window.txtLog.append(logText + "\n"); 
     } 
     catch (Exception e) 
     { 
      logText = "Failed to close " + serialPort.getName() + "(" + e.toString() + ")"; 
      window.txtLog.setForeground(Color.red); 
      window.txtLog.append(logText + "\n"); 
     } 
    } 

    final public boolean getConnected() 
    { 
     return bConnected; 
    } 

    public void setConnected(boolean bConnected) 
    { 
     this.bConnected = bConnected; 
    } 

    //what happens when data is received 
    //pre: serial event is triggered 
    //post: processing on the data it reads 
    public void serialEvent(SerialPortEvent evt) { 

     if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) 
     { 
      try 
      { 

        while (inputT.available() > 0) { 
         inData = inputT.read(); 
         //inDataVector.add(new String("" + (char) inData)); 
         System.out.print(new String("" + (char) inData)); 
         thumb+=new String("" + (char) inData); 
         ThumbTemp thumbTemp=(ThumbTemp)window.abstractDao.getById("id", 1, ThumbTemp.class); 

         if(thumb.length()==100){ 
          thumbTemp.setValue(thumb.split("#")[1].substring(0,2)); 
          window.abstractDao.update(thumbTemp); 
          window.txtLog.append("Thumb Id : "+thumb+"\n"); 
          thumb=""; 
         } 
         else 
         { 
          thumbTemp.setValue("none"); 
          //window.abstractDao.update(""); 
         } 
         window.abstractDao.update(thumbTemp); 
        } 
        //rfid=""; 
      } 
      catch (Exception e) 
      { 
       logText = "Failed to read data. (" + e.toString() + ")"; 
       window.txtLog.setForeground(Color.red); 
       window.txtLog.append(logText + "\n"); 
      } 
     } 
    } 

    //method that can be called to send data 
    //pre: open serial port 
    //post: data sent to the other device 
    public void writeData(int id) 
    { 
     try 
     { 
      outputT.write(id); 
     } 
     catch (Exception e) 
     { 
      logText = "Failed to write data. (" + e.toString() + ")"; 
      window.txtLog.setForeground(Color.red); 
      window.txtLog.append(logText + "\n"); 
     } 
    } 
}