2012-01-30 2 views
1

다음 코드를 가지고 있는데 어떻게하면 COM 포트를 지속적으로들을 수 있을지 모르겠습니다. 그래서 언제든지 데이터를 읽을 수 있습니다. 그래서 스레드를 생성하고 영구적으로 입력 스트림을 열어야합니까? 출력 스트림을 열기 전에 어떻게 닫아야합니까?휴대 기기에서 CommConnection을 지속적으로 듣고 있습니다.

기본적으로 내 모바일 앱은 데이터를 사용할 수있을 때마다 com4 포트 데이터를 인식하고 처리해야하며 데이터를 보낼 수도 있습니다. 앱이 휴대 기기에서 실행되면 이러한 모든 작업이 자동화되어야합니다.

import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import javax.microedition.lcdui.*; 
import javax.microedition.midlet.MIDlet; 
import javax.microedition.midlet.MIDletStateChangeException; 
import javax.microedition.io.*; 

public class MainMidlet extends MIDlet implements CommandListener { 
// displaying this midlet 
private Display display; 
private Form form; 
private StringItem stringItem; 
private Command exitCommand; 
// comm vars 
private volatile CommConnection commConnection = null; 
private volatile InputStream inputStream = null; 
private volatile OutputStream outputStream = null; 
// thread on which we run the listening 
private Thread thread; 
private volatile boolean stopRequested = false; 

public MainMidlet() { 

} 

protected void destroyApp(boolean arg0) throws MIDletStateChangeException { 
    // TODO Auto-generated method stub 

} 

protected void pauseApp() { 
    // TODO Auto-generated method stub 

} 

public void commandAction(Command command, Displayable displayable) { 
    if (displayable == form) { 
     if (command == exitCommand) { 
      exitMIDlet(); 
     } 
    } 
} 

public void startApp() { 
    stringItem = new StringItem("Hello", "Serial app is running!"); 
    form = new Form(null, new Item[] { stringItem }); 
    exitCommand = new Command("Exit", Command.EXIT, 1); 
    form.addCommand(exitCommand); 
    form.setCommandListener(this); 
    display = Display.getDisplay(this); 
    display.setCurrent(form); 

    String ports = System.getProperty("microedition.commports"); 
    String port = ""; 
    int comma = ports.indexOf(','); 
    if (comma > 0) { 
     // Parse the first port from the available ports list. 
     port = ports.substring(0, comma); 
     print("multiple ports found. selecting the first one. " + ports); 
    } else { 
     // Only one serial port available. 
     port = ports; 
    } 
    try { 
     commConnection = (CommConnection) Connector.open("comm:" + port 
       + ";blocking=off;autocts=off;autorts=off"); 
     commConnection.setBaudRate(commConnection.getBaudRate()); 
    } catch (IOException e) { 
     print("IOException in startApp: " + e.getMessage()); 
    } 
} 

public void exitMIDlet() { 
    try { 
     commConnection.close(); 
    } catch (IOException e) { 
     print("IOException in exitMIDlet: " + e.getMessage()); 
    } 
    if (thread.isAlive()) { 
     thread.interrupt(); 
     try { 
      thread.join(); 
     } catch (InterruptedException e) { 
      print("InterruptedException in exitMIDlet: " + e.getMessage()); 
     } 
    } 
    display.setCurrent(null); 
    notifyDestroyed(); 
} 

// write data to serial port 
public void SendData(byte[] data) { 
    try { 
     outputStream = commConnection.openOutputStream(); 
     outputStream.write(data); 
     outputStream.close(); 
    } catch (IOException e) { 
     print("IOException: " + e.getMessage()); 
    } 
} 

// read data from serial port. 
private void GetData() { 
    try { 
     inputStream = commConnection.openInputStream(); 
     // maximum size of reading is 500kb. 
     byte[] buffer = new byte[500000]; 
     StringBuffer message = new StringBuffer(); 
     for (int i = 0; i < buffer.length;) { 
      try { 
       //print("ListenToPort is inside of for now."); 
       Thread.sleep(10); 
      } catch (InterruptedException ex) { 
       print("intrupted in GetData. " + ex.getMessage()); 
      } 
      int available = inputStream.available(); 
      if (available == 0) { 
       continue; 
      } 
      String outText = ""; 
      int count = inputStream.read(buffer, i, available); 
      if (count > 0) { 
       outText = new String(buffer, i, count); 
       i = i + count; 
       message.append(outText); 
       print(
              "GetData: message.append(outText) successful."); 
       if (outText.endsWith("\n")) { 
                        String messageString = message.toString(); 
         print("Message came in: " + messageString); 
        message.delete(0, message.length()); 
       } 
      } 
      print("GetData: inputStream.read().count is zero."); 
      String total = new String(buffer, 0, i); 
     } 
     inputStream.close(); 
    } catch (IOException e) { 
     print("IOException in GetData: " + e.getMessage()); 
    } 
    print("GetData SUCCEEDED."); 
} 

private void print(String str) { 
    int val = form.append(str + "\r\n"); 
    if (val == -1) 
     System.out.print(str + "\r\n"); 
} 
} 
+0

통신 포트에서 무엇을 읽고 싶습니까? – Lucifer

+0

파일 및 문자열. – jim

답변

0

별도의 Thread을 열어 수신을 시작할 수 있습니다. 구조는 아래를 참조하십시오.

Thread commListener = new Thread(new Runnable() { 
    while(true) { // We use a while loop to continually listen to the comm port 

     // Your code here (the listening tasks) 

    } 
}); 
commListener.start(); // Start the Thread 
+0

가 작동하지 않았습니다. 전화는 AT 명령 만 받아들이고 다른 것은 무시합니다. 하이퍼 터미널을 통해 문자열을 보낼 때 아무 일도 일어나지 않지만 AT를 처음에 추가하면 ERROR로 응답합니다. 나는 장치 만 제어 할 수 있고 어떤 데이터도 전송할 수 없다. – jim

+0

@jim 죄송 합니다만, 그때는 당신을 도울 수 없습니다. 나는'CommPort'에 대한 경험이 없으며 J2ME 중급 프로그래밍에 대해서만 알고 있습니다. – Roshnal

관련 문제