0

在使用 boost::asio 创建应用程序时,我为我的目的调整了一个示例。

但是,在让它工作之后,我现在正努力让它更好地工作。为此,我需要以某种方式重置我的串行设备。在类似的应用程序中,这是通过发送break信号来完成的。

出于某种原因,我似乎无法在没有异常的情况下做到这一点。

我正在使用该void send_break()函数,也许这就是问题所在,因为它似乎总是会抛出错误。

这是升压代码:

  /// Send a break sequence to the serial port.
  /**
   * This function causes a break sequence of platform-specific duration to be
   * sent out the serial port.
   *
   * @throws boost::system::system_error Thrown on failure.
   */
  void send_break()
  {
    boost::system::error_code ec;
    this->get_service().send_break(this->get_implementation(), ec);
    boost::asio::detail::throw_error(ec, "send_break");
  }

  /// Send a break sequence to the serial port.
  /**
   * This function causes a break sequence of platform-specific duration to be
   * sent out the serial port.
   *
   * @param ec Set to indicate what error occurred, if any.
   */
  boost::system::error_code send_break(boost::system::error_code& ec)
  {
    return this->get_service().send_break(this->get_implementation(), ec);
  }

这是我试图从以下位置调用函数的代码:

class minicom_client
{
public:
        minicom_client(boost::asio::io_service& io_service, unsigned int baud, const string& device)
                : active_(true),
                  io_service_(io_service),
                  serialPort(io_service, device)
        {
                if (!serialPort.is_open())
                {
                        cerr << "Failed to open serial port\n";
                        return;
                }
                boost::asio::serial_port_base::baud_rate baud_option(baud);             
                serialPort.set_option(baud_option); // set the baud rate after the port has been opened             
                serialPort.send_break();                
                read_start();
        }

编辑:

在玩了一段时间之后,我发现我得到的错误代码是boost::asio::error::operation_not_supported;- 但是当这是一个内置函数时,这怎么可能?!

来自 *win_iocp_serial_port_service.hpp*:

  // Send a break sequence to the serial port.
  boost::system::error_code send_break(implementation_type&,
      boost::system::error_code& ec)
  {
    ec = boost::asio::error::operation_not_supported;
    return ec;
  }

现在我真的迷路了。

4

1 回答 1

1

基本上,您需要打开 COM 端口并通过 Windows API 发送中断。只要您正确包含 windows.h,以下代码就应该可以工作。

#include <windows.h>

TCHAR pcCommPort[512];
_tcscpy(pcCommPort, "COM1");   // Or COM2, COM3, ...

//  Open a handle to the specified com port.
handleToComPort = CreateFile(pcCommPort,
    GENERIC_READ | GENERIC_WRITE,
    0,      //  must be opened with exclusive-access
    NULL,   //  default security attributes
    OPEN_EXISTING, //  must use OPEN_EXISTING
    FILE_ATTRIBUTE_NORMAL,      //  not overlapped I/O
    NULL); //  hTemplate must be NULL for comm devices

::SetCommBreak(handleToComPort);
::Sleep(125);           // Sleep 125ms to ensure a good break
::ClearCommBreak(handleToComPort);
::CloseHandle(handleToComPort); // Close the COM port only if you need to.
于 2015-12-12T00:57:08.000 回答