2014-09-21 3 views
0
import gnu.io.*; 
import java.io.*; 
import java.util.*; 
import java.lang.*; 

public class SerialWrite implements Runnable, SerialPortEventListener{ 

    static String output=""; 

    public void run(){ 
    } 

    static Enumeration portList; 
    static CommPortIdentifier portId; 
    static String dest = "+923216159133"; 
    static String messageString = "Hello Testing"; 
    static InputStream inputStream; 
    static SerialPort serialPort; 
    static OutputStream outputStream; 

    public void serialEvent(SerialPortEvent event){ 
     switch (event.getEventType()){ 
      case SerialPortEvent.BI: 
      case SerialPortEvent.OE: 
      case SerialPortEvent.FE: 
      case SerialPortEvent.PE: 
      case SerialPortEvent.CD: 
      case SerialPortEvent.CTS: 
      case SerialPortEvent.DSR: 
      case SerialPortEvent.RI: 
      case SerialPortEvent.OUTPUT_BUFFER_EMPTY: 
       System.out.println("Error"); 
      break; 
      case SerialPortEvent.DATA_AVAILABLE:{ 
       BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 
       String line = ""; 
       try{ 
        while ((line = reader.readLine()) != null){ 
         if(line.equalsIgnoreCase("OK") || (line.indexOf("+CMGS") != -1)){ 
          output=line; 
         } 
        Thread.sleep(10); 
        } 
       } 
       catch (Exception e){ 
        System.err.println("Error while reading Port " + e); 
       } 
      break; 
     } 
    } //switch 
} 

public SerialWrite(SerialPort serial){ 
    try{ 
     inputStream = serial.getInputStream(); 
     try{ 
      serial.addEventListener(this); 
     } 
     catch (TooManyListenersException e){ 
      System.out.println("Exception in Adding Listener" + e); 
     } 
     serial.notifyOnDataAvailable(true); 
    } 
    catch (Exception ex){ 
     System.out.println("Exception in getting InputStream" + ex); 
    } 
} 

public static void main(String[] args) throws Exception{ 
    int i=0; 
    String line1 = "AT+CMGF=1\r\n"; 
    String line2 = "AT+CMGS=" + "\"" + dest + "\""+"\r\n"; 
    System.out.println("This " + line2); 
    String line3 = messageString; 
    String line4 = "<ctrl+z>"; 
    portList = CommPortIdentifier.getPortIdentifiers(); 
    while (portList.hasMoreElements()){ 
     portId = (CommPortIdentifier) portList.nextElement(); 
     if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){ 
      System.out.println("SMS Sending........"); 
      if (portId.getName().equals("COM3")){ 
       System.out.println("SMS Sending....Port Found"); 
       try{ 
        serialPort = (SerialPort) portId.open("SerialTestApp", 2000); 
        SerialWrite wr = new SerialWrite(serialPort); 
       } 
       catch (PortInUseException e){ 
        System.out.println("Port In Use " + e); 
       } 
       try{ 
        outputStream = serialPort.getOutputStream(); 
       } 
       catch (IOException e){ 
        System.out.println("Error writing to output stream " + e); 
       } 
       try{ 
        serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); 
       } 
       catch (UnsupportedCommOperationException e){ 
        System.out.println("Error"); 
       } 
       try{ 
        System.out.println("It seems OK now"); 
        outputStream.write(line1.getBytes()); 
        byte buffer[] = new byte[10000]; 
        // read the response from mobile phone 
        inputStream.read(buffer); 
        System.out.println("AT Comand response: "+buffer.toString()); 
        /*System.out.println ("done"); 
        outputStream.write(line2.getBytes()); 
        System.out.println("It seems OK now"); 
        outputStream.write(line3.getBytes()); 
        outputStream.write(line4.getBytes()); 
        System.out.println("This one is output "+output); 
        outputStream.flush(); 
        System.out.println("Message Sent!");*/ 
       } 
       catch (IOException e){ 
        System.out.println("Error writing message " + e); 
       } 
      } 
     } 
    } 
} 


public static void showText(String Text){ 
    System.out.println("TEXT "+Text); 
    } 
} 

Я хочу, чтобы отправить сообщение, используя GSM-телефон (NOKIA 110) Сначала я попытался отправить «AT» команды, но ответ я получаю неожиданный показано ниже:Получение неожиданный результат AT COMMAND в Java

SMS Sending........ 
SMS Sending....Port Found 
It seems OK now 
**AT Comand response: [[email protected]** 
SMS Sending........ 
SMS Sending........ 
SMS Sending........ 
SMS Sending........ 

Во-вторых, когда я запускаю всю программу без КОММЕНТАРИЙ, мой мобильный телефон перезапускается в конце. Может ли кто-нибудь помочь мне с этим.

ответ

1

Вы должны изменить способ печати содержимого полученного массива байтов:

String str = new String(buffer); 
System.out.println(str); 

вместо: buffer.toString(), который будет печатать хэш массива буфера. Это то, что вы видите как ответ от устройства.

Что касается вашей второй части, то в запрошенном коде попробуйте раскурить: outputStream.flush();, возможно, устройство все еще ждет команды AT, и команда не была сброшена во входной поток.

+0

Я пробовал это, нет ответа – user2631892

+0

Каков ответ, который вы получаете от устройства при настройке режима SMS - вы получаете ответ как ОК? – BatScream

+0

Я изменил это на System.out.println ("Выход:" + str); и после выхода нет ответа: – user2631892

Смежные вопросы