![](/img/trans.png)
[英]Automatically detect which Com Port is connected to a USB GSM Modem using Java
[英]get com port on which usb modem is connected in java
如何在Java程序中獲取連接USB邊緣調制解調器的com端口。 需要快速幫助。 請告訴我使用哪個庫來獲取com ..(javax.comm除外)。 我嘗試過但是失敗了。 我沒有找到正確安裝它的方法,它會不斷地向我顯示錯誤。 :(
package commtest;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Formatter;
import org.smslib.helper.CommPortIdentifier;
import org.smslib.helper.SerialPort;
public class CommTest
{
private static final String _NO_DEVICE_FOUND = " no device found";
private final static Formatter _formatter = new Formatter(System.out);
static CommPortIdentifier portId;
static Enumeration<CommPortIdentifier> portList;
static int bauds[] = { 9600, 14400, 19200, 28800, 33600, 38400, 56000, 57600, 115200 };
/**
* Wrapper around {@link CommPortIdentifier#getPortIdentifiers()} to be
* avoid unchecked warnings.
*/
private static Enumeration<CommPortIdentifier> getCleanPortIdentifiers()
{
return CommPortIdentifier.getPortIdentifiers();
}
public static void main(String[] args)
{
System.out.println("\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());
for (int i = 0; i < bauds.length; i++)
{
SerialPort serialPort = null;
_formatter.format(" Trying at %6d...", bauds[i]);
try
{
InputStream inStream;
OutputStream outStream;
int c;
String response;
serialPort = portId.open("SMSLibCommTester", 1971);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
serialPort.setSerialPortParams(bauds[i], SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
inStream = serialPort.getInputStream();
outStream = serialPort.getOutputStream();
serialPort.enableReceiveTimeout(1000);
c = inStream.read();
while (c != -1)
c = inStream.read();
outStream.write('A');
outStream.write('T');
outStream.write('\r');
Thread.sleep(1000);
response = "";
StringBuilder sb = new StringBuilder();
c = inStream.read();
while (c != -1)
{
sb.append((char) c);
c = inStream.read();
}
response = sb.toString();
if (response.indexOf("OK") >= 0)
{
try
{
System.out.print(" Getting Info...");
outStream.write('A');
outStream.write('T');
outStream.write('+');
outStream.write('C');
outStream.write('G');
outStream.write('M');
outStream.write('M');
outStream.write('\r');
response = "";
c = inStream.read();
while (c != -1)
{
response += (char) c;
c = inStream.read();
}
System.out.println(" Found: " + response.replaceAll("\\s+OK\\s+", "").replaceAll("\n", "").replaceAll("\r", ""));
}
catch (Exception e)
{
System.out.println(_NO_DEVICE_FOUND);
}
}
else
{
System.out.println(_NO_DEVICE_FOUND);
}
}
catch (Exception e)
{
System.out.print(_NO_DEVICE_FOUND);
Throwable cause = e;
while (cause.getCause() != null)
{
cause = cause.getCause();
}
System.out.println(" (" + cause.getMessage() + ")");
}
finally
{
if (serialPort != null)
{
serialPort.close();
}
}
}
}
}
System.out.println("\nTest complete.");
}
}
這與USB,AT命令等無關...如果您仔細閱讀了錯誤消息,將獲得答案:
win32com.dll: Can't load IA 32-bit .dll on a AMD 64-bit.
此處的主題很糟糕 : 64位Windows上的Javax.comm API
此方法對我有效。此代碼將自動檢測與GSM調制解調器連接的端口並發送SMS。
public class ModamSMS {
public void sendMessage(String num, String massage) throws Exception {
SerialModemGateway gateway = new SerialModemGateway("", "COM5", 9600, "", "");
gateway.setInbound(true);
gateway.setOutbound(true);
OutboundNotification outboundNotification = new OutboundNotification();
InboundNotification inboundNotification = new InboundNotification();
Service service = Service.getInstance();
service.setOutboundMessageNotification(outboundNotification);
service.setInboundMessageNotification(inboundNotification);
service.addGateway(gateway);
service.startService();
OutboundMessage msg = new OutboundMessage(num, massage);
service.sendMessage(msg);
}
public ArrayList sendBulkMessage(ArrayList<String> numbers, String massage)
throws IOException, InterruptedException, SMSLibException {
ArrayList list = new ArrayList();
String connectedport = getConnectedport(numbers.get(0), massage);
System.out.println(connectedport + " port in bulsksmssend method");
if (connectedport != null) {
BasicConfigurator.configure();
SerialModemGateway gateway = new SerialModemGateway("", connectedport, 9600, "", "");
try {
// gateway.setInbound(true);
gateway.setOutbound(true);
OutboundNotification outboundNotification = new OutboundNotification();
// InboundNotification inboundNotification = new
// InboundNotification();
Service service = Service.getInstance();
service.setOutboundMessageNotification(outboundNotification);
// service.setInboundMessageNotification(inboundNotification);
service.addGateway(gateway);
service.startService();
for (int i = 1; i < numbers.size(); i++) {
String num = (String) numbers.get(i);
OutboundMessage msg = new OutboundMessage(num, i + " " + massage);
System.out.println(i + " " + massage);
Thread.sleep(1000);
service.sendMessage(msg);
list.add(num + " Sms send succes");
}
Service.getInstance().stopService();
} catch (SMSLibException | IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
writfile(sw.toString());
}
Service.getInstance().removeGateway(gateway);
} else {
JOptionPane.showMessageDialog(null, "Please make ! \n Modam is correctly inseted\nYou hava SMS package\n ");
}
return list;
}
public class InboundNotification implements IInboundMessageNotification {
// @Override
// Get triggered when a SMS is received
public void process(AGateway gateway, Message.MessageTypes messageTypes, InboundMessage inboundMessage) {
System.out.println(inboundMessage);
try {
gateway.deleteMessage(inboundMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class OutboundNotification implements IOutboundMessageNotification {
// Get triggered when a SMS is sent
public void process(AGateway gateway, OutboundMessage outboundMessage) {
System.out.println(outboundMessage);
}
}
public String getConnectedport(String num, String msge)
throws TimeoutException, GatewayException, SMSLibException, IOException, InterruptedException {
ArrayList<String> allports = new ArrayList<>();
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
while (ports.hasMoreElements()) {
CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
String type;
switch (port.getPortType()) {
case CommPortIdentifier.PORT_PARALLEL:
type = "Parallel";
break;
case CommPortIdentifier.PORT_SERIAL:
allports.add(port.getName());
type = "Serial";
break;
default: /// Shouldn't happen
type = "Unknown";
break;
}
System.out.println(port.getName() + ": " + type);
allports.add(port.getName());
}
String connectedport = null;
for (int a = 0; a < allports.size(); a++) {
connectedport = getport(allports.get(a), num, msge);
if (connectedport != null) {
a = allports.size();
System.out.println(connectedport + " port in for loop");
}
}
return connectedport;
}
private String getport(String port, String num, String msge)
throws TimeoutException, GatewayException, SMSLibException, IOException, InterruptedException {
String returnport = null;
SerialModemGateway gateway = new SerialModemGateway("", port, 9600, "", "");
gateway.setInbound(true);
gateway.setOutbound(true);
OutboundNotification outboundNotification = new OutboundNotification();
InboundNotification inboundNotification = new InboundNotification();
Service service = Service.getInstance();
service.setOutboundMessageNotification(outboundNotification);
service.setInboundMessageNotification(inboundNotification);
try {
service.addGateway(gateway);
service.startService();
OutboundMessage msg = new OutboundMessage(num, msge);
service.sendMessage(msg);
returnport = port;
System.out.println(returnport + " port in port finding method");
} catch (GatewayException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SMSLibException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Service.getInstance().stopService();
Service.getInstance().removeGateway(gateway);
return returnport;
}
public static void main(String args[]) {
BasicConfigurator.configure();
ModamSMS app = new ModamSMS();
ArrayList<String> numbers = new ArrayList<>();
numbers.add("+923075142199");
numbers.add("+923075142199");
try {
// app.sendMessage("+923075142199","plz Allah it shoud work");
app.sendBulkMessage(numbers,
"hy this is me Abdulrehman javed .Who are you and how are you.This is testing sms so do not worry");
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
writfile(sw.toString());
}
}
public static void writfile(String content) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter("Error.txt");
bw = new BufferedWriter(fw);
bw.write(content);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.