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

我的梦境 提交于 2019-12-08 02:41:44

问题


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){}   

}

回答1:


 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.



来源:https://stackoverflow.com/questions/11712717/i-want-to-detect-the-device-through-serial-port-using-rxtx-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!