YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
PortMonitor.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-License-Identifier: BSD-3-Clause
4 */
5
6#include <yarp/os/Log.h>
7#include <string>
10#include <yarp/os/Route.h>
11#include <yarp/os/Contactable.h>
12#include <yarp/os/LogStream.h>
13#include <yarp/os/Network.h>
14
15#include "PortMonitor.h"
16#include "MonitorLogComponent.h"
17
18
19
20using namespace yarp::os;
21
22std::pair<std::string, std::string> parseBlocks(const std::string& input)
23{
24 //This function is not commented because it was generated
25 const std::string sendTag = "+send.portmonitor+";
26 const std::string recvTag = "+recv.portmonitor+";
27
28 size_t posSend = input.find(sendTag);
29 size_t posRecv = input.find(recvTag);
30
31 std::string middle;
32 std::string afterRecv;
33 if (posRecv != std::string::npos)
34 {
35 afterRecv = input.substr(posRecv + recvTag.size());
36 }
37
38 if (posSend != std::string::npos && posRecv != std::string::npos)
39 {
40 size_t start = posSend + sendTag.size();
41 size_t end = (posSend < posRecv) ? posRecv : std::string::npos;
42
43 middle = input.substr(start, end - start);
44 }
45 else if (posSend != std::string::npos && posRecv == std::string::npos)
46 {
47 middle = input.substr(posSend + sendTag.size());
48 }
49 else if (posSend == std::string::npos && posRecv != std::string::npos)
50 {
51 middle = input.substr(0, posRecv);
52 }
53 else
54 {
55 middle = input;
56 }
57
58 return {middle, afterRecv};
59}
60
61std::string separateString(std::string input)
62{
63 std::string output;
64 size_t start = 0;
65 if (start != std::string::npos) {
66 output += " (";
67 for (size_t i = start; i < (size_t)input.length(); i++) {
68 char ch = input[i];
69 if (ch == '+') {
70 output += ") (";
71 } else if (ch == '.') {
72 output += " ";
73 } else {
74 output += ch;
75 }
76 }
77 output += ")";
78 }
79 return output;
80}
81
86// Read connection settings.
88{
90
91 portName = proto.getRoute().getToName();
92 sourceName = proto.getRoute().getFromName();
93 group = getPeers().add(portName,this);
94 if (!group) {
95 yCError(PORTMONITORCARRIER) << "Cannot find group";
96 return false;
97 }
98
99 Property options;
100 //options.fromString(proto.getSenderSpecifier());
101 options.put("source", sourceName);
102 options.put("destination", portName);
103 options.put("sender_side",
104 (proto.getContactable()->getName() == sourceName) ? 1 : 0);
105 options.put("receiver_side",
106 (proto.getContactable()->getName() == portName) ? 1 : 0);
107
108 std::string carrier_options = proto.getRoute().getCarrierName();
109
110 //I want to split a string like this:
111 //fast_tcp+send.portmonitor+file.bottle_compression_zlib+type.dll+recv.portmonitor+file.bottle_compression_zlib+type.dll
112 //into two strings. For senders side:
113 // file.bottle_compression_zlib+type.dll
114 // and for receivers side:
115 // file.bottle_compression_zlib+type.dll
117
118 //This line extract fast_tcp (all the text until the first +)
119 std::string carrier_proto= carrier_options.substr(0, carrier_options.find('+'));
120
121 //Add the carrier
122 options.fromString("(carrier " + carrier_proto + ")",false);
123
124 if (proto.getContactable()->getName() == sourceName)
125 {
126 std::string sendoptions = separateString(file1);
127 options.fromString(sendoptions, false);
128 }
129 else if (proto.getContactable()->getName() == portName)
130 {
131 std::string recvoptions = separateString(file2);
132 options.fromString(recvoptions, false);
133 }
134
135 return configureFromProperty(options);
136}
137
139{
140 // Iterate through all properties and save unknown parameters to paramsMap
142 propertyBottle.fromString(inputoptions.toString());
143
144 for (size_t i = 0; i < propertyBottle.size(); i++)
145 {
146 Value& element = propertyBottle.get(i);
147 if (!element.isList()) { continue; }
148
149 Bottle* entry = element.asList();
150 if (entry->size() < 2) { continue; }
151
152 std::string key = entry->get(0).asString();
153
154 // Skip known parameters
155 if (key == "type" ||
156 key == "file")
157 { continue;}
158
159 // Add unknown parameter to params map
160 auto value = entry->get(1);
161 outputoptions.put(key,value);
162 }
163}
164
166{
168 std::string debug_string_options = options.toString();
170
171 // clear the list of binders, if any, before creating new ones
172 for (auto it=binder.begin(); it!=binder.end(); ++it)
173 {
174 if (*it) {
175 delete *it;
176 *it=nullptr;
177 }
178 }
179 binder.clear();
180
181 std::vector<std::string> scriptstype;
182 std::vector<std::string> filenames;
183 std::vector<std::string> constraints;
184 std::vector<std::string> contexts; // context is used to find the script files
185
186 std::string type = options.check("type", Value("")).asString();
187 std::string file = options.check("file", Value("")).asString();
188 bool sender_side = options.check("sender_side", Value(false)).asBool() == 1;
189 // Validate that mandatory parameters are provided
190 if (type.empty() || file.empty())
191 {
192 if (sender_side)
193 {yCError(PORTMONITORCARRIER) << "Missing required 'type' or 'file' parameter on sender side";}
194 else
195 {yCError(PORTMONITORCARRIER) << "Missing required 'type' or 'file' parameter on receiver side";}
196 return false;
197 }
198
199 scriptstype.push_back(type);
200 filenames.push_back(file);
201 constraints.push_back(options.check("constraint", Value("")).asString());
202 contexts.push_back(options.check("context", Value("")).asString());
203
204 // Optional support for multiple scripts, e.g. type1, file1, constraint1, context1, type2, file2, constraint2, context2, ...
205 for (int i = 1; ; ++i)
206 {
207 std::string typeKey = "type" + std::to_string(i);
208 std::string fileKey = "file" + std::to_string(i);
209 std::string constraintKey = "constraint" + std::to_string(i);
210 std::string contextKey = "context" + std::to_string(i);
211
212 // if typeN is not provided, we assume that there are no more scripts to load
213 if (!options.check(typeKey)) {
214 break;
215 }
216
217 std::string type = options.check(typeKey, Value("")).asString();
218 std::string file = options.check(fileKey, Value("")).asString();
219 // Validate that mandatory parameters are provided
220 if (type.empty() || file.empty())
221 {
222 if (sender_side)
223 yCError(PORTMONITORCARRIER) << "Missing required 'type' or 'file' parameter on sender side";
224 else
225 yCError(PORTMONITORCARRIER) << "Missing required 'type' or 'file' parameter on receiver side";
226 return false;
227 }
228
229 scriptstype.push_back(type);
230 filenames.push_back(file);
231 constraints.push_back(options.check(constraintKey, Value("")).asString());
232 contexts.push_back(options.check(contextKey, Value("")).asString());
233 }
234
235 // Create the monitor binding objects for each script
236 for (size_t i=0; i< scriptstype.size(); i++)
237 {
239 if(mon == nullptr)
240 {
241 //Failed to create monitor
242 return false;
243 }
244
245 // set the acceptance constraint
246 mon->setAcceptConstraint(constraints[i].c_str());
247 binder.push_back(mon);
248 }
249
250 // provide some useful information for the monitor object
251 // which can be accessed in the create() callback.
252 bReady=true;
254 for (size_t i=0; i<binder.size(); i++)
255 {
256 // sets the context for finding the script file
257 std::string strFile = filenames[i];
258 if(scriptstype[i] != "dll")
259 {
262 rf.configure(0, nullptr);
263 strFile = rf.findFile(filenames[i]);
264 if(strFile.empty()) {
265 strFile = rf.findFile(filenames[i] + ".lua");
266 }
267 if(strFile.empty()) {
268 strFile = rf.findFile(filenames[i] + ".py");
269 }
270 }
271
272 // set the information for the monitor object
274 info.clear();
275 info.put("filename", strFile);
276 info.put("type", scriptstype[i]);
277 info.put("source", options.find("source").asString());
278 info.put("destination", options.find("destination").asString());
279 info.put("sender_side", options.find("sender_side").asInt32());
280 info.put("receiver_side",options.find("receiver_side").asInt32());
281 info.put("carrier", options.find("carrier").asString());
282
283 //here, for multiple portmonitors, only the related parameters should be provided...
284 parseParameters(options, info);
285 std::string debugInfoString = info.toString();
287
288 // load the monitor object with the provided information
289 bReady &= binder[i]->load(info);
290 }
292 return bReady;
293}
294
296{
298
299 if(!bReady) {
300 return;
301 }
303 for (size_t i=0; i<binder.size(); i++)
304 {
305 binder[i]->setParams(params);
306 }
308}
309
311{
313
314 if(!bReady) {
315 return;
316 }
318 for (size_t i=0; i<binder.size(); i++)
319 {
320 binder[i]->getParams(params);
321 }
323}
324
325
327{
329
330 if(!bReady) {
331 return reader;
332 }
333
334 // When we are here,
335 // the incoming data should be accessed using localReader.
336 // The reader passed to this function is indeed empty.
337
338 localReader->setParentConnectionReader(&reader);
339
340 //Call the sequence of portmonitors,
341 //feeding the output of one as input to the next one.
343 yarp::os::Things thing;
344 thing.setConnectionReader(*localReader);
345 yarp::os::Things* current = &thing;
346 for (size_t i = 0; i < binder.size(); ++i)
347 {
348 // If no update callback is available, avoid calling it
349 if(!binder[i]->hasUpdate())
350 {
351 continue;
352 }
353 current = &binder[i]->updateData(*current);
354 }
356
357 con.reset();
358 if(current->write(con.getWriter())) {
359 auto& cReader = con.getReader(reader.getWriter());
360 cReader.setParentConnectionReader(&reader);
361 if (current->getPortReader() != nullptr) {
362 cReader.getWriter()->setReplyHandler(*current->getPortReader());
363 }
364 return cReader;
365 }
366 return *localReader;
367}
368
370{
372
373 // TODO: the implementation of this method is not complete yet.
374 // It should call the acceptData method of all the portmonitors in the binder vector, not just the first one.
375
376 if(!bReady) {
377 return false;
378 }
379
380 bool result = true;
381 localReader = &reader;
382 // If no accept callback avoid calling the binder
383 if (binder[0]->hasAccept())
384 {
386 Things thing;
387 // set the reference connection reader
388 thing.setConnectionReader(reader);
389 result &= binder[0]->acceptData(thing);
391 if(!result) {
392 return false;
393 }
394
395 // When data is read here using the reader passed to this functions,
396 // then it won't be available for modifyIncomingData(). Thus, we write
397 // it to a dummy connection and pass it to the modifyOutgoingData() using
398 // localReader.
399 // localReader points to a connection reader which contains
400 // either the original or modified data.
401 if(thing.hasBeenRead()) {
402 con.reset();
403 if(thing.write(con.getWriter())) {
404 localReader = &con.getReader(reader.getWriter());
405 }
406 }
407 }
408
409 if(group!=nullptr) {
410 getPeers().lock();
411 result = group->acceptIncomingData(this);
412 getPeers().unlock();
413 }
414 return result;
415}
416
417
419{
421
422 if(!bReady) {
423 return writer;
424 }
425
426 //Call the sequence of portmonitors,
427 //feeding the output of one as input to the next one.
429 thing.reset();
430 thing.setPortWriter(const_cast<yarp::os::PortWriter*>(&writer));
431 yarp::os::Things* current = &thing;
432 for (size_t i = 0; i < binder.size(); ++i)
433 {
434 // If no update callback is available, avoid calling it
435 if(!binder[i]->hasUpdate())
436 {
437 continue;
438 }
439 current = &binder[i]->updateData(*current);
440 }
442 return *current->getPortWriter();
443}
444
446{
448
449 // TODO: the implementation of this method is not complete yet.
450 // It should call the acceptData method of all the portmonitors in the binder vector, not just the first one.
451
452 if(!bReady) {
453 return false;
454 }
455
456 bool result = true;
457 // If no accept callback avoid calling it
458 if (!binder[0]->hasAccept()) {
459 return true;
460 }
461
463 yarp::os::Things thing;
464 thing.setPortWriter(const_cast<yarp::os::PortWriter*>(&writer));
465 result &= binder[0]->acceptData(thing);
467 return result;
468}
469
471{
473
474 if(!bReady) {
475 return reader;
476 }
477
478 //Call the sequence of portmonitors,
479 //feeding the output of one as input to the next one.
481 thing.reset();
482 thing.setPortReader(&reader);
483 yarp::os::Things* current = &thing;
484 for (size_t i = 0; i < binder.size(); ++i)
485 {
486 // If no reply callback is available, avoid calling it
487 if(!binder[i]->hasUpdateReply())
488 {
489 continue;
490 }
491 current = &binder[i]->updateReply(*current);
492 }
494 return *current->getPortReader();
495}
496
501std::unique_ptr<ElectionOf<PortMonitorGroup>> PortMonitor::peers = nullptr;
502
503// Make a singleton manager for finding peer carriers.
504ElectionOf<PortMonitorGroup>& PortMonitor::getPeers()
505{
507
509 if (peers==nullptr) {
510 peers = std::make_unique<ElectionOf<PortMonitorGroup>>();
513 } else {
515 }
516 return *peers;
517}
518
519// Decide whether data should be accepted, for real.
521{
523
524 //bool accept = true;
525 for (auto& it : peerSet)
526 {
527 PortMonitor *peer = it.first;
528 if(peer != source)
529 {
530 peer->lock();
531 // TODO: check whether we should return false if
532 // the peer monitor object is not ready!
533 if(peer->getBinder()) {
534 peer->getBinder()->peerTrigged();
535 }
536 peer->unlock();
537 }
538 }
539 return source->getBinder()->canAccept();
540}
size_t size_t
const yarp::os::LogComponent & PORTMONITORCARRIER()
void parseParameters(yarp::os::Property &inputoptions, yarp::os::Property &outputoptions)
std::string separateString(std::string input)
std::pair< std::string, std::string > parseBlocks(const std::string &input)
static MonitorBinding * create(const char *script_type)
factory method
virtual bool canAccept()=0
virtual bool peerTrigged()=0
virtual bool acceptIncomingData(PortMonitor *source)
Allow to monitor and modify port data from Lua script Under development.
Definition PortMonitor.h:52
MonitorBinding * getBinder()
void lock() const
void getCarrierParams(yarp::os::Property &params) const override
Get carrier configuration and deliver it by port administrative commands.
yarp::os::ConnectionReader & modifyIncomingData(yarp::os::ConnectionReader &reader) override
Modify incoming payload data, if appropriate.
void unlock() const
const yarp::os::PortWriter & modifyOutgoingData(const yarp::os::PortWriter &writer) override
Modify outgoing payload data, if appropriate.
yarp::os::PortReader & modifyReply(yarp::os::PortReader &reader) override
Modify reply payload data, if appropriate.
void setCarrierParams(const yarp::os::Property &params) override
Configure carrier from port administrative commands.
bool configureFromProperty(yarp::os::Property &options) override
bool acceptIncomingData(yarp::os::ConnectionReader &reader) override
Determine whether incoming data should be accepted.
std::string sourceName
bool acceptOutgoingData(const yarp::os::PortWriter &writer) override
Determine whether outgoing data should be accepted.
std::string portName
bool configure(yarp::os::ConnectionState &proto) override
Class PortMonitor.
A simple collection of objects that can be described and transmitted in a portable way.
Definition Bottle.h:64
A mini-server for performing network communication in the background.
std::string getName() const override
Get name of port.
An interface for reading from a network connection.
virtual ConnectionWriter * getWriter()=0
Gets a way to reply to the message, if possible.
virtual void setParentConnectionReader(ConnectionReader *parentConnectionReader)
Set ConnectionReader to be used for reading the envelope.
The basic state of a connection - route, streams in use, etc.
ConnectionWriter & getWriter()
Get the dummy ConnectionWriter loaded with whatever was written the ConnectionWriter since it was las...
ConnectionReader & getReader(ConnectionWriter *replyWriter=nullptr)
Get the dummy ConnectionReader loaded with whatever was written the ConnectionWriter since it was las...
void reset()
Reset and clear the current ConnectionWriter.
static void unlock()
Call post() on a global mutual-exclusion semaphore allocated by YARP.
Definition Network.cpp:1526
static void lock()
Call wait() on a global mutual-exclusion semaphore allocated by YARP.
Definition Network.cpp:1521
Interface implemented by all objects that can read themselves from the network, such as Bottle object...
Definition PortReader.h:24
Interface implemented by all objects that can write themselves to the network, such as Bottle objects...
Definition PortWriter.h:23
A class for storing options and configuration information.
Definition Property.h:32
Value & find(const std::string &key) const override
Gets a value corresponding to a given keyword.
std::string toString() const override
Return a standard text representation of the content of the object.
void fromString(const std::string &txt, bool wipe=true)
Interprets a string as a list of properties.
void put(const std::string &key, const std::string &value)
Associate the given key with the given string.
Definition Property.cpp:980
bool check(const std::string &key) const override
Check if there exists a property of the given name.
void clear()
Remove all associations.
Helper class for finding config files and other external resources.
bool setDefaultContext(const std::string &contextName)
Sets the context for the current ResourceFinder object.
bool configure(int argc, char *argv[], bool skipFirstArgument=true)
Sets up the ResourceFinder.
std::string findFile(const std::string &name)
Find the full path to a file.
Base class for generic things.
Definition Things.h:18
bool setConnectionReader(yarp::os::ConnectionReader &reader)
set a reference to a ConnectionReader
Definition Things.cpp:46
yarp::os::PortWriter * getPortWriter()
Definition Things.cpp:31
yarp::os::PortReader * getPortReader()
Definition Things.cpp:41
bool write(yarp::os::ConnectionWriter &connection)
Definition Things.cpp:54
void setPortReader(yarp::os::PortReader *reader)
Set the reference to a PortReader object.
Definition Things.cpp:36
void setPortWriter(yarp::os::PortWriter *writer)
Set the reference to a PortWriter object.
Definition Things.cpp:26
bool hasBeenRead()
Definition Things.cpp:75
A single value (typically within a Bottle).
Definition Value.h:44
virtual std::int32_t asInt32() const
Get 32-bit integer value.
Definition Value.cpp:204
virtual std::string asString() const
Get string value.
Definition Value.cpp:240
#define yCError(component,...)
#define yCAssert(component, x)
#define yCTrace(component,...)
An interface to the operating system, including Port based communication.
#define YARP_UNUSED(var)
Definition api.h:162