stream.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2017, 2018 Simon Rasmussen (refactor)
3  *
4  * Copyright 2015, 2016 Thomas Timm Andersen (original version)
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 #include <endian.h>
20 #include <netinet/tcp.h>
21 #include <unistd.h>
22 #include <cstring>
23 
24 #include "ur_modern_driver/log.h"
26 
27 bool URStream::write(const uint8_t* buf, size_t buf_len, size_t& written)
28 {
29  std::lock_guard<std::mutex> lock(write_mutex_);
30  return TCPSocket::write(buf, buf_len, written);
31 }
32 
33 bool URStream::read(uint8_t* buf, size_t buf_len, size_t& total)
34 {
35  std::lock_guard<std::mutex> lock(read_mutex_);
36 
37  bool initial = true;
38  uint8_t* buf_pos = buf;
39  size_t remainder = sizeof(int32_t);
40  size_t read = 0;
41 
42  while (remainder > 0 && TCPSocket::read(buf_pos, remainder, read))
43  {
45  if (initial)
46  {
47  remainder = be32toh(*(reinterpret_cast<int32_t*>(buf)));
48  if (remainder >= (buf_len - sizeof(int32_t)))
49  {
50  LOG_ERROR("Packet size %zd is larger than buffer %zu, discarding.", remainder, buf_len);
51  return false;
52  }
53  initial = false;
54  }
55 
56  total += read;
57  buf_pos += read;
58  remainder -= read;
59  }
60 
61  return remainder == 0;
62 }
bool read(char *character)
Definition: tcp_socket.cpp:134
std::mutex write_mutex_
Definition: stream.h:34
virtual void setOptions(int socket_fd)
Definition: tcp_socket.cpp:38
std::mutex read_mutex_
Definition: stream.h:34
bool write(const uint8_t *buf, size_t buf_len, size_t &written)
Definition: tcp_socket.cpp:164
bool read(uint8_t *buf, size_t buf_len, size_t &read)
Definition: stream.cpp:33
bool write(const uint8_t *buf, size_t buf_len, size_t &written)
Definition: stream.cpp:27
#define LOG_ERROR(format,...)
Definition: log.h:36
int getSocketFD()
Definition: tcp_socket.h:59


ur_modern_driver
Author(s): Thomas Timm Andersen, Simon Rasmussen
autogenerated on Fri Jun 26 2020 03:37:00