YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
MonitorPython.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2026-2026 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-License-Identifier: BSD-3-Clause
4 */
5
6#include <yarp/os/Network.h>
7#include <yarp/os/Log.h>
8#include <yarp/os/LogStream.h>
9
10#include "MonitorPython.h"
11#include "MonitorLogComponent.h"
12
13#include "swigpythonrun.h"
14
15#include <filesystem>
16
17using namespace yarp::os;
18
19namespace {
20YARP_LOG_COMPONENT(PY_PORT_MONITOR, "yarp.portmonitor.MonitorPython")
21
25
26bool appendPythonPath(const std::string& path)
27{
28 if (path.empty()) {
29 return true;
30 }
31
32 PyObject* sysPath = PySys_GetObject((char*)"path"); // Borrowed reference
33 if (sysPath == nullptr || !PyList_Check(sysPath)) {
34 if (PyErr_Occurred()) {
36 }
37 yCError(PY_PORT_MONITOR) << "Unable to access Python sys.path";
38 return false;
39 }
40
41 PyObject* pyPath = PyUnicode_FromString(path.c_str());
42 if (pyPath == nullptr) {
44 return false;
45 }
46
48 if (contains < 0) {
51 return false;
52 }
53
54 if (contains == 0 && PyList_Append(sysPath, pyPath) != 0) {
57 return false;
58 }
59
61 return true;
62}
63}
64
65
69MonitorPython::MonitorPython() : bHasAcceptCallback(false),
70 bHasUpdateCallback(false),
71 bHasUpdateReplyCallback(false),
72 trigger(nullptr)
73{
74 // Initialize the Python Interpreter
75 if (!Py_IsInitialized())
76 {
77 yInfo() << "Calling Py_Initialize from open()";
78 yInfo() << "Python version: " << Py_GetVersion();
79
81 }
82}
83
85{
86 Py_XDECREF(m_lastUpdateResult);
87}
88
89bool MonitorPython::load(const Property &options)
90{
91 std::lock_guard<std::recursive_mutex> guard(m_monitor_mutex);
92
93 const std::filesystem::path scriptPath(options.find("filename").asString());
94 if (scriptPath.empty()) {
95 yCError(PY_PORT_MONITOR) << "Python monitor script filename is empty";
96 return false;
97 }
98
99 m_path = scriptPath.has_parent_path() ? scriptPath.parent_path().string() : std::string();
100 m_pythonScriptName = scriptPath.stem().string();
101 if (m_pythonScriptName.empty()) {
102 yCError(PY_PORT_MONITOR) << "Unable to determine Python module name from" << scriptPath.string();
103 return false;
104 }
105
106 if (!appendPythonPath(m_path)) {
107 return false;
108 }
109
110 if(!loadPythonModule(m_pythonScriptName, m_pModule)) {
111 return false;
112 }
113
114 bHasAcceptCallback = hasPythonFunction("acceptData");
115 bHasUpdateCallback = hasPythonFunction("updateData");
116 bHasUpdateReplyCallback = hasPythonFunction("updateReply");
117 if(hasPythonFunction("create"))
118 {
119 PyObject* pValue = nullptr;
120 PyObject* pArgs = nullptr;
121 if (!functionWrapper("create", pArgs, pValue))
122 {
123 yCError(PY_PORT_MONITOR) << "Unable to call the create function from python \n";
124 return false;
125 }
127 }
128
129 return ensureYarpModuleLoaded();
130}
131
133{
134 std::lock_guard<std::recursive_mutex> guard(m_monitor_mutex);
136 yDebug() << "acceptData called";
137 if (!bHasAcceptCallback) {
139 return true;
140 }
141 if (!ensureYarpModuleLoaded()) {
143 return false;
144 }
146 if (type == nullptr) {
147 yCError(PY_PORT_MONITOR) << "Swig type of Things is not found";
149 return false;
150 }
151 PyObject* pyThing = SWIG_NewPointerObj((void*)&thing, type, 0);
152 if (pyThing == nullptr) {
153 if (PyErr_Occurred()) {
154 PyErr_Print();
155 }
157 return false;
158 }
160 if (pArgs == nullptr) {
162 if (PyErr_Occurred()) {
163 PyErr_Print();
164 }
166 return false;
167 }
168 if (PyTuple_SetItem(pArgs, 0, pyThing) != 0) {
171 if (PyErr_Occurred()) {
172 PyErr_Print();
173 }
175 return false;
176 }
177 PyObject* pValue = nullptr;
178 if (!functionWrapper("acceptData", pArgs, pValue)) {
179 yCError(PY_PORT_MONITOR) << "Unable to call the acceptData function from python";
182 return false;
183 }
185 if (pValue == nullptr) {
187 return false;
188 }
189 const int accepted = PyObject_IsTrue(pValue);
191 if (accepted < 0) {
192 if (PyErr_Occurred()) {
193 PyErr_Print();
194 }
196 return false;
197 }
198 return accepted != 0;
199}
200
201
203{
204 std::lock_guard<std::recursive_mutex> guard(m_monitor_mutex);
206
207 if (!ensureYarpModuleLoaded()) {
209 return thing;
210 }
211
213 if (type == nullptr) {
214 yCError(PY_PORT_MONITOR) << "Swig type of Things is not found";
216 return thing;
217 }
218
219 PyObject* pyThing = SWIG_NewPointerObj((void*)&thing, type, 0);
220 if (pyThing == nullptr) {
221 if (PyErr_Occurred()) {
222 PyErr_Print();
223 }
225 return thing;
226 }
227
230 if (pArgs == nullptr) {
231 PyErr_Print();
233 return thing;
234 }
235
236 PyObject* pRetValue = nullptr;
237 std::string func_name = "updateData";
238 yDebug() << "Calling " << func_name << " function from python \n";
239 if (!functionWrapper(func_name, pArgs, pRetValue))
240 {
241 yError() << "Unable to call the " << func_name << " function from python \n";
242 }
243
245
246 if (pRetValue != nullptr) {
247 yarp::os::Things* result = nullptr;
248 if (SWIG_ConvertPtr(pRetValue, (void**)(&result), type, 0) == SWIG_OK && result != nullptr) {
249 if (result != &thing) {
250 Py_XDECREF(m_lastUpdateResult);
251 m_lastUpdateResult = pRetValue;
252 pRetValue = nullptr;
253 }
256 return *result;
257 }
258 PyErr_Clear();
259
261 yarp::os::PortWriter* writer = nullptr;
262 if (writerType != nullptr &&
263 SWIG_ConvertPtr(pRetValue, (void**)(&writer), writerType, 0) == SWIG_OK &&
264 writer != nullptr) {
265 thing.setPortWriter(writer);
266 Py_XDECREF(m_lastUpdateResult);
267 m_lastUpdateResult = pRetValue;
268 pRetValue = nullptr;
269 } else {
270 PyErr_Clear();
271 }
272 }
273
275
277 return thing;
278}
279
281{
282 std::lock_guard<std::recursive_mutex> guard(m_monitor_mutex);
284
285 PyObject* pRetValue = nullptr;
287 std::string func_name = "updateReply";
288 if (pArgs == nullptr) {
289 PyErr_Print();
290 yCError(PY_PORT_MONITOR) << "Unable to allocate arguments for the " << func_name << " function";
292 return thing;
293 }
295 if (pThing == nullptr) {
297 PyErr_Print();
298 yCError(PY_PORT_MONITOR) << "Unable to convert reply thing for the " << func_name << " function";
300 return thing;
301 }
303 yCDebug(PY_PORT_MONITOR) << "Calling " << func_name << " function from python";
304 if (!functionWrapper(func_name, pArgs, pRetValue))
305 {
306 yCError(PY_PORT_MONITOR) << "Unable to call the " << func_name << " function from python \n";
309 return thing;
310 }
311 if (pRetValue != nullptr && pRetValue != Py_None) {
314 reinterpret_cast<void**>(&updatedThing),
316 0) == SWIG_OK && updatedThing != nullptr && updatedThing != &thing) {
317 thing = *updatedThing;
318 }
319 }
323 return thing;
324}
325
327{
328 std::lock_guard<std::recursive_mutex> guard(m_monitor_mutex);
330
331 if (!ensureYarpModuleLoaded()) {
333 return false;
334 }
335
337 if (type == nullptr) {
338 yCError(PY_PORT_MONITOR) << "Swig type of Property is not found";
340 return false;
341 }
342
343 PyObject* pyParams = SWIG_NewPointerObj((void*)&params, type, 0);
344 if (pyParams == nullptr) {
345 if (PyErr_Occurred()) {
346 PyErr_Print();
347 }
349 return false;
350 }
351
354 if (pArgs == nullptr) {
355 PyErr_Print();
357 return false;
358 }
359
360 PyObject* pRetValue = nullptr;
361 std::string func_name = "setParams";
362 if (!functionWrapper(func_name, pArgs, pRetValue))
363 {
364 yCError(PY_PORT_MONITOR) << "Unable to call the " << func_name << " function from python";
367 return false;
368 }
372 return true;
373}
374
376{
377 std::lock_guard<std::recursive_mutex> guard(m_monitor_mutex);
379
380 if (!ensureYarpModuleLoaded()) {
382 return false;
383 }
384
386 if (type == nullptr) {
387 yCError(PY_PORT_MONITOR) << "Swig type of Property is not found";
389 return false;
390 }
391
392 PyObject* pyParams = SWIG_NewPointerObj((void*)&params, type, 0);
393 if (pyParams == nullptr) {
394 if (PyErr_Occurred()) {
395 PyErr_Print();
396 }
398 return false;
399 }
400
403 if (pArgs == nullptr) {
404 PyErr_Print();
406 return false;
407 }
408
409 PyObject* pRetValue = nullptr;
410 std::string func_name = "getParams";
411 if (!functionWrapper(func_name, pArgs, pRetValue))
412 {
413 yCError(PY_PORT_MONITOR) << "Unable to call the " << func_name << " function from python";
416 return false;
417 }
419
420 if (pRetValue != nullptr && pRetValue != Py_None) {
423 reinterpret_cast<void**>(&updatedParams),
424 type,
425 0) == SWIG_OK && updatedParams != nullptr && updatedParams != &params) {
426 params = *updatedParams;
427 }
428 }
431 return true;
432}
433
435{
436 std::lock_guard<std::recursive_mutex> guard(m_monitor_mutex);
438 PyObject* pRetValue = nullptr;
439 PyObject* pArgs = nullptr;
440 std::string func_name = "trig";
441 if (!functionWrapper(func_name, pArgs, pRetValue))
442 {
443 yCError(PY_PORT_MONITOR) << "Unable to call the " << func_name << " function from python \n";
445 return false;
446 }
448 return true;
449}
450
452{
453 if (constraint == "") {
454 return true;
455 }
456
458
463 std::string strConstraint = constraint;
464 std::string strDummy = strConstraint;
465 searchReplace(strDummy, "(", " ");
466 searchReplace(strDummy, ")", " ");
467 // wrap it with some guard space
468 strDummy = " " + strDummy + " ";
469 std::string delimiter = " ";
470 size_t pos = 0;
471 std::string token;
472 while ((pos = strDummy.find(delimiter)) != std::string::npos)
473 {
474 token = strDummy.substr(0, pos);
475 if(token.size() && !isKeyword(token.c_str()))
476 {
477 record.lock();
478 std::string value = (record.hasEvent(token.c_str())) ? "True" : "False";
479 record.unlock();
480 searchReplace(strConstraint, token, value);
481 }
482 strDummy.erase(0, pos + delimiter.length());
483 }
484 yCTrace(PY_PORT_MONITOR, "constraint = \'%s\'", strConstraint.c_str());
485 /*
486 * Evaluate the boolean expression using the embedded Python interpreter.
487 * The expression is expected to contain only Python boolean operators and
488 * the True/False literals injected above.
489 */
493 PyObject* result = nullptr;
494 bool accepted = false;
495 if ((globals == nullptr) || (locals == nullptr)) {
496 yCError(PY_PORT_MONITOR, "Failed to allocate Python dictionaries to evaluate constraint '%s'", strConstraint.c_str());
500 return false;
501 }
502 return true;
505 if (result == nullptr) {
506 yCError(PY_PORT_MONITOR, "Failed to evaluate constraint '%s'", strConstraint.c_str());
507 PyErr_Clear();
508 } else {
509 int isTrue = PyObject_IsTrue(result);
510 if (isTrue < 0) {
511 yCError(PY_PORT_MONITOR, "Constraint '%s' did not evaluate to a valid boolean value", strConstraint.c_str());
512 PyErr_Clear();
513 } else {
514 accepted = (isTrue != 0);
515 }
516 }
517 Py_XDECREF(result);
521 return accepted;
522}
523
524
525inline void MonitorPython::searchReplace(std::string& str, const std::string& oldStr, const std::string& newStr)
526{
527 size_t pos = 0;
528 while((pos = str.find(oldStr, pos)) != std::string::npos)
529 {
530 str.replace(pos, oldStr.length(), newStr);
531 pos += newStr.length();
532 }
533}
534
535inline void MonitorPython::trimString(std::string& str)
536{
537 std::string::size_type pos = str.find_last_not_of(' ');
538 if(pos != std::string::npos) {
539 str.erase(pos + 1);
540 pos = str.find_first_not_of(' ');
541 if (pos != std::string::npos) {
542 str.erase(0, pos);
543 }
544 } else {
545 str.erase(str.begin(), str.end());
546 }
547}
548
549inline bool MonitorPython::isKeyword(const char* str)
550{
551 if (!str) {
552 return false;
553 }
554
555 std::string token = str;
556 if ((token == "true") || (token == "false") || (token == "and") || (token == "or") || (token == "not")) {
557 return true;
558 }
559 return false;
560}
561
562
568bool MonitorPython::loadPythonModule(const std::string& moduleName, PyObject* &pModule)
569{
570 pModule = nullptr;
572 if (!Py_IsInitialized())
573 {
574 yInfo()<<"Calling loadPythonModule Py_Initialize";
576 }
577
578 if (!appendPythonPath(m_path)) {
580 return false;
581 }
582
583 PyObject *pName = PyUnicode_DecodeFSDefault(moduleName.c_str());
584 if (pName == nullptr) {
585 PyErr_Print();
586 yCError(PY_PORT_MONITOR) << "Unable to decode Python module name: " << moduleName;
588 return false;
589 }
590
593
594 if (pModule == nullptr) {
595 PyErr_Print();
596 yCError(PY_PORT_MONITOR) << "Failed to load Python module: " << moduleName;
598 return false;
599 }
601 return true;
602}
603
604
605bool MonitorPython::functionWrapper(std::string functionName, PyObject* &pArgs, PyObject* &pValue)
606{
607 pValue = nullptr;
608 if (!Py_IsInitialized())
609 {
610 yInfo()<<"Calling functionWrapper Py_Initialize";
612 }
613
614 PyObject *pFunc; //Interpreted name of the function
615
616 if (m_pModule != NULL) // Check if the Module has been found and loaded
617 {
618 // Get the function inside the module
619 pFunc = PyObject_GetAttrString(m_pModule, functionName.c_str());
620
621 if (pFunc && PyCallable_Check(pFunc)) // Check if the function has been found and is callable
622 {
623 // Call the function
626 // Check the return value
627 if (pValue != NULL)
628 {
629 // Clear memory
630 return true;
631 }
632 else
633 { // Call Failed
634 PyErr_Print();
635 yCError(PY_PORT_MONITOR) << "Call failed";
636
637 return false;
638 }
639 }
640 else
641 { // Function not found in the py module
642 if (PyErr_Occurred())
643 PyErr_Print();
644 yCError(PY_PORT_MONITOR) << "Cannot find function: " << functionName;
646
647 return false;
648 }
649 }
650 else
651 { // Module not found or loaded
652 PyErr_Print();
653 yCError(PY_PORT_MONITOR) << "Failed to load: " << m_pythonScriptName;
654 return false;
655 }
656}
657
658bool MonitorPython::hasPythonFunction(const std::string& functionName)
659{
660 PyObject* pFunc = PyObject_GetAttrString(m_pModule, functionName.c_str());
661 if (pFunc == nullptr) {
663 PyErr_Clear(); // Function simply does not exist.
664 } else {
665 PyErr_Print(); // Real error during lookup.
666 }
667
668 return false;
669 }
670
671 const bool isCallable = PyCallable_Check(pFunc);
672
674
675 return isCallable;
676}
677
678bool MonitorPython::ensureYarpModuleLoaded()
679{
680 if (!Py_IsInitialized())
681 {
682 yInfo()<<"Calling ensureYarpModuleLoaded Py_Initialize";
684 }
685
686 if (SWIG_GetModule(nullptr) != nullptr) {
687 return true;
688 }
689
691 if (yarpModule == nullptr) {
692 PyErr_Print();
693 yCError(PY_PORT_MONITOR) << "Unable to import the yarp Python module";
694 return false;
695 }
697
698 if (SWIG_GetModule(nullptr) == nullptr) {
699 yCError(PY_PORT_MONITOR) << "The yarp Python module did not register SWIG runtime data";
700 return false;
701 }
702
703 return true;
704}
705
706bool MonitorPython::classWrapper(PyObject* &pClassInstance, std::string methodName, PyObject* &pClassMethodArgs, PyObject* &pValue)
707{
708 if (!Py_IsInitialized())
709 {
710 yInfo()<<"Calling classWrapper Py_Initialize";
712 }
713 PyObject *pMethod; // Converted name of the class method to PyObject
714
715 yCInfo(PY_PORT_MONITOR) << "[classWrapper] converting method from str";
717
718 if (pMethod == NULL)
719 {
720 yCError(PY_PORT_MONITOR) << "[classWrapper] Unable to convert methodName to python";
721 if (PyErr_Occurred())
722 PyErr_Print();
724 return false;
725 }
726
727 yCInfo(PY_PORT_MONITOR) << "[classWrapper] class instance check";
728 if (pClassInstance==NULL)
729 {
730 yCError(PY_PORT_MONITOR) << "[classWrapper] Class instance NULL";
731 if (PyErr_Occurred())
732 PyErr_Print();
734 return false;
735 }
736
737 yCInfo(PY_PORT_MONITOR) << "[classWrapper] calling method class";
739
740 if (pValue==NULL)
741 {
742 yCError(PY_PORT_MONITOR) << "[classWrapper] Returned NULL Value from Class call";
743 if (PyErr_Occurred())
744 PyErr_Print();
746 return false;
747 }
749 return true;
750}
#define yInfo(...)
Definition Log.h:319
#define yError(...)
Definition Log.h:361
#define yDebug(...)
Definition Log.h:275
A singleton class to record the port monitor events.
static MonitorEventRecord & getInstance()
bool peerTrigged() override
bool setParams(const yarp::os::Property &params) override
bool load(const yarp::os::Property &options) override
yarp::os::Things & updateData(yarp::os::Things &thing) override
bool acceptData(yarp::os::Things &thing) override
bool canAccept() override
bool getParams(yarp::os::Property &params) override
MonitorPython()
Class MonitorPython.
yarp::os::Things & updateReply(yarp::os::Things &thing) override
~MonitorPython() override
A mini-server for performing network communication in the background.
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:33
Value & find(const std::string &key) const override
Gets a value corresponding to a given keyword.
Base class for generic things.
Definition Things.h:18
void setPortWriter(yarp::os::PortWriter *writer)
Set the reference to a PortWriter object.
Definition Things.cpp:26
virtual std::string asString() const
Get string value.
Definition Value.cpp:246
#define yCInfo(component,...)
#define yCError(component,...)
#define yCTrace(component,...)
#define yCDebug(component,...)
#define YARP_LOG_COMPONENT(name,...)
STL namespace.
An interface to the operating system, including Port based communication.
Definition OSTestMsg.cpp:13
The main, catch-all namespace for YARP.
Definition dirs.h:16
#define SWIG_ConvertPtr(L, idx, ptr, type, flags)
#define SWIG_NewPointerObj(L, ptr, type, owner)
#define SWIG_GetModule(clientdata)
static swig_type_info * SWIG_TypeQuery(lua_State *clientdata, const char *name)
#define SWIG_OK
Definition swigluarun.h:280