我正在寻找一些有效的代码,可以帮助我使用 RX/TX
库监视 com 端口是否仍然打开。
假设我有一个硬件设备,它使用虚拟 com 端口与 PC 进行通信,并且该设备可以随时插入和拔出。我想在电脑上显示连接状态。
我已经尝试过使用下面的缓冲读取器之类的东西,它注册了设备已断开连接,但我必须用另一种方法从头开始重新打开端口。
我正在寻找诸如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);
}
}
最佳答案
免责声明:将此视为部分答案,因为我对串行端口的工作原理没有深入了解,并且我的测试无法产生任何有用的结果。不管怎样,在这里发帖希望这些内容对您有所帮助。
不幸的是,据我所知,没有办法接收任何类型的“连接/断开”事件消息。遗憾的是,由于我不太熟悉串行端口的工作原理,因此我无法给您完整且正确的解释。然而,从 some research ,该论坛中发布的答案之一是这样说的:
There's no event by the system to inform you of [a disconnection event] because that would require exclusive use of the COM port. 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. That assumes the device follows the pins standards; not all devices do.
请注意,海报和我提供的链接正在 C# 上下文中讨论此问题。然而,这似乎与端口的一般工作方式有关,无论语言如何,所以我有信心同样可以应用于 RXTX Java。
有some events你可以尝试去听听。在我的测试中,我只能接收 DATA_AVAILABLE
事件,但是我的设置有点不同(Raspberry PI),目前我无法从端口物理断开设备连接,我可以只尝试阻止设备文件(这可以解释我的测试失败)。
如果您想尝试自己监听事件,请让您的类(class)实现 SerialPortListener
,注册所需的事件,检查 serialEvent
方法中的事件。这是一个例子:
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());
}
}
如果最终失败,我相信唯一的其他替代方案与您当前的解决方案类似;尝试从端口读取数据,如果失败,则视为已断开连接,并相应地设置指示器。在每次迭代时,如果断开连接,则尝试重新连接;如果重新连接成功,请将指示器重置为“已连接”。
抱歉,我无法提供更多帮助。希望其中一些可能会带来一些有用的东西。
旁注:
如果您想稍微干燥一下代码,请将 Thread.sleep(500)
放入 finally block 中,因为无论如何它都会执行。
关于Java检查com端口连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23085983/