@@ -40,26 +40,26 @@ namespace create {
4040
4141 bool Serial::connect (const std::string& portName, const int & baud, std::function<void ()> cb) {
4242 using namespace boost ::asio;
43- port.open (portName);
44- port.set_option (serial_port::baud_rate (baud));
45- port.set_option (serial_port::character_size (8 ));
46- port.set_option (serial_port::parity (serial_port::parity::none));
47- port.set_option (serial_port::stop_bits (serial_port::stop_bits::one));
48- port.set_option (serial_port::flow_control (serial_port::flow_control::none));
43+ if (!openPort (portName, baud)) {
44+ return false ;
45+ }
4946
5047 signals.async_wait (std::bind (&Serial::signalHandler, this , std::placeholders::_1, std::placeholders::_2));
5148
5249 usleep (1000000 );
5350
54- if (port.is_open ()) {
55- callback = cb;
56- bool startReadSuccess = startReading ();
57- if (!startReadSuccess) {
58- port.close ();
59- }
60- return startReadSuccess;
51+ if (!port.is_open ()) {
52+ return false ;
53+ }
54+
55+ callback = cb;
56+ bool startReadSuccess = startReading ();
57+ if (!startReadSuccess) {
58+ closePort ();
59+ return false ;
6160 }
62- return false ;
61+
62+ return true ;
6363 }
6464
6565 void Serial::disconnect () {
@@ -76,6 +76,33 @@ namespace create {
7676 }
7777 }
7878
79+ bool Serial::openPort (const std::string& portName, const int & baud) {
80+ using namespace boost ::asio;
81+ try {
82+ port.open (portName);
83+ port.set_option (serial_port::baud_rate (baud));
84+ port.set_option (serial_port::character_size (8 ));
85+ port.set_option (serial_port::parity (serial_port::parity::none));
86+ port.set_option (serial_port::stop_bits (serial_port::stop_bits::one));
87+ port.set_option (serial_port::flow_control (serial_port::flow_control::none));
88+ } catch (const boost::system::system_error& /* e*/ ) {
89+ CERR (" [create::Serial] " , " failed to open port: " << portName);
90+ return false ;
91+ }
92+ return true ;
93+ }
94+
95+ bool Serial::closePort () {
96+ using namespace boost ::asio;
97+ try {
98+ port.close ();
99+ } catch (const boost::system::system_error& /* e*/ ) {
100+ CERR (" [create::Serial] " , " failed to close port" );
101+ return false ;
102+ }
103+ return true ;
104+ }
105+
79106 bool Serial::startReading () {
80107 if (!connected ()) return false ;
81108
@@ -186,8 +213,13 @@ namespace create {
186213 CERR (" [create::Serial] " , " send failed, not connected." );
187214 return false ;
188215 }
189- // TODO: catch boost exceptions
190- boost::asio::write (port, boost::asio::buffer (bytes, numBytes));
216+
217+ try {
218+ boost::asio::write (port, boost::asio::buffer (bytes, numBytes));
219+ } catch (const boost::system::system_error & e) {
220+ CERR (" [create::Serial] " , " failed to write bytes to port" );
221+ return false ;
222+ }
191223 return true ;
192224 }
193225
0 commit comments