我试图通过串口事件监听器发送短信,但我收到此错误NoSuchPortException

时间:2014-11-07 12:14:23

标签: java sms

在此代码完美运行之前的一周,但在格式化系统之后,在尝试通过usb发送短信连接我的诺基亚c3手机时会发出NoSuchPortException

错误日志为

enter code here`INFO: Server startup in 17344 ms
+919032055002     null
problem is here in getting port number
javax.comm.NoSuchPortException
Port id is : null
at javax.comm.CommPortIdentifier.getPortIdentifier(CommPortIdentifier.java:105)
at com.gces.sms.SerialConnection.openConnection(SerialConnection.java:73)
at com.gces.sms.Sender.send(Sender.java:68)
at com.gces.sms.SMSClient.run(SMSClient.java:38)
at java.lang.Thread.run(Unknown Source)
in sms client & msg is :  null
java.lang.NullPointerException
at com.gces.sms.SerialConnection.openConnection(SerialConnection.java:90)
at com.gces.sms.Sender.send(Sender.java:68)
at com.gces.sms.SMSClient.run(SMSClient.java:38)
at java.lang.Thread.run(Unknown Source)

并且代码在这里

package com.gces.sms;

import javax.comm.*;
import java.io.*;
import java.awt.TextArea;
import java.awt.event.*;
import java.util.TooManyListenersException;

public class SerialConnection implements SerialPortEventListener,
                 CommPortOwnershipListener {

private SerialParameters parameters;
private OutputStream os;
private InputStream is;
private KeyHandler keyHandler;

private CommPortIdentifier portId;
private SerialPort sPort;

private boolean open;

private String receptionString="";

public String getIncommingString(){
  byte[] bVal= receptionString.getBytes();
  receptionString="";
  return new String (bVal);
}
public SerialConnection(SerialParameters parameters) {
    this.parameters = parameters;
open = false;
}
public void openConnection() throws SerialConnectionException {

try {

    portId = CommPortIdentifier.getPortIdentifier(parameters.getPortName());
} catch (NoSuchPortException e) {
        System.out.println("problem is here in getting port number");
        e.printStackTrace();
}catch(Exception e)
    {
        e.printStackTrace();
    }
   System.out.println("Port id is : "+portId);
try {
    sPort = (SerialPort)portId.open("SMSConnector", 30000);
} catch (PortInUseException e) {

    throw new SerialConnectionException(e.getMessage());
}
    sPort.sendBreak(1000);

try {
    setConnectionParameters();
} catch (SerialConnectionException e) {
    sPort.close();
    throw e;
}
try {
    os = sPort.getOutputStream();
    is = sPort.getInputStream();
} catch (IOException e) {
    sPort.close();
    throw new SerialConnectionException("Error opening i/o streams");
}
try {
    sPort.addEventListener(this);
} catch (TooManyListenersException e) {
    sPort.close();
    throw new SerialConnectionException("too many listeners added");
}
sPort.notifyOnDataAvailable(true);
try {
    sPort.enableReceiveTimeout(30);
} catch (UnsupportedCommOperationException e) {
}
portId.addPortOwnershipListener(this);

open = true;
}

 public void setConnectionParameters() throws SerialConnectionException {


int oldBaudRate = sPort.getBaudRate();
int oldDatabits = sPort.getDataBits();
int oldStopbits = sPort.getStopBits();
int oldParity   = sPort.getParity();
int oldFlowControl = sPort.getFlowControlMode();

try {
    sPort.setSerialPortParams(parameters.getBaudRate(),
                  parameters.getDatabits(),
                  parameters.getStopbits(),
                  parameters.getParity());
} catch (UnsupportedCommOperationException e) {
    parameters.setBaudRate(oldBaudRate);
    parameters.setDatabits(oldDatabits);
    parameters.setStopbits(oldStopbits);
    parameters.setParity(oldParity);
    throw new SerialConnectionException("Unsupported parameter");
}

try {
    sPort.setFlowControlMode(parameters.getFlowControlIn()
                   | parameters.getFlowControlOut());
} catch (UnsupportedCommOperationException e) {
    throw new SerialConnectionException("Unsupported flow control");
}
}

public void closeConnection() {
if (!open) {
    return;
}

if (sPort != null) {
    try {
        os.close();
        is.close();
    } catch (IOException e) {
    System.err.println(e);
    }
    sPort.close();
    portId.removePortOwnershipListener(this);
}

open = false;
}
public void sendBreak() {
sPort.sendBreak(1000);
}
public boolean isOpen() {
return open;
}
public void serialEvent(SerialPortEvent e) {
StringBuffer inputBuffer = new StringBuffer();
int newData = 0;

switch (e.getEventType()) {

    case SerialPortEvent.DATA_AVAILABLE:
        while (newData != -1) {
            try {
                newData = is.read();
            if (newData == -1) {
            break;
            }
            if ('\r' == (char)newData) {
            inputBuffer.append('\n');
            } else {
                inputBuffer.append((char)newData);
            }
            } catch (IOException ex) {
                System.err.println(ex);
                return;
            }
        }
    receptionString=receptionString+ (new String(inputBuffer));

    break;

    case SerialPortEvent.BI:
    receptionString=receptionString+("\n--- BREAK RECEIVED ---\n");
}

}

public void ownershipChange(int type) {
  /*
if (type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED) {
    PortRequestedDialog prd = new PortRequestedDialog(parent);
}
    */
}

class KeyHandler extends KeyAdapter {
OutputStream os;

/**
Creates the KeyHandler.
@param os The OutputStream for the port.
*/
public KeyHandler(OutputStream os) {
    super();
    this.os = os;
}

/**
Handles the KeyEvent.
Gets the <code>char</char> generated by the <code>KeyEvent</code>,
converts it to an <code>int</code>, writes it to the <code>
OutputStream</code> for the port.
*/
    public void keyTyped(KeyEvent evt) {
        char newCharacter = evt.getKeyChar();
        if ((int)newCharacter==10) newCharacter = '\r';
        System.out.println ((int)newCharacter);
    try {
        os.write((int)newCharacter);
    } catch (IOException e) {
    System.err.println("OutputStream write error: " + e);
    }
    }
}
    public void send(String message) {
        byte[] theBytes= (message+"\n").getBytes();
        for (int i=0; i<theBytes.length;i++){

          char newCharacter = (char)theBytes[i];
          if ((int)newCharacter==10) newCharacter = '\r';

      try {
        os.write((int)newCharacter);
          } catch (IOException e) {
              System.err.println("OutputStream write error: " + e);
          }

        }
        //System.out.println (">'" +message +"' sent");




    }



 }

,第二个文件代码为

package com.gces.sms;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Date;

import com.gces.sms.SerialConnection;
import com.gces.sms.SerialConnectionException;
import com.gces.sms.SerialParameters;

public class Sender implements Runnable  {

private static final long STANDARD=500;
private static final long LONG=2000;
private static final long  VERYLONG=20000;

SerialConnection mySerial =null;

static final private char cntrlZ=(char)26;
String in, out;
Thread aThread=null;
private long delay=STANDARD;
String recipient=null;
String message=null;

 //private String csca="+919084051550"; // the message center uninor
 //private String csca="+919837099995"; // the message center idea
 private String csca="+919032055002"; // the message center docomo
 private SerialParameters defaultParameters= new SerialParameters ("COM4",9600,0,0,8,1,0);
 public int step;
 public int status=-1;
 public long messageNo=-1;
 public Sender(String recipient, String message){

 this.recipient=recipient;
 this.message=message;

 }

 public int send () throws Exception {
  File file = new File("C:\\db_backup\\SMS.txt");
  BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
  String line = null;
  String port = null;
  int flag=0;
  while( (line = br.readLine())!= null ){
      if(flag==0)
          port=line;
      else if(flag==1)
          csca=line;
      else
          br.close();
      flag++;
  }
  //br.close();
  defaultParameters= new SerialParameters (port,9600,0,0,8,1,0);
 SerialParameters params = defaultParameters;
 System.out.println(csca+"     "+port); 
 mySerial =new SerialConnection (params);


    mySerial.openConnection();

 aThread=new Thread(this);

 aThread.start() ;
 //log("start");

 return 0;
 }

public void run(){

boolean timeOut=false;
long startTime=(new Date()).getTime();



 while ((step <7) && (!timeOut)){
 timeOut=((new Date()).getTime() - startTime)>delay;

  //if atz does not work, type to send cntrlZ and retry, in case a message was stuck
  if (timeOut && (step==1)) {
      step=-1;
      mySerial.send(        ""+cntrlZ);
  }

  //read incoming string
  String result=  mySerial.getIncommingString() ;

  //System.out.println("<- in rrrrrrrrrr "+result+"\n--------");
  int expectedResult=-1;

  try{
    //log ("Step:"+step);

    switch (step){
      case 0:

        mySerial.send("atz");
        delay=LONG;
        startTime=(new Date()).getTime();
        break;

      case 1:
        delay=STANDARD;
        mySerial.send("ath0");
        startTime=(new Date()).getTime();
        break;
      case 2:
        expectedResult=result.indexOf("OK");

        //log ("received ok ="+expectedResult);
        if (expectedResult>-1){
          mySerial.send("at+cmgf=1");
          startTime=(new Date()).getTime();
        }else{
            step=step-1;
        }
        break;
      case 3:
        expectedResult=result.indexOf("OK");

       // log ("received ok ="+expectedResult);
        if (expectedResult>-1){
          mySerial.send("at+csca=\""+csca+"\"");
          startTime=(new Date()).getTime();
        }else{
          step=step-1;
        }

        break;
      case 4:
        expectedResult=result.indexOf("OK");

       // log ("received ok ="+expectedResult);
        if (expectedResult>-1){
          mySerial.send("at+cmgs=\""+recipient+"\"");
          startTime=(new Date()).getTime();
        }else{
          step=step-1;
        }

        break;
      case 5:
        expectedResult=result.indexOf(">");

        //log ("received ok ="+expectedResult);
        if (expectedResult>-1){
          mySerial.send(message+cntrlZ);
          startTime=(new Date()).getTime();
        }else{
          step=step-1;
        }
        delay=VERYLONG;//waiting for message ack

        break;

      case 6:
        expectedResult=result.indexOf("OK");
        //read message number
        if (expectedResult>-1){
          int n=result.indexOf("CMGS:");
          result=result.substring(n+5);
          //System.out.println(result);
          n=result.indexOf("\n");
          status=0;
         // result="1                        11";
          try{
              messageNo=Long.parseLong(result.substring(0,n).trim() );
              }
              catch(NumberFormatException e){
                  //result="1                                    ";
                  messageNo=1;
              }
          log ("sent message no:"+messageNo);


        }else{
          step=step-1;
        }

      break;
    }
    step=step+1;

    aThread.sleep(100);

   }catch (Exception e){
      e.printStackTrace();
   }
  }

  mySerial.closeConnection() ;

  //if timed out set status

   if (timeOut ) {
    status=-2;
    log("*** time out at step "+step+"***");
  }
 }
  private void log(String s){
  System.out.println (new java.util.Date()+":"+this.getClass().getName()+":"+s);
 }
 }

此代码工作正常,但在格式化系统后会出现这些错误......

0 个答案:

没有答案