2009-11-05 41 views
4

我編寫了一個Java應用程序,用於從USB GSM調制解調器讀取和發送SMS消息。我使用SMSLib(使用JavaCommAPI),並且它在Windows上運行。我需要通過COM端口,調制解調器似乎已連接到。自動檢測哪個Com端口使用Java連接到USB GSM調制解調器

到目前爲止,我一直在使用Windows設備管理器手動查找COM端口,並將其寫入屬性文件中。我想知道是否有方法來檢測哪個COM端口,調制解調器連接到編程?

  1. 這將節省的每一次
  2. 的端口號變爲尋找它的麻煩,如果我拔下/重新插上它有時

謝謝!

+0

在Windows設備管理器中找到COM端口,因爲我也在使用GSM調制解調器,但在Windows設備管理器中找不到任何COM端口。回覆請我急需幫助。 – Aniket 2013-02-22 14:34:59

回答

2
package com.cubepro.util; 

import java.util.Collection; 
import java.util.Collections; 
import java.util.Enumeration; 
import java.util.Formatter; 

import org.apache.log4j.Logger; 
import org.smslib.helper.CommPortIdentifier; 

import com.cubepro.general.CommonConstants; 

import com.cubepro.util.SendMessage; 

public class CommPortTester { 
    private static final String _NO_DEVICE_FOUND = " no device found"; 

    private final static Formatter _formatter = new Formatter(System.out); 

    private static Logger log = Logger.getLogger(CommPortTester.class); 

    static CommPortIdentifier portId; 

    static Enumeration<CommPortIdentifier> portList; 

    static int bauds[] = { 9600, 14400, 19200, 28800, 33600, 38400, 56000, 
          57600, 115200 }; 

    public static final String MAINCLASS = "org.smslib.Service"; 

    public CommPortTester() throws Exception { 
     Class.forName(MAINCLASS); 
    } 

    /** 
    * Wrapper around {@link CommPortIdentifier#getPortIdentifiers()} to be 
    * avoid unchecked warnings. 
    */ 
    private static Enumeration<CommPortIdentifier> getCleanPortIdentifiers() { 
     return CommPortIdentifier.getPortIdentifiers(); 
    } 

    public String testAndQualifyPort() throws Exception { 
     String status = CommonConstants.MODEM_STATUS_ERROR; 
     SendMessage sendMessage = new SendMessage(); 

     log.debug("\nSearching for devices..."); 
     portList = getCleanPortIdentifiers(); 

     while (portList.hasMoreElements()) { 
     portId = portList.nextElement(); 
     if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { 
      _formatter.format("%nFound port: %-5s%n", portId.getName()); 
      try { 
       if(portId.getName() 
       boolean comPortSuccess = sendMessage.doIt(portId.getName()); 
       if(comPortSuccess == true){ 
        return portId.getName(); 
       } 
      } catch (final Exception e) { 
       log.debug(" Modem error occured -",e); 
      } 
     } 
     } 
     log.debug("\nTest complete."); 
     return status; 
    } 

    public static void main(String[]args){ 
     try{ 
     CommPortTester tester = new CommPortTester(); 
     tester.testAndQualifyPort(); 
     }catch(Exception e){ 
     e.printStackTrace(); 
     } 
    } 
} 
+0

在Windows設備管理器中找到COM端口,因爲我也在使用GSM調制解調器,但在Windows設備管理器中找不到任何COM端口。回覆請我急需幫助 – Aniket 2013-02-22 14:57:31

相關問題