Reading from a port in Java

不羁的心 提交于 2019-12-13 04:43:36

问题


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.
2. The port assign to my gsm modem is COM11 . I saw it from DeviceManager -> modems -> myModem-> Advance -> AdvancePortSettings.
3. I write the Java code to read incomming message.

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. Do anyone know what is going on? I am not getting any error or exceptions.


回答1:


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. Try moving sp.addEventListener(this); further up, just after '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. Your run method actually does nothing except send the thread to sleep after everything has happened.

Move all your code from the constructor to the run() method if you want it to run in a separate thread.




回答2:


The following code , is to send and read message using a GSM module, this may help you

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,



来源:https://stackoverflow.com/questions/25882157/reading-from-a-port-in-java

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