在移动设备中持续监听 Co​​mmConnection

发布于 12-31 23:37 字数 4951 浏览 4 评论 0原文

我有以下代码,但我不知道如何不断监听 com 端口。因此,只要有数据,我就可以读取它。那么我应该创建一个线程并永久打开它的输入流吗?在打开输出流之前我应该​​如何关闭它?

基本上,只要数据可用,我的移动端应用程序就应该知道并处理 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");
}
}

I have the following code and I don't know how can I listen to the com port constantly. So whenever data is available I can read it. So should I create a thread and open the input stream on it permanently? How should I close it before opening an output stream?

Basically my app on mobile side should be aware and process the com4 port data whenever the data is available and also be able to send data. All these tasks should be automated once the app start running on mobile device.

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");
}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

节枝2025-01-07 23:37:49

您可以打开一个单独的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

You could open a separate Thread and start listening from there. See below for the structure:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文