简体   繁体   中英

I want to detect the device through serial port using RxTx in java

I want to detect the device through serial port using RxTx in java and device is programmed that if it recieves a specific word from computer it will reply "ok" and if the computer receives ok.. it will stop sending the word and highlight that the device is attached. PLEASE HELP ME. and one more thing.. i have to check for every port.. please will you code a method that auto-cycle through the ports till the device is detected. My code sends the word only one time even being in a infinite loop. code:

private void cb1KeyPressed(java.awt.event.KeyEvent evt) {                               
    // TODO add your handling code here:
    try{
    l1.setText("Port: "+cb1.getSelectedItem().toString()+" is Selected");
    selectedPort = cb1.getSelectedItem().toString();// TODO add your handling code here
    rs.connect(selectedPort);
    for(;;)
    {
        CommPortSender.send(new ProtocolImpl().getMessage("KITM"));//send message
        if(pi.rmess().equalsIgnoreCase("OK"))//received message
        {
            l1.setText("The Device is attached to: "+selectedPort);
            CommPortSender.send(new ProtocolImpl().getMessage("OK ACK"));//send message
            break;
        }
        else
        {
            rs.disconnect(selectedPort);
            continue;
        }
    }
    }
    catch(Exception e){}   

}
 static void listPorts()
    {
        java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
        while ( portEnum.hasMoreElements() ) 
        {
            CommPortIdentifier portIdentifier = portEnum.nextElement();
            System.out.println(portIdentifier.getName()  +  " - " +  getPortTypeName(portIdentifier.getPortType()) );
        }        
    }

    static String getPortTypeName ( int portType )
    {
        switch ( portType )
        {
            case CommPortIdentifier.PORT_I2C:
                return "I2C";
            case CommPortIdentifier.PORT_PARALLEL:
                return "Parallel";
            case CommPortIdentifier.PORT_RAW:
                return "Raw";
            case CommPortIdentifier.PORT_RS485:
                return "RS485";
            case CommPortIdentifier.PORT_SERIAL:
                return "Serial";
            default:
                return "unknown type";
        }
    }

5 minutes of googling could have told you the same thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM