80 Buffer::iterator iter(buffer.begin());
81 Buffer::iterator iter_begin(buffer.begin());
82 while (iter != buffer.end())
95 if (std::distance(iter_begin, iter) > 0)
97 std::ostringstream ss;
98 ss <<
"Out-of-sync with VESC, unknown data leading valid frame. Discarding " 99 << std::distance(iter_begin, iter) <<
" bytes.";
105 iter = iter + packet->frame().size();
110 else if (bytes_needed > 0)
126 if (iter == buffer.end())
130 if (std::distance(iter_begin, iter) > 0)
132 std::ostringstream ss;
133 ss <<
"Out-of-sync with VESC, discarding " << std::distance(iter_begin, iter) <<
" bytes.";
136 buffer.erase(buffer.begin(), iter);
141 std::max(bytes_needed, std::min(4096, static_cast<int>(
serial_.
available())));
142 int bytes_read =
serial_.
read(buffer, bytes_to_read);
143 if (bytes_needed > 0 && 0 == bytes_read && !buffer.empty())
145 error_handler_(
"Possibly out-of-sync with VESC, read timout in the middle of a frame.");
171 impl_->packet_handler_ = handler;
177 impl_->error_handler_ = handler;
192 impl_->serial_.setPort(port);
193 impl_->serial_.open();
195 catch (
const std::exception& e)
197 std::stringstream ss;
198 ss <<
"Failed to open the serial port to the VESC. " << e.what();
203 impl_->rx_thread_run_ =
true;
214 impl_->rx_thread_run_ =
false;
215 impl_->rx_thread_.join();
216 impl_->serial_.close();
222 return impl_->serial_.isOpen();
227 size_t written =
impl_->serial_.write(packet.
frame());
228 if (written != packet.
frame().size())
230 std::stringstream ss;
231 ss <<
"Wrote " << written <<
" bytes, expected " << packet.
frame().size() <<
".";
VescInterface(const std::string &port=std::string(), const PacketHandlerFunction &packet_handler=PacketHandlerFunction(), const ErrorHandlerFunction &error_handler=ErrorHandlerFunction())
std::function< void(const VescPacketConstPtr &)> PacketHandlerFunction
PacketHandlerFunction packet_handler_
std::vector< uint8_t > Buffer
void setPosition(double position)
std::unique_ptr< Impl > impl_
std::function< void(const std::string &)> ErrorHandlerFunction
void setDutyCycle(double duty_cycle)
virtual const Buffer & frame() const
void connect(const std::string &port)
static VescPacketPtr createPacket(const Buffer::const_iterator &begin, const Buffer::const_iterator &end, int *num_bytes_needed, std::string *what)
static const int VESC_MIN_FRAME_SIZE
Smallest VESC frame size, in bytes.
void setCurrent(double current)
void setBrake(double brake)
void setServo(double servo)
void send(const VescPacket &packet)
void setSpeed(double speed)
size_t read(uint8_t *buffer, size_t size)
std::shared_ptr< VescPacket const > VescPacketConstPtr
static const unsigned int VESC_SOF_VAL_LARGE_FRAME
VESC start of "large" frame value.
void setErrorHandler(const ErrorHandlerFunction &handler)
static const unsigned int VESC_SOF_VAL_SMALL_FRAME
VESC start of "small" frame value.
std::thread rxThreadHelper()
ErrorHandlerFunction error_handler_
void setPacketHandler(const PacketHandlerFunction &handler)