Boost logo

Boost Users :

Subject: Re: [Boost-users] Issue with asio::serial_port - async_write_some handler isn't firing
From: Igor R (boost.lists_at_[hidden])
Date: 2013-04-13 16:09:15


> boost::asio::io_service gService;
> boost::asio::serial_port gPort(gService);
>
> void WriteComplete(const boost::system::error_code& error, std::size_t
> bytes_transferred)
> {
> cout << "Write complete." << endl;
> gPort.close();
> }
>
> int _tmain(int argc, _TCHAR* argv[])
> {
> gPort.open("COM3");
> if(!gPort.is_open())
> {
> cout << "Could not open com port." << endl;
> return 0;
> }
> cout << "Open" << endl;
>
> typedef boost::asio::serial_port_base asio_serial;
>
> gPort.set_option( asio_serial::baud_rate( 9600 ) );
> gPort.set_option( asio_serial::flow_control( asio_serial::flow_control::none
> ) );
> gPort.set_option( asio_serial::parity( asio_serial::parity::none ) );
> gPort.set_option( asio_serial::stop_bits( asio_serial::stop_bits::one ) );
> gPort.set_option( asio_serial::character_size( 8 ) );
>
> char command = '.';
> cout << "Sending command '" << command << "'" << endl;
>
> gPort.async_write_some(
> boost::asio::buffer(&command, sizeof(command)),
> boost::bind( &WriteComplete, boost::asio::placeholders::error,
> boost::asio::placeholders::bytes_transferred )
> );
>
> cout << "Press any key to continue.";
> cin.ignore();
> cin.get();
>
> return 0;
> }

Note that the completion handler WriteComplete will never be invoked
because you don't call gService.run(). Did you take a look at ASIO
docs?
http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio.html
To make the above code work you can either change async_write() to
write(), i.e. write the data synchronously, or call gService.run()
instead of cin.get().
Besides, note that you pass an address of a local object to
async.operation (async_write_some(buffer(&command,
sizeof(command))...), which is dangerous in general, although it'd
work in this particular case if you'd put blocking gService.run() call
before the end of the scope.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net