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 #ifndef HAND_BRIDGE_SERIAL_PORT_H_
00019 #define HAND_BRIDGE_SERIAL_PORT_H_
00020
00021 #include "pigpio.h"
00022
00023 #include <boost/lexical_cast.hpp>
00024 #include <boost/chrono.hpp>
00025 #include <boost/thread.hpp>
00026
00027 class SerialPort {
00028 int ser_port;
00029 public:
00030 bool isOpen() const{
00031 return ser_port >= 0 && serDataAvailable(ser_port) >= 0;
00032 }
00033 bool init(char * param)
00034 {
00035 unsigned int baud = 57600;
00036 if(char * delim = strchr(param, '@')){
00037 *delim = 0;
00038 baud = boost::lexical_cast<unsigned int>(delim + 1);
00039 }
00040 ser_port = serOpen(param, baud, 0);
00041 printf("%s opened as %d\n", param, ser_port);
00042 return isOpen();
00043 }
00044
00045 template<typename Duration> int waitData(const Duration& duration){
00046 boost::chrono::steady_clock::time_point deadline = boost::chrono::steady_clock::now() + duration;
00047 int len;
00048 while((len = serDataAvailable(ser_port)) == 0 && boost::chrono::steady_clock::now() < deadline)
00049 boost::this_thread::sleep_for(boost::chrono::milliseconds(1));
00050 return len;
00051 }
00052
00053 int readByte(){
00054 return serReadByte(ser_port);
00055 }
00056 int read(char *buf, unsigned count){
00057 return serRead(ser_port, buf, count);
00058 }
00059 bool write(uint8_t* data, int length)
00060 {
00061 return serWrite(ser_port, reinterpret_cast<char*>(data), length) == 0;
00062 }
00063 bool write(const std::string &line){
00064 return serWrite(ser_port, const_cast<char *>(line.c_str()), line.size()) == 0;
00065 }
00066 void close(){
00067 if(isOpen()) serClose(ser_port);
00068 }
00069 SerialPort() : ser_port(-1) {}
00070 ~SerialPort(){
00071 close();
00072 }
00073 };
00074
00075
00076 #endif // HAND_BRIDGE_SERIAL_PORT_H_