【问题标题】:Java rxtx code to connect to rfcomm0 is not working连接到 rfcomm0 的 Java rxtx 代码不起作用
【发布时间】:2023-03-28 22:52:01
【问题描述】:

我已经成功地将我的 arduino uno R3 与蓝牙伴侣模块连接起来,并且能够通过蓝牙将数据发送到运行 Ubuntu 12.04 的笔记本电脑。 (使用串口协议)。数据在 rfcomm0 上接收。

以下代码显示接收到的数据:sudo screen /dev/rfcomm0

现在我在 Java 程序中读取这些数据时遇到了问题。我已经参考了http://playground.arduino.cc/Interfacing/Java 的代码。这使用 rxtx 库来访问串行端口。

代码如下:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier; 
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent; 
import gnu.io.SerialPortEventListener; 
import java.util.Enumeration;


public class SerialTest implements SerialPortEventListener {
    SerialPort serialPort;
    /** The port we're normally going to use. */
    private static final String PORT_NAMES[] = { 
            "/dev/tty.usbserial-A9007UX1", // Mac OS X
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
//          "/dev/ttyACM0" // Ubuntu
            "/dev/rfcomm0" // Ubuntu Bluetooth
    };
    /**
    * A BufferedReader which will be fed by a InputStreamReader 
    * converting the bytes into characters 
    * making the displayed results codepage independent
    */
    private BufferedReader input;
    /** The output stream to the port */
    private OutputStream output;
    /** Milliseconds to block while waiting for port open */
    private static final int TIME_OUT = 2000;
    /** Default bits per second for COM port. */
    private static final int DATA_RATE = 9600;

    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        //First, Find an instance of serial port as set in PORT_NAMES.
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }

        try {
            // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(),
                    TIME_OUT);

            // set port parameters
            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            // open the streams
            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
            output = serialPort.getOutputStream();

            // add event listeners
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }

    /**
     * This should be called when you stop using the port.
     * This will prevent port locking on platforms like Linux.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    /**
     * Handle an event on the serial port. Read the data and print it.
     */
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine=input.readLine();
                System.out.println(inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    public static void main(String[] args) throws Exception {
        SerialTest main = new SerialTest();
        main.initialize();
        Thread t=new Thread() {
            public void run() {
                //the following line will keep this app alive for 10 seconds,
                //waiting for events to occur and responding to them (printing incoming messages to console).
                try {Thread.sleep(10000);} catch (InterruptedException ie) {}
            }
        };
        System.out.println("Started");
        t.start();
        t.join();
        main.close();
        System.out.println("Stopped");
    }
}

此程序编译成功,但执行时显示:"Could not find COM port."

注意:当从 USB 端口 /dev/ttyACM0 读取数据时,此代码可以完美运行。当我尝试从蓝牙端口/dev/rfcomm0 读取数据时出现问题。

所以基本上我需要一个 java 程序来读取 rfcomm0 端口。非常感谢任何帮助。

【问题讨论】:

  • 您是否尝试在CommPortIdentifier currPortId = ... 行之后添加System.out.println(currPortId.getName()); 调用以查看正在找到哪些端口ID?
  • @angelatlarge : System.out.println(currPortId.getName()); 返回 /dev/ttyACM0 嗯...我已将我的 arduino 连接到该端口以启动它...看起来这会干扰蓝牙串行端口 rfcomm0。让我从其他来源为 arduino 供电并尝试一下。
  • 好的,很明显,听起来Java 没有找到您的/dev/rfcomm0 端口。但是,您说 sudo screen /dev/rfcomm0 正在工作,这表明这是 Java/JVM 特定的问题?
  • 原来screen 命令有效是因为sudo... java 程序无法从 rfcomm0 读取,因为它没有权限。

标签: java bluetooth arduino rxtx rfcomm


【解决方案1】:

感谢@angelatlarge 的建议。

问题是java程序没有访问/dev/rfcomm0的权限。

提供权限的命令:sudo chmod a+rw /dev/rfcomm0

所以授予/dev/rfcomm0 的权限为我解决了这个问题。 现在java程序可以从rfcomm0端口读取数据了。

【讨论】:

  • 也许在一段时间过去后接受您自己的答案,以便人们知道问题已解决。真高兴你做到了!虽然现在我想起来了,你不应该用权限来保护/dev/ttyACM0,对吧?如果您在代码中将其注释为“可接受的”端口名称,那么您的 java 代码不应该打开它,对吧?
  • 尽管我在java程序中注释了/dev/ttyACM0,但System.out.println(currPortId.getName());确实出于某种原因显示了它!查看图片:www5.picturepush.com/photo/a/12432443/img/12432443.png > ...
  • 不,它应该显示,我们预计:打印语句在if之上。但它不应该超过 if (currPortId.getName().equals(portName)) { :这意味着你不应该限制对它的访问。抱歉不清楚。
  • 对!因此,唯一需要的更改是获得/dev/rfcomm0 的许可。用它试过了,它奏效了。改变了我的答案。谢谢
  • 酷。也许在可以(有等待期)之后继续接受您的回答,以便人们知道问题已经解决。
猜你喜欢
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 2019-10-10
  • 2020-01-18
  • 1970-01-01
相关资源
最近更新 更多