YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
PortCoreInputUnit.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-FileCopyrightText: 2006-2010 RobotCub Consortium
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
8
9#include <yarp/os/Name.h>
10#include <yarp/os/PortInfo.h>
11#include <yarp/os/PortReport.h>
12#include <yarp/os/Time.h>
16
17#include <cstdio>
18
19
20using namespace yarp::os::impl;
21using namespace yarp::os;
22
23namespace {
24YARP_OS_LOG_COMPONENT(PORTCOREINPUTUNIT, "yarp.os.impl.PortCoreInputUnit")
25} // namespace
26
28 int index,
29 InputProtocol* ip,
30 bool reversed) :
31 PortCoreUnit(owner, index),
32 ip(ip),
33 phase(1),
34 access(1),
35 closing(false),
36 finished(false),
37 running(false),
38 name(owner.getName()),
39 localReader(nullptr),
40 reversed(reversed)
41{
42 yCIAssert(PORTCOREINPUTUNIT, getName(), ip != nullptr);
43
45 if (creator != nullptr) {
46 localReader = creator->create();
47 }
48}
49
51{
52 closeMain();
53 if (localReader != nullptr) {
54 delete localReader;
55 localReader = nullptr;
56 }
57}
58
59
61{
62 yCIDebug(PORTCOREINPUTUNIT, getName(), "new input connection to %s starting", getOwner().getName().c_str());
63
64 phase.wait();
65
66 bool result = PortCoreUnit::start();
67 if (result) {
68 yCIDebug(PORTCOREINPUTUNIT, getName(), "new input connection to %s started ok", getOwner().getName().c_str());
69 phase.wait();
70 phase.post();
71 } else {
72 yCIDebug(PORTCOREINPUTUNIT, getName(), "new input connection to %s failed to start", getOwner().getName().c_str());
73 phase.post();
74 }
75
76 return result;
77}
78
79
81{
82 running = true;
83 phase.post();
84
85 Route route;
86 bool wasNoticed = false;
87 bool posted = false;
88
89 bool done = false;
90
91 yCIAssert(PORTCOREINPUTUNIT, getName(), ip != nullptr);
92
93 PortCommand cmd;
94
95 bool ok = true;
96 if (!reversed) {
97 ip->open(getName());
98 }
99 if (!ok) {
100 yCIDebug(PORTCOREINPUTUNIT, getName(), "new input connection to %s is broken", getOwner().getName().c_str());
101 done = true;
102 } else {
103 route = ip->getRoute();
104
105 // just before going official, tag any lurking inputs from
106 // the same source as undesired
107 if (Name(route.getFromName()).isRooted()) {
108 yCIDebug(PORTCOREINPUTUNIT, getName(), "Port %s starting up, flushing routes %s->*->%s",
109 getOwner().getName().c_str(),
110 route.getFromName().c_str(),
111 route.getToName().c_str());
113 route.getToName(),
114 "*"),
115 true);
116 }
117 officialRoute = route;
118 setMode();
119 getOwner().reportUnit(this, true);
120
121 std::string msg = "Receiving input from " + route.getFromName() + " to " + route.getToName() + " using " + route.getCarrierName();
122 if (Name(route.getFromName()).isRooted() && (reversed || ip->getConnection().isPush())) {
123 yCIInfo(PORTCOREINPUTUNIT, getName(), "%s", msg.c_str());
124 posted = true;
125 } else {
126 yCIDebug(PORTCOREINPUTUNIT, getName(), "%s", msg.c_str());
127 }
128
129 // Report the new connection
131 info.message = msg;
133 info.incoming = true;
134 info.created = true;
135 info.sourceName = route.getFromName();
136 info.targetName = route.getToName();
137 info.portName = info.targetName;
138 info.carrierName = route.getCarrierName();
139
140 if (info.sourceName != "admin" && info.sourceName != "null") {
142 wasNoticed = true;
143 }
144 }
145
146 if (!reversed) {
147 if (!ip->getConnection().isPush()) {
148 /* IP=OP */
149 OutputProtocol* op = &(ip->getOutput());
150 Route r = op->getRoute();
151 // reverse route
152 r.swapNames();
153 op->rename(r);
154
155 getOwner().addOutput(op);
156 ip = nullptr;
157 done = true;
158 }
159 }
160
161 if (closing) {
162 done = true;
163 }
164
165 auto* id = reinterpret_cast<void*>(this);
166
167 if (ip != nullptr && !ip->getConnection().canEscape()) {
168 InputStream* is = &ip->getInputStream();
169 is->setReadEnvelopeCallback(envelopeReadCallback, this);
170 }
171
172 while (!done) {
173 if (ip == nullptr) {
174 break;
175 }
177
178 if (br.getReference() != nullptr) {
179 //printf("HAVE A REFERENCE\n");
180 if (localReader != nullptr) {
181 bool ok = localReader->read(br);
182 if (!br.isActive()) {
183 break;
184 }
185 if (!ok) {
186 continue;
187 }
188 } else {
189 PortCore& man = getOwner();
190 bool ok = man.readBlock(br, id, nullptr);
191 if (!br.isActive()) {
192 break;
193 }
194 if (!ok) {
195 continue;
196 }
197 }
198 //printf("DONE WITH A REFERENCE\n");
199 if (ip != nullptr) {
200 ip->endRead();
201 }
202 continue;
203 }
204
205 if (ip->getConnection().canEscape()) {
206 bool ok = cmd.read(br);
207 if (!br.isActive()) {
208 break;
209 }
210 if (!ok) {
211 continue;
212 }
213 } else {
214 cmd = PortCommand('d', "");
215 if (!ip->isOk()) {
216 break;
217 }
218 }
219
220 if (closing || isDoomed()) {
221 break;
222 }
223 char key = cmd.getKey();
224 //printf("Port command is [%c:%d/%s]\n",
225 // (key>=32)?key:'?', key, cmd.getText().c_str());
226
227 PortCore& man = getOwner();
228 OutputStream* os = nullptr;
229 if (br.isTextMode()) {
230 os = &(ip->getOutputStream());
231 }
232
233 switch (key) {
234 case '/':
236 getName(),
237 "Port command (%s): %s should add connection: %s",
238 route.toString().c_str(),
239 getOwner().getName().c_str(),
240 cmd.getText().c_str());
241 man.addOutput(cmd.getText(), id, os);
242 break;
243 case '!':
245 getName(),
246 "Port command (%s): %s should remove output: %s",
247 route.toString().c_str(),
248 getOwner().getName().c_str(),
249 cmd.getText().c_str());
250 man.removeOutput(cmd.getText().substr(1, std::string::npos), id, os);
251 break;
252 case '~':
254 getName(),
255 "Port command (%s): %s should remove input: %s",
256 route.toString().c_str(),
257 getOwner().getName().c_str(),
258 cmd.getText().c_str());
259 man.removeInput(cmd.getText().substr(1, std::string::npos), id, os);
260 break;
261 case '*':
262 man.describe(id, os);
263 break;
264 case 'D':
265 case 'd': {
266 if (key == 'D') {
267 ip->suppressReply();
268 }
269
270 std::string env = cmd.getText();
271 if (env.length() > 2) {
272 yCITrace(PORTCOREINPUTUNIT, getName(), "***** received an envelope! [%s]", env.c_str());
273 std::string env2 = env.substr(2, env.length());
274 man.setEnvelope(env2);
275 ip->setEnvelope(env2);
276 }
277 if (localReader != nullptr) {
278 localReader->read(br);
279 if (!br.isActive()) {
280 done = true;
281 break;
282 }
283 } else {
284 if (ip->getReceiver().acceptIncomingData(br)) {
285 ConnectionReader* cr = &(ip->getReceiver().modifyIncomingData(br));
287 modifier.inputMutex.lock();
288 if (modifier.inputModifier != nullptr) {
289 if (modifier.inputModifier->acceptIncomingData(*cr)) {
290 cr = &(modifier.inputModifier->modifyIncomingData(*cr));
291 modifier.inputMutex.unlock();
292 man.readBlock(*cr, id, os);
293 } else {
294 modifier.inputMutex.unlock();
295 skipIncomingData(*cr);
296 }
297 } else {
298 modifier.inputMutex.unlock();
299 man.readBlock(*cr, id, os);
300 }
301 } else {
302 skipIncomingData(br);
303 }
304 if (!br.isActive()) {
305 done = true;
306 break;
307 }
308 }
309 } break;
310 case 'a': {
311 man.adminBlock(br, id);
312 } break;
313 case 'r':
314 /*
315 In YARP implementation, OP=IP.
316 (This information is used rarely, and when used
317 is tagged with OP=IP keyword)
318 If it were not true, memory alloc would need to
319 reorganized here
320 */
321 {
322 OutputProtocol* op = &(ip->getOutput());
323 ip->endRead();
324 Route r = op->getRoute();
325 // reverse route
326 r.swapNames();
327 op->rename(r);
328
329 getOwner().addOutput(op);
330 ip = nullptr;
331 done = true;
332 }
333 break;
334 case 'q':
335 done = true;
336 break;
337 case '?':
338 case 'h':
339 if (os != nullptr) {
341 bw.appendLine("This is a YARP port. Here are the commands it responds to:");
342 bw.appendLine("* Gives a description of this port");
343 bw.appendLine("d Signals the beginning of input for the port's owner");
344 bw.appendLine(R"(do The same as "d" except replies should be suppressed ("data-only"))");
345 bw.appendLine("q Disconnects");
346 bw.appendLine("r Reverse connection type to be a reader");
347 bw.appendLine("/port Requests to send output to /port");
348 bw.appendLine("!/port Requests to stop sending output to /port");
349 bw.appendLine("~/port Requests to stop receiving input from /port");
350 bw.appendLine("a Signals the beginning of an administrative message");
351 bw.appendLine("? Gives this help");
352 bw.write(*os);
353 }
354 break;
355 default:
356 if (os != nullptr) {
358 bw.appendLine("Port command not understood.");
359 bw.appendLine("Type d to send data to the port's owner.");
360 bw.appendLine("Type ? for help.");
361 bw.write(*os);
362 }
363 break;
364 }
365 if (ip != nullptr) {
366 ip->endRead();
367 }
368 if (ip == nullptr) {
369 break;
370 }
371 if (closing || isDoomed() || (!ip->isOk())) {
372 break;
373 }
374 }
375
376 setDoomed();
377
378 yCIDebug(PORTCOREINPUTUNIT, getName(), "Closing ip");
379 access.wait();
380 if (ip != nullptr) {
381 ip->close();
382 }
383 access.post();
384 yCIDebug(PORTCOREINPUTUNIT, getName(), "Closed ip");
385
386 std::string msg = std::string("Removing input from ") + route.getFromName() + " to " + route.getToName();
387
388 if (Name(route.getFromName()).isRooted()) {
389 if (posted) {
390 yCIInfo(PORTCOREINPUTUNIT, getName(), "%s", msg.c_str());
391 }
392 } else {
393 yCIDebug(PORTCOREINPUTUNIT, getName(), "(unrooted) shutting down");
394 }
395
396 getOwner().reportUnit(this, false);
397
398 if (wasNoticed) {
399 // Report the disappearing connection
401 info.message = msg;
403 info.incoming = true;
404 info.created = false;
405 info.sourceName = route.getFromName();
406 info.targetName = route.getToName();
407 info.portName = info.targetName;
408 info.carrierName = route.getCarrierName();
409
410 if (info.sourceName != "admin") {
412 }
413 }
414
415 if (localReader != nullptr) {
416 delete localReader;
417 localReader = nullptr;
418 }
419
420 running = false;
421 finished = true;
422
423 // it would be nice to get my entry removed from the port immediately,
424 // but it would be a bit dodgy to delete this object and join this
425 // thread within and from themselves
426}
427
429{
430 return true;
431}
432
434{
435 closeMain();
436}
437
439{
440 return finished;
441}
442
443const std::string& PortCoreInputUnit::getName()
444{
445 return name;
446}
447
449{
450 // give a kick (unfortunately unavoidable)
451 access.wait();
452 if (!closing) {
453 if (ip != nullptr) {
454 ip->interrupt();
455 }
456 closing = true;
457 }
458 access.post();
459 return true;
460}
461
463{
464 if (ip != nullptr) {
465 ip->getReceiver().setCarrierParams(params);
466 }
467}
468
470{
471 if (ip != nullptr) {
472 ip->getReceiver().getCarrierParams(params);
473 }
474}
475
476// return the protocol object
481
482void PortCoreInputUnit::closeMain()
483{
484 access.wait();
485 Route r = getRoute();
486 access.post();
487
488 yCIDebug(PORTCOREINPUTUNIT, getName(), "[%s] closing", r.toString().c_str());
489
490 if (running) {
491 yCIDebug(PORTCOREINPUTUNIT, getName(), "[%s] joining", r.toString().c_str());
492 interrupt();
493 join();
494 yCIDebug(PORTCOREINPUTUNIT, getName(), "[%s] joined", r.toString().c_str());
495 }
496
497 if (ip != nullptr) {
498 ip->close();
499 delete ip;
500 ip = nullptr;
501 }
502 running = false;
503 closing = false;
504}
505
506
508{
509 return officialRoute;
510}
511
512
513bool PortCoreInputUnit::skipIncomingData(yarp::os::ConnectionReader& reader)
514{
515 size_t pending = reader.getSize();
516 if (pending > 0) {
517 while (pending > 0) {
518 char buf[10000];
519 size_t next = (pending < sizeof(buf)) ? pending : sizeof(buf);
520 reader.expectBlock(&buf[0], next);
521 pending -= next;
522 }
523 return true;
524 }
525 return false;
526}
527
528
530{
531 bool busy = false;
532 access.wait();
533 if (ip != nullptr) {
534 busy = ip->isReplying();
535 }
536 access.post();
537 return busy;
538}
539
540
541void PortCoreInputUnit::envelopeReadCallback(void* data, const Bytes& envelope)
542{
543 auto* p = reinterpret_cast<PortCoreInputUnit*>(data);
544 if (p == nullptr) {
545 return;
546 }
547 p->getOwner().setEnvelope(envelope.get());
548 p->ip->setEnvelope(envelope.get());
549}
A mini-server for performing network communication in the background.
bool setEnvelope(PortWriter &envelope) override
Set an envelope (e.g., a timestamp) to the next message which will be sent.
void write(bool forceStrict=false)
Write the current object being returned by BufferedPort::prepare.
A simple abstraction for a block of bytes.
Definition Bytes.h:24
const char * get() const
Definition Bytes.cpp:27
An interface for reading from a network connection.
virtual size_t getSize() const =0
Checks how much data is available.
virtual bool expectBlock(char *data, size_t len)=0
Read a block of data from the network connection.
The input side of an active connection between two ports.
virtual bool open(const std::string &name)=0
Start negotiating a carrier, using the given name as our own if a name is needed (this should general...
virtual bool isOk() const =0
Check if the connection is valid and can be used.
virtual OutputStream & getOutputStream()=0
Access the output stream associated with the connection.
virtual InputStream & getInputStream()=0
Access the input stream associated with the connection.
virtual void close()=0
Negotiate an end to operations.
virtual void setEnvelope(const std::string &str)=0
Set the envelope that will be attached to the next message.
virtual void endRead()=0
End the current read operation, begin by beginRead().
virtual const Route & getRoute() const =0
Get the route associated with this connection.
virtual ConnectionReader & beginRead()=0
Begin a read operation, with bytes read via the returned yarp::os::ConnectionReader object.
virtual void suppressReply()=0
Make sure that any attempt to send a reply to input will be denied.
virtual void interrupt()=0
Try to get operations interrupted.
virtual bool isReplying() const =0
virtual Connection & getReceiver()=0
It is possible to chain a basic connection with a modifier.
virtual OutputProtocol & getOutput()=0
Get an interface for doing write operations on the connection.
virtual Connection & getConnection()=0
Get the basic connection through which we are communicating.
Simple specification of the minimum functions needed from input streams.
Definition InputStream.h:25
virtual bool setReadEnvelopeCallback(readEnvelopeCallbackType callback, void *data)
Install a callback that the InputStream will have to call when the envelope is read from a message in...
Simple abstraction for a YARP port name.
Definition Name.h:18
bool isRooted() const
Check if port name begins with "/".
Definition Name.cpp:16
The output side of an active connection between two ports.
virtual const Route & getRoute() const =0
virtual void rename(const Route &route)=0
Relabel the route after the fact (e.g.
Simple specification of the minimum functions needed from output streams.
Information about a port connection or event.
Definition PortInfo.h:25
std::string message
A human-readable description of contents.
Definition PortInfo.h:68
@ PORTINFO_CONNECTION
Information about an incoming or outgoing connection.
Definition PortInfo.h:39
A creator for readers.
virtual bool read(ConnectionReader &reader)=0
Read this object from a network connection.
A class for storing options and configuration information.
Definition Property.h:32
Information about a connection between two ports.
Definition Route.h:28
const std::string & getToName() const
Get the destination of the route.
Definition Route.cpp:103
const std::string & getCarrierName() const
Get the carrier type of the route.
Definition Route.cpp:123
std::string toString() const
Render a text form of the route, "source->carrier->dest".
Definition Route.cpp:138
const std::string & getFromName() const
Get the source of the route.
Definition Route.cpp:93
void swapNames()
Swap from and to names.
Definition Route.cpp:133
void wait()
Decrement the counter, even if we must wait to do that.
Definition Semaphore.cpp:96
void post()
Increment the counter.
A helper for creating cached object descriptions.
Simple Readable and Writable object representing a command to a YARP port.
Definition PortCommand.h:24
bool read(yarp::os::ConnectionReader &reader) override
Read this object from a network connection.
Manager for a single input to a port.
PortCoreInputUnit(PortCore &owner, int index, InputProtocol *ip, bool reversed)
Constructor.
void run() override
The body of the thread associated with this input.
bool start() override
Start a thread running to serve this input.
void getCarrierParams(yarp::os::Property &params) override
void setCarrierParams(const yarp::os::Property &params) override
Set arbitrary parameters for this connection.
bool interrupt() override
Interrupt the connection.
This manages a single threaded resource related to a single input or output connection.
void setMode()
Check the carrier used for the connection, and see if it has a "log" modifier.
void setDoomed()
Request that this connection be shut down as soon as possible.
bool readBlock(ConnectionReader &reader, void *id, yarp::os::OutputStream *os)
Read a block of regular payload data.
yarp::os::PortReaderCreator * getReadCreator()
Get the creator of callbacks.
bool removeInput(const std::string &src, void *id, yarp::os::OutputStream *os)
Remove an input connection.
void setEnvelope(const std::string &envelope)
Set some envelope information to pass along with a message without actually being part of the message...
bool removeIO(const Route &route, bool synch=false)
Remove any connection matching the supplied route.
void report(const yarp::os::PortInfo &info)
Handle a port event (connection, disconnection, etc) Generate a description of the connections associ...
void reportUnit(PortCoreUnit *unit, bool active)
Called by a connection handler with active=true just after it is fully configured,...
bool removeOutput(const std::string &dest, void *id, yarp::os::OutputStream *os)
Remove an output connection.
void describe(void *id, yarp::os::OutputStream *os)
Produce a text description of the port and its connections.
bool adminBlock(ConnectionReader &reader, void *id)
Read a block of administrative data.
yarp::os::impl::PortDataModifier & getPortModifier()
bool addOutput(const std::string &dest, void *id, yarp::os::OutputStream *os, bool onlyIfNeeded=false)
Add an output connection to this port.
Definition PortCore.cpp:841
This is the heart of a yarp port.
Definition PortCore.h:102
int join(double seconds=-1)
#define yCIAssert(component, id, x)
#define yCIInfo(component, id,...)
#define yCITrace(component, id,...)
#define yCIDebug(component, id,...)
#define YARP_OS_LOG_COMPONENT(name, name_string)
The components from which ports and connections are built.
An interface to the operating system, including Port based communication.