【问题标题】:Is asio::serial_port able to check physical disconnection?asio::serial_port 是否能够检查物理断开连接?
【发布时间】:2022-12-18 14:29:02
【问题描述】:

我正在使用用于串行通信的 boost::asio 库,但在使用它时遇到了一些问题。下面是我的问题代码。

std::unique_ptr<asio::serial_port> port_;
asio::io_service io_;

// Connect serial port 'COM8'
port_ = std::make_unique<asio::serial_port>(asio::serial_port(io_, "COM8"));
std::cout << port_->is_open() << std::endl; // True

Sleep(5000);
/// **Now I unplug the device connected to the COM8 port of my PC.**

std::cout << port_->is_open() << std::endl;
/// Still printed true.
/// I think the reason @asio::serial_port::is_open() returns true 
/// is because I didn't called @asio::serial_port::close() before. 
/// Then how can I check the physical disconnection?

拔下设备后,如何以编程方式知道设备是否仍然可用?

【问题讨论】:

  • is_open() 如果类实例是“开放的”。基本上,如果允许调用实例上的操作。也许有一些方法可以使用本机句柄来检测通信丢失,但它不可移植。通常在创建套接字后,会分配读/写例程,当该例程失败时,我们会得到指示,表明套接字出现问题。
  • 串口通信没有检测连接/断开的方法,因为在协议级别没有定期的心跳或保持活动消息。你必须自己实施。

标签: c++ boost-asio


【解决方案1】:

您可以在尝试读/写操作时检测到它:

例如。来自exception overload of write_some

升压::系统::系统错误

失败时抛出。 boost::asio::error::eof 的错误代码表示 连接已被对等方关闭。

【讨论】:

    【解决方案2】:

    感谢@sehe,这是我的解决方案。 (以port_作为私有成员变量的方法)

    inline bool _IsConnected() {
      bool connected = (port_ != nullptr && port_->is_open());
      if (connected) {
        try {
          // Sned any string that doesn't define
          // in your communication protocol.
          std::string s = "0"; 
          port_->write_some(asio::buffer("0"));
        }
        catch (const std::exception& err) {
          connected = false;
        }
      }
      return connected;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 2010-12-31
      相关资源
      最近更新 更多