00001 00032 // Based on example from: 00033 // https://github.com/labust/labust-ros-pkg/wiki/Create-a-Serial-Port-application 00034 00035 #ifndef CREATE_SERIAL_H 00036 #define CREATE_SERIAL_H 00037 00038 #include <boost/asio.hpp> 00039 #include <boost/thread.hpp> 00040 #include <boost/thread/condition_variable.hpp> 00041 #include <boost/function.hpp> 00042 #include <boost/shared_ptr.hpp> 00043 00044 #include "create/data.h" 00045 #include "create/types.h" 00046 #include "create/util.h" 00047 00048 namespace create { 00049 class Serial { 00050 00051 protected: 00052 boost::asio::io_service io; 00053 boost::asio::serial_port port; 00054 00055 private: 00056 boost::thread ioThread; 00057 boost::condition_variable dataReadyCond; 00058 boost::mutex dataReadyMut; 00059 bool dataReady; 00060 bool isReading; 00061 bool firstRead; 00062 uint8_t byteRead; 00063 00064 00065 // Callback executed when data arrives from Create 00066 void onData(const boost::system::error_code& e, const std::size_t& size); 00067 // Callback to execute once data arrives 00068 boost::function<void()> callback; 00069 // Start and stop reading data from Create 00070 bool startReading(); 00071 void stopReading(); 00072 00073 protected: 00074 boost::shared_ptr<Data> data; 00075 // These are for possible diagnostics 00076 uint64_t corruptPackets; 00077 uint64_t totalPackets; 00078 00079 virtual bool startSensorStream() = 0; 00080 virtual void processByte(uint8_t byteRead) = 0; 00081 00082 // Notifies main thread that data is fresh and makes the user callback 00083 void notifyDataReady(); 00084 00085 public: 00086 Serial(boost::shared_ptr<Data> data); 00087 ~Serial(); 00088 bool connect(const std::string& port, const int& baud = 115200, boost::function<void()> cb = 0); 00089 void disconnect(); 00090 inline bool connected() const { return port.is_open(); }; 00091 bool send(const uint8_t* bytes, const uint32_t numBytes); 00092 bool sendOpcode(const Opcode& code); 00093 uint64_t getNumCorruptPackets() const; 00094 uint64_t getTotalPackets() const; 00095 }; 00096 } // namespace create 00097 00098 #endif // CREATE_SERIAL_H