在使用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;
}
现在我真的迷失了。
答案 0 :(得分: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.