简体   繁体   English

Java检查com端口连接

[英]Java check com port connection

I am looking for a bit of efficient code that can assist me in monitoring if a com port is still open using the RX/TX libraries.我正在寻找一些有效的代码,可以帮助我使用RX/TX库监控 com 端口是否仍然打开。

Lets say I have a hardware device that communicates to the PC using a virtual com port and that device can be plugged in and out at any time.假设我有一个硬件设备,它使用虚拟 com 端口与 PC 通信,并且该设备可以随时插入和拔出。 I want to show a connection status on the pc.我想在电脑上显示连接状态。

I have tried this with something like a buffered reader below and it registered that the device gets disconnected but I have to re-open the port from scratch in another method.我已经用下面的缓冲阅读器尝试过这个,它注册了设备断开连接,但我必须用另一种方法从头开始重新打开端口。

I am looking from something short like comPort.isOpen () or something?我正在寻找像comPort.isOpen ()类的comPort.isOpen ()

// Set the value of is running
Start.isRunning = true;

// Check to see if the device is connected
while (Start.isRunning) {
    // Try to connect to the device
    try {
        // Create a Buffered Reader
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(serialPort.getInputStream()));

        // Read the output
        if (Character.toString((char) reader.read()).equalsIgnoreCase(
            "^")) {
            // Set the connected flag
            Start.CONNECTED_FLAG = true;

            // Set the connected fag
            AddComponents.TFconnected.setText("Connected");
        }

        // Close the reader
        reader.close();

        // Let the thread sleep
        Thread.sleep(500);
    }

    // Catch a error if the device is disconnected
    catch (Exception err) {
        // Set the connected flag
        Start.CONNECTED_FLAG = false;
        // Set the connected fag
        AddComponents.TFconnected.setText("Disconnected");

        // Let the thread sleep
        Thread.sleep(500);
    }
}

Disclaimer: Consider this a partial answer because I do not have intimate knowledge of the workings of serial ports, and my tests could not produce anything useful.免责声明:将此视为部分答案,因为我对串行端口的工作原理没有深入了解,而且我的测试无法产生任何有用的信息。 Posting here regardless in the hopes any of this is helpful.无论如何都在这里发帖,希望这些都对您有所帮助。

Unfortunately, as far as I know, there is no way to receive any kind of "connection / disconnection" event messages.不幸的是,据我所知,没有办法接收任何类型的“连接/断开”事件消息。 Sadly, as I am not intimately familiar with the workings of serial ports, I cannot give you a full and proper explanation.遗憾的是,由于我对串口的工作原理不是很熟悉,我无法给你一个完整和正确的解释。 However, from some research , one of the answers posted in that forum had this to say:但是,根据一些研究,该论坛上发布的其中一个答案是这样说的:

There's no event by the system to inform you of [a disconnection event] because that would require exclusive use of the COM port.系统没有事件通知您[断开连接事件],因为这需要独占使用 COM 端口。 If you have a SerialPort object created and have opened a port you should get a CDChanged when a devices is plugged in and unplugged from the serial port.如果您创建了一个 SerialPort 对象并打开了一个端口,则当设备从串行端口插入和拔出时,您应该得到一个 CDChanged。 That assumes the device follows the pins standards;假设设备遵循引脚标准; not all devices do.并非所有设备都可以。

Note that the poster, and the link I've provided, are discussing this within the context of C#.请注意,海报和我提供的链接是在 C# 上下文中讨论的。 However this seems to be related to how the ports work in general, regardless of language, so I am somewhat confident the same can be applied to RXTX Java.然而,这似乎与端口的一般工作方式有关,无论语言如何,所以我有点相信同样可以应用于 RXTX Java。

There are some events you can attempt to listen for.您可以尝试监听一些事件 In my tests I was only ever able to receive the DATA_AVAILABLE event, however my setup is a bit different (Raspberry PI) and I can't at the moment physically disconnect the device from the port, I can only attempt to block the device file (which may explain the failure of my test).在我的测试中,我只能接收到DATA_AVAILABLE事件,但是我的设置有点不同(Raspberry PI),我目前无法从端口物理断开设备,我只能尝试阻止设备文件(这可以解释我的测试失败)。

If you would like to attempt the event listening yourself, have your class implement SerialPortListener , register for the desired events, check the events in your serialEvent method.如果您想尝试自己监听事件,请让您的类实现SerialPortListener ,注册所需的事件,检查serialEvent方法中的事件。 Here is an example:下面是一个例子:

public class YourClass implements SerialPortListener{
    private SerialPort serialPort;

    // ... serial port gets set up at some point ...

    public void registerEvents(){
        serialPort.addEventListener(this);

        // listen to all the events
        serialPort.notifyOnBreakInterrupt(true);
        serialPort.notifyOnCarrierDetect(true);
        serialPort.notifyOnCTS(true);
        serialPort.notifyOnDataAvailable(true);
        serialPort.notifyOnDSR(true);
        serialPort.notifyOnFramingError(true);
        serialPort.notifyOnOutputEmpty(true);
        serialPort.notifyOnOverrunError(true);
        serialPort.notifyOnParityError(true);
        serialPort.notifyOnRingIndicator(true);
    }

    @Override
    public void serialEvent(SerialPortEvent event) {
        System.out.println("Received event. Type: " + event.getEventType() + ", old value: " + event.getOldValue() + ", new value: " + event.getNewValue());
    }
}

If that ultimately fails, I believe the only other alternative is similar to your current solution;如果最终失败,我相信唯一的其他选择与您当前的解决方案相似; attempt to read from the port, and if it fails, consider it disconnected, and set your indicator accordingly.尝试从端口读取,如果失败,则认为它已断开连接,并相应地设置指示器。 At each iteration, if it is disconnected, attempt to reconnect;在每次迭代时,如果断开连接,则尝试重新连接; if reconnect succeeds, reset your indicator to "connected".如果重新连接成功,请将指示器重置为“已连接”。

Sorry I cannot be of more assistance.抱歉,我无法提供更多帮助。 Hopefully some of that may lead to something useful.希望其中一些可能会带来一些有用的东西。

Side Note:边注:

If you want to DRY up your code slightly, put the Thread.sleep(500) in a finally block instead, since it appears to be executed regardless.如果你想稍微干点你的代码,把Thread.sleep(500)放在 finally 块中,因为它似乎无论如何都会被执行。

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

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