我正在寻找一些有效的代码,可以帮助我使用RX/TX库监视com端口是否仍然处于打开状态。
假设我有一个硬件设备,可以使用虚拟com端口与PC进行通信,而且该设备可以在任何时候插入或拔出。我想在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);
}
}发布于 2014-04-15 19:39:55
免责声明:认为这是一个部分的答案,因为我不熟悉串口的工作,我的测试无法产生任何有用的东西。无论在这里张贴,希望任何这都是有帮助的。
不幸的是,据我所知,无法接收任何类型的“连接/断开”事件消息。可悲的是,由于我不太熟悉串口的工作原理,所以我无法给你一个完整而恰当的解释。然而,在一些研究上,论坛上发布的一个答案是这样说的:
系统没有通知您断开连接事件的事件,因为这需要对COM端口进行独占使用。如果您已经创建了一个SerialPort对象,并且已经打开了一个端口,那么当设备插入并从串口拔出时,您应该会得到一个CDChanged。这假设设备遵循引脚标准;并不是所有设备都这样做。
请注意,海报和我提供的链接是在C#上下文中讨论的。然而,这似乎与端口的一般工作方式有关,无论语言如何,所以我有点相信RXTX也可以使用相同的端口。
有一些你可以尝试监听的一些事件。在我的测试中,我只能接收到DATA_AVAILABLE事件,但是我的设置有点不同(Raspberry ),目前我不能物理地断开设备与端口的连接,我只能尝试阻止设备文件(这可能解释我的测试失败)。
如果您想自己尝试侦听事件,让您的类实现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块中,因为它似乎是被执行的。
https://stackoverflow.com/questions/23085983
复制相似问题