2015-02-18 2 views
0

Я пытаюсь выполнить команды at в java, я сделал это в matlab, но мне было немного сложно в java. Есть ли api для java для последовательной связи или при командах? Мне нужна помощь для объявления последовательного порта, а затем для отправки по ним команд. Я нашел этот код Java, чтобы открыть последовательный порт (com12), но он не открывает последовательный порт.отправка AT-команд в java для модема для проектирования телекоммуникаций

static Enumeration portList; 
static CommPortIdentifier portId; 
static String messageString = "at \n"; 
static SerialPort serialPort; 
static OutputStream outputStream; 
public static void main(String[] args) throws IOException { 
    // TODO code application logic here 
portList = CommPortIdentifier.getPortIdentifiers(); 
System.out.println("trying"); 

while (portList.hasMoreElements()) { 
System.out.println("trying"); 
portId = (CommPortIdentifier) portList.nextElement(); 
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { 
System.out.println("trying"); 

     if (portId.getName().equals("COM12")) { 
System.out.println("found"); 
      try { 
       serialPort = (SerialPort) 
        portId.open("SimpleWriteApp", 2000); 
      } catch (PortInUseException e) {System.out.println("err");} 
      try { 
       outputStream = serialPort.getOutputStream(); 
      } catch (IOException e) {System.out.println("err1");} 
      try { 
       serialPort.setSerialPortParams(9600, 
        SerialPort.DATABITS_8, 
        SerialPort.STOPBITS_1, 
        SerialPort.PARITY_NONE); 
      } catch (UnsupportedCommOperationException e)      
      {   
      System.out.println("err2");} 
      outputStream.write(messageString.getBytes()); 
      System.out.println(messageString); 
      outputStream.close(); 
      serialPort.close(); 
      } 
      } 
      } 
       } 

Я использую дизайн телекоммуникационный модем, я выполнил команды в срок тера терминала, поэтому я уверен, что нет ничего плохого с модемом или пути я посылаю команды. Я думаю, что борюсь за открытие последовательного порта и отправлю персонажа каретки.

Заранее спасибо

+0

Где конкретно происходит сбой кода? Вы получаете какие-либо исключения или сообщения об ошибках? – Kenster

ответ

0

Следующий код может помочь вам

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; 
    String f_id=""; 
    String dateNow=""; 
    String dateNow1=""; 
public String recvdData="aa"; 


public static void main(String args[]) 
{ 
    SerialComm obj=new SerialComm(); 

} 


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

// //    Thread.sleep(2000); 
       // sendMsg(); 
       //readSMS(1); 
       //getRFID(); 
       }  
      } 
    } 
    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; 
       this.recvdData=data; 
      } 
      System.out.println("data=========="+this.recvdData); 
      getRFID(this.recvdData); 
     } 
     catch (Exception e) 
     { 
      System.out.println("Exception in serial event-->"+e); 
     } 

     break;//break from switch case 1: 
     }//end of switch 
    } 
public void sendMsg() 
    { 


     try 
     { 

      System.out.println("Sending"); 
      sendAT(); 
      System.out.println("AT OK"); 
      sendAT_CMGF(); 
      System.out.println("Enabled text mode"); 
      sendMessage("9xxxxxxxx","testing"); 
      System.out.println("Message Sent"); 
      //readSMS(1); 


      System.exit(0); 
     } 
     catch(Exception e) 
     { 
     System.out.println(e); 
     } 

    } 
    public void sendAT() { 
     try{ 
      System.out.println("Sending AT"); 
      this.recvdData=""; 
      String mysms="AT"; 
      out.write(mysms.getBytes()); 
      out.write(13); 
      Thread.sleep(500); 
      if(this.recvdData.contains("OK")) 
      { 
       return; 
      }else{ 
       sendAT(); 
      } 
      return; 
     }catch(Exception e){ 
      System.out.println(e); 
     } 

    } 
    } 

Может быть не прекрасный ответ, просто сослаться как команда AT использует

+0

Я пробовал библиотеку jssc, он более прост в использовании, и он отлично работает :) Я предлагаю использовать библиотеку jssc –

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