serial_port.h
Go to the documentation of this file.
00001 /*
00002  * Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *   http://www.apache.org/licenses/LICENSE-2.0
00009 
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
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_


cob_hand_bridge
Author(s): Mathias Lüdtke
autogenerated on Thu Jun 6 2019 20:43:57