RobotsIO
Loading...
Searching...
No Matches
YarpBufferedPort.hpp
1/*
2 * Copyright (C) 2019 Istituto Italiano di Tecnologia (IIT)
3 *
4 * This software may be modified and distributed under the terms of the
5 * BSD 3-Clause license. See the accompanying LICENSE file for details.
6 */
7
8#ifndef ROBOTSIO_YARPBUFFEREDPORT_H
9#define ROBOTSIO_YARPBUFFEREDPORT_H
10
11#include <yarp/os/BufferedPort.h>
12#include <yarp/os/Network.h>
13#include <yarp/os/Stamp.h>
14
15#include <string>
16#include <unordered_map>
17
18namespace RobotsIO {
19 namespace Utils {
20 template<class T>
21 class YarpBufferedPort;
22 }
23}
24
25
26template<class T>
28{
29public:
30 YarpBufferedPort(const std::string& port_name);
31
32 virtual ~YarpBufferedPort();
33
34 void send_data(const T& data);
35
36 T* receive_data(const bool& blocking);
37
38 double time_stamp();
39
40 void set_time_stamp(const double& stamp);
41
42 std::size_t flush();
43
44protected:
45 yarp::os::Network yarp_;
46
47 yarp::os::BufferedPort<T> port_;
48
49 yarp::os::Stamp stamp_;
50
51 const std::string log_name_ = "YarpBufferedPort";
52};
53
54
55template<class T>
57{
58 if (!yarp_.checkNetwork())
59 {
60 throw(std::runtime_error(log_name_ + "::ctor. Error: YARP network is not available."));
61 }
62
63 if(!port_.open(port_name))
64 {
65 throw(std::runtime_error(log_name_ + "::ctor. Error: cannot open port " + port_name + "."));
66 }
67}
68
69
70template <class T>
72{
73 if(!(port_.isClosed()))
74 port_.close();
75}
76
77
78template <class T>
80{
81 T& data_to_be_sent = port_.prepare();
82
83 port_.setEnvelope(stamp_);
84
85 data_to_be_sent = data;
86
87 port_.write();
88}
89
90
91template <class T>
93{
94 return port_.read(blocking);
95}
96
97
98template <class T>
100{
101 yarp::os::Stamp stamp;
102 port_.getEnvelope(stamp);
103
104 return stamp.getTime();
105}
106
107
108template <class T>
110{
111 stamp_.update(stamp);
112}
113
114
115template <class T>
117{
118 std::size_t pending_reads = port_.getPendingReads();
119 for (std::size_t i = 0; i < pending_reads; i++)
120 port_.read(false);
121
122 return pending_reads;
123}
124
125#endif /* ROBOTSIO_YARPBUFFEREDPORT_H */