简体   繁体   English

从Java中的端口读取

[英]Reading from a port in Java

Here is the scenario: 这是场景:

1. I have a GSM modem which is connected to my computer, It's working I can read and send SMS via the built-in program. 1.我有一个与计算机连接的GSM调制解调器,可以正常运行,可以通过内置程序读取和发送SMS。
2. The port assign to my gsm modem is COM11 . 2.分配给我的gsm调制解调器的端口是COM11。 I saw it from DeviceManager -> modems -> myModem-> Advance -> AdvancePortSettings . 我从DeviceManager -> modems -> myModem-> Advance -> AdvancePortSettings看到了它。
3. I write the Java code to read incomming message. 3.我编写Java代码以读取传入的消息。

The code is as follows: 代码如下:

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");
        }
    }
}

When I send an SMS on the GSM modem, I am not getting in serialEvent() call back method. 当我在GSM调制解调器上发送SMS时,我没有进入serialEvent()回调方法。 Do anyone know what is going on? 有人知道发生了什么吗? I am not getting any error or exceptions. 我没有收到任何错误或异常。

This isn't a definitive answer, but your code has made several question marks appear above my head. 这不是一个确定的答案,但是您的代码在我的头顶上方出现了几个问号。

To answer why you're not getting anything in the method listening on the SerialEvent, it might be that you are adding the listener after the event has happened. 要回答为什么在SerialEvent侦听方法中没有得到任何结果,可能是事件发生后您正在添加侦听器。 Try moving sp.addEventListener(this); 尝试移动sp.addEventListener(this); further up, just after 'pid.open'. 在pid.open之后。

However think a bit about what the thread is doing. 但是,请考虑一下线程在做什么。 All your code is in the constructor of your class, then at the end of the constructor, after everything has happened, you call thread.start(), so none of your code is running in a separate thread. 您所有的代码都在类的构造函数中,然后在构造函数的末尾,在所有事情发生之后,您调用thread.start(),因此您的代码均未在单独的线程中运行。 Your run method actually does nothing except send the thread to sleep after everything has happened. 实际上,您的run方法什么都不做,只是在发生所有事情后让线程进入睡眠状态。

Move all your code from the constructor to the run() method if you want it to run in a separate thread. 如果您希望所有代码在单独的线程中运行,请将其从构造函数移至run()方法。

The following code , is to send and read message using a GSM module, this may help you 以下代码用于使用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 
}

Method to read Message 读取消息的方法

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

  }

Check these code, i got the output by using this code, 检查这些代码,我通过使用此代码获得了输出,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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