Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034 #ifndef SENSORS_UTIL_ASCIISERIAL_H
00035 #define SENSORS_UTIL_ASCIISERIAL_H
00036
00037 #include <boost/asio.hpp>
00038 #include <boost/thread.hpp>
00039 #include <boost/function.hpp>
00040
00041 #include <string>
00042 #include <iosfwd>
00043
00044 namespace labust
00045 {
00046 namespace comms
00047 {
00051 class ASCIISerial
00052 {
00054 typedef boost::function<void(const std::string&)> CallbackType;
00055
00056 public:
00060 ASCIISerial():
00061 port(io),
00062 connected(false){};
00066 ~ASCIISerial()
00067 {
00068 io.stop();
00069 runner.join();
00070 };
00071
00079 bool connect(const std::string& port_name, int baud)
00080 try
00081 {
00082 using namespace boost::asio;
00083 port.open(port_name);
00084 port.set_option(serial_port::baud_rate(baud));
00085 port.set_option(serial_port::flow_control(
00086 serial_port::flow_control::none));
00087
00088 connected = port.is_open();
00089
00090 if (connected)
00091 {
00092
00093 this->startReceive();
00094 runner = boost::thread(boost::bind(&boost::asio::io_service::run,&io));
00095 }
00096
00097 return connected;
00098 }
00099 catch (std::exception& e)
00100 {
00101 std::cerr<<e.what()<<std::endl;
00102 throw;
00103 }
00104
00109 void registerCallback(const CallbackType& callback)
00110 {
00111 boost::mutex::scoped_lock l(callback_mux);
00112 this->callback = callback;
00113 };
00119 inline bool send(const std::string& msg)
00120 {
00121 boost::asio::write(port, boost::asio::buffer(msg));
00122 return true;
00123 }
00124
00125 private:
00131 void onData(const boost::system::error_code& e, std::size_t size)
00132 {
00133 if (!e)
00134 {
00135 std::istream is(&buffer);
00136 std::string data(size,'\0');
00137 is.read(&data[0],size);
00138 if (!callback.empty()) callback(data);
00139 }
00140 this->startReceive();
00141 }
00142
00144 void startReceive()
00145 {
00146 boost::asio::async_read_until(port, buffer,
00147 "\r\n",
00148 boost::bind(&ASCIISerial::onData, this, _1,_2));
00149 }
00150
00152 boost::asio::io_service io;
00154 boost::asio::serial_port port;
00156 boost::thread runner;
00158 boost::asio::streambuf buffer;
00160 bool connected;
00161
00163 CallbackType callback;
00165 boost::mutex callback_mux;
00166 };
00167 }
00168 }
00169
00170
00171 #endif