0

这是场景:

1.我有一个 GSM 调制解调器,它连接到我的电脑,它正在工作,我可以通过内置程序读取和发送短信。
2.分配给我的 gsm 调制解调器的端口是 COM11 。我从DeviceManager -> modems -> myModem-> Advance -> AdvancePortSettings.
3.我编写Java代码来读取传入消息。

代码如下:

public class PScanner implements SerialPortEventListener, Runnable {
    CommPortIdentifier pid = null;
    SerialPort sp;
    BufferedReader input;
    OutputStream output;

    public PScanner() {
        try {
            Enumeration e = CommPortIdentifier.getPortIdentifiers();
            while (e.hasMoreElements()) {
                CommPortIdentifier cpi = (CommPortIdentifier) e.nextElement();
                if (cpi.getName().equals("COM11")) {
                    pid = cpi;
                    break;
                }
            }
            sp = (SerialPort) pid.open(getClass().getName(), 2000);
            sp.setSerialPortParams(115200, SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            InputStream is = sp.getInputStream();
            input = new BufferedReader(new InputStreamReader(is));
            output = sp.getOutputStream();
            sp.addEventListener(this);
            sp.notifyOnDataAvailable(true);
            new Thread(this).start();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public synchronized void serialEvent(SerialPortEvent oEvent) {
        System.out.println("serialEvent CallBack");
    }

    public synchronized void close() {
        if (sp != null) {
            sp.removeEventListener();
            sp.close();
        }
    }

    @Override
    public void run() {
        try {
            Thread.sleep(20000);
        } catch (InterruptedException ex) {
            Logger.getLogger(PScanner.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            System.out.println("done");
        }
    }
}

当我在 GSM 调制解调器上发送 SMS 时,我没有进入serialEvent()回叫方法。有谁知道发生了什么?我没有收到任何错误或异常。

4

2 回答 2

0

这不是一个确定的答案,但是您的代码使我头顶出现了几个问号。

要回答为什么您在侦听 SerialEvent 的方法中没有得到任何东西,可能是您在事件发生后添加了侦听器。尝试sp.addEventListener(this);进一步向上移动,就在“pid.open”之后。

但是,请考虑一下线程在做什么。你所有的代码都在你的类的构造函数中,然后在构造函数的最后,在所有事情发生之后,你调用thread.start(),所以你的代码都没有在单独的线程中运行。您的 run 方法实际上什么都不做,只是在所有事情发生后让线程进入睡眠状态。

如果您希望它在单独的线程中运行,请将所有代码从构造函数移动到 run() 方法。

于 2014-09-17T04:55:20.300 回答
0

以下代码是使用 GSM 模块发送和读取消息,这可能会对您有所帮助

import java.sql.*;
import java.io.*;
import java.util.*;
import java.text.*;
import gnu.io.*;

public class SerialComm implements SerialPortEventListener 

{
int result=0;
static CommPortIdentifier portId=null;
Enumeration portList=null;
static InputStream inputStream=null;
static OutputStream out=null;
static SerialPort serialPort=null;
static int srate=9600;//B-Rate
String data=null;
int i=0;
String number="";
int status=0;
public  String recvdData="aa";  
String pswd="";
String actualpswd="";
 public static void main(String args[]) 
 { 
   SerialComm obj=new SerialComm();

  }   


 public SerialComm() 
 {
 try
{
    if(this.detectPort())
    {
        if(this.initPort()) 
        {

                //Thread.sleep(2000);
             // sendMessage();

            }    
        }
 }
 catch(Exception e)
    {
    System.out.println("Error in SerialComm()-->"+e);
 }
}



 public boolean detectPort() 
 {

 boolean portFound = false;
 //String defaultPort = "/dev/ttyUSB0";
 String defaultPort = "COM1";
 try 
 {
    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements())
     {

        CommPortIdentifier portID = (CommPortIdentifier) portList.nextElement();

        if (portID.getPortType() == CommPortIdentifier.PORT_SERIAL) 
        {

            if (portID.getName().equals(defaultPort))
            {
            this.portId=portID;
            System.out.println("Found port: "+portId.getName());
            portFound = true;
            break;
            } 
        } 

     } 
        if (!portFound) 
        {
        System.out.println("port " + defaultPort + " not found.");
        }
  }
 catch(Exception e)
 {
        portFound = false;
 }  

 return portFound;  

}
public boolean initPort() 
{

 try 
 { 
        serialPort = (SerialPort) portId.open("SerialCommApp", 2000);     
 }
 catch (PortInUseException e) 
 {
    System.out.println("Port in use-->"+e);
 }

 try 
 {
    inputStream = serialPort.getInputStream();
    out=serialPort.getOutputStream();
 } 
 catch (IOException e) 
 {
    System.out.println("IO Error-->"+e);
 }

 try 
 { 
        serialPort.addEventListener(this);
 } 
 catch (TooManyListenersException e) 
 {
    System.out.println("Too many LIstener-->"+e);
 }

serialPort.notifyOnDataAvailable(true);

 try 
 {
   serialPort.setSerialPortParams(srate, SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
   serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
 }
 catch (UnsupportedCommOperationException e) 
 {
    System.out.println("Error while setting parameters-->"+e);
 }

   System.out.println("Port Initialized....");
   return true;

 }
public synchronized void serialEvent(SerialPortEvent event) 
{

  switch (event.getEventType()) 
  {
   case SerialPortEvent.DATA_AVAILABLE:
    System.out.println("DATA_AVAILABLE");

    byte[] readBuffer = new byte[1024];
    int numBytes=1024;
    data="";

    try 
    {
        Thread.sleep(100);          
        while (inputStream.available() > 0)
        {
            numBytes = inputStream.read(readBuffer);//count of reading data
            data=data+new String(readBuffer,0,numBytes);
            data=data.trim();
            this.recvdData+=data;
        }
        System.out.println("data=========="+this.recvdData);

    } 
    catch (Exception e) 
    {
        System.out.println("Exception in serial event-->"+e);
    }

    break;//break from switch case 1:
    }//end of switch 
}

读取消息的方法

public void sendMessage(String num, String msg) {
    try{
        System.out.println("Sending Message");
        this.recvdData="";
        String dq=String.valueOf((char)34);
        String mysms="AT+CMGS="+dq+num+dq;
        out.write(mysms.getBytes());
        out.write(13);
        Thread.sleep(500);
        mysms=msg;
        out.write(mysms.getBytes());
        out.write(26);
        out.write(13);
        Thread.sleep(500);
        if(this.recvdData.contains("OK"))
        {
            return;
        }else if(this.recvdData.contains(">")){
            out.write(26);
            out.write(13);              
            sendMessage(num,msg);
        }else{
            sendMessage(num,msg);
        }
        return;
    }catch(Exception e){
        System.out.println(e);
    }

  }

检查这些代码,我使用此代码得到了输出,

于 2014-09-17T07:05:34.683 回答