繁体   English   中英

使用Shell和Java读取和写入串行端口

[英]Reading and writing to a serial port using shell and Java

我正在尝试使用Shell和Java的组合读取和写入串行端口。 目的是能够使用PrintWriter和BufferedReader从连接到串行端口的设备发送和接收命令。 我知道这可以通过不同的方式完成(无需使用shell),但这不是我想要的。 我希望能够使用Shell和Java做到这一点。

这是我的代码:

static String port = "/dev/tty.usbmodem411";
static int baudRate = 9600;
private static String command = "screen " + port + " " + baudRate;

public static void main(String[] args) throws Exception {
    System.out.println("Command is " + command);
    Process p = Runtime.getRuntime().exec(command);
    //p.waitFor();

    BufferedReader reader =
            new BufferedReader(new InputStreamReader(
            p.getInputStream()));
    String line = reader.readLine();
    while(true)
    {
        if (line != null) {
            System.out.println(line);

        }
        line = reader.readLine();
    }

}

通过此代码,我专门尝试从串行端口读取。 我正在使用Java运行Shell命令来访问串行端口,然后从命令中读取输出。

但是,当我运行此代码时,总是收到一条消息,指出“必须连接到终端”。 我还尝试过更改command = "screen " + port + " " + baudRate;command = "screen " + port + " " + baudRate; command = "screen -dm" + port + " " + baudRate; ,但是我什么也没得到。 我已经咨询了几个类似的问题, 从Java执行屏幕命令以及如何在Linux中打开命令终端? 但我仍然不知道该怎么办才能解决此问题。 我觉得这一定很简单,但是经过数小时的研究,我不知道该怎么办。

您可以使用UUCP软件包中的命令cu来代替屏幕 要安装UUCP软件包sudo apt-get install uucpsudo yum install uucp

然后使用以下命令: static String command = "cu -l " + port + " -s " + baudRate;

一些解释:

  • screen -d分离会话(它在后台运行),这就是为什么您看不到任何数据的原因。
  • 屏幕需要终端,这对于Java来说并不容易。 请参阅如何在Linux中打开命令终端?

您的描述表明您只需要访问串行端口上接收的流。 您表示希望使用shell命令来访问端口。 为什么不使用cat ...将从端口接收的内容发送到标准输出。

如果这可行,那么为什么不能仅打开串行端口并直接从中读取?

使用screen似乎会带来该窗口管理器提供的所有全屏处理,这不太可能正确处理。 例如,应为输出格式化屏幕的终端类型?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM